text
stringlengths
1
1.05M
//Framework #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Utilities/interface/EDMException.h" #include "FWCore/Utilities/interface/InputTag.h" //DataFormats #include <DataFormats/TrackReco/interface/Track.h> #include <DataFormats/METReco/interface/CaloMET.h> #include <DataFormats/Math/interface/deltaPhi.h> //STL #include <math.h> //ROOT #include "TLorentzVector.h" #include "Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h" //TODO put those namespaces into functions? using namespace std; using namespace edm; // constructor ---------------------------------------------------------------- AlignmentTwoBodyDecayTrackSelector::AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet & cfg, edm::ConsumesCollector& iC) { LogDebug("Alignment") << "> applying two body decay Trackfilter ..."; theMassrangeSwitch = cfg.getParameter<bool>( "applyMassrangeFilter" ); if (theMassrangeSwitch){ theMinMass = cfg.getParameter<double>( "minXMass" ); theMaxMass = cfg.getParameter<double>( "maxXMass" ); theDaughterMass = cfg.getParameter<double>( "daughterMass" ); theCandNumber = cfg.getParameter<unsigned int>( "numberOfCandidates" );//Number of candidates to keep secThrBool = cfg.getParameter<bool> ( "applySecThreshold" ); thesecThr = cfg.getParameter<double>( "secondThreshold" ); LogDebug("Alignment") << "> Massrange min,max : " << theMinMass << "," << theMaxMass << "\n> Mass of daughter Particle : " << theDaughterMass; }else{ theMinMass = 0; theMaxMass = 0; theDaughterMass = 0; } theChargeSwitch = cfg.getParameter<bool>( "applyChargeFilter" ); if(theChargeSwitch){ theCharge = cfg.getParameter<int>( "charge" ); theUnsignedSwitch = cfg.getParameter<bool>( "useUnsignedCharge" ); if(theUnsignedSwitch) theCharge=std::abs(theCharge); LogDebug("Alignment") << "> Desired Charge, unsigned: "<<theCharge<<" , "<<theUnsignedSwitch; }else{ theCharge =0; theUnsignedSwitch = true; } theMissingETSwitch = cfg.getParameter<bool>( "applyMissingETFilter" ); if(theMissingETSwitch){ edm::InputTag theMissingETSource = cfg.getParameter<InputTag>( "missingETSource" ); theMissingETToken = iC.consumes<reco::CaloMETCollection>(theMissingETSource); LogDebug("Alignment") << "> missing Et Source: "<< theMissingETSource; } theAcoplanarityFilterSwitch = cfg.getParameter<bool>( "applyAcoplanarityFilter" ); if(theAcoplanarityFilterSwitch){ theAcoplanarDistance = cfg.getParameter<double>( "acoplanarDistance" ); LogDebug("Alignment") << "> Acoplanar Distance: "<<theAcoplanarDistance; } } // destructor ----------------------------------------------------------------- AlignmentTwoBodyDecayTrackSelector::~AlignmentTwoBodyDecayTrackSelector() {} ///returns if any of the Filters is used. bool AlignmentTwoBodyDecayTrackSelector::useThisFilter() { return theMassrangeSwitch || theChargeSwitch || theAcoplanarityFilterSwitch; } // do selection --------------------------------------------------------------- AlignmentTwoBodyDecayTrackSelector::Tracks AlignmentTwoBodyDecayTrackSelector::select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& iSetup) { Tracks result = tracks; if (theMassrangeSwitch) { if (theMissingETSwitch) result = checkMETMass(result,iEvent); else result = checkMass(result); } LogDebug("Alignment") << "> TwoBodyDecay tracks all,kept: " << tracks.size() << "," << result.size(); return result; } template<class T> struct higherTwoBodyDecayPt : public std::binary_function<T,T,bool> { bool operator()( const T& a, const T& b ) { return a.first > b.first ; } }; ///checks if the mass of the X is in the mass region AlignmentTwoBodyDecayTrackSelector::Tracks AlignmentTwoBodyDecayTrackSelector::checkMass(const Tracks& cands) const { Tracks result; LogDebug("Alignment") <<"> cands size : "<< cands.size(); if (cands.size()<2) return result; TLorentzVector track0; TLorentzVector track1; TLorentzVector mother; typedef pair<const reco::Track*,const reco::Track*> constTrackPair; typedef pair<double,constTrackPair> candCollectionItem; vector<candCollectionItem> candCollection; for (unsigned int iCand = 0; iCand < cands.size(); iCand++) { track0.SetXYZT(cands.at(iCand)->px(), cands.at(iCand)->py(), cands.at(iCand)->pz(), sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass )); for (unsigned int jCand = iCand+1; jCand < cands.size(); jCand++) { track1.SetXYZT(cands.at(jCand)->px(), cands.at(jCand)->py(), cands.at(jCand)->pz(), sqrt( cands.at(jCand)->p()*cands.at(jCand)->p() + theDaughterMass*theDaughterMass )); if (secThrBool==true && track1.Pt() < thesecThr && track0.Pt()< thesecThr) continue; mother = track0 + track1; const reco::Track *trk1 = cands.at(iCand); const reco::Track *trk2 = cands.at(jCand); bool correctCharge = true; if (theChargeSwitch) correctCharge = this->checkCharge(trk1, trk2); bool acoplanarTracks = true; if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkAcoplanarity(trk1, trk2); if (mother.M() > theMinMass && mother.M() < theMaxMass && correctCharge && acoplanarTracks) { candCollection.push_back(candCollectionItem(mother.Pt(), constTrackPair(trk1, trk2))); } } } if (candCollection.size()==0) return result; sort(candCollection.begin(), candCollection.end(), higherTwoBodyDecayPt<candCollectionItem>()); std::map<const reco::Track*,unsigned int> uniqueTrackIndex; std::map<const reco::Track*,unsigned int>::iterator it; for (unsigned int i=0; i<candCollection.size() && i<theCandNumber; i++) { constTrackPair & trackPair = candCollection[i].second; it = uniqueTrackIndex.find(trackPair.first); if (it==uniqueTrackIndex.end()) { result.push_back(trackPair.first); uniqueTrackIndex[trackPair.first] = i; } it = uniqueTrackIndex.find(trackPair.second); if (it==uniqueTrackIndex.end()) { result.push_back(trackPair.second); uniqueTrackIndex[trackPair.second] = i; } } return result; } ///checks if the mass of the X is in the mass region adding missing E_T AlignmentTwoBodyDecayTrackSelector::Tracks AlignmentTwoBodyDecayTrackSelector::checkMETMass(const Tracks& cands,const edm::Event& iEvent) const { Tracks result; LogDebug("Alignment") <<"> cands size : "<< cands.size(); if (cands.size()==0) return result; TLorentzVector track; TLorentzVector met4; TLorentzVector mother; Handle<reco::CaloMETCollection> missingET; iEvent.getByToken(theMissingETToken ,missingET); if (!missingET.isValid()) { LogError("Alignment")<< "@SUB=AlignmentTwoBodyDecayTrackSelector::checkMETMass" << "> could not optain missingET Collection!"; return result; } typedef pair<double,const reco::Track*> candCollectionItem; vector<candCollectionItem> candCollection; for (reco::CaloMETCollection::const_iterator itMET = missingET->begin(); itMET != missingET->end(); ++itMET) { met4.SetXYZT((*itMET).px(), (*itMET).py(), (*itMET).pz(), (*itMET).p()); for (unsigned int iCand = 0; iCand < cands.size(); iCand++) { track.SetXYZT(cands.at(iCand)->px(), cands.at(iCand)->py(), cands.at(iCand)->pz(), sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass )); mother = track + met4; const reco::Track *trk = cands.at(iCand); const reco::CaloMET *met = &(*itMET); bool correctCharge = true; if (theChargeSwitch) correctCharge = this->checkCharge(trk); bool acoplanarTracks = true; if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkMETAcoplanarity(trk, met); if (mother.M() > theMinMass && mother.M() < theMaxMass && correctCharge && acoplanarTracks) { candCollection.push_back(candCollectionItem(mother.Pt(), trk)); } } } if (candCollection.size()==0) return result; sort(candCollection.begin(), candCollection.end(), higherTwoBodyDecayPt<candCollectionItem>()); std::map<const reco::Track*,unsigned int> uniqueTrackIndex; std::map<const reco::Track*,unsigned int>::iterator it; for (unsigned int i=0; i<candCollection.size() && i<theCandNumber; i++) { it = uniqueTrackIndex.find(candCollection[i].second); if (it==uniqueTrackIndex.end()) { result.push_back(candCollection[i].second); uniqueTrackIndex[candCollection[i].second] = i; } } return result; } ///checks if the mother has charge = [theCharge] bool AlignmentTwoBodyDecayTrackSelector::checkCharge(const reco::Track* trk1, const reco::Track* trk2)const { int sumCharge = trk1->charge(); if (trk2) sumCharge += trk2->charge(); if (theUnsignedSwitch) sumCharge = std::abs(sumCharge); if (sumCharge == theCharge) return true; return false; } ///checks if the [cands] are acoplanar (returns empty set if not) bool AlignmentTwoBodyDecayTrackSelector::checkAcoplanarity(const reco::Track* trk1, const reco::Track* trk2)const { if (fabs(deltaPhi(trk1->phi(),trk2->phi()-M_PI)) < theAcoplanarDistance) return true; return false; } ///checks if the [cands] are acoplanar (returns empty set if not) bool AlignmentTwoBodyDecayTrackSelector::checkMETAcoplanarity(const reco::Track* trk1, const reco::CaloMET* met)const { if (fabs(deltaPhi(trk1->phi(),met->phi()-M_PI)) < theAcoplanarDistance) return true; return false; } //===================HELPERS=================== ///print Information on Track-Collection void AlignmentTwoBodyDecayTrackSelector::printTracks(const Tracks& col) const { int count = 0; LogDebug("Alignment") << ">......................................"; for(Tracks::const_iterator it = col.begin();it < col.end();++it,++count){ LogDebug("Alignment") <<"> Track No. "<< count <<": p = ("<<(*it)->px()<<","<<(*it)->py()<<","<<(*it)->pz()<<")\n" <<"> pT = "<<(*it)->pt()<<" eta = "<<(*it)->eta()<<" charge = "<<(*it)->charge(); } LogDebug("Alignment") << ">......................................"; }
; A111495: Floor of 10^n/Li(10^n) - 1. ; 0,2,4,7,9,11,14,16,18,20,23,25,27,30,32,34,37,39,41,44,46,48,50,53,55,57,60,62,64,67,69,71,73,76,78,80,83,85,87,90,92,94,97,99,101,103,106,108,110,113,115,117,120,122,124,126,129,131,133,136,138,140,143,145 mov $5,$0 add $0,4 mov $2,$0 add $0,4 mov $7,10 lpb $0,1 add $7,4 mov $0,$7 add $0,8 mov $4,$2 mov $7,1 add $7,$0 mov $0,$6 add $0,7 mul $4,$0 lpe div $4,$7 mov $1,$4 sub $1,1 mov $3,$5 mul $3,2 add $1,$3
; A121199: 12n+7^n+5^n. ; 2,24,98,504,3074,19992,133346,901752,6155522,42306840,292240994,2026155000,14085427970,98109713688,684326588642,4778079088248,33385518460418,233393453440536,1632228295176290,11417968671701496,79887633729252866,559022701241487384,3912205234374003938,27380668269035994744,191640836025341805314,1341366642887841854232,9388970453767139071586,65719812944131203967992,460023789447724580117762,3220092020328102822541080,22540271613266873566379234,157780038647718884007621240,1104450957308286033268190210,7731110135029271458951547928,54117538114561246343031926882,378821602648710455053078954488,2651745397774881838630830022658,18562188680593716136712196874776,129935175245003729288467311714530,909545499119264686676680849967736,6366814855856045715023814289615106,44567685801098284546601941726521624,311973709658217814533389800581742178 mov $2,1 add $2,$0 seq $0,121201 ; 7^n+5^n-2n. add $0,8 mul $2,14 add $0,$2 sub $0,22
aci -128 ; CE 80 aci 127 ; CE 7F aci 255 ; CE FF adc (hl) ; 8E adc (ix) ; DD 8E 00 adc (ix+127) ; DD 8E 7F adc (ix-128) ; DD 8E 80 adc (iy) ; FD 8E 00 adc (iy+127) ; FD 8E 7F adc (iy-128) ; FD 8E 80 adc -128 ; CE 80 adc 127 ; CE 7F adc 255 ; CE FF adc a ; 8F adc a, (hl) ; 8E adc a, (ix) ; DD 8E 00 adc a, (ix+127) ; DD 8E 7F adc a, (ix-128) ; DD 8E 80 adc a, (iy) ; FD 8E 00 adc a, (iy+127) ; FD 8E 7F adc a, (iy-128) ; FD 8E 80 adc a, -128 ; CE 80 adc a, 127 ; CE 7F adc a, 255 ; CE FF adc a, a ; 8F adc a, b ; 88 adc a, c ; 89 adc a, d ; 8A adc a, e ; 8B adc a, h ; 8C adc a, l ; 8D adc b ; 88 adc c ; 89 adc d ; 8A adc e ; 8B adc h ; 8C adc hl, bc ; ED 4A adc hl, de ; ED 5A adc hl, hl ; ED 6A adc hl, sp ; ED 7A adc l ; 8D adc m ; 8E add (hl) ; 86 add (ix) ; DD 86 00 add (ix+127) ; DD 86 7F add (ix-128) ; DD 86 80 add (iy) ; FD 86 00 add (iy+127) ; FD 86 7F add (iy-128) ; FD 86 80 add -128 ; C6 80 add 127 ; C6 7F add 255 ; C6 FF add a ; 87 add a, (hl) ; 86 add a, (ix) ; DD 86 00 add a, (ix+127) ; DD 86 7F add a, (ix-128) ; DD 86 80 add a, (iy) ; FD 86 00 add a, (iy+127) ; FD 86 7F add a, (iy-128) ; FD 86 80 add a, -128 ; C6 80 add a, 127 ; C6 7F add a, 255 ; C6 FF add a, a ; 87 add a, b ; 80 add a, c ; 81 add a, d ; 82 add a, e ; 83 add a, h ; 84 add a, l ; 85 add b ; 80 add bc, -32768 ; E5 21 00 80 09 44 4D E1 add bc, 32767 ; E5 21 FF 7F 09 44 4D E1 add bc, 65535 ; E5 21 FF FF 09 44 4D E1 add bc, a ; CD @__z80asm__add_bc_a add c ; 81 add d ; 82 add de, -32768 ; E5 21 00 80 19 54 5D E1 add de, 32767 ; E5 21 FF 7F 19 54 5D E1 add de, 65535 ; E5 21 FF FF 19 54 5D E1 add de, a ; CD @__z80asm__add_de_a add e ; 83 add h ; 84 add hl, -32768 ; D5 11 00 80 19 D1 add hl, 32767 ; D5 11 FF 7F 19 D1 add hl, 65535 ; D5 11 FF FF 19 D1 add hl, a ; CD @__z80asm__add_hl_a add hl, bc ; 09 add hl, de ; 19 add hl, hl ; 29 add hl, sp ; 39 add ix, bc ; DD 09 add ix, de ; DD 19 add ix, ix ; DD 29 add ix, sp ; DD 39 add iy, bc ; FD 09 add iy, de ; FD 19 add iy, iy ; FD 29 add iy, sp ; FD 39 add l ; 85 add m ; 86 add.a sp, -128 ; E5 3E 80 6F 17 9F 67 39 F9 E1 add.a sp, 127 ; E5 3E 7F 6F 17 9F 67 39 F9 E1 adi -128 ; C6 80 adi 127 ; C6 7F adi 255 ; C6 FF ana a ; A7 ana b ; A0 ana c ; A1 ana d ; A2 ana e ; A3 ana h ; A4 ana l ; A5 ana m ; A6 and (hl) ; A6 and (ix) ; DD A6 00 and (ix+127) ; DD A6 7F and (ix-128) ; DD A6 80 and (iy) ; FD A6 00 and (iy+127) ; FD A6 7F and (iy-128) ; FD A6 80 and -128 ; E6 80 and 127 ; E6 7F and 255 ; E6 FF and a ; A7 and a, (hl) ; A6 and a, (ix) ; DD A6 00 and a, (ix+127) ; DD A6 7F and a, (ix-128) ; DD A6 80 and a, (iy) ; FD A6 00 and a, (iy+127) ; FD A6 7F and a, (iy-128) ; FD A6 80 and a, -128 ; E6 80 and a, 127 ; E6 7F and a, 255 ; E6 FF and a, a ; A7 and a, b ; A0 and a, c ; A1 and a, d ; A2 and a, e ; A3 and a, h ; A4 and a, l ; A5 and b ; A0 and c ; A1 and d ; A2 and e ; A3 and h ; A4 and l ; A5 and.a hl, bc ; 7C A0 67 7D A1 6F and.a hl, de ; 7C A2 67 7D A3 6F ani -128 ; E6 80 ani 127 ; E6 7F ani 255 ; E6 FF arhl ; CB 2C CB 1D bit 0, (hl) ; CB 46 bit 0, (ix) ; DD CB 00 46 bit 0, (ix+127) ; DD CB 7F 46 bit 0, (ix-128) ; DD CB 80 46 bit 0, (iy) ; FD CB 00 46 bit 0, (iy+127) ; FD CB 7F 46 bit 0, (iy-128) ; FD CB 80 46 bit 0, a ; CB 47 bit 0, b ; CB 40 bit 0, c ; CB 41 bit 0, d ; CB 42 bit 0, e ; CB 43 bit 0, h ; CB 44 bit 0, l ; CB 45 bit 1, (hl) ; CB 4E bit 1, (ix) ; DD CB 00 4E bit 1, (ix+127) ; DD CB 7F 4E bit 1, (ix-128) ; DD CB 80 4E bit 1, (iy) ; FD CB 00 4E bit 1, (iy+127) ; FD CB 7F 4E bit 1, (iy-128) ; FD CB 80 4E bit 1, a ; CB 4F bit 1, b ; CB 48 bit 1, c ; CB 49 bit 1, d ; CB 4A bit 1, e ; CB 4B bit 1, h ; CB 4C bit 1, l ; CB 4D bit 2, (hl) ; CB 56 bit 2, (ix) ; DD CB 00 56 bit 2, (ix+127) ; DD CB 7F 56 bit 2, (ix-128) ; DD CB 80 56 bit 2, (iy) ; FD CB 00 56 bit 2, (iy+127) ; FD CB 7F 56 bit 2, (iy-128) ; FD CB 80 56 bit 2, a ; CB 57 bit 2, b ; CB 50 bit 2, c ; CB 51 bit 2, d ; CB 52 bit 2, e ; CB 53 bit 2, h ; CB 54 bit 2, l ; CB 55 bit 3, (hl) ; CB 5E bit 3, (ix) ; DD CB 00 5E bit 3, (ix+127) ; DD CB 7F 5E bit 3, (ix-128) ; DD CB 80 5E bit 3, (iy) ; FD CB 00 5E bit 3, (iy+127) ; FD CB 7F 5E bit 3, (iy-128) ; FD CB 80 5E bit 3, a ; CB 5F bit 3, b ; CB 58 bit 3, c ; CB 59 bit 3, d ; CB 5A bit 3, e ; CB 5B bit 3, h ; CB 5C bit 3, l ; CB 5D bit 4, (hl) ; CB 66 bit 4, (ix) ; DD CB 00 66 bit 4, (ix+127) ; DD CB 7F 66 bit 4, (ix-128) ; DD CB 80 66 bit 4, (iy) ; FD CB 00 66 bit 4, (iy+127) ; FD CB 7F 66 bit 4, (iy-128) ; FD CB 80 66 bit 4, a ; CB 67 bit 4, b ; CB 60 bit 4, c ; CB 61 bit 4, d ; CB 62 bit 4, e ; CB 63 bit 4, h ; CB 64 bit 4, l ; CB 65 bit 5, (hl) ; CB 6E bit 5, (ix) ; DD CB 00 6E bit 5, (ix+127) ; DD CB 7F 6E bit 5, (ix-128) ; DD CB 80 6E bit 5, (iy) ; FD CB 00 6E bit 5, (iy+127) ; FD CB 7F 6E bit 5, (iy-128) ; FD CB 80 6E bit 5, a ; CB 6F bit 5, b ; CB 68 bit 5, c ; CB 69 bit 5, d ; CB 6A bit 5, e ; CB 6B bit 5, h ; CB 6C bit 5, l ; CB 6D bit 6, (hl) ; CB 76 bit 6, (ix) ; DD CB 00 76 bit 6, (ix+127) ; DD CB 7F 76 bit 6, (ix-128) ; DD CB 80 76 bit 6, (iy) ; FD CB 00 76 bit 6, (iy+127) ; FD CB 7F 76 bit 6, (iy-128) ; FD CB 80 76 bit 6, a ; CB 77 bit 6, b ; CB 70 bit 6, c ; CB 71 bit 6, d ; CB 72 bit 6, e ; CB 73 bit 6, h ; CB 74 bit 6, l ; CB 75 bit 7, (hl) ; CB 7E bit 7, (ix) ; DD CB 00 7E bit 7, (ix+127) ; DD CB 7F 7E bit 7, (ix-128) ; DD CB 80 7E bit 7, (iy) ; FD CB 00 7E bit 7, (iy+127) ; FD CB 7F 7E bit 7, (iy-128) ; FD CB 80 7E bit 7, a ; CB 7F bit 7, b ; CB 78 bit 7, c ; CB 79 bit 7, d ; CB 7A bit 7, e ; CB 7B bit 7, h ; CB 7C bit 7, l ; CB 7D bit.a 0, (hl) ; CB 46 bit.a 0, (ix) ; DD CB 00 46 bit.a 0, (ix+127) ; DD CB 7F 46 bit.a 0, (ix-128) ; DD CB 80 46 bit.a 0, (iy) ; FD CB 00 46 bit.a 0, (iy+127) ; FD CB 7F 46 bit.a 0, (iy-128) ; FD CB 80 46 bit.a 0, a ; CB 47 bit.a 0, b ; CB 40 bit.a 0, c ; CB 41 bit.a 0, d ; CB 42 bit.a 0, e ; CB 43 bit.a 0, h ; CB 44 bit.a 0, l ; CB 45 bit.a 1, (hl) ; CB 4E bit.a 1, (ix) ; DD CB 00 4E bit.a 1, (ix+127) ; DD CB 7F 4E bit.a 1, (ix-128) ; DD CB 80 4E bit.a 1, (iy) ; FD CB 00 4E bit.a 1, (iy+127) ; FD CB 7F 4E bit.a 1, (iy-128) ; FD CB 80 4E bit.a 1, a ; CB 4F bit.a 1, b ; CB 48 bit.a 1, c ; CB 49 bit.a 1, d ; CB 4A bit.a 1, e ; CB 4B bit.a 1, h ; CB 4C bit.a 1, l ; CB 4D bit.a 2, (hl) ; CB 56 bit.a 2, (ix) ; DD CB 00 56 bit.a 2, (ix+127) ; DD CB 7F 56 bit.a 2, (ix-128) ; DD CB 80 56 bit.a 2, (iy) ; FD CB 00 56 bit.a 2, (iy+127) ; FD CB 7F 56 bit.a 2, (iy-128) ; FD CB 80 56 bit.a 2, a ; CB 57 bit.a 2, b ; CB 50 bit.a 2, c ; CB 51 bit.a 2, d ; CB 52 bit.a 2, e ; CB 53 bit.a 2, h ; CB 54 bit.a 2, l ; CB 55 bit.a 3, (hl) ; CB 5E bit.a 3, (ix) ; DD CB 00 5E bit.a 3, (ix+127) ; DD CB 7F 5E bit.a 3, (ix-128) ; DD CB 80 5E bit.a 3, (iy) ; FD CB 00 5E bit.a 3, (iy+127) ; FD CB 7F 5E bit.a 3, (iy-128) ; FD CB 80 5E bit.a 3, a ; CB 5F bit.a 3, b ; CB 58 bit.a 3, c ; CB 59 bit.a 3, d ; CB 5A bit.a 3, e ; CB 5B bit.a 3, h ; CB 5C bit.a 3, l ; CB 5D bit.a 4, (hl) ; CB 66 bit.a 4, (ix) ; DD CB 00 66 bit.a 4, (ix+127) ; DD CB 7F 66 bit.a 4, (ix-128) ; DD CB 80 66 bit.a 4, (iy) ; FD CB 00 66 bit.a 4, (iy+127) ; FD CB 7F 66 bit.a 4, (iy-128) ; FD CB 80 66 bit.a 4, a ; CB 67 bit.a 4, b ; CB 60 bit.a 4, c ; CB 61 bit.a 4, d ; CB 62 bit.a 4, e ; CB 63 bit.a 4, h ; CB 64 bit.a 4, l ; CB 65 bit.a 5, (hl) ; CB 6E bit.a 5, (ix) ; DD CB 00 6E bit.a 5, (ix+127) ; DD CB 7F 6E bit.a 5, (ix-128) ; DD CB 80 6E bit.a 5, (iy) ; FD CB 00 6E bit.a 5, (iy+127) ; FD CB 7F 6E bit.a 5, (iy-128) ; FD CB 80 6E bit.a 5, a ; CB 6F bit.a 5, b ; CB 68 bit.a 5, c ; CB 69 bit.a 5, d ; CB 6A bit.a 5, e ; CB 6B bit.a 5, h ; CB 6C bit.a 5, l ; CB 6D bit.a 6, (hl) ; CB 76 bit.a 6, (ix) ; DD CB 00 76 bit.a 6, (ix+127) ; DD CB 7F 76 bit.a 6, (ix-128) ; DD CB 80 76 bit.a 6, (iy) ; FD CB 00 76 bit.a 6, (iy+127) ; FD CB 7F 76 bit.a 6, (iy-128) ; FD CB 80 76 bit.a 6, a ; CB 77 bit.a 6, b ; CB 70 bit.a 6, c ; CB 71 bit.a 6, d ; CB 72 bit.a 6, e ; CB 73 bit.a 6, h ; CB 74 bit.a 6, l ; CB 75 bit.a 7, (hl) ; CB 7E bit.a 7, (ix) ; DD CB 00 7E bit.a 7, (ix+127) ; DD CB 7F 7E bit.a 7, (ix-128) ; DD CB 80 7E bit.a 7, (iy) ; FD CB 00 7E bit.a 7, (iy+127) ; FD CB 7F 7E bit.a 7, (iy-128) ; FD CB 80 7E bit.a 7, a ; CB 7F bit.a 7, b ; CB 78 bit.a 7, c ; CB 79 bit.a 7, d ; CB 7A bit.a 7, e ; CB 7B bit.a 7, h ; CB 7C bit.a 7, l ; CB 7D call -32768 ; CD 00 80 call 32767 ; CD FF 7F call 65535 ; CD FF FF call c, -32768 ; DC 00 80 call c, 32767 ; DC FF 7F call c, 65535 ; DC FF FF call m, -32768 ; FC 00 80 call m, 32767 ; FC FF 7F call m, 65535 ; FC FF FF call nc, -32768 ; D4 00 80 call nc, 32767 ; D4 FF 7F call nc, 65535 ; D4 FF FF call nv, -32768 ; E4 00 80 call nv, 32767 ; E4 FF 7F call nv, 65535 ; E4 FF FF call nz, -32768 ; C4 00 80 call nz, 32767 ; C4 FF 7F call nz, 65535 ; C4 FF FF call p, -32768 ; F4 00 80 call p, 32767 ; F4 FF 7F call p, 65535 ; F4 FF FF call pe, -32768 ; EC 00 80 call pe, 32767 ; EC FF 7F call pe, 65535 ; EC FF FF call po, -32768 ; E4 00 80 call po, 32767 ; E4 FF 7F call po, 65535 ; E4 FF FF call v, -32768 ; EC 00 80 call v, 32767 ; EC FF 7F call v, 65535 ; EC FF FF call z, -32768 ; CC 00 80 call z, 32767 ; CC FF 7F call z, 65535 ; CC FF FF cc -32768 ; DC 00 80 cc 32767 ; DC FF 7F cc 65535 ; DC FF FF ccf ; 3F cm -32768 ; FC 00 80 cm 32767 ; FC FF 7F cm 65535 ; FC FF FF cma ; 2F cmc ; 3F cmp (hl) ; BE cmp (ix) ; DD BE 00 cmp (ix+127) ; DD BE 7F cmp (ix-128) ; DD BE 80 cmp (iy) ; FD BE 00 cmp (iy+127) ; FD BE 7F cmp (iy-128) ; FD BE 80 cmp -128 ; FE 80 cmp 127 ; FE 7F cmp 255 ; FE FF cmp a ; BF cmp a, (hl) ; BE cmp a, (ix) ; DD BE 00 cmp a, (ix+127) ; DD BE 7F cmp a, (ix-128) ; DD BE 80 cmp a, (iy) ; FD BE 00 cmp a, (iy+127) ; FD BE 7F cmp a, (iy-128) ; FD BE 80 cmp a, -128 ; FE 80 cmp a, 127 ; FE 7F cmp a, 255 ; FE FF cmp a, a ; BF cmp a, b ; B8 cmp a, c ; B9 cmp a, d ; BA cmp a, e ; BB cmp a, h ; BC cmp a, l ; BD cmp b ; B8 cmp c ; B9 cmp d ; BA cmp e ; BB cmp h ; BC cmp l ; BD cmp m ; BE cnc -32768 ; D4 00 80 cnc 32767 ; D4 FF 7F cnc 65535 ; D4 FF FF cnv -32768 ; E4 00 80 cnv 32767 ; E4 FF 7F cnv 65535 ; E4 FF FF cnz -32768 ; C4 00 80 cnz 32767 ; C4 FF 7F cnz 65535 ; C4 FF FF cp (hl) ; BE cp (ix) ; DD BE 00 cp (ix+127) ; DD BE 7F cp (ix-128) ; DD BE 80 cp (iy) ; FD BE 00 cp (iy+127) ; FD BE 7F cp (iy-128) ; FD BE 80 cp -128 ; FE 80 cp 127 ; FE 7F cp 255 ; FE FF cp a ; BF cp a, (hl) ; BE cp a, (ix) ; DD BE 00 cp a, (ix+127) ; DD BE 7F cp a, (ix-128) ; DD BE 80 cp a, (iy) ; FD BE 00 cp a, (iy+127) ; FD BE 7F cp a, (iy-128) ; FD BE 80 cp a, -128 ; FE 80 cp a, 127 ; FE 7F cp a, 255 ; FE FF cp a, a ; BF cp a, b ; B8 cp a, c ; B9 cp a, d ; BA cp a, e ; BB cp a, h ; BC cp a, l ; BD cp b ; B8 cp c ; B9 cp d ; BA cp e ; BB cp h ; BC cp l ; BD cpd ; ED A9 cpdr ; ED B9 cpe -32768 ; EC 00 80 cpe 32767 ; EC FF 7F cpe 65535 ; EC FF FF cpi ; ED A1 cpi -128 ; FE 80 cpi 127 ; FE 7F cpi 255 ; FE FF cpir ; ED B1 cpl ; 2F cpl a ; 2F cpo -32768 ; E4 00 80 cpo 32767 ; E4 FF 7F cpo 65535 ; E4 FF FF cv -32768 ; EC 00 80 cv 32767 ; EC FF 7F cv 65535 ; EC FF FF cz -32768 ; CC 00 80 cz 32767 ; CC FF 7F cz 65535 ; CC FF FF daa ; 27 dad b ; 09 dad bc ; 09 dad d ; 19 dad de ; 19 dad h ; 29 dad hl ; 29 dad sp ; 39 dcr a ; 3D dcr b ; 05 dcr c ; 0D dcr d ; 15 dcr e ; 1D dcr h ; 25 dcr l ; 2D dcr m ; 35 dcx b ; 0B dcx bc ; 0B dcx d ; 1B dcx de ; 1B dcx h ; 2B dcx hl ; 2B dcx sp ; 3B dec (hl) ; 35 dec (ix) ; DD 35 00 dec (ix+127) ; DD 35 7F dec (ix-128) ; DD 35 80 dec (iy) ; FD 35 00 dec (iy+127) ; FD 35 7F dec (iy-128) ; FD 35 80 dec a ; 3D dec b ; 05 dec bc ; 0B dec c ; 0D dec d ; 15 dec de ; 1B dec e ; 1D dec h ; 25 dec hl ; 2B dec ix ; DD 2B dec iy ; FD 2B dec l ; 2D dec sp ; 3B di ; F3 djnz ASMPC ; 10 FE djnz b, ASMPC ; 10 FE dsub ; CD @__z80asm__sub_hl_bc ei ; FB ex (sp), hl ; E3 ex (sp), ix ; DD E3 ex (sp), iy ; FD E3 ex af, af ; 08 ex af, af' ; 08 ex de, hl ; EB exx ; D9 halt ; 76 hlt ; 76 im 0 ; ED 46 im 1 ; ED 56 im 2 ; ED 5E in (c) ; ED 70 in -128 ; DB 80 in 127 ; DB 7F in 255 ; DB FF in a, (-128) ; DB 80 in a, (127) ; DB 7F in a, (255) ; DB FF in a, (c) ; ED 78 in b, (c) ; ED 40 in c, (c) ; ED 48 in d, (c) ; ED 50 in e, (c) ; ED 58 in f, (c) ; ED 70 in h, (c) ; ED 60 in l, (c) ; ED 68 in0 (-128) ; ED 30 80 in0 (127) ; ED 30 7F in0 (255) ; ED 30 FF in0 a, (-128) ; ED 38 80 in0 a, (127) ; ED 38 7F in0 a, (255) ; ED 38 FF in0 b, (-128) ; ED 00 80 in0 b, (127) ; ED 00 7F in0 b, (255) ; ED 00 FF in0 c, (-128) ; ED 08 80 in0 c, (127) ; ED 08 7F in0 c, (255) ; ED 08 FF in0 d, (-128) ; ED 10 80 in0 d, (127) ; ED 10 7F in0 d, (255) ; ED 10 FF in0 e, (-128) ; ED 18 80 in0 e, (127) ; ED 18 7F in0 e, (255) ; ED 18 FF in0 f, (-128) ; ED 30 80 in0 f, (127) ; ED 30 7F in0 f, (255) ; ED 30 FF in0 h, (-128) ; ED 20 80 in0 h, (127) ; ED 20 7F in0 h, (255) ; ED 20 FF in0 l, (-128) ; ED 28 80 in0 l, (127) ; ED 28 7F in0 l, (255) ; ED 28 FF inc (hl) ; 34 inc (ix) ; DD 34 00 inc (ix+127) ; DD 34 7F inc (ix-128) ; DD 34 80 inc (iy) ; FD 34 00 inc (iy+127) ; FD 34 7F inc (iy-128) ; FD 34 80 inc a ; 3C inc b ; 04 inc bc ; 03 inc c ; 0C inc d ; 14 inc de ; 13 inc e ; 1C inc h ; 24 inc hl ; 23 inc ix ; DD 23 inc iy ; FD 23 inc l ; 2C inc sp ; 33 ind ; ED AA indr ; ED BA ini ; ED A2 inir ; ED B2 inr a ; 3C inr b ; 04 inr c ; 0C inr d ; 14 inr e ; 1C inr h ; 24 inr l ; 2C inr m ; 34 inx b ; 03 inx bc ; 03 inx d ; 13 inx de ; 13 inx h ; 23 inx hl ; 23 inx sp ; 33 jc -32768 ; DA 00 80 jc 32767 ; DA FF 7F jc 65535 ; DA FF FF jm -32768 ; FA 00 80 jm 32767 ; FA FF 7F jm 65535 ; FA FF FF jmp -32768 ; C3 00 80 jmp 32767 ; C3 FF 7F jmp 65535 ; C3 FF FF jnc -32768 ; D2 00 80 jnc 32767 ; D2 FF 7F jnc 65535 ; D2 FF FF jnv -32768 ; E2 00 80 jnv 32767 ; E2 FF 7F jnv 65535 ; E2 FF FF jnz -32768 ; C2 00 80 jnz 32767 ; C2 FF 7F jnz 65535 ; C2 FF FF jp (bc) ; C5 C9 jp (de) ; D5 C9 jp (hl) ; E9 jp (ix) ; DD E9 jp (iy) ; FD E9 jp -32768 ; C3 00 80 jp 32767 ; C3 FF 7F jp 65535 ; C3 FF FF jp c, -32768 ; DA 00 80 jp c, 32767 ; DA FF 7F jp c, 65535 ; DA FF FF jp m, -32768 ; FA 00 80 jp m, 32767 ; FA FF 7F jp m, 65535 ; FA FF FF jp nc, -32768 ; D2 00 80 jp nc, 32767 ; D2 FF 7F jp nc, 65535 ; D2 FF FF jp nv, -32768 ; E2 00 80 jp nv, 32767 ; E2 FF 7F jp nv, 65535 ; E2 FF FF jp nz, -32768 ; C2 00 80 jp nz, 32767 ; C2 FF 7F jp nz, 65535 ; C2 FF FF jp p, -32768 ; F2 00 80 jp p, 32767 ; F2 FF 7F jp p, 65535 ; F2 FF FF jp pe, -32768 ; EA 00 80 jp pe, 32767 ; EA FF 7F jp pe, 65535 ; EA FF FF jp po, -32768 ; E2 00 80 jp po, 32767 ; E2 FF 7F jp po, 65535 ; E2 FF FF jp v, -32768 ; EA 00 80 jp v, 32767 ; EA FF 7F jp v, 65535 ; EA FF FF jp z, -32768 ; CA 00 80 jp z, 32767 ; CA FF 7F jp z, 65535 ; CA FF FF jpe -32768 ; EA 00 80 jpe 32767 ; EA FF 7F jpe 65535 ; EA FF FF jpo -32768 ; E2 00 80 jpo 32767 ; E2 FF 7F jpo 65535 ; E2 FF FF jr ASMPC ; 18 FE jr c, ASMPC ; 38 FE jr nc, ASMPC ; 30 FE jr nz, ASMPC ; 20 FE jr z, ASMPC ; 28 FE jv -32768 ; EA 00 80 jv 32767 ; EA FF 7F jv 65535 ; EA FF FF jz -32768 ; CA 00 80 jz 32767 ; CA FF 7F jz 65535 ; CA FF FF ld (-32768), a ; 32 00 80 ld (-32768), bc ; ED 43 00 80 ld (-32768), de ; ED 53 00 80 ld (-32768), hl ; 22 00 80 ld (-32768), ix ; DD 22 00 80 ld (-32768), iy ; FD 22 00 80 ld (-32768), sp ; ED 73 00 80 ld (32767), a ; 32 FF 7F ld (32767), bc ; ED 43 FF 7F ld (32767), de ; ED 53 FF 7F ld (32767), hl ; 22 FF 7F ld (32767), ix ; DD 22 FF 7F ld (32767), iy ; FD 22 FF 7F ld (32767), sp ; ED 73 FF 7F ld (65535), a ; 32 FF FF ld (65535), bc ; ED 43 FF FF ld (65535), de ; ED 53 FF FF ld (65535), hl ; 22 FF FF ld (65535), ix ; DD 22 FF FF ld (65535), iy ; FD 22 FF FF ld (65535), sp ; ED 73 FF FF ld (bc), a ; 02 ld (bc+), a ; 02 03 ld (bc-), a ; 02 0B ld (de), a ; 12 ld (de+), a ; 12 13 ld (de-), a ; 12 1B ld (hl), -128 ; 36 80 ld (hl), 127 ; 36 7F ld (hl), 255 ; 36 FF ld (hl), a ; 77 ld (hl), b ; 70 ld (hl), c ; 71 ld (hl), d ; 72 ld (hl), e ; 73 ld (hl), h ; 74 ld (hl), l ; 75 ld (hl+), a ; 77 23 ld (hl-), a ; 77 2B ld (hld), a ; 77 2B ld (hli), a ; 77 23 ld (ix), -128 ; DD 36 00 80 ld (ix), 127 ; DD 36 00 7F ld (ix), 255 ; DD 36 00 FF ld (ix), a ; DD 77 00 ld (ix), b ; DD 70 00 ld (ix), c ; DD 71 00 ld (ix), d ; DD 72 00 ld (ix), e ; DD 73 00 ld (ix), h ; DD 74 00 ld (ix), l ; DD 75 00 ld (ix+127), -128 ; DD 36 7F 80 ld (ix+127), 127 ; DD 36 7F 7F ld (ix+127), 255 ; DD 36 7F FF ld (ix+127), a ; DD 77 7F ld (ix+127), b ; DD 70 7F ld (ix+127), c ; DD 71 7F ld (ix+127), d ; DD 72 7F ld (ix+127), e ; DD 73 7F ld (ix+127), h ; DD 74 7F ld (ix+127), l ; DD 75 7F ld (ix-128), -128 ; DD 36 80 80 ld (ix-128), 127 ; DD 36 80 7F ld (ix-128), 255 ; DD 36 80 FF ld (ix-128), a ; DD 77 80 ld (ix-128), b ; DD 70 80 ld (ix-128), c ; DD 71 80 ld (ix-128), d ; DD 72 80 ld (ix-128), e ; DD 73 80 ld (ix-128), h ; DD 74 80 ld (ix-128), l ; DD 75 80 ld (iy), -128 ; FD 36 00 80 ld (iy), 127 ; FD 36 00 7F ld (iy), 255 ; FD 36 00 FF ld (iy), a ; FD 77 00 ld (iy), b ; FD 70 00 ld (iy), c ; FD 71 00 ld (iy), d ; FD 72 00 ld (iy), e ; FD 73 00 ld (iy), h ; FD 74 00 ld (iy), l ; FD 75 00 ld (iy+127), -128 ; FD 36 7F 80 ld (iy+127), 127 ; FD 36 7F 7F ld (iy+127), 255 ; FD 36 7F FF ld (iy+127), a ; FD 77 7F ld (iy+127), b ; FD 70 7F ld (iy+127), c ; FD 71 7F ld (iy+127), d ; FD 72 7F ld (iy+127), e ; FD 73 7F ld (iy+127), h ; FD 74 7F ld (iy+127), l ; FD 75 7F ld (iy-128), -128 ; FD 36 80 80 ld (iy-128), 127 ; FD 36 80 7F ld (iy-128), 255 ; FD 36 80 FF ld (iy-128), a ; FD 77 80 ld (iy-128), b ; FD 70 80 ld (iy-128), c ; FD 71 80 ld (iy-128), d ; FD 72 80 ld (iy-128), e ; FD 73 80 ld (iy-128), h ; FD 74 80 ld (iy-128), l ; FD 75 80 ld a, (-32768) ; 3A 00 80 ld a, (32767) ; 3A FF 7F ld a, (65535) ; 3A FF FF ld a, (bc) ; 0A ld a, (bc+) ; 0A 03 ld a, (bc-) ; 0A 0B ld a, (de) ; 1A ld a, (de+) ; 1A 13 ld a, (de-) ; 1A 1B ld a, (hl) ; 7E ld a, (hl+) ; 7E 23 ld a, (hl-) ; 7E 2B ld a, (hld) ; 7E 2B ld a, (hli) ; 7E 23 ld a, (ix) ; DD 7E 00 ld a, (ix+127) ; DD 7E 7F ld a, (ix-128) ; DD 7E 80 ld a, (iy) ; FD 7E 00 ld a, (iy+127) ; FD 7E 7F ld a, (iy-128) ; FD 7E 80 ld a, -128 ; 3E 80 ld a, 127 ; 3E 7F ld a, 255 ; 3E FF ld a, a ; 7F ld a, b ; 78 ld a, c ; 79 ld a, d ; 7A ld a, e ; 7B ld a, h ; 7C ld a, i ; ED 57 ld a, l ; 7D ld a, r ; ED 5F ld b, (hl) ; 46 ld b, (ix) ; DD 46 00 ld b, (ix+127) ; DD 46 7F ld b, (ix-128) ; DD 46 80 ld b, (iy) ; FD 46 00 ld b, (iy+127) ; FD 46 7F ld b, (iy-128) ; FD 46 80 ld b, -128 ; 06 80 ld b, 127 ; 06 7F ld b, 255 ; 06 FF ld b, a ; 47 ld b, b ; 40 ld b, c ; 41 ld b, d ; 42 ld b, e ; 43 ld b, h ; 44 ld b, l ; 45 ld bc, (-32768) ; ED 4B 00 80 ld bc, (32767) ; ED 4B FF 7F ld bc, (65535) ; ED 4B FF FF ld bc, -32768 ; 01 00 80 ld bc, 32767 ; 01 FF 7F ld bc, 65535 ; 01 FF FF ld bc, de ; 42 4B ld bc, hl ; 44 4D ld c, (hl) ; 4E ld c, (ix) ; DD 4E 00 ld c, (ix+127) ; DD 4E 7F ld c, (ix-128) ; DD 4E 80 ld c, (iy) ; FD 4E 00 ld c, (iy+127) ; FD 4E 7F ld c, (iy-128) ; FD 4E 80 ld c, -128 ; 0E 80 ld c, 127 ; 0E 7F ld c, 255 ; 0E FF ld c, a ; 4F ld c, b ; 48 ld c, c ; 49 ld c, d ; 4A ld c, e ; 4B ld c, h ; 4C ld c, l ; 4D ld d, (hl) ; 56 ld d, (ix) ; DD 56 00 ld d, (ix+127) ; DD 56 7F ld d, (ix-128) ; DD 56 80 ld d, (iy) ; FD 56 00 ld d, (iy+127) ; FD 56 7F ld d, (iy-128) ; FD 56 80 ld d, -128 ; 16 80 ld d, 127 ; 16 7F ld d, 255 ; 16 FF ld d, a ; 57 ld d, b ; 50 ld d, c ; 51 ld d, d ; 52 ld d, e ; 53 ld d, h ; 54 ld d, l ; 55 ld de, (-32768) ; ED 5B 00 80 ld de, (32767) ; ED 5B FF 7F ld de, (65535) ; ED 5B FF FF ld de, -32768 ; 11 00 80 ld de, 32767 ; 11 FF 7F ld de, 65535 ; 11 FF FF ld de, bc ; 50 59 ld de, hl ; 54 5D ld de, sp ; EB 21 00 00 39 EB ld de, sp+0 ; EB 21 00 00 39 EB ld de, sp+255 ; EB 21 FF 00 39 EB ld e, (hl) ; 5E ld e, (ix) ; DD 5E 00 ld e, (ix+127) ; DD 5E 7F ld e, (ix-128) ; DD 5E 80 ld e, (iy) ; FD 5E 00 ld e, (iy+127) ; FD 5E 7F ld e, (iy-128) ; FD 5E 80 ld e, -128 ; 1E 80 ld e, 127 ; 1E 7F ld e, 255 ; 1E FF ld e, a ; 5F ld e, b ; 58 ld e, c ; 59 ld e, d ; 5A ld e, e ; 5B ld e, h ; 5C ld e, l ; 5D ld h, (hl) ; 66 ld h, (ix) ; DD 66 00 ld h, (ix+127) ; DD 66 7F ld h, (ix-128) ; DD 66 80 ld h, (iy) ; FD 66 00 ld h, (iy+127) ; FD 66 7F ld h, (iy-128) ; FD 66 80 ld h, -128 ; 26 80 ld h, 127 ; 26 7F ld h, 255 ; 26 FF ld h, a ; 67 ld h, b ; 60 ld h, c ; 61 ld h, d ; 62 ld h, e ; 63 ld h, h ; 64 ld h, l ; 65 ld hl, (-32768) ; 2A 00 80 ld hl, (32767) ; 2A FF 7F ld hl, (65535) ; 2A FF FF ld hl, -32768 ; 21 00 80 ld hl, 32767 ; 21 FF 7F ld hl, 65535 ; 21 FF FF ld hl, bc ; 60 69 ld hl, de ; 62 6B ld hl, sp ; 21 00 00 39 ld hl, sp+-128 ; 21 80 FF 39 ld hl, sp+127 ; 21 7F 00 39 ld i, a ; ED 47 ld ix, (-32768) ; DD 2A 00 80 ld ix, (32767) ; DD 2A FF 7F ld ix, (65535) ; DD 2A FF FF ld ix, -32768 ; DD 21 00 80 ld ix, 32767 ; DD 21 FF 7F ld ix, 65535 ; DD 21 FF FF ld iy, (-32768) ; FD 2A 00 80 ld iy, (32767) ; FD 2A FF 7F ld iy, (65535) ; FD 2A FF FF ld iy, -32768 ; FD 21 00 80 ld iy, 32767 ; FD 21 FF 7F ld iy, 65535 ; FD 21 FF FF ld l, (hl) ; 6E ld l, (ix) ; DD 6E 00 ld l, (ix+127) ; DD 6E 7F ld l, (ix-128) ; DD 6E 80 ld l, (iy) ; FD 6E 00 ld l, (iy+127) ; FD 6E 7F ld l, (iy-128) ; FD 6E 80 ld l, -128 ; 2E 80 ld l, 127 ; 2E 7F ld l, 255 ; 2E FF ld l, a ; 6F ld l, b ; 68 ld l, c ; 69 ld l, d ; 6A ld l, e ; 6B ld l, h ; 6C ld l, l ; 6D ld r, a ; ED 4F ld sp, (-32768) ; ED 7B 00 80 ld sp, (32767) ; ED 7B FF 7F ld sp, (65535) ; ED 7B FF FF ld sp, -32768 ; 31 00 80 ld sp, 32767 ; 31 FF 7F ld sp, 65535 ; 31 FF FF ld sp, hl ; F9 ld sp, ix ; DD F9 ld sp, iy ; FD F9 lda -32768 ; 3A 00 80 lda 32767 ; 3A FF 7F lda 65535 ; 3A FF FF ldax b ; 0A ldax bc ; 0A ldax d ; 1A ldax de ; 1A ldd ; ED A8 ldd (bc), a ; 02 0B ldd (de), a ; 12 1B ldd (hl), a ; 77 2B ldd a, (bc) ; 0A 0B ldd a, (de) ; 1A 1B ldd a, (hl) ; 7E 2B lddr ; ED B8 ldi ; ED A0 ldi (bc), a ; 02 03 ldi (de), a ; 12 13 ldi (hl), a ; 77 23 ldi a, (bc) ; 0A 03 ldi a, (de) ; 1A 13 ldi a, (hl) ; 7E 23 ldir ; ED B0 lhld -32768 ; 2A 00 80 lhld 32767 ; 2A FF 7F lhld 65535 ; 2A FF FF lxi b, -32768 ; 01 00 80 lxi b, 32767 ; 01 FF 7F lxi b, 65535 ; 01 FF FF lxi bc, -32768 ; 01 00 80 lxi bc, 32767 ; 01 FF 7F lxi bc, 65535 ; 01 FF FF lxi d, -32768 ; 11 00 80 lxi d, 32767 ; 11 FF 7F lxi d, 65535 ; 11 FF FF lxi de, -32768 ; 11 00 80 lxi de, 32767 ; 11 FF 7F lxi de, 65535 ; 11 FF FF lxi h, -32768 ; 21 00 80 lxi h, 32767 ; 21 FF 7F lxi h, 65535 ; 21 FF FF lxi hl, -32768 ; 21 00 80 lxi hl, 32767 ; 21 FF 7F lxi hl, 65535 ; 21 FF FF lxi sp, -32768 ; 31 00 80 lxi sp, 32767 ; 31 FF 7F lxi sp, 65535 ; 31 FF FF mlt bc ; ED 4C mlt de ; ED 5C mlt hl ; ED 6C mlt sp ; ED 7C mov a, a ; 7F mov a, b ; 78 mov a, c ; 79 mov a, d ; 7A mov a, e ; 7B mov a, h ; 7C mov a, l ; 7D mov a, m ; 7E mov b, a ; 47 mov b, b ; 40 mov b, c ; 41 mov b, d ; 42 mov b, e ; 43 mov b, h ; 44 mov b, l ; 45 mov b, m ; 46 mov c, a ; 4F mov c, b ; 48 mov c, c ; 49 mov c, d ; 4A mov c, e ; 4B mov c, h ; 4C mov c, l ; 4D mov c, m ; 4E mov d, a ; 57 mov d, b ; 50 mov d, c ; 51 mov d, d ; 52 mov d, e ; 53 mov d, h ; 54 mov d, l ; 55 mov d, m ; 56 mov e, a ; 5F mov e, b ; 58 mov e, c ; 59 mov e, d ; 5A mov e, e ; 5B mov e, h ; 5C mov e, l ; 5D mov e, m ; 5E mov h, a ; 67 mov h, b ; 60 mov h, c ; 61 mov h, d ; 62 mov h, e ; 63 mov h, h ; 64 mov h, l ; 65 mov h, m ; 66 mov l, a ; 6F mov l, b ; 68 mov l, c ; 69 mov l, d ; 6A mov l, e ; 6B mov l, h ; 6C mov l, l ; 6D mov l, m ; 6E mov m, a ; 77 mov m, b ; 70 mov m, c ; 71 mov m, d ; 72 mov m, e ; 73 mov m, h ; 74 mov m, l ; 75 mvi a, -128 ; 3E 80 mvi a, 127 ; 3E 7F mvi a, 255 ; 3E FF mvi b, -128 ; 06 80 mvi b, 127 ; 06 7F mvi b, 255 ; 06 FF mvi c, -128 ; 0E 80 mvi c, 127 ; 0E 7F mvi c, 255 ; 0E FF mvi d, -128 ; 16 80 mvi d, 127 ; 16 7F mvi d, 255 ; 16 FF mvi e, -128 ; 1E 80 mvi e, 127 ; 1E 7F mvi e, 255 ; 1E FF mvi h, -128 ; 26 80 mvi h, 127 ; 26 7F mvi h, 255 ; 26 FF mvi l, -128 ; 2E 80 mvi l, 127 ; 2E 7F mvi l, 255 ; 2E FF mvi m, -128 ; 36 80 mvi m, 127 ; 36 7F mvi m, 255 ; 36 FF neg ; ED 44 neg a ; ED 44 nop ; 00 or (hl) ; B6 or (ix) ; DD B6 00 or (ix+127) ; DD B6 7F or (ix-128) ; DD B6 80 or (iy) ; FD B6 00 or (iy+127) ; FD B6 7F or (iy-128) ; FD B6 80 or -128 ; F6 80 or 127 ; F6 7F or 255 ; F6 FF or a ; B7 or a, (hl) ; B6 or a, (ix) ; DD B6 00 or a, (ix+127) ; DD B6 7F or a, (ix-128) ; DD B6 80 or a, (iy) ; FD B6 00 or a, (iy+127) ; FD B6 7F or a, (iy-128) ; FD B6 80 or a, -128 ; F6 80 or a, 127 ; F6 7F or a, 255 ; F6 FF or a, a ; B7 or a, b ; B0 or a, c ; B1 or a, d ; B2 or a, e ; B3 or a, h ; B4 or a, l ; B5 or b ; B0 or c ; B1 or d ; B2 or e ; B3 or h ; B4 or l ; B5 ora a ; B7 ora b ; B0 ora c ; B1 ora d ; B2 ora e ; B3 ora h ; B4 ora l ; B5 ora m ; B6 ori -128 ; F6 80 ori 127 ; F6 7F ori 255 ; F6 FF otdm ; ED 8B otdmr ; ED 9B otdr ; ED BB otim ; ED 83 otimr ; ED 93 otir ; ED B3 out (-128), a ; D3 80 out (127), a ; D3 7F out (255), a ; D3 FF out (c), 0 ; ED 71 out (c), a ; ED 79 out (c), b ; ED 41 out (c), c ; ED 49 out (c), d ; ED 51 out (c), e ; ED 59 out (c), h ; ED 61 out (c), l ; ED 69 out -128 ; D3 80 out 127 ; D3 7F out 255 ; D3 FF out0 (-128), a ; ED 39 80 out0 (-128), b ; ED 01 80 out0 (-128), c ; ED 09 80 out0 (-128), d ; ED 11 80 out0 (-128), e ; ED 19 80 out0 (-128), h ; ED 21 80 out0 (-128), l ; ED 29 80 out0 (127), a ; ED 39 7F out0 (127), b ; ED 01 7F out0 (127), c ; ED 09 7F out0 (127), d ; ED 11 7F out0 (127), e ; ED 19 7F out0 (127), h ; ED 21 7F out0 (127), l ; ED 29 7F out0 (255), a ; ED 39 FF out0 (255), b ; ED 01 FF out0 (255), c ; ED 09 FF out0 (255), d ; ED 11 FF out0 (255), e ; ED 19 FF out0 (255), h ; ED 21 FF out0 (255), l ; ED 29 FF outd ; ED AB outi ; ED A3 pchl ; E9 pop af ; F1 pop b ; C1 pop bc ; C1 pop d ; D1 pop de ; D1 pop h ; E1 pop hl ; E1 pop ix ; DD E1 pop iy ; FD E1 pop psw ; F1 push af ; F5 push b ; C5 push bc ; C5 push d ; D5 push de ; D5 push h ; E5 push hl ; E5 push ix ; DD E5 push iy ; FD E5 push psw ; F5 ral ; 17 rar ; 1F rc ; D8 rdel ; CB 13 CB 12 res 0, (hl) ; CB 86 res 0, (ix) ; DD CB 00 86 res 0, (ix+127) ; DD CB 7F 86 res 0, (ix-128) ; DD CB 80 86 res 0, (iy) ; FD CB 00 86 res 0, (iy+127) ; FD CB 7F 86 res 0, (iy-128) ; FD CB 80 86 res 0, a ; CB 87 res 0, b ; CB 80 res 0, c ; CB 81 res 0, d ; CB 82 res 0, e ; CB 83 res 0, h ; CB 84 res 0, l ; CB 85 res 1, (hl) ; CB 8E res 1, (ix) ; DD CB 00 8E res 1, (ix+127) ; DD CB 7F 8E res 1, (ix-128) ; DD CB 80 8E res 1, (iy) ; FD CB 00 8E res 1, (iy+127) ; FD CB 7F 8E res 1, (iy-128) ; FD CB 80 8E res 1, a ; CB 8F res 1, b ; CB 88 res 1, c ; CB 89 res 1, d ; CB 8A res 1, e ; CB 8B res 1, h ; CB 8C res 1, l ; CB 8D res 2, (hl) ; CB 96 res 2, (ix) ; DD CB 00 96 res 2, (ix+127) ; DD CB 7F 96 res 2, (ix-128) ; DD CB 80 96 res 2, (iy) ; FD CB 00 96 res 2, (iy+127) ; FD CB 7F 96 res 2, (iy-128) ; FD CB 80 96 res 2, a ; CB 97 res 2, b ; CB 90 res 2, c ; CB 91 res 2, d ; CB 92 res 2, e ; CB 93 res 2, h ; CB 94 res 2, l ; CB 95 res 3, (hl) ; CB 9E res 3, (ix) ; DD CB 00 9E res 3, (ix+127) ; DD CB 7F 9E res 3, (ix-128) ; DD CB 80 9E res 3, (iy) ; FD CB 00 9E res 3, (iy+127) ; FD CB 7F 9E res 3, (iy-128) ; FD CB 80 9E res 3, a ; CB 9F res 3, b ; CB 98 res 3, c ; CB 99 res 3, d ; CB 9A res 3, e ; CB 9B res 3, h ; CB 9C res 3, l ; CB 9D res 4, (hl) ; CB A6 res 4, (ix) ; DD CB 00 A6 res 4, (ix+127) ; DD CB 7F A6 res 4, (ix-128) ; DD CB 80 A6 res 4, (iy) ; FD CB 00 A6 res 4, (iy+127) ; FD CB 7F A6 res 4, (iy-128) ; FD CB 80 A6 res 4, a ; CB A7 res 4, b ; CB A0 res 4, c ; CB A1 res 4, d ; CB A2 res 4, e ; CB A3 res 4, h ; CB A4 res 4, l ; CB A5 res 5, (hl) ; CB AE res 5, (ix) ; DD CB 00 AE res 5, (ix+127) ; DD CB 7F AE res 5, (ix-128) ; DD CB 80 AE res 5, (iy) ; FD CB 00 AE res 5, (iy+127) ; FD CB 7F AE res 5, (iy-128) ; FD CB 80 AE res 5, a ; CB AF res 5, b ; CB A8 res 5, c ; CB A9 res 5, d ; CB AA res 5, e ; CB AB res 5, h ; CB AC res 5, l ; CB AD res 6, (hl) ; CB B6 res 6, (ix) ; DD CB 00 B6 res 6, (ix+127) ; DD CB 7F B6 res 6, (ix-128) ; DD CB 80 B6 res 6, (iy) ; FD CB 00 B6 res 6, (iy+127) ; FD CB 7F B6 res 6, (iy-128) ; FD CB 80 B6 res 6, a ; CB B7 res 6, b ; CB B0 res 6, c ; CB B1 res 6, d ; CB B2 res 6, e ; CB B3 res 6, h ; CB B4 res 6, l ; CB B5 res 7, (hl) ; CB BE res 7, (ix) ; DD CB 00 BE res 7, (ix+127) ; DD CB 7F BE res 7, (ix-128) ; DD CB 80 BE res 7, (iy) ; FD CB 00 BE res 7, (iy+127) ; FD CB 7F BE res 7, (iy-128) ; FD CB 80 BE res 7, a ; CB BF res 7, b ; CB B8 res 7, c ; CB B9 res 7, d ; CB BA res 7, e ; CB BB res 7, h ; CB BC res 7, l ; CB BD res.a 0, (hl) ; CB 86 res.a 0, (ix) ; DD CB 00 86 res.a 0, (ix+127) ; DD CB 7F 86 res.a 0, (ix-128) ; DD CB 80 86 res.a 0, (iy) ; FD CB 00 86 res.a 0, (iy+127) ; FD CB 7F 86 res.a 0, (iy-128) ; FD CB 80 86 res.a 0, a ; CB 87 res.a 0, b ; CB 80 res.a 0, c ; CB 81 res.a 0, d ; CB 82 res.a 0, e ; CB 83 res.a 0, h ; CB 84 res.a 0, l ; CB 85 res.a 1, (hl) ; CB 8E res.a 1, (ix) ; DD CB 00 8E res.a 1, (ix+127) ; DD CB 7F 8E res.a 1, (ix-128) ; DD CB 80 8E res.a 1, (iy) ; FD CB 00 8E res.a 1, (iy+127) ; FD CB 7F 8E res.a 1, (iy-128) ; FD CB 80 8E res.a 1, a ; CB 8F res.a 1, b ; CB 88 res.a 1, c ; CB 89 res.a 1, d ; CB 8A res.a 1, e ; CB 8B res.a 1, h ; CB 8C res.a 1, l ; CB 8D res.a 2, (hl) ; CB 96 res.a 2, (ix) ; DD CB 00 96 res.a 2, (ix+127) ; DD CB 7F 96 res.a 2, (ix-128) ; DD CB 80 96 res.a 2, (iy) ; FD CB 00 96 res.a 2, (iy+127) ; FD CB 7F 96 res.a 2, (iy-128) ; FD CB 80 96 res.a 2, a ; CB 97 res.a 2, b ; CB 90 res.a 2, c ; CB 91 res.a 2, d ; CB 92 res.a 2, e ; CB 93 res.a 2, h ; CB 94 res.a 2, l ; CB 95 res.a 3, (hl) ; CB 9E res.a 3, (ix) ; DD CB 00 9E res.a 3, (ix+127) ; DD CB 7F 9E res.a 3, (ix-128) ; DD CB 80 9E res.a 3, (iy) ; FD CB 00 9E res.a 3, (iy+127) ; FD CB 7F 9E res.a 3, (iy-128) ; FD CB 80 9E res.a 3, a ; CB 9F res.a 3, b ; CB 98 res.a 3, c ; CB 99 res.a 3, d ; CB 9A res.a 3, e ; CB 9B res.a 3, h ; CB 9C res.a 3, l ; CB 9D res.a 4, (hl) ; CB A6 res.a 4, (ix) ; DD CB 00 A6 res.a 4, (ix+127) ; DD CB 7F A6 res.a 4, (ix-128) ; DD CB 80 A6 res.a 4, (iy) ; FD CB 00 A6 res.a 4, (iy+127) ; FD CB 7F A6 res.a 4, (iy-128) ; FD CB 80 A6 res.a 4, a ; CB A7 res.a 4, b ; CB A0 res.a 4, c ; CB A1 res.a 4, d ; CB A2 res.a 4, e ; CB A3 res.a 4, h ; CB A4 res.a 4, l ; CB A5 res.a 5, (hl) ; CB AE res.a 5, (ix) ; DD CB 00 AE res.a 5, (ix+127) ; DD CB 7F AE res.a 5, (ix-128) ; DD CB 80 AE res.a 5, (iy) ; FD CB 00 AE res.a 5, (iy+127) ; FD CB 7F AE res.a 5, (iy-128) ; FD CB 80 AE res.a 5, a ; CB AF res.a 5, b ; CB A8 res.a 5, c ; CB A9 res.a 5, d ; CB AA res.a 5, e ; CB AB res.a 5, h ; CB AC res.a 5, l ; CB AD res.a 6, (hl) ; CB B6 res.a 6, (ix) ; DD CB 00 B6 res.a 6, (ix+127) ; DD CB 7F B6 res.a 6, (ix-128) ; DD CB 80 B6 res.a 6, (iy) ; FD CB 00 B6 res.a 6, (iy+127) ; FD CB 7F B6 res.a 6, (iy-128) ; FD CB 80 B6 res.a 6, a ; CB B7 res.a 6, b ; CB B0 res.a 6, c ; CB B1 res.a 6, d ; CB B2 res.a 6, e ; CB B3 res.a 6, h ; CB B4 res.a 6, l ; CB B5 res.a 7, (hl) ; CB BE res.a 7, (ix) ; DD CB 00 BE res.a 7, (ix+127) ; DD CB 7F BE res.a 7, (ix-128) ; DD CB 80 BE res.a 7, (iy) ; FD CB 00 BE res.a 7, (iy+127) ; FD CB 7F BE res.a 7, (iy-128) ; FD CB 80 BE res.a 7, a ; CB BF res.a 7, b ; CB B8 res.a 7, c ; CB B9 res.a 7, d ; CB BA res.a 7, e ; CB BB res.a 7, h ; CB BC res.a 7, l ; CB BD ret ; C9 ret c ; D8 ret m ; F8 ret nc ; D0 ret nv ; E0 ret nz ; C0 ret p ; F0 ret pe ; E8 ret po ; E0 ret v ; E8 ret z ; C8 reti ; ED 4D retn ; ED 45 rl (hl) ; CB 16 rl (ix) ; DD CB 00 16 rl (ix+127) ; DD CB 7F 16 rl (ix-128) ; DD CB 80 16 rl (iy) ; FD CB 00 16 rl (iy+127) ; FD CB 7F 16 rl (iy-128) ; FD CB 80 16 rl a ; CB 17 rl b ; CB 10 rl bc ; CB 11 CB 10 rl c ; CB 11 rl d ; CB 12 rl de ; CB 13 CB 12 rl e ; CB 13 rl h ; CB 14 rl hl ; CB 15 CB 14 rl l ; CB 15 rla ; 17 rlc ; 07 rlc (hl) ; CB 06 rlc (ix) ; DD CB 00 06 rlc (ix+127) ; DD CB 7F 06 rlc (ix-128) ; DD CB 80 06 rlc (iy) ; FD CB 00 06 rlc (iy+127) ; FD CB 7F 06 rlc (iy-128) ; FD CB 80 06 rlc a ; CB 07 rlc b ; CB 00 rlc c ; CB 01 rlc d ; CB 02 rlc e ; CB 03 rlc h ; CB 04 rlc l ; CB 05 rlca ; 07 rld ; ED 6F rlde ; CB 13 CB 12 rm ; F8 rnc ; D0 rnv ; E0 rnz ; C0 rp ; F0 rpe ; E8 rpo ; E0 rr (hl) ; CB 1E rr (ix) ; DD CB 00 1E rr (ix+127) ; DD CB 7F 1E rr (ix-128) ; DD CB 80 1E rr (iy) ; FD CB 00 1E rr (iy+127) ; FD CB 7F 1E rr (iy-128) ; FD CB 80 1E rr a ; CB 1F rr b ; CB 18 rr bc ; CB 18 CB 19 rr c ; CB 19 rr d ; CB 1A rr de ; CB 1A CB 1B rr e ; CB 1B rr h ; CB 1C rr hl ; CB 1C CB 1D rr l ; CB 1D rra ; 1F rrc ; 0F rrc (hl) ; CB 0E rrc (ix) ; DD CB 00 0E rrc (ix+127) ; DD CB 7F 0E rrc (ix-128) ; DD CB 80 0E rrc (iy) ; FD CB 00 0E rrc (iy+127) ; FD CB 7F 0E rrc (iy-128) ; FD CB 80 0E rrc a ; CB 0F rrc b ; CB 08 rrc c ; CB 09 rrc d ; CB 0A rrc e ; CB 0B rrc h ; CB 0C rrc l ; CB 0D rrca ; 0F rrd ; ED 67 rrhl ; CB 2C CB 1D rst 0 ; C7 rst 1 ; CF rst 16 ; D7 rst 2 ; D7 rst 24 ; DF rst 3 ; DF rst 32 ; E7 rst 4 ; E7 rst 40 ; EF rst 48 ; F7 rst 5 ; EF rst 56 ; FF rst 6 ; F7 rst 7 ; FF rst 8 ; CF rv ; E8 rz ; C8 sbb a ; 9F sbb b ; 98 sbb c ; 99 sbb d ; 9A sbb e ; 9B sbb h ; 9C sbb l ; 9D sbb m ; 9E sbc (hl) ; 9E sbc (ix) ; DD 9E 00 sbc (ix+127) ; DD 9E 7F sbc (ix-128) ; DD 9E 80 sbc (iy) ; FD 9E 00 sbc (iy+127) ; FD 9E 7F sbc (iy-128) ; FD 9E 80 sbc -128 ; DE 80 sbc 127 ; DE 7F sbc 255 ; DE FF sbc a ; 9F sbc a, (hl) ; 9E sbc a, (ix) ; DD 9E 00 sbc a, (ix+127) ; DD 9E 7F sbc a, (ix-128) ; DD 9E 80 sbc a, (iy) ; FD 9E 00 sbc a, (iy+127) ; FD 9E 7F sbc a, (iy-128) ; FD 9E 80 sbc a, -128 ; DE 80 sbc a, 127 ; DE 7F sbc a, 255 ; DE FF sbc a, a ; 9F sbc a, b ; 98 sbc a, c ; 99 sbc a, d ; 9A sbc a, e ; 9B sbc a, h ; 9C sbc a, l ; 9D sbc b ; 98 sbc c ; 99 sbc d ; 9A sbc e ; 9B sbc h ; 9C sbc hl, bc ; ED 42 sbc hl, de ; ED 52 sbc hl, hl ; ED 62 sbc hl, sp ; ED 72 sbc l ; 9D sbi -128 ; DE 80 sbi 127 ; DE 7F sbi 255 ; DE FF scf ; 37 set 0, (hl) ; CB C6 set 0, (ix) ; DD CB 00 C6 set 0, (ix+127) ; DD CB 7F C6 set 0, (ix-128) ; DD CB 80 C6 set 0, (iy) ; FD CB 00 C6 set 0, (iy+127) ; FD CB 7F C6 set 0, (iy-128) ; FD CB 80 C6 set 0, a ; CB C7 set 0, b ; CB C0 set 0, c ; CB C1 set 0, d ; CB C2 set 0, e ; CB C3 set 0, h ; CB C4 set 0, l ; CB C5 set 1, (hl) ; CB CE set 1, (ix) ; DD CB 00 CE set 1, (ix+127) ; DD CB 7F CE set 1, (ix-128) ; DD CB 80 CE set 1, (iy) ; FD CB 00 CE set 1, (iy+127) ; FD CB 7F CE set 1, (iy-128) ; FD CB 80 CE set 1, a ; CB CF set 1, b ; CB C8 set 1, c ; CB C9 set 1, d ; CB CA set 1, e ; CB CB set 1, h ; CB CC set 1, l ; CB CD set 2, (hl) ; CB D6 set 2, (ix) ; DD CB 00 D6 set 2, (ix+127) ; DD CB 7F D6 set 2, (ix-128) ; DD CB 80 D6 set 2, (iy) ; FD CB 00 D6 set 2, (iy+127) ; FD CB 7F D6 set 2, (iy-128) ; FD CB 80 D6 set 2, a ; CB D7 set 2, b ; CB D0 set 2, c ; CB D1 set 2, d ; CB D2 set 2, e ; CB D3 set 2, h ; CB D4 set 2, l ; CB D5 set 3, (hl) ; CB DE set 3, (ix) ; DD CB 00 DE set 3, (ix+127) ; DD CB 7F DE set 3, (ix-128) ; DD CB 80 DE set 3, (iy) ; FD CB 00 DE set 3, (iy+127) ; FD CB 7F DE set 3, (iy-128) ; FD CB 80 DE set 3, a ; CB DF set 3, b ; CB D8 set 3, c ; CB D9 set 3, d ; CB DA set 3, e ; CB DB set 3, h ; CB DC set 3, l ; CB DD set 4, (hl) ; CB E6 set 4, (ix) ; DD CB 00 E6 set 4, (ix+127) ; DD CB 7F E6 set 4, (ix-128) ; DD CB 80 E6 set 4, (iy) ; FD CB 00 E6 set 4, (iy+127) ; FD CB 7F E6 set 4, (iy-128) ; FD CB 80 E6 set 4, a ; CB E7 set 4, b ; CB E0 set 4, c ; CB E1 set 4, d ; CB E2 set 4, e ; CB E3 set 4, h ; CB E4 set 4, l ; CB E5 set 5, (hl) ; CB EE set 5, (ix) ; DD CB 00 EE set 5, (ix+127) ; DD CB 7F EE set 5, (ix-128) ; DD CB 80 EE set 5, (iy) ; FD CB 00 EE set 5, (iy+127) ; FD CB 7F EE set 5, (iy-128) ; FD CB 80 EE set 5, a ; CB EF set 5, b ; CB E8 set 5, c ; CB E9 set 5, d ; CB EA set 5, e ; CB EB set 5, h ; CB EC set 5, l ; CB ED set 6, (hl) ; CB F6 set 6, (ix) ; DD CB 00 F6 set 6, (ix+127) ; DD CB 7F F6 set 6, (ix-128) ; DD CB 80 F6 set 6, (iy) ; FD CB 00 F6 set 6, (iy+127) ; FD CB 7F F6 set 6, (iy-128) ; FD CB 80 F6 set 6, a ; CB F7 set 6, b ; CB F0 set 6, c ; CB F1 set 6, d ; CB F2 set 6, e ; CB F3 set 6, h ; CB F4 set 6, l ; CB F5 set 7, (hl) ; CB FE set 7, (ix) ; DD CB 00 FE set 7, (ix+127) ; DD CB 7F FE set 7, (ix-128) ; DD CB 80 FE set 7, (iy) ; FD CB 00 FE set 7, (iy+127) ; FD CB 7F FE set 7, (iy-128) ; FD CB 80 FE set 7, a ; CB FF set 7, b ; CB F8 set 7, c ; CB F9 set 7, d ; CB FA set 7, e ; CB FB set 7, h ; CB FC set 7, l ; CB FD set.a 0, (hl) ; CB C6 set.a 0, (ix) ; DD CB 00 C6 set.a 0, (ix+127) ; DD CB 7F C6 set.a 0, (ix-128) ; DD CB 80 C6 set.a 0, (iy) ; FD CB 00 C6 set.a 0, (iy+127) ; FD CB 7F C6 set.a 0, (iy-128) ; FD CB 80 C6 set.a 0, a ; CB C7 set.a 0, b ; CB C0 set.a 0, c ; CB C1 set.a 0, d ; CB C2 set.a 0, e ; CB C3 set.a 0, h ; CB C4 set.a 0, l ; CB C5 set.a 1, (hl) ; CB CE set.a 1, (ix) ; DD CB 00 CE set.a 1, (ix+127) ; DD CB 7F CE set.a 1, (ix-128) ; DD CB 80 CE set.a 1, (iy) ; FD CB 00 CE set.a 1, (iy+127) ; FD CB 7F CE set.a 1, (iy-128) ; FD CB 80 CE set.a 1, a ; CB CF set.a 1, b ; CB C8 set.a 1, c ; CB C9 set.a 1, d ; CB CA set.a 1, e ; CB CB set.a 1, h ; CB CC set.a 1, l ; CB CD set.a 2, (hl) ; CB D6 set.a 2, (ix) ; DD CB 00 D6 set.a 2, (ix+127) ; DD CB 7F D6 set.a 2, (ix-128) ; DD CB 80 D6 set.a 2, (iy) ; FD CB 00 D6 set.a 2, (iy+127) ; FD CB 7F D6 set.a 2, (iy-128) ; FD CB 80 D6 set.a 2, a ; CB D7 set.a 2, b ; CB D0 set.a 2, c ; CB D1 set.a 2, d ; CB D2 set.a 2, e ; CB D3 set.a 2, h ; CB D4 set.a 2, l ; CB D5 set.a 3, (hl) ; CB DE set.a 3, (ix) ; DD CB 00 DE set.a 3, (ix+127) ; DD CB 7F DE set.a 3, (ix-128) ; DD CB 80 DE set.a 3, (iy) ; FD CB 00 DE set.a 3, (iy+127) ; FD CB 7F DE set.a 3, (iy-128) ; FD CB 80 DE set.a 3, a ; CB DF set.a 3, b ; CB D8 set.a 3, c ; CB D9 set.a 3, d ; CB DA set.a 3, e ; CB DB set.a 3, h ; CB DC set.a 3, l ; CB DD set.a 4, (hl) ; CB E6 set.a 4, (ix) ; DD CB 00 E6 set.a 4, (ix+127) ; DD CB 7F E6 set.a 4, (ix-128) ; DD CB 80 E6 set.a 4, (iy) ; FD CB 00 E6 set.a 4, (iy+127) ; FD CB 7F E6 set.a 4, (iy-128) ; FD CB 80 E6 set.a 4, a ; CB E7 set.a 4, b ; CB E0 set.a 4, c ; CB E1 set.a 4, d ; CB E2 set.a 4, e ; CB E3 set.a 4, h ; CB E4 set.a 4, l ; CB E5 set.a 5, (hl) ; CB EE set.a 5, (ix) ; DD CB 00 EE set.a 5, (ix+127) ; DD CB 7F EE set.a 5, (ix-128) ; DD CB 80 EE set.a 5, (iy) ; FD CB 00 EE set.a 5, (iy+127) ; FD CB 7F EE set.a 5, (iy-128) ; FD CB 80 EE set.a 5, a ; CB EF set.a 5, b ; CB E8 set.a 5, c ; CB E9 set.a 5, d ; CB EA set.a 5, e ; CB EB set.a 5, h ; CB EC set.a 5, l ; CB ED set.a 6, (hl) ; CB F6 set.a 6, (ix) ; DD CB 00 F6 set.a 6, (ix+127) ; DD CB 7F F6 set.a 6, (ix-128) ; DD CB 80 F6 set.a 6, (iy) ; FD CB 00 F6 set.a 6, (iy+127) ; FD CB 7F F6 set.a 6, (iy-128) ; FD CB 80 F6 set.a 6, a ; CB F7 set.a 6, b ; CB F0 set.a 6, c ; CB F1 set.a 6, d ; CB F2 set.a 6, e ; CB F3 set.a 6, h ; CB F4 set.a 6, l ; CB F5 set.a 7, (hl) ; CB FE set.a 7, (ix) ; DD CB 00 FE set.a 7, (ix+127) ; DD CB 7F FE set.a 7, (ix-128) ; DD CB 80 FE set.a 7, (iy) ; FD CB 00 FE set.a 7, (iy+127) ; FD CB 7F FE set.a 7, (iy-128) ; FD CB 80 FE set.a 7, a ; CB FF set.a 7, b ; CB F8 set.a 7, c ; CB F9 set.a 7, d ; CB FA set.a 7, e ; CB FB set.a 7, h ; CB FC set.a 7, l ; CB FD shld -32768 ; 22 00 80 shld 32767 ; 22 FF 7F shld 65535 ; 22 FF FF sla (hl) ; CB 26 sla (ix) ; DD CB 00 26 sla (ix+127) ; DD CB 7F 26 sla (ix-128) ; DD CB 80 26 sla (iy) ; FD CB 00 26 sla (iy+127) ; FD CB 7F 26 sla (iy-128) ; FD CB 80 26 sla a ; CB 27 sla b ; CB 20 sla c ; CB 21 sla d ; CB 22 sla e ; CB 23 sla h ; CB 24 sla l ; CB 25 sli (hl) ; CB 36 sli (ix) ; DD CB 00 36 sli (ix+127) ; DD CB 7F 36 sli (ix-128) ; DD CB 80 36 sli (iy) ; FD CB 00 36 sli (iy+127) ; FD CB 7F 36 sli (iy-128) ; FD CB 80 36 sli a ; CB 37 sli b ; CB 30 sli c ; CB 31 sli d ; CB 32 sli e ; CB 33 sli h ; CB 34 sli l ; CB 35 sll (hl) ; CB 36 sll (ix) ; DD CB 00 36 sll (ix+127) ; DD CB 7F 36 sll (ix-128) ; DD CB 80 36 sll (iy) ; FD CB 00 36 sll (iy+127) ; FD CB 7F 36 sll (iy-128) ; FD CB 80 36 sll a ; CB 37 sll b ; CB 30 sll c ; CB 31 sll d ; CB 32 sll e ; CB 33 sll h ; CB 34 sll l ; CB 35 slp ; ED 76 sphl ; F9 sra (hl) ; CB 2E sra (ix) ; DD CB 00 2E sra (ix+127) ; DD CB 7F 2E sra (ix-128) ; DD CB 80 2E sra (iy) ; FD CB 00 2E sra (iy+127) ; FD CB 7F 2E sra (iy-128) ; FD CB 80 2E sra a ; CB 2F sra b ; CB 28 sra bc ; CB 28 CB 19 sra c ; CB 29 sra d ; CB 2A sra de ; CB 2A CB 1B sra e ; CB 2B sra h ; CB 2C sra hl ; CB 2C CB 1D sra l ; CB 2D srl (hl) ; CB 3E srl (ix) ; DD CB 00 3E srl (ix+127) ; DD CB 7F 3E srl (ix-128) ; DD CB 80 3E srl (iy) ; FD CB 00 3E srl (iy+127) ; FD CB 7F 3E srl (iy-128) ; FD CB 80 3E srl a ; CB 3F srl b ; CB 38 srl c ; CB 39 srl d ; CB 3A srl e ; CB 3B srl h ; CB 3C srl l ; CB 3D sta -32768 ; 32 00 80 sta 32767 ; 32 FF 7F sta 65535 ; 32 FF FF stax b ; 02 stax bc ; 02 stax d ; 12 stax de ; 12 stc ; 37 sub (hl) ; 96 sub (ix) ; DD 96 00 sub (ix+127) ; DD 96 7F sub (ix-128) ; DD 96 80 sub (iy) ; FD 96 00 sub (iy+127) ; FD 96 7F sub (iy-128) ; FD 96 80 sub -128 ; D6 80 sub 127 ; D6 7F sub 255 ; D6 FF sub a ; 97 sub a, (hl) ; 96 sub a, (ix) ; DD 96 00 sub a, (ix+127) ; DD 96 7F sub a, (ix-128) ; DD 96 80 sub a, (iy) ; FD 96 00 sub a, (iy+127) ; FD 96 7F sub a, (iy-128) ; FD 96 80 sub a, -128 ; D6 80 sub a, 127 ; D6 7F sub a, 255 ; D6 FF sub a, a ; 97 sub a, b ; 90 sub a, c ; 91 sub a, d ; 92 sub a, e ; 93 sub a, h ; 94 sub a, l ; 95 sub b ; 90 sub c ; 91 sub d ; 92 sub e ; 93 sub h ; 94 sub hl, bc ; CD @__z80asm__sub_hl_bc sub hl, de ; CD @__z80asm__sub_hl_de sub hl, hl ; CD @__z80asm__sub_hl_hl sub hl, sp ; CD @__z80asm__sub_hl_sp sub l ; 95 sub m ; 96 sui -128 ; D6 80 sui 127 ; D6 7F sui 255 ; D6 FF test (hl) ; ED 34 test (ix) ; DD ED 00 34 test (ix+127) ; DD ED 7F 34 test (ix-128) ; DD ED 80 34 test (iy) ; FD ED 00 34 test (iy+127) ; FD ED 7F 34 test (iy-128) ; FD ED 80 34 test -128 ; ED 64 80 test 127 ; ED 64 7F test 255 ; ED 64 FF test a ; ED 3C test a, (hl) ; ED 34 test a, (ix) ; DD ED 00 34 test a, (ix+127) ; DD ED 7F 34 test a, (ix-128) ; DD ED 80 34 test a, (iy) ; FD ED 00 34 test a, (iy+127) ; FD ED 7F 34 test a, (iy-128) ; FD ED 80 34 test a, -128 ; ED 64 80 test a, 127 ; ED 64 7F test a, 255 ; ED 64 FF test a, a ; ED 3C test a, b ; ED 04 test a, c ; ED 0C test a, d ; ED 14 test a, e ; ED 1C test a, h ; ED 24 test a, l ; ED 2C test b ; ED 04 test c ; ED 0C test d ; ED 14 test e ; ED 1C test h ; ED 24 test l ; ED 2C tst (hl) ; ED 34 tst (ix) ; DD ED 00 34 tst (ix+127) ; DD ED 7F 34 tst (ix-128) ; DD ED 80 34 tst (iy) ; FD ED 00 34 tst (iy+127) ; FD ED 7F 34 tst (iy-128) ; FD ED 80 34 tst -128 ; ED 64 80 tst 127 ; ED 64 7F tst 255 ; ED 64 FF tst a ; ED 3C tst a, (hl) ; ED 34 tst a, (ix) ; DD ED 00 34 tst a, (ix+127) ; DD ED 7F 34 tst a, (ix-128) ; DD ED 80 34 tst a, (iy) ; FD ED 00 34 tst a, (iy+127) ; FD ED 7F 34 tst a, (iy-128) ; FD ED 80 34 tst a, -128 ; ED 64 80 tst a, 127 ; ED 64 7F tst a, 255 ; ED 64 FF tst a, a ; ED 3C tst a, b ; ED 04 tst a, c ; ED 0C tst a, d ; ED 14 tst a, e ; ED 1C tst a, h ; ED 24 tst a, l ; ED 2C tst b ; ED 04 tst c ; ED 0C tst d ; ED 14 tst e ; ED 1C tst h ; ED 24 tst l ; ED 2C tstio -128 ; ED 74 80 tstio 127 ; ED 74 7F tstio 255 ; ED 74 FF xchg ; EB xor (hl) ; AE xor (ix) ; DD AE 00 xor (ix+127) ; DD AE 7F xor (ix-128) ; DD AE 80 xor (iy) ; FD AE 00 xor (iy+127) ; FD AE 7F xor (iy-128) ; FD AE 80 xor -128 ; EE 80 xor 127 ; EE 7F xor 255 ; EE FF xor a ; AF xor a, (hl) ; AE xor a, (ix) ; DD AE 00 xor a, (ix+127) ; DD AE 7F xor a, (ix-128) ; DD AE 80 xor a, (iy) ; FD AE 00 xor a, (iy+127) ; FD AE 7F xor a, (iy-128) ; FD AE 80 xor a, -128 ; EE 80 xor a, 127 ; EE 7F xor a, 255 ; EE FF xor a, a ; AF xor a, b ; A8 xor a, c ; A9 xor a, d ; AA xor a, e ; AB xor a, h ; AC xor a, l ; AD xor b ; A8 xor c ; A9 xor d ; AA xor e ; AB xor h ; AC xor l ; AD xra a ; AF xra b ; A8 xra c ; A9 xra d ; AA xra e ; AB xra h ; AC xra l ; AD xra m ; AE xri -128 ; EE 80 xri 127 ; EE 7F xri 255 ; EE FF xthl ; E3
dnl x86 mpn_divrem_2 -- Divide an mpn number by a normalized 2-limb number. dnl Copyright 2007, 2008 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 norm frac C 486 C P5 C P6-13 29.2 C P6-15 *26 C K6 C K7 22 C K8 *19 C P4-f1 C P4-f2 *65 C P4-f3 C P4-f4 *72 C A star means numbers not updated for the latest version of the code. C TODO C * Perhaps keep ecx or esi in stack slot, freeing up a reg for q0. C * The loop has not been carefully tuned. We should at the very least do C some local insn swapping. C * The code outside the main loop is what gcc generated. Clean up! C * Clean up stack slot usage. C INPUT PARAMETERS C qp C fn C up_param C un_param C dp C eax ebx ecx edx esi edi ebp C cnt qp ASM_START() TEXT ALIGN(16) PROLOGUE(mpn_divrem_2) push %ebp push %edi push %esi push %ebx sub $36, %esp mov 68(%esp), %ecx C un mov 72(%esp), %esi C dp movl $0, 32(%esp) lea 0(,%ecx,4), %edi add 64(%esp), %edi C up mov (%esi), %ebx mov 4(%esi), %eax mov %ebx, 20(%esp) sub $12, %edi mov %eax, 24(%esp) mov %edi, 12(%esp) mov 8(%edi), %ebx mov 4(%edi), %ebp cmp %eax, %ebx jb L(8) seta %dl cmp 20(%esp), %ebp setae %al orb %dl, %al C "orb" form to placate Sun tools jne L(35) L(8): mov 60(%esp), %esi C fn lea -3(%esi,%ecx), %edi test %edi, %edi js L(9) mov 24(%esp), %edx mov $-1, %esi mov %esi, %eax mov %esi, %ecx not %edx divl 24(%esp) mov %eax, %esi imul 24(%esp), %eax mov %eax, (%esp) mov %esi, %eax mull 20(%esp) mov (%esp), %eax add 20(%esp), %eax adc $0, %ecx add %eax, %edx adc $0, %ecx mov %ecx, %eax js L(32) L(36): dec %esi sub 24(%esp), %edx sbb $0, %eax jns L(36) L(32): mov %esi, 16(%esp) C di mov %edi, %ecx C un mov 12(%esp), %esi C up mov 24(%esp), %eax neg %eax mov %eax, 4(%esp) C -d1 ALIGN(16) nop C eax ebx ecx edx esi edi ebp 0 4 8 12 16 20 24 28 32 56 60 C n2 un up n1 q0 -d1 di d0 d1 msl qp fn L(loop): mov 16(%esp), %eax C di mul %ebx add %ebp, %eax mov %eax, (%esp) C q0 adc %ebx, %edx mov %edx, %edi C q imul 4(%esp), %edx mov 20(%esp), %eax lea (%edx, %ebp), %ebx C n1 -= ... mul %edi xor %ebp, %ebp cmp 60(%esp), %ecx jl L(19) mov (%esi), %ebp sub $4, %esi L(19): sub 20(%esp), %ebp sbb 24(%esp), %ebx sub %eax, %ebp sbb %edx, %ebx mov 20(%esp), %eax C d1 inc %edi xor %edx, %edx cmp (%esp), %ebx adc $-1, %edx C mask add %edx, %edi C q-- and %edx, %eax C d0 or 0 and 24(%esp), %edx C d1 or 0 add %eax, %ebp adc %edx, %ebx cmp 24(%esp), %ebx jae L(fix) L(bck): mov 56(%esp), %edx mov %edi, (%edx, %ecx, 4) dec %ecx jns L(loop) L(9): mov 64(%esp), %esi C up mov %ebp, (%esi) mov %ebx, 4(%esi) mov 32(%esp), %eax add $36, %esp pop %ebx pop %esi pop %edi pop %ebp ret L(fix): seta %dl cmp 20(%esp), %ebp setae %al orb %dl, %al C "orb" form to placate Sun tools je L(bck) inc %edi sub 20(%esp), %ebp sbb 24(%esp), %ebx jmp L(bck) L(35): sub 20(%esp), %ebp sbb 24(%esp), %ebx movl $1, 32(%esp) jmp L(8) EPILOGUE()
%library("libm.dylib", "math") %library("libc.dylib", "libc") %import("samples/imported.asm", "imported") # this changes the default code size just before we start the next function # we can call it at any time before a function to change its code size %code_size(200) # these are part of this module, you can also have them in a function MY_NAME = "Zed A. Shaw" MY_AGE = 1200 MY_INITIAL = 'A' function puts_sample() : int # this one is part of a function another_name = "Joe Blow" # prints a simple string with puts movi.p(R0, another_name) prepare.i(1) pusharg.p(R0) finish(libc.puts) # this is a global that we've set movi.p(R0, MY_NAME) prepare.i(1) pusharg.p(R0) finish(libc.puts) end # Ok, this is just fucking weird, but could be cool as hell when coroutines are in. # You can access the constants that other functions declare. function data_sharing_test() : int movi.p(R0, self.puts_sample.another_name) prepare.i(1) pusharg.p(R0) finish(libc.puts) end %leaf function test1() : int movi.i(R1, 10000) movi.i(R0, 20) mulr.i(RET, R1, R0) end %leaf function test2(): int movi.i(RET, 100) end function malloc_test() : void movi.ui(R0, 1024) prepare.i(1) pusharg.ui(R0) finish(libc.malloc) movr.ui(R0, RET) prepare.i(1) pusharg.ui(R0) finish(libc.free) end # yes, this replaces the code in test1 with test2 and calls it function make_test1_test2() : int movi.ui(R1, 0) next: ldxi.c(R0, R1, self.test2) stxi.c(self.test1, R1, R0) addi.ui(R1, R1, 1) blti.ui(next:, R1, 21) calli(self.test1) end %leaf function incrementer() : int movi.i(R0, 0) again: addi.i(R1, R0, 1) movr.i(R0, R1) blti.i(again:, R0, 10) movr.i(RET, R0) end %leaf function reflect(in : uint) : uint getarg.ui(RET, in) end %leaf function fibit(in : ulong) : ulong getarg.ul(R2, in) movi.ul(R1, 1) blti.ul(exit:, R2, 2) subi.ul(R2, R2, 1) movi.ul(R0, 1) loop: subi.ul(R2, R2, 1) addr.ul(V0, R0, R1) movr.ul(R0, R1) addi.ul(R1, V0, 1) bnei.ul(loop:, R2, 0) exit: movr.ul(RET, R1) end function fibit_huge_loop() : ulong movi.ui(V1, 5000000) again: prepare.i(1) movi.ul(R0, 93) pusharg.ul(R0) finish(self.fibit) retval.ul(R0) # decrement and repeat subi.ui(V1, V1, 1) bgti.ui(again:, V1, 0) # grab the last value as a check movr.ul(RET, R0) end function print_fibit10() : ulong prepare.i(1) movi.ul(R0, 93) pusharg.ul(R0) finish(self.fibit) # can also just be returned right away since RET already has it retval.ul(R0) movr.ul(RET, R0) end function print_reflect() : uint prepare.i(1) movi.ui(R0, 93) pusharg.ui(R0) finish(self.reflect) # since we return right away we don't need to do the retval/movr end function nfibs(in : uint) : uint getarg.ui(V0, in) # V0 = n blti.ui(exit:, V0, 2) subi.ui(V1, V0, 1) # V1 = n - 1 subi.ui(V2, V0, 2) # V2 = n - 2 # call first recursion prepare.i(1) pusharg.ui(V1) # V1 = nfibs(n-1) finish(self.nfibs) retval.i(V1) # call second recursion prepare.i(1) pusharg.ui(V2) # V2 = nfibs(n-2) finish(self.nfibs) retval.i(V2) addi.ui(V1, V1, 1) # V1++ addr.ui(RET, V1, V2) # V1 + V2 + 1 exit: movi.i(RET, 1) end function print_nfibs10() : uint prepare.i(1) movi.ui(R0, 10) pusharg.ui(R0) finish(self.nfibs) retval.ui(R0) movr.ui(RET, R0) end function lots_of_parameters(one : ui, two : ui, three : ui) : void end function main() : float calli(self.incrementer) calli(self.test1) calli(self.test2) calli(self.make_test1_test2) calli(self.test1) calli(self.print_reflect) calli(self.print_nfibs10) calli(self.fibit_huge_loop) calli(imported.imported_setup) movi.f(R0, 10.0) prepare.i(1) pusharg.f(R0) finish(math.cosf) retval.f(R0) movr.f(RET, R0) end
; background ; Displays a background pattern. .INCLUDE "../lib/header.asm" .INCLUDE "../lib/registers.asm" .INCLUDE "../lib/settings.asm" .INCLUDE "../lib/initialization.asm" .BANK 0 .ORG 0 .SECTION "" Main: Reset ; Set accumulator register to 8-bit sep #$20 ; Set background mode to 0 (4 layers with 4 colors) and tile size to 16x16 lda #$10 sta BGMODE ; Set background layer 1 to use tilemap segment 1 (address $0400 in VRAM) lda #$04 sta BG1SC ; Set background layer 1 to use background character segment 0 (address $0000 in VRAM) stz BG12NBA ; Set color 1 of palette 0 to white lda #$01 sta CGADD lda #$FF sta CGDATA lda #$7F sta CGDATA ; Set color 1 of palette 1 to orange lda #$05 sta CGADD lda #$FF sta CGDATA lda #$00 sta CGDATA ; Set VRAM write mode to increment the VRAM address after writing VMDATAL ; We will not be writing VMDATAH (bits for plane 1 of the background characters) lda #VMAINC_INC_L sta VMAINC ; Set VRAM address to background layer 1's character segment, character 2 (@2bpp) lda #$10 sta VMADD ; Write bits for character 2 plane 0 (tile 1 part A) lda #%00000000 sta VMDATAL lda #%00000000 sta VMDATAL lda #%00111111 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL ; Write bits for character 3 plane 0 (tile 1 part A) lda #%00000000 sta VMDATAL lda #%00000000 sta VMDATAL lda #%11111110 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL ; Set VRAM address to background layer 1's character segment, character 18 (@2bpp) ; Characters for 16x16 tiles are interleaved in VRAM, so we skipped characters for other tiles lda #$90 sta VMADD ; Write bits for character 18 plane 0 (tile 1 part C) lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00100000 sta VMDATAL lda #%00111111 sta VMDATAL lda #%00000000 sta VMDATAL ; Write bits for character 19 plane 0 (tile 1 part D) lda #%10000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%00000010 sta VMDATAL lda #%11111110 sta VMDATAL lda #%00000000 sta VMDATAL ; Set VRAM write mode to increment the VRAM address after writing VMDATAH lda #VMAINC_INC_H sta VMAINC ; Reset index registers to 16-bit rep #$10 ; Write tilemap segment 1 starting at tile 0 ldx #$0400 stx VMADD ; Tile 0 refers to character 2 lda #$02 sta VMDATAL ; Tile 0 uses palette 1 (where color 1 is orange) lda #%00000100 sta VMDATAH ; The next tiles also refer to character 2 lda #$02 ; We will create 14 tiles in tilemap ldx #$000E - sta VMDATAL ; These tiles use palette 0 (where color 1 is white) stz VMDATAH dex bne - ; The last tile also refers to character 2 lda #$02 sta VMDATAL ; This tile uses palette 1 (where color 1 is orange) lda #%00000100 sta VMDATAH ; Enable background layer 1 lda #$01 sta TM ; Enable the screen at full brightness lda #$0F sta INIDISP ; Enable VBlank lda #NMITIMEN_NMI_ENABLE sta NMITIMEN ; Keep waiting for interrupts - wai jmp - VBlank: rti IRQ: lda TIMEUP rti .ENDS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;Mult.asm - Multiplicacao de numeros de dois digitos ;Prof. Roberto M. Ziller - 04.01.2000 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; LETECLA EQU 02E7H ; MOSTRAD EQU 0363H ; sinonimos para sub-rotinas em ROM ORG 2000H ; endereco inicial do programa INICIO: LXI SP,20C0H ; define inicio da pilha LOOP0: CALL LE_DADO ; leitura de N1 (acumulador) MOV B,A ; copia N1 para o registrador B CALL LE_DADO ; leitura de N2 (acumulador) MOV C,A ; copia N2 para o registrador C CALL MULT ; DE = C * B CALL MOSTRAD ; apresenta resultado JMP LOOP0 ; reinicia LE_DADO:CALL LETECLA ; le o digito mais significativo RLC RLC RLC RLC ; multiplica-o por 16 MOV E,A ; digito mais significativo em E CALL LETECLA ; le digito menos significativo ORA E ; compoe numero de dois digitos RET ; retorna com numero em A MULT: MVI D,00 ; inicializacoes MVI A,00 LOOP1: ADD B ; soma N1 ao acumulador JNC CONT ; "vai 1"? INR D ; incrementa D se a soma passa de FF CONT: DCR C JNZ LOOP1 ; repete a soma N2 vezes MOV E,A ; transfere o resultado para E RET ; retorno com resultado no par DE END
// // Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20714 // // /// // Buffer Definitions: // // cbuffer cbCS // { // // uint4 g_param; // Offset: 0 Size: 16 // float4 g_paramf; // Offset: 16 Size: 16 // // } // // Resource bind info for oldPosVelo // { // // struct // { // // float4 pos; // Offset: 0 // float4 velo; // Offset: 16 // // } $Element; // Offset: 0 Size: 32 // // } // // Resource bind info for newPosVelo // { // // struct // { // // float4 pos; // Offset: 0 // float4 velo; // Offset: 16 // // } $Element; // Offset: 0 Size: 32 // // } // // // Resource Bindings: // // Name Type Format Dim Slot Elements // ------------------------------ ---------- ------- ----------- ---- -------- // oldPosVelo texture struct r/o 0 1 // newPosVelo UAV struct r/w 0 1 // cbCS cbuffer NA NA 0 1 // // // // Input signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // no Input // // Output signature: // // Name Index Mask Register SysValue Format Used // -------------------- ----- ------ -------- -------- ------- ------ // no Output cs_4_0 dcl_globalFlags refactoringAllowed dcl_constantbuffer cb0[2], immediateIndexed dcl_resource_structured t0, 32 dcl_uav_structured u0, 32 dcl_input vThreadIDInGroupFlattened dcl_input vThreadID.x dcl_temps 4 dcl_tgsm_structured g0, 16, 128 dcl_thread_group 128, 1, 1 ld_structured r0.xyzw, vThreadID.x, l(0), t0.xyzw mov r1.xyzw, l(0,0,0,0) loop uge r2.x, r1.w, cb0[0].y breakc_nz r2.x ishl r2.x, r1.w, l(7) iadd r2.x, r2.x, vThreadIDInGroupFlattened.x ld_structured r2.xyz, r2.x, l(0), t0.xyzx store_structured g0.xyz, vThreadIDInGroupFlattened.x, l(0), r2.xyzx sync_g_t ld_structured r2.xyz, l(0), l(0), g0.xyzx add r2.xyz, -r0.xyzx, r2.xyzx dp3 r2.w, r2.xyzx, r2.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.x, r2.w, r2.w mul r2.w, r2.w, r3.x mul r2.w, r2.w, l(66.730003) mad r2.xyz, r2.xyzx, r2.wwww, r1.xyzx ld_structured r3.xyz, l(1), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(2), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(3), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(4), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(5), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(6), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(7), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(8), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(9), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(10), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(11), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(12), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(13), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(14), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(15), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(16), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(17), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(18), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(19), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(20), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(21), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(22), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(23), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(24), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(25), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(26), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(27), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(28), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(29), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(30), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(31), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(32), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(33), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(34), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(35), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(36), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(37), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(38), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(39), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(40), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(41), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(42), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(43), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(44), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(45), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(46), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(47), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(48), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(49), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(50), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(51), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(52), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(53), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(54), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(55), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(56), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(57), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(58), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(59), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(60), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(61), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(62), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(63), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(64), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(65), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(66), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(67), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(68), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(69), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(70), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(71), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(72), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(73), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(74), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(75), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(76), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(77), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(78), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(79), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(80), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(81), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(82), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(83), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(84), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(85), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(86), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(87), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(88), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(89), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(90), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(91), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(92), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(93), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(94), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(95), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(96), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(97), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(98), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(99), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(100), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(101), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(102), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(103), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(104), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(105), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(106), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(107), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(108), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(109), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(110), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(111), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(112), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(113), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(114), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(115), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(116), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(117), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(118), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(119), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(120), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(121), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(122), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(123), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(124), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(125), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(126), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r2.xyz, r3.xyzx, r2.wwww, r2.xyzx ld_structured r3.xyz, l(127), l(0), g0.xyzx add r3.xyz, -r0.xyzx, r3.xyzx dp3 r2.w, r3.xyzx, r3.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.w, r2.w, r2.w mul r2.w, r2.w, r3.w mul r2.w, r2.w, l(66.730003) mad r1.xyz, r3.xyzx, r2.wwww, r2.xyzx sync_g_t iadd r1.w, r1.w, l(1) endloop ult r1.w, vThreadID.x, cb0[0].x if_nz r1.w ld_structured r2.xyz, vThreadID.x, l(16), t0.xyzx ishl r1.w, cb0[0].y, l(7) iadd r1.w, -r1.w, cb0[0].x dp3 r2.w, -r0.xyzx, -r0.xyzx add r2.w, r2.w, l(0.000002) sqrt r2.w, r2.w div r2.w, l(1.000000, 1.000000, 1.000000, 1.000000), r2.w mul r3.x, r2.w, r2.w mul r2.w, r2.w, r3.x mul r2.w, r2.w, l(66.730003) itof r1.w, r1.w mul r1.w, r1.w, r2.w mad r1.xyz, -r0.xyzx, r1.wwww, r1.xyzx mad r2.xyz, r1.xyzx, cb0[1].xxxx, r2.xyzx mul r2.xyz, r2.xyzx, cb0[1].yyyy mad r0.xyz, r2.xyzx, cb0[1].xxxx, r0.xyzx store_structured u0.xyzw, vThreadID.x, l(0), r0.xyzw dp3 r0.x, r1.xyzx, r1.xyzx sqrt r2.w, r0.x store_structured u0.xyzw, vThreadID.x, l(16), r2.xyzw endif ret // Approximately 1317 instruction slots used
_kill: file format elf32-i386 Disassembly of section .text: 00001000 <main>: #include "stat.h" #include "user.h" int main(int argc, char **argv) { 1000: 55 push %ebp 1001: 89 e5 mov %esp,%ebp 1003: 57 push %edi 1004: 56 push %esi 1005: 53 push %ebx int i; if(argc < 2){ 1006: bb 01 00 00 00 mov $0x1,%ebx { 100b: 83 e4 f0 and $0xfffffff0,%esp 100e: 83 ec 10 sub $0x10,%esp 1011: 8b 75 08 mov 0x8(%ebp),%esi 1014: 8b 7d 0c mov 0xc(%ebp),%edi if(argc < 2){ 1017: 83 fe 01 cmp $0x1,%esi 101a: 7e 23 jle 103f <main+0x3f> 101c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi printf(2, "usage: kill pid...\n"); exit(); } for(i=1; i<argc; i++) kill(atoi(argv[i])); 1020: 8b 04 9f mov (%edi,%ebx,4),%eax for(i=1; i<argc; i++) 1023: 83 c3 01 add $0x1,%ebx kill(atoi(argv[i])); 1026: 89 04 24 mov %eax,(%esp) 1029: e8 f2 01 00 00 call 1220 <atoi> 102e: 89 04 24 mov %eax,(%esp) 1031: e8 7c 02 00 00 call 12b2 <kill> for(i=1; i<argc; i++) 1036: 39 f3 cmp %esi,%ebx 1038: 75 e6 jne 1020 <main+0x20> exit(); 103a: e8 43 02 00 00 call 1282 <exit> printf(2, "usage: kill pid...\n"); 103f: c7 44 24 04 81 17 00 movl $0x1781,0x4(%esp) 1046: 00 1047: c7 04 24 02 00 00 00 movl $0x2,(%esp) 104e: e8 8d 03 00 00 call 13e0 <printf> exit(); 1053: e8 2a 02 00 00 call 1282 <exit> 1058: 66 90 xchg %ax,%ax 105a: 66 90 xchg %ax,%ax 105c: 66 90 xchg %ax,%ax 105e: 66 90 xchg %ax,%ax 00001060 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 1060: 55 push %ebp 1061: 89 e5 mov %esp,%ebp 1063: 8b 45 08 mov 0x8(%ebp),%eax 1066: 8b 4d 0c mov 0xc(%ebp),%ecx 1069: 53 push %ebx char *os; os = s; while((*s++ = *t++) != 0) 106a: 89 c2 mov %eax,%edx 106c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1070: 83 c1 01 add $0x1,%ecx 1073: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 1077: 83 c2 01 add $0x1,%edx 107a: 84 db test %bl,%bl 107c: 88 5a ff mov %bl,-0x1(%edx) 107f: 75 ef jne 1070 <strcpy+0x10> ; return os; } 1081: 5b pop %ebx 1082: 5d pop %ebp 1083: c3 ret 1084: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 108a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00001090 <strcmp>: int strcmp(const char *p, const char *q) { 1090: 55 push %ebp 1091: 89 e5 mov %esp,%ebp 1093: 8b 55 08 mov 0x8(%ebp),%edx 1096: 53 push %ebx 1097: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 109a: 0f b6 02 movzbl (%edx),%eax 109d: 84 c0 test %al,%al 109f: 74 2d je 10ce <strcmp+0x3e> 10a1: 0f b6 19 movzbl (%ecx),%ebx 10a4: 38 d8 cmp %bl,%al 10a6: 74 0e je 10b6 <strcmp+0x26> 10a8: eb 2b jmp 10d5 <strcmp+0x45> 10aa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 10b0: 38 c8 cmp %cl,%al 10b2: 75 15 jne 10c9 <strcmp+0x39> p++, q++; 10b4: 89 d9 mov %ebx,%ecx 10b6: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 10b9: 0f b6 02 movzbl (%edx),%eax p++, q++; 10bc: 8d 59 01 lea 0x1(%ecx),%ebx while(*p && *p == *q) 10bf: 0f b6 49 01 movzbl 0x1(%ecx),%ecx 10c3: 84 c0 test %al,%al 10c5: 75 e9 jne 10b0 <strcmp+0x20> 10c7: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 10c9: 29 c8 sub %ecx,%eax } 10cb: 5b pop %ebx 10cc: 5d pop %ebp 10cd: c3 ret 10ce: 0f b6 09 movzbl (%ecx),%ecx while(*p && *p == *q) 10d1: 31 c0 xor %eax,%eax 10d3: eb f4 jmp 10c9 <strcmp+0x39> 10d5: 0f b6 cb movzbl %bl,%ecx 10d8: eb ef jmp 10c9 <strcmp+0x39> 10da: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 000010e0 <strlen>: uint strlen(char *s) { 10e0: 55 push %ebp 10e1: 89 e5 mov %esp,%ebp 10e3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 10e6: 80 39 00 cmpb $0x0,(%ecx) 10e9: 74 12 je 10fd <strlen+0x1d> 10eb: 31 d2 xor %edx,%edx 10ed: 8d 76 00 lea 0x0(%esi),%esi 10f0: 83 c2 01 add $0x1,%edx 10f3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 10f7: 89 d0 mov %edx,%eax 10f9: 75 f5 jne 10f0 <strlen+0x10> ; return n; } 10fb: 5d pop %ebp 10fc: c3 ret for(n = 0; s[n]; n++) 10fd: 31 c0 xor %eax,%eax } 10ff: 5d pop %ebp 1100: c3 ret 1101: eb 0d jmp 1110 <memset> 1103: 90 nop 1104: 90 nop 1105: 90 nop 1106: 90 nop 1107: 90 nop 1108: 90 nop 1109: 90 nop 110a: 90 nop 110b: 90 nop 110c: 90 nop 110d: 90 nop 110e: 90 nop 110f: 90 nop 00001110 <memset>: void* memset(void *dst, int c, uint n) { 1110: 55 push %ebp 1111: 89 e5 mov %esp,%ebp 1113: 8b 55 08 mov 0x8(%ebp),%edx 1116: 57 push %edi } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 1117: 8b 4d 10 mov 0x10(%ebp),%ecx 111a: 8b 45 0c mov 0xc(%ebp),%eax 111d: 89 d7 mov %edx,%edi 111f: fc cld 1120: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 1122: 89 d0 mov %edx,%eax 1124: 5f pop %edi 1125: 5d pop %ebp 1126: c3 ret 1127: 89 f6 mov %esi,%esi 1129: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00001130 <strchr>: char* strchr(const char *s, char c) { 1130: 55 push %ebp 1131: 89 e5 mov %esp,%ebp 1133: 8b 45 08 mov 0x8(%ebp),%eax 1136: 53 push %ebx 1137: 8b 55 0c mov 0xc(%ebp),%edx for(; *s; s++) 113a: 0f b6 18 movzbl (%eax),%ebx 113d: 84 db test %bl,%bl 113f: 74 1d je 115e <strchr+0x2e> if(*s == c) 1141: 38 d3 cmp %dl,%bl 1143: 89 d1 mov %edx,%ecx 1145: 75 0d jne 1154 <strchr+0x24> 1147: eb 17 jmp 1160 <strchr+0x30> 1149: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1150: 38 ca cmp %cl,%dl 1152: 74 0c je 1160 <strchr+0x30> for(; *s; s++) 1154: 83 c0 01 add $0x1,%eax 1157: 0f b6 10 movzbl (%eax),%edx 115a: 84 d2 test %dl,%dl 115c: 75 f2 jne 1150 <strchr+0x20> return (char*)s; return 0; 115e: 31 c0 xor %eax,%eax } 1160: 5b pop %ebx 1161: 5d pop %ebp 1162: c3 ret 1163: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1169: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00001170 <gets>: char* gets(char *buf, int max) { 1170: 55 push %ebp 1171: 89 e5 mov %esp,%ebp 1173: 57 push %edi 1174: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 1175: 31 f6 xor %esi,%esi { 1177: 53 push %ebx 1178: 83 ec 2c sub $0x2c,%esp cc = read(0, &c, 1); 117b: 8d 7d e7 lea -0x19(%ebp),%edi for(i=0; i+1 < max; ){ 117e: eb 31 jmp 11b1 <gets+0x41> cc = read(0, &c, 1); 1180: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1187: 00 1188: 89 7c 24 04 mov %edi,0x4(%esp) 118c: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1193: e8 02 01 00 00 call 129a <read> if(cc < 1) 1198: 85 c0 test %eax,%eax 119a: 7e 1d jle 11b9 <gets+0x49> break; buf[i++] = c; 119c: 0f b6 45 e7 movzbl -0x19(%ebp),%eax for(i=0; i+1 < max; ){ 11a0: 89 de mov %ebx,%esi buf[i++] = c; 11a2: 8b 55 08 mov 0x8(%ebp),%edx if(c == '\n' || c == '\r') 11a5: 3c 0d cmp $0xd,%al buf[i++] = c; 11a7: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 11ab: 74 0c je 11b9 <gets+0x49> 11ad: 3c 0a cmp $0xa,%al 11af: 74 08 je 11b9 <gets+0x49> for(i=0; i+1 < max; ){ 11b1: 8d 5e 01 lea 0x1(%esi),%ebx 11b4: 3b 5d 0c cmp 0xc(%ebp),%ebx 11b7: 7c c7 jl 1180 <gets+0x10> break; } buf[i] = '\0'; 11b9: 8b 45 08 mov 0x8(%ebp),%eax 11bc: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 11c0: 83 c4 2c add $0x2c,%esp 11c3: 5b pop %ebx 11c4: 5e pop %esi 11c5: 5f pop %edi 11c6: 5d pop %ebp 11c7: c3 ret 11c8: 90 nop 11c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000011d0 <stat>: int stat(char *n, struct stat *st) { 11d0: 55 push %ebp 11d1: 89 e5 mov %esp,%ebp 11d3: 56 push %esi 11d4: 53 push %ebx 11d5: 83 ec 10 sub $0x10,%esp int fd; int r; fd = open(n, O_RDONLY); 11d8: 8b 45 08 mov 0x8(%ebp),%eax 11db: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 11e2: 00 11e3: 89 04 24 mov %eax,(%esp) 11e6: e8 d7 00 00 00 call 12c2 <open> if(fd < 0) 11eb: 85 c0 test %eax,%eax fd = open(n, O_RDONLY); 11ed: 89 c3 mov %eax,%ebx if(fd < 0) 11ef: 78 27 js 1218 <stat+0x48> return -1; r = fstat(fd, st); 11f1: 8b 45 0c mov 0xc(%ebp),%eax 11f4: 89 1c 24 mov %ebx,(%esp) 11f7: 89 44 24 04 mov %eax,0x4(%esp) 11fb: e8 da 00 00 00 call 12da <fstat> close(fd); 1200: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 1203: 89 c6 mov %eax,%esi close(fd); 1205: e8 a0 00 00 00 call 12aa <close> return r; 120a: 89 f0 mov %esi,%eax } 120c: 83 c4 10 add $0x10,%esp 120f: 5b pop %ebx 1210: 5e pop %esi 1211: 5d pop %ebp 1212: c3 ret 1213: 90 nop 1214: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi return -1; 1218: b8 ff ff ff ff mov $0xffffffff,%eax 121d: eb ed jmp 120c <stat+0x3c> 121f: 90 nop 00001220 <atoi>: int atoi(const char *s) { 1220: 55 push %ebp 1221: 89 e5 mov %esp,%ebp 1223: 8b 4d 08 mov 0x8(%ebp),%ecx 1226: 53 push %ebx int n; n = 0; while('0' <= *s && *s <= '9') 1227: 0f be 11 movsbl (%ecx),%edx 122a: 8d 42 d0 lea -0x30(%edx),%eax 122d: 3c 09 cmp $0x9,%al n = 0; 122f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 1234: 77 17 ja 124d <atoi+0x2d> 1236: 66 90 xchg %ax,%ax n = n*10 + *s++ - '0'; 1238: 83 c1 01 add $0x1,%ecx 123b: 8d 04 80 lea (%eax,%eax,4),%eax 123e: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 1242: 0f be 11 movsbl (%ecx),%edx 1245: 8d 5a d0 lea -0x30(%edx),%ebx 1248: 80 fb 09 cmp $0x9,%bl 124b: 76 eb jbe 1238 <atoi+0x18> return n; } 124d: 5b pop %ebx 124e: 5d pop %ebp 124f: c3 ret 00001250 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 1250: 55 push %ebp char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 1251: 31 d2 xor %edx,%edx { 1253: 89 e5 mov %esp,%ebp 1255: 56 push %esi 1256: 8b 45 08 mov 0x8(%ebp),%eax 1259: 53 push %ebx 125a: 8b 5d 10 mov 0x10(%ebp),%ebx 125d: 8b 75 0c mov 0xc(%ebp),%esi while(n-- > 0) 1260: 85 db test %ebx,%ebx 1262: 7e 12 jle 1276 <memmove+0x26> 1264: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 1268: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 126c: 88 0c 10 mov %cl,(%eax,%edx,1) 126f: 83 c2 01 add $0x1,%edx while(n-- > 0) 1272: 39 da cmp %ebx,%edx 1274: 75 f2 jne 1268 <memmove+0x18> return vdst; } 1276: 5b pop %ebx 1277: 5e pop %esi 1278: 5d pop %ebp 1279: c3 ret 0000127a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 127a: b8 01 00 00 00 mov $0x1,%eax 127f: cd 40 int $0x40 1281: c3 ret 00001282 <exit>: SYSCALL(exit) 1282: b8 02 00 00 00 mov $0x2,%eax 1287: cd 40 int $0x40 1289: c3 ret 0000128a <wait>: SYSCALL(wait) 128a: b8 03 00 00 00 mov $0x3,%eax 128f: cd 40 int $0x40 1291: c3 ret 00001292 <pipe>: SYSCALL(pipe) 1292: b8 04 00 00 00 mov $0x4,%eax 1297: cd 40 int $0x40 1299: c3 ret 0000129a <read>: SYSCALL(read) 129a: b8 05 00 00 00 mov $0x5,%eax 129f: cd 40 int $0x40 12a1: c3 ret 000012a2 <write>: SYSCALL(write) 12a2: b8 10 00 00 00 mov $0x10,%eax 12a7: cd 40 int $0x40 12a9: c3 ret 000012aa <close>: SYSCALL(close) 12aa: b8 15 00 00 00 mov $0x15,%eax 12af: cd 40 int $0x40 12b1: c3 ret 000012b2 <kill>: SYSCALL(kill) 12b2: b8 06 00 00 00 mov $0x6,%eax 12b7: cd 40 int $0x40 12b9: c3 ret 000012ba <exec>: SYSCALL(exec) 12ba: b8 07 00 00 00 mov $0x7,%eax 12bf: cd 40 int $0x40 12c1: c3 ret 000012c2 <open>: SYSCALL(open) 12c2: b8 0f 00 00 00 mov $0xf,%eax 12c7: cd 40 int $0x40 12c9: c3 ret 000012ca <mknod>: SYSCALL(mknod) 12ca: b8 11 00 00 00 mov $0x11,%eax 12cf: cd 40 int $0x40 12d1: c3 ret 000012d2 <unlink>: SYSCALL(unlink) 12d2: b8 12 00 00 00 mov $0x12,%eax 12d7: cd 40 int $0x40 12d9: c3 ret 000012da <fstat>: SYSCALL(fstat) 12da: b8 08 00 00 00 mov $0x8,%eax 12df: cd 40 int $0x40 12e1: c3 ret 000012e2 <link>: SYSCALL(link) 12e2: b8 13 00 00 00 mov $0x13,%eax 12e7: cd 40 int $0x40 12e9: c3 ret 000012ea <mkdir>: SYSCALL(mkdir) 12ea: b8 14 00 00 00 mov $0x14,%eax 12ef: cd 40 int $0x40 12f1: c3 ret 000012f2 <chdir>: SYSCALL(chdir) 12f2: b8 09 00 00 00 mov $0x9,%eax 12f7: cd 40 int $0x40 12f9: c3 ret 000012fa <dup>: SYSCALL(dup) 12fa: b8 0a 00 00 00 mov $0xa,%eax 12ff: cd 40 int $0x40 1301: c3 ret 00001302 <getpid>: SYSCALL(getpid) 1302: b8 0b 00 00 00 mov $0xb,%eax 1307: cd 40 int $0x40 1309: c3 ret 0000130a <sbrk>: SYSCALL(sbrk) 130a: b8 0c 00 00 00 mov $0xc,%eax 130f: cd 40 int $0x40 1311: c3 ret 00001312 <sleep>: SYSCALL(sleep) 1312: b8 0d 00 00 00 mov $0xd,%eax 1317: cd 40 int $0x40 1319: c3 ret 0000131a <uptime>: SYSCALL(uptime) 131a: b8 0e 00 00 00 mov $0xe,%eax 131f: cd 40 int $0x40 1321: c3 ret 00001322 <shm_open>: SYSCALL(shm_open) 1322: b8 16 00 00 00 mov $0x16,%eax 1327: cd 40 int $0x40 1329: c3 ret 0000132a <shm_close>: SYSCALL(shm_close) 132a: b8 17 00 00 00 mov $0x17,%eax 132f: cd 40 int $0x40 1331: c3 ret 1332: 66 90 xchg %ax,%ax 1334: 66 90 xchg %ax,%ax 1336: 66 90 xchg %ax,%ax 1338: 66 90 xchg %ax,%ax 133a: 66 90 xchg %ax,%ax 133c: 66 90 xchg %ax,%ax 133e: 66 90 xchg %ax,%ax 00001340 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 1340: 55 push %ebp 1341: 89 e5 mov %esp,%ebp 1343: 57 push %edi 1344: 56 push %esi 1345: 89 c6 mov %eax,%esi 1347: 53 push %ebx 1348: 83 ec 4c sub $0x4c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 134b: 8b 5d 08 mov 0x8(%ebp),%ebx 134e: 85 db test %ebx,%ebx 1350: 74 09 je 135b <printint+0x1b> 1352: 89 d0 mov %edx,%eax 1354: c1 e8 1f shr $0x1f,%eax 1357: 84 c0 test %al,%al 1359: 75 75 jne 13d0 <printint+0x90> neg = 1; x = -xx; } else { x = xx; 135b: 89 d0 mov %edx,%eax neg = 0; 135d: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 1364: 89 75 c0 mov %esi,-0x40(%ebp) } i = 0; 1367: 31 ff xor %edi,%edi 1369: 89 ce mov %ecx,%esi 136b: 8d 5d d7 lea -0x29(%ebp),%ebx 136e: eb 02 jmp 1372 <printint+0x32> do{ buf[i++] = digits[x % base]; 1370: 89 cf mov %ecx,%edi 1372: 31 d2 xor %edx,%edx 1374: f7 f6 div %esi 1376: 8d 4f 01 lea 0x1(%edi),%ecx 1379: 0f b6 92 9c 17 00 00 movzbl 0x179c(%edx),%edx }while((x /= base) != 0); 1380: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 1382: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 1385: 75 e9 jne 1370 <printint+0x30> if(neg) 1387: 8b 55 c4 mov -0x3c(%ebp),%edx buf[i++] = digits[x % base]; 138a: 89 c8 mov %ecx,%eax 138c: 8b 75 c0 mov -0x40(%ebp),%esi if(neg) 138f: 85 d2 test %edx,%edx 1391: 74 08 je 139b <printint+0x5b> buf[i++] = '-'; 1393: 8d 4f 02 lea 0x2(%edi),%ecx 1396: c6 44 05 d8 2d movb $0x2d,-0x28(%ebp,%eax,1) while(--i >= 0) 139b: 8d 79 ff lea -0x1(%ecx),%edi 139e: 66 90 xchg %ax,%ax 13a0: 0f b6 44 3d d8 movzbl -0x28(%ebp,%edi,1),%eax 13a5: 83 ef 01 sub $0x1,%edi write(fd, &c, 1); 13a8: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 13af: 00 13b0: 89 5c 24 04 mov %ebx,0x4(%esp) 13b4: 89 34 24 mov %esi,(%esp) 13b7: 88 45 d7 mov %al,-0x29(%ebp) 13ba: e8 e3 fe ff ff call 12a2 <write> while(--i >= 0) 13bf: 83 ff ff cmp $0xffffffff,%edi 13c2: 75 dc jne 13a0 <printint+0x60> putc(fd, buf[i]); } 13c4: 83 c4 4c add $0x4c,%esp 13c7: 5b pop %ebx 13c8: 5e pop %esi 13c9: 5f pop %edi 13ca: 5d pop %ebp 13cb: c3 ret 13cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi x = -xx; 13d0: 89 d0 mov %edx,%eax 13d2: f7 d8 neg %eax neg = 1; 13d4: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) 13db: eb 87 jmp 1364 <printint+0x24> 13dd: 8d 76 00 lea 0x0(%esi),%esi 000013e0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 13e0: 55 push %ebp 13e1: 89 e5 mov %esp,%ebp 13e3: 57 push %edi char *s; int c, i, state; uint *ap; state = 0; 13e4: 31 ff xor %edi,%edi { 13e6: 56 push %esi 13e7: 53 push %ebx 13e8: 83 ec 3c sub $0x3c,%esp ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 13eb: 8b 5d 0c mov 0xc(%ebp),%ebx ap = (uint*)(void*)&fmt + 1; 13ee: 8d 45 10 lea 0x10(%ebp),%eax { 13f1: 8b 75 08 mov 0x8(%ebp),%esi ap = (uint*)(void*)&fmt + 1; 13f4: 89 45 d4 mov %eax,-0x2c(%ebp) for(i = 0; fmt[i]; i++){ 13f7: 0f b6 13 movzbl (%ebx),%edx 13fa: 83 c3 01 add $0x1,%ebx 13fd: 84 d2 test %dl,%dl 13ff: 75 39 jne 143a <printf+0x5a> 1401: e9 c2 00 00 00 jmp 14c8 <printf+0xe8> 1406: 66 90 xchg %ax,%ax c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 1408: 83 fa 25 cmp $0x25,%edx 140b: 0f 84 bf 00 00 00 je 14d0 <printf+0xf0> write(fd, &c, 1); 1411: 8d 45 e2 lea -0x1e(%ebp),%eax 1414: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 141b: 00 141c: 89 44 24 04 mov %eax,0x4(%esp) 1420: 89 34 24 mov %esi,(%esp) state = '%'; } else { putc(fd, c); 1423: 88 55 e2 mov %dl,-0x1e(%ebp) write(fd, &c, 1); 1426: e8 77 fe ff ff call 12a2 <write> 142b: 83 c3 01 add $0x1,%ebx for(i = 0; fmt[i]; i++){ 142e: 0f b6 53 ff movzbl -0x1(%ebx),%edx 1432: 84 d2 test %dl,%dl 1434: 0f 84 8e 00 00 00 je 14c8 <printf+0xe8> if(state == 0){ 143a: 85 ff test %edi,%edi c = fmt[i] & 0xff; 143c: 0f be c2 movsbl %dl,%eax if(state == 0){ 143f: 74 c7 je 1408 <printf+0x28> } } else if(state == '%'){ 1441: 83 ff 25 cmp $0x25,%edi 1444: 75 e5 jne 142b <printf+0x4b> if(c == 'd'){ 1446: 83 fa 64 cmp $0x64,%edx 1449: 0f 84 31 01 00 00 je 1580 <printf+0x1a0> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 144f: 25 f7 00 00 00 and $0xf7,%eax 1454: 83 f8 70 cmp $0x70,%eax 1457: 0f 84 83 00 00 00 je 14e0 <printf+0x100> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 145d: 83 fa 73 cmp $0x73,%edx 1460: 0f 84 a2 00 00 00 je 1508 <printf+0x128> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 1466: 83 fa 63 cmp $0x63,%edx 1469: 0f 84 35 01 00 00 je 15a4 <printf+0x1c4> putc(fd, *ap); ap++; } else if(c == '%'){ 146f: 83 fa 25 cmp $0x25,%edx 1472: 0f 84 e0 00 00 00 je 1558 <printf+0x178> write(fd, &c, 1); 1478: 8d 45 e6 lea -0x1a(%ebp),%eax 147b: 83 c3 01 add $0x1,%ebx 147e: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1485: 00 } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 1486: 31 ff xor %edi,%edi write(fd, &c, 1); 1488: 89 44 24 04 mov %eax,0x4(%esp) 148c: 89 34 24 mov %esi,(%esp) 148f: 89 55 d0 mov %edx,-0x30(%ebp) 1492: c6 45 e6 25 movb $0x25,-0x1a(%ebp) 1496: e8 07 fe ff ff call 12a2 <write> putc(fd, c); 149b: 8b 55 d0 mov -0x30(%ebp),%edx write(fd, &c, 1); 149e: 8d 45 e7 lea -0x19(%ebp),%eax 14a1: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 14a8: 00 14a9: 89 44 24 04 mov %eax,0x4(%esp) 14ad: 89 34 24 mov %esi,(%esp) putc(fd, c); 14b0: 88 55 e7 mov %dl,-0x19(%ebp) write(fd, &c, 1); 14b3: e8 ea fd ff ff call 12a2 <write> for(i = 0; fmt[i]; i++){ 14b8: 0f b6 53 ff movzbl -0x1(%ebx),%edx 14bc: 84 d2 test %dl,%dl 14be: 0f 85 76 ff ff ff jne 143a <printf+0x5a> 14c4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } } } 14c8: 83 c4 3c add $0x3c,%esp 14cb: 5b pop %ebx 14cc: 5e pop %esi 14cd: 5f pop %edi 14ce: 5d pop %ebp 14cf: c3 ret state = '%'; 14d0: bf 25 00 00 00 mov $0x25,%edi 14d5: e9 51 ff ff ff jmp 142b <printf+0x4b> 14da: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 14e0: 8b 45 d4 mov -0x2c(%ebp),%eax 14e3: b9 10 00 00 00 mov $0x10,%ecx state = 0; 14e8: 31 ff xor %edi,%edi printint(fd, *ap, 16, 0); 14ea: c7 04 24 00 00 00 00 movl $0x0,(%esp) 14f1: 8b 10 mov (%eax),%edx 14f3: 89 f0 mov %esi,%eax 14f5: e8 46 fe ff ff call 1340 <printint> ap++; 14fa: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 14fe: e9 28 ff ff ff jmp 142b <printf+0x4b> 1503: 90 nop 1504: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 1508: 8b 45 d4 mov -0x2c(%ebp),%eax ap++; 150b: 83 45 d4 04 addl $0x4,-0x2c(%ebp) s = (char*)*ap; 150f: 8b 38 mov (%eax),%edi s = "(null)"; 1511: b8 95 17 00 00 mov $0x1795,%eax 1516: 85 ff test %edi,%edi 1518: 0f 44 f8 cmove %eax,%edi while(*s != 0){ 151b: 0f b6 07 movzbl (%edi),%eax 151e: 84 c0 test %al,%al 1520: 74 2a je 154c <printf+0x16c> 1522: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 1528: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 152b: 8d 45 e3 lea -0x1d(%ebp),%eax s++; 152e: 83 c7 01 add $0x1,%edi write(fd, &c, 1); 1531: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1538: 00 1539: 89 44 24 04 mov %eax,0x4(%esp) 153d: 89 34 24 mov %esi,(%esp) 1540: e8 5d fd ff ff call 12a2 <write> while(*s != 0){ 1545: 0f b6 07 movzbl (%edi),%eax 1548: 84 c0 test %al,%al 154a: 75 dc jne 1528 <printf+0x148> state = 0; 154c: 31 ff xor %edi,%edi 154e: e9 d8 fe ff ff jmp 142b <printf+0x4b> 1553: 90 nop 1554: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi write(fd, &c, 1); 1558: 8d 45 e5 lea -0x1b(%ebp),%eax state = 0; 155b: 31 ff xor %edi,%edi write(fd, &c, 1); 155d: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1564: 00 1565: 89 44 24 04 mov %eax,0x4(%esp) 1569: 89 34 24 mov %esi,(%esp) 156c: c6 45 e5 25 movb $0x25,-0x1b(%ebp) 1570: e8 2d fd ff ff call 12a2 <write> 1575: e9 b1 fe ff ff jmp 142b <printf+0x4b> 157a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 10, 1); 1580: 8b 45 d4 mov -0x2c(%ebp),%eax 1583: b9 0a 00 00 00 mov $0xa,%ecx state = 0; 1588: 66 31 ff xor %di,%di printint(fd, *ap, 10, 1); 158b: c7 04 24 01 00 00 00 movl $0x1,(%esp) 1592: 8b 10 mov (%eax),%edx 1594: 89 f0 mov %esi,%eax 1596: e8 a5 fd ff ff call 1340 <printint> ap++; 159b: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 159f: e9 87 fe ff ff jmp 142b <printf+0x4b> putc(fd, *ap); 15a4: 8b 45 d4 mov -0x2c(%ebp),%eax state = 0; 15a7: 31 ff xor %edi,%edi putc(fd, *ap); 15a9: 8b 00 mov (%eax),%eax write(fd, &c, 1); 15ab: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 15b2: 00 15b3: 89 34 24 mov %esi,(%esp) putc(fd, *ap); 15b6: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 15b9: 8d 45 e4 lea -0x1c(%ebp),%eax 15bc: 89 44 24 04 mov %eax,0x4(%esp) 15c0: e8 dd fc ff ff call 12a2 <write> ap++; 15c5: 83 45 d4 04 addl $0x4,-0x2c(%ebp) 15c9: e9 5d fe ff ff jmp 142b <printf+0x4b> 15ce: 66 90 xchg %ax,%ax 000015d0 <free>: static Header base; static Header *freep; void free(void *ap) { 15d0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 15d1: a1 58 1a 00 00 mov 0x1a58,%eax { 15d6: 89 e5 mov %esp,%ebp 15d8: 57 push %edi 15d9: 56 push %esi 15da: 53 push %ebx 15db: 8b 5d 08 mov 0x8(%ebp),%ebx if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 15de: 8b 08 mov (%eax),%ecx bp = (Header*)ap - 1; 15e0: 8d 53 f8 lea -0x8(%ebx),%edx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 15e3: 39 d0 cmp %edx,%eax 15e5: 72 11 jb 15f8 <free+0x28> 15e7: 90 nop if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 15e8: 39 c8 cmp %ecx,%eax 15ea: 72 04 jb 15f0 <free+0x20> 15ec: 39 ca cmp %ecx,%edx 15ee: 72 10 jb 1600 <free+0x30> 15f0: 89 c8 mov %ecx,%eax for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 15f2: 39 d0 cmp %edx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 15f4: 8b 08 mov (%eax),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 15f6: 73 f0 jae 15e8 <free+0x18> 15f8: 39 ca cmp %ecx,%edx 15fa: 72 04 jb 1600 <free+0x30> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 15fc: 39 c8 cmp %ecx,%eax 15fe: 72 f0 jb 15f0 <free+0x20> break; if(bp + bp->s.size == p->s.ptr){ 1600: 8b 73 fc mov -0x4(%ebx),%esi 1603: 8d 3c f2 lea (%edx,%esi,8),%edi 1606: 39 cf cmp %ecx,%edi 1608: 74 1e je 1628 <free+0x58> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 160a: 89 4b f8 mov %ecx,-0x8(%ebx) if(p + p->s.size == bp){ 160d: 8b 48 04 mov 0x4(%eax),%ecx 1610: 8d 34 c8 lea (%eax,%ecx,8),%esi 1613: 39 f2 cmp %esi,%edx 1615: 74 28 je 163f <free+0x6f> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 1617: 89 10 mov %edx,(%eax) freep = p; 1619: a3 58 1a 00 00 mov %eax,0x1a58 } 161e: 5b pop %ebx 161f: 5e pop %esi 1620: 5f pop %edi 1621: 5d pop %ebp 1622: c3 ret 1623: 90 nop 1624: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 1628: 03 71 04 add 0x4(%ecx),%esi 162b: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 162e: 8b 08 mov (%eax),%ecx 1630: 8b 09 mov (%ecx),%ecx 1632: 89 4b f8 mov %ecx,-0x8(%ebx) if(p + p->s.size == bp){ 1635: 8b 48 04 mov 0x4(%eax),%ecx 1638: 8d 34 c8 lea (%eax,%ecx,8),%esi 163b: 39 f2 cmp %esi,%edx 163d: 75 d8 jne 1617 <free+0x47> p->s.size += bp->s.size; 163f: 03 4b fc add -0x4(%ebx),%ecx freep = p; 1642: a3 58 1a 00 00 mov %eax,0x1a58 p->s.size += bp->s.size; 1647: 89 48 04 mov %ecx,0x4(%eax) p->s.ptr = bp->s.ptr; 164a: 8b 53 f8 mov -0x8(%ebx),%edx 164d: 89 10 mov %edx,(%eax) } 164f: 5b pop %ebx 1650: 5e pop %esi 1651: 5f pop %edi 1652: 5d pop %ebp 1653: c3 ret 1654: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 165a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00001660 <malloc>: return freep; } void* malloc(uint nbytes) { 1660: 55 push %ebp 1661: 89 e5 mov %esp,%ebp 1663: 57 push %edi 1664: 56 push %esi 1665: 53 push %ebx 1666: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 1669: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 166c: 8b 1d 58 1a 00 00 mov 0x1a58,%ebx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 1672: 8d 48 07 lea 0x7(%eax),%ecx 1675: c1 e9 03 shr $0x3,%ecx if((prevp = freep) == 0){ 1678: 85 db test %ebx,%ebx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 167a: 8d 71 01 lea 0x1(%ecx),%esi if((prevp = freep) == 0){ 167d: 0f 84 9b 00 00 00 je 171e <malloc+0xbe> 1683: 8b 13 mov (%ebx),%edx 1685: 8b 7a 04 mov 0x4(%edx),%edi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 1688: 39 fe cmp %edi,%esi 168a: 76 64 jbe 16f0 <malloc+0x90> 168c: 8d 04 f5 00 00 00 00 lea 0x0(,%esi,8),%eax if(nu < 4096) 1693: bb 00 80 00 00 mov $0x8000,%ebx 1698: 89 45 e4 mov %eax,-0x1c(%ebp) 169b: eb 0e jmp 16ab <malloc+0x4b> 169d: 8d 76 00 lea 0x0(%esi),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 16a0: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 16a2: 8b 78 04 mov 0x4(%eax),%edi 16a5: 39 fe cmp %edi,%esi 16a7: 76 4f jbe 16f8 <malloc+0x98> 16a9: 89 c2 mov %eax,%edx p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 16ab: 3b 15 58 1a 00 00 cmp 0x1a58,%edx 16b1: 75 ed jne 16a0 <malloc+0x40> if(nu < 4096) 16b3: 8b 45 e4 mov -0x1c(%ebp),%eax 16b6: 81 fe 00 10 00 00 cmp $0x1000,%esi 16bc: bf 00 10 00 00 mov $0x1000,%edi 16c1: 0f 43 fe cmovae %esi,%edi 16c4: 0f 42 c3 cmovb %ebx,%eax p = sbrk(nu * sizeof(Header)); 16c7: 89 04 24 mov %eax,(%esp) 16ca: e8 3b fc ff ff call 130a <sbrk> if(p == (char*)-1) 16cf: 83 f8 ff cmp $0xffffffff,%eax 16d2: 74 18 je 16ec <malloc+0x8c> hp->s.size = nu; 16d4: 89 78 04 mov %edi,0x4(%eax) free((void*)(hp + 1)); 16d7: 83 c0 08 add $0x8,%eax 16da: 89 04 24 mov %eax,(%esp) 16dd: e8 ee fe ff ff call 15d0 <free> return freep; 16e2: 8b 15 58 1a 00 00 mov 0x1a58,%edx if((p = morecore(nunits)) == 0) 16e8: 85 d2 test %edx,%edx 16ea: 75 b4 jne 16a0 <malloc+0x40> return 0; 16ec: 31 c0 xor %eax,%eax 16ee: eb 20 jmp 1710 <malloc+0xb0> if(p->s.size >= nunits){ 16f0: 89 d0 mov %edx,%eax 16f2: 89 da mov %ebx,%edx 16f4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi if(p->s.size == nunits) 16f8: 39 fe cmp %edi,%esi 16fa: 74 1c je 1718 <malloc+0xb8> p->s.size -= nunits; 16fc: 29 f7 sub %esi,%edi 16fe: 89 78 04 mov %edi,0x4(%eax) p += p->s.size; 1701: 8d 04 f8 lea (%eax,%edi,8),%eax p->s.size = nunits; 1704: 89 70 04 mov %esi,0x4(%eax) freep = prevp; 1707: 89 15 58 1a 00 00 mov %edx,0x1a58 return (void*)(p + 1); 170d: 83 c0 08 add $0x8,%eax } } 1710: 83 c4 1c add $0x1c,%esp 1713: 5b pop %ebx 1714: 5e pop %esi 1715: 5f pop %edi 1716: 5d pop %ebp 1717: c3 ret prevp->s.ptr = p->s.ptr; 1718: 8b 08 mov (%eax),%ecx 171a: 89 0a mov %ecx,(%edx) 171c: eb e9 jmp 1707 <malloc+0xa7> base.s.ptr = freep = prevp = &base; 171e: c7 05 58 1a 00 00 5c movl $0x1a5c,0x1a58 1725: 1a 00 00 base.s.size = 0; 1728: ba 5c 1a 00 00 mov $0x1a5c,%edx base.s.ptr = freep = prevp = &base; 172d: c7 05 5c 1a 00 00 5c movl $0x1a5c,0x1a5c 1734: 1a 00 00 base.s.size = 0; 1737: c7 05 60 1a 00 00 00 movl $0x0,0x1a60 173e: 00 00 00 1741: e9 46 ff ff ff jmp 168c <malloc+0x2c> 1746: 66 90 xchg %ax,%ax 1748: 66 90 xchg %ax,%ax 174a: 66 90 xchg %ax,%ax 174c: 66 90 xchg %ax,%ax 174e: 66 90 xchg %ax,%ax 00001750 <uacquire>: #include "uspinlock.h" #include "x86.h" void uacquire(struct uspinlock *lk) { 1750: 55 push %ebp xchg(volatile uint *addr, uint newval) { uint result; // The + in "+m" denotes a read-modify-write operand. asm volatile("lock; xchgl %0, %1" : 1751: b9 01 00 00 00 mov $0x1,%ecx 1756: 89 e5 mov %esp,%ebp 1758: 8b 55 08 mov 0x8(%ebp),%edx 175b: 90 nop 175c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1760: 89 c8 mov %ecx,%eax 1762: f0 87 02 lock xchg %eax,(%edx) // The xchg is atomic. while(xchg(&lk->locked, 1) != 0) 1765: 85 c0 test %eax,%eax 1767: 75 f7 jne 1760 <uacquire+0x10> ; // Tell the C compiler and the processor to not move loads or stores // past this point, to ensure that the critical section's memory // references happen after the lock is acquired. __sync_synchronize(); 1769: 0f ae f0 mfence } 176c: 5d pop %ebp 176d: c3 ret 176e: 66 90 xchg %ax,%ax 00001770 <urelease>: void urelease (struct uspinlock *lk) { 1770: 55 push %ebp 1771: 89 e5 mov %esp,%ebp 1773: 8b 45 08 mov 0x8(%ebp),%eax __sync_synchronize(); 1776: 0f ae f0 mfence // Release the lock, equivalent to lk->locked = 0. // This code can't use a C assignment, since it might // not be atomic. A real OS would use C atomics here. asm volatile("movl $0, %0" : "+m" (lk->locked) : ); 1779: c7 00 00 00 00 00 movl $0x0,(%eax) } 177f: 5d pop %ebp 1780: c3 ret
; A262070: a(n) = ceiling( log_3( binomial(n,2) ) ). ; Submitted by Jamie Morken(s4) ; 0,1,2,3,3,3,4,4,4,4,4,4,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,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 add $0,2 lpb $0 mov $2,$0 min $0,1 bin $2,2 sub $2,$0 lpe lpb $2 div $2,3 add $3,3 lpe mov $0,$3 div $0,3
; A091311: Partial sums of 3^A007814(n). ; 0,1,4,5,14,15,18,19,46,47,50,51,60,61,64,65,146,147,150,151,160,161,164,165,192,193,196,197,206,207,210,211,454,455,458,459,468,469,472,473,500,501,504,505,514,515,518,519,600,601,604,605,614,615,618,619 mov $27,$0 add $27,1 lpb $27 clr $0,25 sub $27,1 sub $0,$27 lpb $0 gcd $0,1073741824 add $3,3 lpb $0 div $0,2 mul $3,3 lpe mov $2,$3 lpe mov $1,$2 div $1,9 add $26,$1 lpe mov $1,$26
; A265046: Coordination sequence for a 4.6.6 point in the 3-transitive tiling {4.6.6, 6.6.6, 6.6.6.6} of the plane by squares and dominoes (hexagons). ; 1,3,5,8,13,18,23,28,32,36,40,44,48,52,56,60,64,68,72,76,80,84,88,92,96,100,104,108,112,116,120,124,128,132,136,140,144,148,152,156,160,164,168,172,176,180,184,188,192,196,200,204,208,212,216,220,224,228,232,236,240,244,248,252,256,260,264,268,272,276,280,284,288,292,296,300,304,308,312,316,320,324,328,332,336,340,344,348,352,356,360,364,368,372,376,380,384,388,392,396,400,404,408,412,416,420,424,428,432,436,440,444,448,452,456,460,464,468,472,476,480,484,488,492,496,500,504,508,512,516,520,524,528,532,536,540,544,548,552,556,560,564,568,572,576,580,584,588,592,596,600,604,608,612,616,620,624,628,632,636,640,644,648,652,656,660,664,668,672,676,680,684,688,692,696,700,704,708,712,716,720,724,728,732,736,740,744,748,752,756,760,764,768,772,776,780,784,788,792,796,800,804,808,812,816,820,824,828,832,836,840,844,848,852,856,860,864,868,872,876,880,884,888,892,896,900,904,908,912,916,920,924,928,932,936,940,944,948,952,956,960,964,968,972,976,980,984,988,992,996 mov $3,$0 mul $0,2 mov $1,$0 sub $1,1 mov $2,7 add $2,$3 trn $2,$0 trn $1,$2 add $1,$0 add $1,1
#include "balancestablemodel.h" #include "settings.h" #include "utils.h" BalancesTableModel::BalancesTableModel(QObject *parent) : QAbstractTableModel(parent) { } void BalancesTableModel::setNewData(const QMap<QString, double>* balances, const QList<UnspentOutput>* outputs) { int currentRows = rowCount(QModelIndex()); // Copy over the utxos for our use delete utxos; utxos = new QList<UnspentOutput>(); // This is a QList deep copy. *utxos = *outputs; // Process the address balances into a list delete modeldata; modeldata = new QList<std::tuple<QString, QString>>(); std::for_each(balances->constKeyValueBegin(), balances->constKeyValueEnd(), [=] (auto it) { modeldata->push_back(std::make_tuple(it.first, QString::number(it.second, 'g', 8))); }); // And then update the data dataChanged(index(0, 0), index(modeldata->size()-1, columnCount(index(0,0))-1)); // Change the layout only if the number of rows changed if (modeldata && modeldata->size() != currentRows) layoutChanged(); } BalancesTableModel::~BalancesTableModel() { delete modeldata; delete utxos; } int BalancesTableModel::rowCount(const QModelIndex&) const { if (modeldata == nullptr) return 0; return modeldata->size(); } int BalancesTableModel::columnCount(const QModelIndex&) const { return 2; } QVariant BalancesTableModel::data(const QModelIndex &index, int role) const { if (role == Qt::TextAlignmentRole && index.column() == 1) return QVariant(Qt::AlignRight | Qt::AlignVCenter); if (role == Qt::ForegroundRole) { // If any of the UTXOs for this address has zero confirmations, paint it in red const auto& addr = std::get<0>(modeldata->at(index.row())); for (auto utxo : *utxos) { if (utxo.address == addr && utxo.confirmations == 0) { QBrush b; b.setColor(Qt::red); return b; } } // Else, just return the default brush QBrush b; b.setColor(Qt::black); return b; } if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return std::get<0>(modeldata->at(index.row())); case 1: return Settings::getInstance()->getZECDisplayFormat(std::get<1>(modeldata->at(index.row())).toDouble()); } } if(role == Qt::ToolTipRole) { switch (index.column()) { case 0: return std::get<0>(modeldata->at(index.row())); case 1: { auto bal = std::get<1>(modeldata->at(index.row())).toDouble(); return Settings::getInstance()->getUSDFormat(bal); } } } return QVariant(); } QVariant BalancesTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if (role == Qt::TextAlignmentRole && section == 1) { return QVariant(Qt::AlignRight | Qt::AlignVCenter); } if (role == Qt::FontRole) { QFont f; f.setBold(true); return f; } if (role != Qt::DisplayRole) return QVariant(); if (orientation == Qt::Horizontal) { switch (section) { case 0: return tr("Address"); case 1: return tr("Amount"); default: return QVariant(); } } return QVariant(); }
; A257272: a(n) = 2^(n-1)*(2^n+7). ; 4,9,22,60,184,624,2272,8640,33664,132864,527872,2104320,8402944,33583104,134275072,536985600,2147713024,8590393344,34360655872,137440788480,549759483904,2199030595584,8796107702272,35184401448960,140737547075584,562950070861824,2251800048566272,9007199724503040,36028797958488064,144115189954904064,576460756061519872,2305843016729886720,9223372051887161344,36893488177483874304,147573952649805955072,590295810478964736000,2361183241675340775424,9444732966220326764544,37778931863919234383872 mov $1,2 pow $1,$0 add $1,4 bin $1,2 sub $1,6 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r14 push %r15 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0x8907, %r13 nop nop and %rdi, %rdi movb $0x61, (%r13) nop nop cmp $10715, %rdx lea addresses_UC_ht+0x88fd, %r15 nop nop nop sub $42057, %rsi movups (%r15), %xmm0 vpextrq $0, %xmm0, %r9 nop nop and %rsi, %rsi lea addresses_A_ht+0xafb5, %rsi lea addresses_WT_ht+0x1aebd, %rdi nop nop xor %r14, %r14 mov $12, %rcx rep movsw nop nop dec %rdi lea addresses_normal_ht+0xaebd, %rsi lea addresses_D_ht+0xa1c4, %rdi xor $40893, %r15 mov $69, %rcx rep movsq nop nop cmp %rsi, %rsi lea addresses_A_ht+0x19dfd, %rsi lea addresses_normal_ht+0x6d6e, %rdi nop cmp $64663, %rdx mov $22, %rcx rep movsq and %rdi, %rdi lea addresses_WC_ht+0x9ffd, %rdx nop nop nop nop add %rdi, %rdi and $0xffffffffffffffc0, %rdx movntdqa (%rdx), %xmm2 vpextrq $1, %xmm2, %r15 nop dec %r15 lea addresses_D_ht+0x1abd, %rsi lea addresses_WT_ht+0x55, %rdi clflush (%rdi) nop nop nop xor %rdx, %rdx mov $105, %rcx rep movsq nop nop inc %r15 lea addresses_WC_ht+0x1bb57, %r14 nop nop nop nop sub %r15, %r15 mov (%r14), %r13 nop add %rdi, %rdi lea addresses_normal_ht+0xebd, %rsi lea addresses_WC_ht+0x1617d, %rdi nop dec %r9 mov $97, %rcx rep movsl nop nop cmp $33451, %rsi lea addresses_normal_ht+0x1bcfd, %r15 add %rcx, %rcx mov (%r15), %r14 nop nop cmp %r9, %r9 lea addresses_UC_ht+0xc3c3, %rsi nop nop nop inc %rdi mov (%rsi), %r13 nop xor $64834, %rcx lea addresses_WT_ht+0x1cbe5, %rsi lea addresses_UC_ht+0x1327d, %rdi nop inc %r14 mov $50, %rcx rep movsb nop nop nop nop nop dec %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r15 push %r9 push %rbp push %rcx push %rdi push %rsi // Store lea addresses_WT+0xb90, %r10 nop nop nop cmp %r15, %r15 movw $0x5152, (%r10) nop sub $41787, %r15 // REPMOV lea addresses_PSE+0x199f5, %rsi lea addresses_WC+0x1c97d, %rdi nop nop and $37737, %r11 mov $40, %rcx rep movsb nop nop nop nop nop dec %rcx // Store mov $0x65d8e500000008fd, %rdi nop nop nop nop xor $18731, %r15 movw $0x5152, (%rdi) nop nop nop nop dec %rdi // Load lea addresses_RW+0x14ce1, %r11 nop nop nop inc %r9 mov (%r11), %edi nop nop nop nop nop xor $32224, %rcx // Faulty Load mov $0x65d8e500000008fd, %rbp nop nop nop nop nop and $57653, %r15 movb (%rbp), %r12b lea oracles, %r10 and $0xff, %r12 shlq $12, %r12 mov (%r10,%r12,1), %r12 pop %rsi pop %rdi pop %rcx pop %rbp pop %r9 pop %r15 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': True, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'} {'src': {'congruent': 2, 'same': False, 'type': 'addresses_PSE'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_WC'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'src': {'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 4, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'NT': True, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 3, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'REPM'} {'00': 250, '52': 21579} 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 00 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 52 */
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %rax push %rbx lea addresses_WC_ht+0x2c08, %rbx nop nop nop nop cmp $8131, %r12 movb $0x61, (%rbx) and $33540, %rax pop %rbx pop %rax pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r14 push %r8 push %r9 push %rcx push %rdi push %rdx // Store lea addresses_A+0x1e4b3, %rcx nop nop nop nop nop inc %rdx mov $0x5152535455565758, %r8 movq %r8, %xmm2 vmovups %ymm2, (%rcx) nop nop nop cmp %rcx, %rcx // Store lea addresses_WC+0xd88, %r9 nop nop sub %rcx, %rcx movl $0x51525354, (%r9) nop nop sub $53898, %r9 // Store lea addresses_WC+0xd88, %r9 nop nop nop xor $27738, %r14 mov $0x5152535455565758, %rdx movq %rdx, %xmm1 movups %xmm1, (%r9) nop nop nop add %r8, %r8 // Store lea addresses_D+0x1588, %rdx nop nop cmp $37926, %rcx mov $0x5152535455565758, %r8 movq %r8, %xmm0 vmovups %ymm0, (%rdx) nop nop nop nop nop sub $56655, %r14 // Store lea addresses_RW+0x1fd88, %r14 nop nop sub %rdx, %rdx mov $0x5152535455565758, %rcx movq %rcx, (%r14) nop and %r9, %r9 // Load lea addresses_UC+0xa0d0, %rdx clflush (%rdx) nop nop nop add %r14, %r14 movups (%rdx), %xmm0 vpextrq $1, %xmm0, %rdi nop nop nop sub %r9, %r9 // Store lea addresses_WT+0x2628, %r13 sub $1100, %r14 movb $0x51, (%r13) nop xor %rdi, %rdi // Store lea addresses_A+0x7c88, %rcx nop nop nop xor $32649, %rdi mov $0x5152535455565758, %r8 movq %r8, %xmm2 movups %xmm2, (%rcx) sub $22976, %r9 // Store lea addresses_normal+0xec8, %r9 nop nop nop cmp $63595, %rcx mov $0x5152535455565758, %rdx movq %rdx, (%r9) nop inc %r14 // Faulty Load lea addresses_PSE+0xe588, %r14 and %r13, %r13 vmovaps (%r14), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %rdx lea oracles, %r8 and $0xff, %rdx shlq $12, %rdx mov (%r8,%rdx,1), %rdx pop %rdx pop %rdi pop %rcx pop %r9 pop %r8 pop %r14 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_PSE', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 16, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 32, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_RW', 'same': False, 'size': 8, 'congruent': 8, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WT', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal', 'same': False, 'size': 8, 'congruent': 6, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_PSE', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'00': 3407, '08': 3, '58': 1, '07': 17060, '50': 1358} 07 00 07 07 07 07 50 07 07 07 07 07 50 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 07 07 00 07 07 07 00 00 00 07 07 07 50 07 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 00 07 07 07 07 07 07 07 00 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 07 07 50 07 07 50 07 07 07 00 07 07 07 07 50 07 07 00 50 07 07 07 00 07 07 07 07 07 07 00 50 07 07 07 07 07 50 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 00 07 07 50 07 07 07 07 07 07 00 50 07 00 07 50 07 07 00 50 07 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 50 07 50 07 07 07 00 07 07 07 07 00 07 07 07 07 00 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 07 07 00 07 07 07 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 00 07 07 07 07 07 07 07 07 07 07 00 00 07 07 07 00 50 07 07 07 07 07 07 07 07 07 07 00 50 07 07 07 00 07 07 07 07 07 07 00 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 00 07 07 00 07 07 07 07 00 00 07 07 50 07 00 07 07 07 07 07 07 07 00 07 07 00 07 00 07 07 00 07 07 07 07 00 50 07 07 07 07 07 07 07 07 07 07 00 07 50 00 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 50 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 50 07 07 50 07 07 00 07 07 07 00 07 07 07 07 07 07 07 07 07 00 07 07 07 07 07 07 07 07 07 00 07 07 07 00 00 50 07 50 07 07 07 50 07 07 00 07 07 07 07 07 00 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 00 07 07 07 07 07 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 50 07 07 07 00 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 07 07 07 07 00 07 07 07 07 50 07 50 07 07 07 07 50 07 07 07 07 07 07 07 07 07 07 50 07 07 07 07 07 00 07 07 07 00 07 00 07 07 07 07 07 07 07 07 07 50 00 07 07 07 07 07 00 07 07 07 07 07 07 00 50 07 07 07 07 07 07 07 07 07 07 07 00 00 07 00 07 50 07 07 07 07 00 07 07 07 07 07 07 07 07 07 07 00 50 07 07 07 07 07 07 00 50 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 50 00 07 07 07 00 07 07 07 07 07 07 07 00 07 00 07 07 07 07 07 07 07 00 00 07 07 00 50 07 07 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 50 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 00 07 07 07 07 07 07 50 07 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 07 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 50 00 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 07 00 00 50 00 07 07 07 07 07 07 07 07 07 07 07 07 07 07 00 07 07 50 07 07 07 00 07 07 07 07 07 07 50 00 00 07 00 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 50 07 07 07 07 07 07 07 07 00 07 07 07 00 00 07 07 07 50 07 07 07 07 07 07 00 07 07 07 50 07 50 07 50 07 07 07 07 07 50 50 07 07 50 50 07 00 00 50 07 50 00 */
;****************************************************************************** ;* H.264 intra prediction asm optimizations ;* Copyright (c) 2010 Jason Garrett-Glaser ;* Copyright (c) 2010 Holger Lubitz ;* Copyright (c) 2010 Loren Merritt ;* Copyright (c) 2010 Ronald S. Bultje ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with FFmpeg; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "x86inc.asm" %include "x86util.asm" SECTION_RODATA tm_shuf: times 8 db 0x03, 0x80 pw_ff00: times 8 dw 0xff00 plane_shuf: db -8, -7, -6, -5, -4, -3, -2, -1 db 1, 2, 3, 4, 5, 6, 7, 8 plane8_shuf: db -4, -3, -2, -1, 0, 0, 0, 0 db 1, 2, 3, 4, 0, 0, 0, 0 pw_0to7: dw 0, 1, 2, 3, 4, 5, 6, 7 pw_1to8: dw 1, 2, 3, 4, 5, 6, 7, 8 pw_m8tom1: dw -8, -7, -6, -5, -4, -3, -2, -1 pw_m4to4: dw -4, -3, -2, -1, 1, 2, 3, 4 SECTION .text cextern pb_1 cextern pb_3 cextern pw_4 cextern pw_5 cextern pw_8 cextern pw_16 cextern pw_17 cextern pw_32 ;----------------------------------------------------------------------------- ; void pred16x16_vertical(uint8_t *src, int stride) ;----------------------------------------------------------------------------- cglobal pred16x16_vertical_mmx, 2,3 sub r0, r1 mov r2, 8 movq mm0, [r0+0] movq mm1, [r0+8] .loop: movq [r0+r1*1+0], mm0 movq [r0+r1*1+8], mm1 movq [r0+r1*2+0], mm0 movq [r0+r1*2+8], mm1 lea r0, [r0+r1*2] dec r2 jg .loop REP_RET cglobal pred16x16_vertical_sse, 2,3 sub r0, r1 mov r2, 4 movaps xmm0, [r0] .loop: movaps [r0+r1*1], xmm0 movaps [r0+r1*2], xmm0 lea r0, [r0+r1*2] movaps [r0+r1*1], xmm0 movaps [r0+r1*2], xmm0 lea r0, [r0+r1*2] dec r2 jg .loop REP_RET ;----------------------------------------------------------------------------- ; void pred16x16_horizontal(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_H 1 cglobal pred16x16_horizontal_%1, 2,3 mov r2, 8 %ifidn %1, ssse3 mova m2, [pb_3] %endif .loop: movd m0, [r0+r1*0-4] movd m1, [r0+r1*1-4] %ifidn %1, ssse3 pshufb m0, m2 pshufb m1, m2 %else punpcklbw m0, m0 punpcklbw m1, m1 %ifidn %1, mmxext pshufw m0, m0, 0xff pshufw m1, m1, 0xff %else punpckhwd m0, m0 punpckhwd m1, m1 punpckhdq m0, m0 punpckhdq m1, m1 %endif mova [r0+r1*0+8], m0 mova [r0+r1*1+8], m1 %endif mova [r0+r1*0], m0 mova [r0+r1*1], m1 lea r0, [r0+r1*2] dec r2 jg .loop REP_RET %endmacro INIT_MMX PRED16x16_H mmx PRED16x16_H mmxext INIT_XMM PRED16x16_H ssse3 ;----------------------------------------------------------------------------- ; void pred16x16_dc(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_DC 1 cglobal pred16x16_dc_%1, 2,7 mov r4, r0 sub r0, r1 pxor mm0, mm0 pxor mm1, mm1 psadbw mm0, [r0+0] psadbw mm1, [r0+8] dec r0 movzx r5d, byte [r0+r1*1] paddw mm0, mm1 movd r6d, mm0 lea r0, [r0+r1*2] %rep 7 movzx r2d, byte [r0+r1*0] movzx r3d, byte [r0+r1*1] add r5d, r2d add r6d, r3d lea r0, [r0+r1*2] %endrep movzx r2d, byte [r0+r1*0] add r5d, r6d lea r2d, [r2+r5+16] shr r2d, 5 %ifidn %1, mmxext movd m0, r2d punpcklbw m0, m0 pshufw m0, m0, 0 %elifidn %1, sse2 movd m0, r2d punpcklbw m0, m0 pshuflw m0, m0, 0 punpcklqdq m0, m0 %elifidn %1, ssse3 pxor m1, m1 movd m0, r2d pshufb m0, m1 %endif %if mmsize==8 mov r3d, 8 .loop: mova [r4+r1*0+0], m0 mova [r4+r1*0+8], m0 mova [r4+r1*1+0], m0 mova [r4+r1*1+8], m0 %else mov r3d, 4 .loop: mova [r4+r1*0], m0 mova [r4+r1*1], m0 lea r4, [r4+r1*2] mova [r4+r1*0], m0 mova [r4+r1*1], m0 %endif lea r4, [r4+r1*2] dec r3d jg .loop REP_RET %endmacro INIT_MMX PRED16x16_DC mmxext INIT_XMM PRED16x16_DC sse2 PRED16x16_DC ssse3 ;----------------------------------------------------------------------------- ; void pred16x16_tm_vp8(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro PRED16x16_TM_MMX 1 cglobal pred16x16_tm_vp8_%1, 2,5 sub r0, r1 pxor mm7, mm7 movq mm0, [r0+0] movq mm2, [r0+8] movq mm1, mm0 movq mm3, mm2 punpcklbw mm0, mm7 punpckhbw mm1, mm7 punpcklbw mm2, mm7 punpckhbw mm3, mm7 movzx r3d, byte [r0-1] mov r4d, 16 .loop: movzx r2d, byte [r0+r1-1] sub r2d, r3d movd mm4, r2d %ifidn %1, mmx punpcklwd mm4, mm4 punpckldq mm4, mm4 %else pshufw mm4, mm4, 0 %endif movq mm5, mm4 movq mm6, mm4 movq mm7, mm4 paddw mm4, mm0 paddw mm5, mm1 paddw mm6, mm2 paddw mm7, mm3 packuswb mm4, mm5 packuswb mm6, mm7 movq [r0+r1+0], mm4 movq [r0+r1+8], mm6 add r0, r1 dec r4d jg .loop REP_RET %endmacro PRED16x16_TM_MMX mmx PRED16x16_TM_MMX mmxext cglobal pred16x16_tm_vp8_sse2, 2,6,6 sub r0, r1 pxor xmm2, xmm2 movdqa xmm0, [r0] movdqa xmm1, xmm0 punpcklbw xmm0, xmm2 punpckhbw xmm1, xmm2 movzx r4d, byte [r0-1] mov r5d, 8 .loop: movzx r2d, byte [r0+r1*1-1] movzx r3d, byte [r0+r1*2-1] sub r2d, r4d sub r3d, r4d movd xmm2, r2d movd xmm4, r3d pshuflw xmm2, xmm2, 0 pshuflw xmm4, xmm4, 0 punpcklqdq xmm2, xmm2 punpcklqdq xmm4, xmm4 movdqa xmm3, xmm2 movdqa xmm5, xmm4 paddw xmm2, xmm0 paddw xmm3, xmm1 paddw xmm4, xmm0 paddw xmm5, xmm1 packuswb xmm2, xmm3 packuswb xmm4, xmm5 movdqa [r0+r1*1], xmm2 movdqa [r0+r1*2], xmm4 lea r0, [r0+r1*2] dec r5d jg .loop REP_RET ;----------------------------------------------------------------------------- ; void pred16x16_plane(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro H264_PRED16x16_PLANE 3 cglobal pred16x16_plane_%3_%1, 2, 7, %2 mov r2, r1 ; +stride neg r1 ; -stride movh m0, [r0+r1 -1] %if mmsize == 8 pxor m4, m4 movh m1, [r0+r1 +3 ] movh m2, [r0+r1 +8 ] movh m3, [r0+r1 +12] punpcklbw m0, m4 punpcklbw m1, m4 punpcklbw m2, m4 punpcklbw m3, m4 pmullw m0, [pw_m8tom1 ] pmullw m1, [pw_m8tom1+8] pmullw m2, [pw_1to8 ] pmullw m3, [pw_1to8 +8] paddw m0, m2 paddw m1, m3 %else ; mmsize == 16 %ifidn %1, sse2 pxor m2, m2 movh m1, [r0+r1 +8] punpcklbw m0, m2 punpcklbw m1, m2 pmullw m0, [pw_m8tom1] pmullw m1, [pw_1to8] paddw m0, m1 %else ; ssse3 movhps m0, [r0+r1 +8] pmaddubsw m0, [plane_shuf] ; H coefficients %endif movhlps m1, m0 %endif paddw m0, m1 %ifidn %1, mmx mova m1, m0 psrlq m1, 32 %elifidn %1, mmx2 pshufw m1, m0, 0xE %else ; mmsize == 16 pshuflw m1, m0, 0xE %endif paddw m0, m1 %ifidn %1, mmx mova m1, m0 psrlq m1, 16 %elifidn %1, mmx2 pshufw m1, m0, 0x1 %else pshuflw m1, m0, 0x1 %endif paddw m0, m1 ; sum of H coefficients lea r4, [r0+r2*8-1] lea r3, [r0+r2*4-1] add r4, r2 %ifdef ARCH_X86_64 %define e_reg r11 %else %define e_reg r0 %endif movzx e_reg, byte [r3+r2*2 ] movzx r5, byte [r4+r1 ] sub r5, e_reg movzx e_reg, byte [r3+r2 ] movzx r6, byte [r4 ] sub r6, e_reg lea r5, [r5+r6*2] movzx e_reg, byte [r3+r1 ] movzx r6, byte [r4+r2*2 ] sub r6, e_reg lea r5, [r5+r6*4] movzx e_reg, byte [r3 ] %ifdef ARCH_X86_64 movzx r10, byte [r4+r2 ] sub r10, e_reg %else movzx r6, byte [r4+r2 ] sub r6, e_reg lea r5, [r5+r6*4] sub r5, r6 %endif lea e_reg, [r3+r1*4] lea r3, [r4+r2*4] movzx r4, byte [e_reg+r2 ] movzx r6, byte [r3 ] sub r6, r4 %ifdef ARCH_X86_64 lea r6, [r10+r6*2] lea r5, [r5+r6*2] add r5, r6 %else lea r5, [r5+r6*4] lea r5, [r5+r6*2] %endif movzx r4, byte [e_reg ] %ifdef ARCH_X86_64 movzx r10, byte [r3 +r2 ] sub r10, r4 sub r5, r10 %else movzx r6, byte [r3 +r2 ] sub r6, r4 lea r5, [r5+r6*8] sub r5, r6 %endif movzx r4, byte [e_reg+r1 ] movzx r6, byte [r3 +r2*2] sub r6, r4 %ifdef ARCH_X86_64 add r6, r10 %endif lea r5, [r5+r6*8] movzx r4, byte [e_reg+r2*2] movzx r6, byte [r3 +r1 ] sub r6, r4 lea r5, [r5+r6*4] add r5, r6 ; sum of V coefficients %ifndef ARCH_X86_64 mov r0, r0m %endif %ifidn %3, h264 lea r5, [r5*5+32] sar r5, 6 %elifidn %3, rv40 lea r5, [r5*5] sar r5, 6 %elifidn %3, svq3 test r5, r5 lea r6, [r5+3] cmovs r5, r6 sar r5, 2 ; V/4 lea r5, [r5*5] ; 5*(V/4) test r5, r5 lea r6, [r5+15] cmovs r5, r6 sar r5, 4 ; (5*(V/4))/16 %endif movzx r4, byte [r0+r1 +15] movzx r3, byte [r3+r2*2 ] lea r3, [r3+r4+1] shl r3, 4 movd r1d, m0 movsx r1d, r1w %ifnidn %3, svq3 %ifidn %3, h264 lea r1d, [r1d*5+32] %else ; rv40 lea r1d, [r1d*5] %endif sar r1d, 6 %else ; svq3 test r1d, r1d lea r4d, [r1d+3] cmovs r1d, r4d sar r1d, 2 ; H/4 lea r1d, [r1d*5] ; 5*(H/4) test r1d, r1d lea r4d, [r1d+15] cmovs r1d, r4d sar r1d, 4 ; (5*(H/4))/16 %endif movd m0, r1d add r1d, r5d add r3d, r1d shl r1d, 3 sub r3d, r1d ; a movd m1, r5d movd m3, r3d %ifidn %1, mmx punpcklwd m0, m0 punpcklwd m1, m1 punpcklwd m3, m3 punpckldq m0, m0 punpckldq m1, m1 punpckldq m3, m3 %elifidn %1, mmx2 pshufw m0, m0, 0x0 pshufw m1, m1, 0x0 pshufw m3, m3, 0x0 %else pshuflw m0, m0, 0x0 pshuflw m1, m1, 0x0 pshuflw m3, m3, 0x0 punpcklqdq m0, m0 ; splat H (words) punpcklqdq m1, m1 ; splat V (words) punpcklqdq m3, m3 ; splat a (words) %endif %ifidn %3, svq3 SWAP 0, 1 %endif mova m2, m0 %if mmsize == 8 mova m5, m0 %endif pmullw m0, [pw_0to7] ; 0*H, 1*H, ..., 7*H (words) %if mmsize == 16 psllw m2, 3 %else psllw m5, 3 psllw m2, 2 mova m6, m5 paddw m6, m2 %endif paddw m0, m3 ; a + {0,1,2,3,4,5,6,7}*H paddw m2, m0 ; a + {8,9,10,11,12,13,14,15}*H %if mmsize == 8 paddw m5, m0 ; a + {8,9,10,11}*H paddw m6, m0 ; a + {12,13,14,15}*H %endif mov r4, 8 .loop mova m3, m0 ; b[0..7] mova m4, m2 ; b[8..15] psraw m3, 5 psraw m4, 5 packuswb m3, m4 mova [r0], m3 %if mmsize == 8 mova m3, m5 ; b[8..11] mova m4, m6 ; b[12..15] psraw m3, 5 psraw m4, 5 packuswb m3, m4 mova [r0+8], m3 %endif paddw m0, m1 paddw m2, m1 %if mmsize == 8 paddw m5, m1 paddw m6, m1 %endif mova m3, m0 ; b[0..7] mova m4, m2 ; b[8..15] psraw m3, 5 psraw m4, 5 packuswb m3, m4 mova [r0+r2], m3 %if mmsize == 8 mova m3, m5 ; b[8..11] mova m4, m6 ; b[12..15] psraw m3, 5 psraw m4, 5 packuswb m3, m4 mova [r0+r2+8], m3 %endif paddw m0, m1 paddw m2, m1 %if mmsize == 8 paddw m5, m1 paddw m6, m1 %endif lea r0, [r0+r2*2] dec r4 jg .loop REP_RET %endmacro INIT_MMX H264_PRED16x16_PLANE mmx, 0, h264 H264_PRED16x16_PLANE mmx, 0, rv40 H264_PRED16x16_PLANE mmx, 0, svq3 H264_PRED16x16_PLANE mmx2, 0, h264 H264_PRED16x16_PLANE mmx2, 0, rv40 H264_PRED16x16_PLANE mmx2, 0, svq3 INIT_XMM H264_PRED16x16_PLANE sse2, 8, h264 H264_PRED16x16_PLANE sse2, 8, rv40 H264_PRED16x16_PLANE sse2, 8, svq3 H264_PRED16x16_PLANE ssse3, 8, h264 H264_PRED16x16_PLANE ssse3, 8, rv40 H264_PRED16x16_PLANE ssse3, 8, svq3 ;----------------------------------------------------------------------------- ; void pred8x8_plane(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro H264_PRED8x8_PLANE 2 cglobal pred8x8_plane_%1, 2, 7, %2 mov r2, r1 ; +stride neg r1 ; -stride movd m0, [r0+r1 -1] %if mmsize == 8 pxor m2, m2 movh m1, [r0+r1 +4 ] punpcklbw m0, m2 punpcklbw m1, m2 pmullw m0, [pw_m4to4] pmullw m1, [pw_m4to4+8] %else ; mmsize == 16 %ifidn %1, sse2 pxor m2, m2 movd m1, [r0+r1 +4] punpckldq m0, m1 punpcklbw m0, m2 pmullw m0, [pw_m4to4] %else ; ssse3 movhps m0, [r0+r1 +4] ; this reads 4 bytes more than necessary pmaddubsw m0, [plane8_shuf] ; H coefficients %endif movhlps m1, m0 %endif paddw m0, m1 %ifnidn %1, ssse3 %ifidn %1, mmx mova m1, m0 psrlq m1, 32 %elifidn %1, mmx2 pshufw m1, m0, 0xE %else ; mmsize == 16 pshuflw m1, m0, 0xE %endif paddw m0, m1 %endif ; !ssse3 %ifidn %1, mmx mova m1, m0 psrlq m1, 16 %elifidn %1, mmx2 pshufw m1, m0, 0x1 %else pshuflw m1, m0, 0x1 %endif paddw m0, m1 ; sum of H coefficients lea r4, [r0+r2*4-1] lea r3, [r0 -1] add r4, r2 %ifdef ARCH_X86_64 %define e_reg r11 %else %define e_reg r0 %endif movzx e_reg, byte [r3+r2*2 ] movzx r5, byte [r4+r1 ] sub r5, e_reg movzx e_reg, byte [r3 ] %ifdef ARCH_X86_64 movzx r10, byte [r4+r2 ] sub r10, e_reg sub r5, r10 %else movzx r6, byte [r4+r2 ] sub r6, e_reg lea r5, [r5+r6*4] sub r5, r6 %endif movzx e_reg, byte [r3+r1 ] movzx r6, byte [r4+r2*2 ] sub r6, e_reg %ifdef ARCH_X86_64 add r6, r10 %endif lea r5, [r5+r6*4] movzx e_reg, byte [r3+r2 ] movzx r6, byte [r4 ] sub r6, e_reg lea r6, [r5+r6*2] lea r5, [r6*9+16] lea r5, [r5+r6*8] sar r5, 5 %ifndef ARCH_X86_64 mov r0, r0m %endif movzx r3, byte [r4+r2*2 ] movzx r4, byte [r0+r1 +7] lea r3, [r3+r4+1] shl r3, 4 movd r1d, m0 movsx r1d, r1w imul r1d, 17 add r1d, 16 sar r1d, 5 movd m0, r1d add r1d, r5d sub r3d, r1d add r1d, r1d sub r3d, r1d ; a movd m1, r5d movd m3, r3d %ifidn %1, mmx punpcklwd m0, m0 punpcklwd m1, m1 punpcklwd m3, m3 punpckldq m0, m0 punpckldq m1, m1 punpckldq m3, m3 %elifidn %1, mmx2 pshufw m0, m0, 0x0 pshufw m1, m1, 0x0 pshufw m3, m3, 0x0 %else pshuflw m0, m0, 0x0 pshuflw m1, m1, 0x0 pshuflw m3, m3, 0x0 punpcklqdq m0, m0 ; splat H (words) punpcklqdq m1, m1 ; splat V (words) punpcklqdq m3, m3 ; splat a (words) %endif %if mmsize == 8 mova m2, m0 %endif pmullw m0, [pw_0to7] ; 0*H, 1*H, ..., 7*H (words) paddw m0, m3 ; a + {0,1,2,3,4,5,6,7}*H %if mmsize == 8 psllw m2, 2 paddw m2, m0 ; a + {4,5,6,7}*H %endif mov r4, 4 ALIGN 16 .loop %if mmsize == 16 mova m3, m0 ; b[0..7] paddw m0, m1 psraw m3, 5 mova m4, m0 ; V+b[0..7] paddw m0, m1 psraw m4, 5 packuswb m3, m4 movh [r0], m3 movhps [r0+r2], m3 %else ; mmsize == 8 mova m3, m0 ; b[0..3] mova m4, m2 ; b[4..7] paddw m0, m1 paddw m2, m1 psraw m3, 5 psraw m4, 5 mova m5, m0 ; V+b[0..3] mova m6, m2 ; V+b[4..7] paddw m0, m1 paddw m2, m1 psraw m5, 5 psraw m6, 5 packuswb m3, m4 packuswb m5, m6 mova [r0], m3 mova [r0+r2], m5 %endif lea r0, [r0+r2*2] dec r4 jg .loop REP_RET %endmacro INIT_MMX H264_PRED8x8_PLANE mmx, 0 H264_PRED8x8_PLANE mmx2, 0 INIT_XMM H264_PRED8x8_PLANE sse2, 8 H264_PRED8x8_PLANE ssse3, 8 ;----------------------------------------------------------------------------- ; void pred8x8_vertical(uint8_t *src, int stride) ;----------------------------------------------------------------------------- cglobal pred8x8_vertical_mmx, 2,2 sub r0, r1 movq mm0, [r0] %rep 3 movq [r0+r1*1], mm0 movq [r0+r1*2], mm0 lea r0, [r0+r1*2] %endrep movq [r0+r1*1], mm0 movq [r0+r1*2], mm0 RET ;----------------------------------------------------------------------------- ; void pred8x8_horizontal(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8_H 1 cglobal pred8x8_horizontal_%1, 2,3 mov r2, 4 %ifidn %1, ssse3 mova m2, [pb_3] %endif .loop: movd m0, [r0+r1*0-4] movd m1, [r0+r1*1-4] %ifidn %1, ssse3 pshufb m0, m2 pshufb m1, m2 %else punpcklbw m0, m0 punpcklbw m1, m1 %ifidn %1, mmxext pshufw m0, m0, 0xff pshufw m1, m1, 0xff %else punpckhwd m0, m0 punpckhwd m1, m1 punpckhdq m0, m0 punpckhdq m1, m1 %endif %endif mova [r0+r1*0], m0 mova [r0+r1*1], m1 lea r0, [r0+r1*2] dec r2 jg .loop REP_RET %endmacro INIT_MMX PRED8x8_H mmx PRED8x8_H mmxext PRED8x8_H ssse3 ;----------------------------------------------------------------------------- ; void pred8x8_top_dc_mmxext(uint8_t *src, int stride) ;----------------------------------------------------------------------------- cglobal pred8x8_top_dc_mmxext, 2,5 sub r0, r1 movq mm0, [r0] pxor mm1, mm1 pxor mm2, mm2 lea r2, [r0+r1*2] punpckhbw mm1, mm0 punpcklbw mm0, mm2 psadbw mm1, mm2 ; s1 lea r3, [r2+r1*2] psadbw mm0, mm2 ; s0 psrlw mm1, 1 psrlw mm0, 1 pavgw mm1, mm2 lea r4, [r3+r1*2] pavgw mm0, mm2 pshufw mm1, mm1, 0 pshufw mm0, mm0, 0 ; dc0 (w) packuswb mm0, mm1 ; dc0,dc1 (b) movq [r0+r1*1], mm0 movq [r0+r1*2], mm0 lea r0, [r3+r1*2] movq [r2+r1*1], mm0 movq [r2+r1*2], mm0 movq [r3+r1*1], mm0 movq [r3+r1*2], mm0 movq [r0+r1*1], mm0 movq [r0+r1*2], mm0 RET ;----------------------------------------------------------------------------- ; void pred8x8_dc_mmxext(uint8_t *src, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred8x8_dc_mmxext, 2,5 sub r0, r1 pxor m7, m7 movd m0, [r0+0] movd m1, [r0+4] psadbw m0, m7 ; s0 mov r4, r0 psadbw m1, m7 ; s1 movzx r2d, byte [r0+r1*1-1] movzx r3d, byte [r0+r1*2-1] lea r0, [r0+r1*2] add r2d, r3d movzx r3d, byte [r0+r1*1-1] add r2d, r3d movzx r3d, byte [r0+r1*2-1] add r2d, r3d lea r0, [r0+r1*2] movd m2, r2d ; s2 movzx r2d, byte [r0+r1*1-1] movzx r3d, byte [r0+r1*2-1] lea r0, [r0+r1*2] add r2d, r3d movzx r3d, byte [r0+r1*1-1] add r2d, r3d movzx r3d, byte [r0+r1*2-1] add r2d, r3d movd m3, r2d ; s3 punpcklwd m0, m1 mov r0, r4 punpcklwd m2, m3 punpckldq m0, m2 ; s0, s1, s2, s3 pshufw m3, m0, 11110110b ; s2, s1, s3, s3 lea r2, [r0+r1*2] pshufw m0, m0, 01110100b ; s0, s1, s3, s1 paddw m0, m3 lea r3, [r2+r1*2] psrlw m0, 2 pavgw m0, m7 ; s0+s2, s1, s3, s1+s3 lea r4, [r3+r1*2] packuswb m0, m0 punpcklbw m0, m0 movq m1, m0 punpcklbw m0, m0 punpckhbw m1, m1 movq [r0+r1*1], m0 movq [r0+r1*2], m0 movq [r2+r1*1], m0 movq [r2+r1*2], m0 movq [r3+r1*1], m1 movq [r3+r1*2], m1 movq [r4+r1*1], m1 movq [r4+r1*2], m1 RET ;----------------------------------------------------------------------------- ; void pred8x8_dc_rv40(uint8_t *src, int stride) ;----------------------------------------------------------------------------- cglobal pred8x8_dc_rv40_mmxext, 2,7 mov r4, r0 sub r0, r1 pxor mm0, mm0 psadbw mm0, [r0] dec r0 movzx r5d, byte [r0+r1*1] movd r6d, mm0 lea r0, [r0+r1*2] %rep 3 movzx r2d, byte [r0+r1*0] movzx r3d, byte [r0+r1*1] add r5d, r2d add r6d, r3d lea r0, [r0+r1*2] %endrep movzx r2d, byte [r0+r1*0] add r5d, r6d lea r2d, [r2+r5+8] shr r2d, 4 movd mm0, r2d punpcklbw mm0, mm0 pshufw mm0, mm0, 0 mov r3d, 4 .loop: movq [r4+r1*0], mm0 movq [r4+r1*1], mm0 lea r4, [r4+r1*2] dec r3d jg .loop REP_RET ;----------------------------------------------------------------------------- ; void pred8x8_tm_vp8(uint8_t *src, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8_TM_MMX 1 cglobal pred8x8_tm_vp8_%1, 2,6 sub r0, r1 pxor mm7, mm7 movq mm0, [r0] movq mm1, mm0 punpcklbw mm0, mm7 punpckhbw mm1, mm7 movzx r4d, byte [r0-1] mov r5d, 4 .loop: movzx r2d, byte [r0+r1*1-1] movzx r3d, byte [r0+r1*2-1] sub r2d, r4d sub r3d, r4d movd mm2, r2d movd mm4, r3d %ifidn %1, mmx punpcklwd mm2, mm2 punpcklwd mm4, mm4 punpckldq mm2, mm2 punpckldq mm4, mm4 %else pshufw mm2, mm2, 0 pshufw mm4, mm4, 0 %endif movq mm3, mm2 movq mm5, mm4 paddw mm2, mm0 paddw mm3, mm1 paddw mm4, mm0 paddw mm5, mm1 packuswb mm2, mm3 packuswb mm4, mm5 movq [r0+r1*1], mm2 movq [r0+r1*2], mm4 lea r0, [r0+r1*2] dec r5d jg .loop REP_RET %endmacro PRED8x8_TM_MMX mmx PRED8x8_TM_MMX mmxext cglobal pred8x8_tm_vp8_sse2, 2,6,4 sub r0, r1 pxor xmm1, xmm1 movq xmm0, [r0] punpcklbw xmm0, xmm1 movzx r4d, byte [r0-1] mov r5d, 4 .loop: movzx r2d, byte [r0+r1*1-1] movzx r3d, byte [r0+r1*2-1] sub r2d, r4d sub r3d, r4d movd xmm2, r2d movd xmm3, r3d pshuflw xmm2, xmm2, 0 pshuflw xmm3, xmm3, 0 punpcklqdq xmm2, xmm2 punpcklqdq xmm3, xmm3 paddw xmm2, xmm0 paddw xmm3, xmm0 packuswb xmm2, xmm3 movq [r0+r1*1], xmm2 movhps [r0+r1*2], xmm2 lea r0, [r0+r1*2] dec r5d jg .loop REP_RET cglobal pred8x8_tm_vp8_ssse3, 2,3,6 sub r0, r1 movdqa xmm4, [tm_shuf] pxor xmm1, xmm1 movq xmm0, [r0] punpcklbw xmm0, xmm1 movd xmm5, [r0-4] pshufb xmm5, xmm4 mov r2d, 4 .loop: movd xmm2, [r0+r1*1-4] movd xmm3, [r0+r1*2-4] pshufb xmm2, xmm4 pshufb xmm3, xmm4 psubw xmm2, xmm5 psubw xmm3, xmm5 paddw xmm2, xmm0 paddw xmm3, xmm0 packuswb xmm2, xmm3 movq [r0+r1*1], xmm2 movhps [r0+r1*2], xmm2 lea r0, [r0+r1*2] dec r2d jg .loop REP_RET ; dest, left, right, src, tmp ; output: %1 = (t[n-1] + t[n]*2 + t[n+1] + 2) >> 2 %macro PRED4x4_LOWPASS 5 mova %5, %2 pavgb %2, %3 pxor %3, %5 mova %1, %4 pand %3, [pb_1] psubusb %2, %3 pavgb %1, %2 %endmacro ;----------------------------------------------------------------------------- ; void pred8x8l_top_dc(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_TOP_DC 1 cglobal pred8x8l_top_dc_%1, 4,4 sub r0, r3 pxor mm7, mm7 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 ; top_left jz .fix_lt_2 test r2, r2 ; top_right jz .fix_tr_1 jmp .body .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 ; top_right jnz .body .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 .body PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5 psadbw mm7, mm0 paddw mm7, [pw_4] psrlw mm7, 3 pshufw mm7, mm7, 0 packuswb mm7, mm7 %rep 3 movq [r0+r3*1], mm7 movq [r0+r3*2], mm7 lea r0, [r0+r3*2] %endrep movq [r0+r3*1], mm7 movq [r0+r3*2], mm7 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_TOP_DC mmxext %define PALIGNR PALIGNR_SSSE3 PRED8x8L_TOP_DC ssse3 ;----------------------------------------------------------------------------- ;void pred8x8l_dc(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_DC 1 cglobal pred8x8l_dc_%1, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jnz .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .body .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .body .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .body lea r1, [r0+r3*2] PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5 pxor mm0, mm0 pxor mm1, mm1 lea r2, [r1+r3*2] psadbw mm0, mm7 psadbw mm1, mm6 paddw mm0, [pw_8] paddw mm0, mm1 lea r4, [r2+r3*2] psrlw mm0, 4 pshufw mm0, mm0, 0 packuswb mm0, mm0 movq [r0+r3*1], mm0 movq [r0+r3*2], mm0 movq [r1+r3*1], mm0 movq [r1+r3*2], mm0 movq [r2+r3*1], mm0 movq [r2+r3*2], mm0 movq [r4+r3*1], mm0 movq [r4+r3*2], mm0 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_DC mmxext %define PALIGNR PALIGNR_SSSE3 PRED8x8L_DC ssse3 ;----------------------------------------------------------------------------- ; void pred8x8l_horizontal(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_HORIZONTAL 1 cglobal pred8x8l_horizontal_%1, 4,4 sub r0, r3 lea r2, [r0+r3*2] movq mm0, [r0+r3*1-8] test r1, r1 lea r1, [r0+r3] cmovnz r1, r0 punpckhbw mm0, [r1+r3*0-8] movq mm1, [r2+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r2, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r1+r3*0-8] mov r0, r2 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 movq mm3, mm7 lea r1, [r0+r3*2] movq mm7, mm3 punpckhbw mm3, mm3 punpcklbw mm7, mm7 pshufw mm0, mm3, 0xff pshufw mm1, mm3, 0xaa lea r2, [r1+r3*2] pshufw mm2, mm3, 0x55 pshufw mm3, mm3, 0x00 pshufw mm4, mm7, 0xff pshufw mm5, mm7, 0xaa pshufw mm6, mm7, 0x55 pshufw mm7, mm7, 0x00 movq [r0+r3*1], mm0 movq [r0+r3*2], mm1 movq [r1+r3*1], mm2 movq [r1+r3*2], mm3 movq [r2+r3*1], mm4 movq [r2+r3*2], mm5 lea r0, [r2+r3*2] movq [r0+r3*1], mm6 movq [r0+r3*2], mm7 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_HORIZONTAL mmxext %define PALIGNR PALIGNR_SSSE3 PRED8x8L_HORIZONTAL ssse3 ;----------------------------------------------------------------------------- ; void pred8x8l_vertical(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_VERTICAL 1 cglobal pred8x8l_vertical_%1, 4,4 sub r0, r3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 ; top_left jz .fix_lt_2 test r2, r2 ; top_right jz .fix_tr_1 jmp .body .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 ; top_right jnz .body .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 .body PRED4x4_LOWPASS mm0, mm2, mm1, mm3, mm5 %rep 3 movq [r0+r3*1], mm0 movq [r0+r3*2], mm0 lea r0, [r0+r3*2] %endrep movq [r0+r3*1], mm0 movq [r0+r3*2], mm0 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_VERTICAL mmxext %define PALIGNR PALIGNR_SSSE3 PRED8x8L_VERTICAL ssse3 ;----------------------------------------------------------------------------- ;void pred8x8l_down_left(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred8x8l_down_left_mmxext, 4,5 sub r0, r3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 jmp .do_top .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .fix_tr_2: punpckhbw mm3, mm3 pshufw mm1, mm3, 0xFF jmp .do_topright .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq mm7, mm4 test r2, r2 jz .fix_tr_2 movq mm0, [r0+8] movq mm5, mm0 movq mm2, mm0 movq mm4, mm0 psrlq mm5, 56 PALIGNR mm2, mm3, 7, mm3 PALIGNR mm5, mm4, 1, mm4 PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4 .do_topright: lea r1, [r0+r3*2] movq mm6, mm1 psrlq mm1, 56 movq mm4, mm1 lea r2, [r1+r3*2] movq mm2, mm6 PALIGNR mm2, mm7, 1, mm0 movq mm3, mm6 PALIGNR mm3, mm7, 7, mm0 PALIGNR mm4, mm6, 1, mm0 movq mm5, mm7 movq mm1, mm7 movq mm7, mm6 lea r4, [r2+r3*2] psllq mm1, 8 PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6 PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6 movq [r4+r3*2], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r4+r3*1], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r2+r3*2], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r2+r3*1], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r1+r3*2], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r1+r3*1], mm1 movq mm2, mm0 psllq mm1, 8 psrlq mm2, 56 psllq mm0, 8 por mm1, mm2 movq [r0+r3*2], mm1 psllq mm1, 8 psrlq mm0, 56 por mm1, mm0 movq [r0+r3*1], mm1 RET %macro PRED8x8L_DOWN_LEFT 1 cglobal pred8x8l_down_left_%1, 4,4 sub r0, r3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 ; top_left jz .fix_lt_2 test r2, r2 ; top_right jz .fix_tr_1 jmp .do_top .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 ; top_right jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .fix_tr_2: punpckhbw mm3, mm3 pshufw mm1, mm3, 0xFF jmp .do_topright .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq2dq xmm3, mm4 test r2, r2 ; top_right jz .fix_tr_2 movq mm0, [r0+8] movq mm5, mm0 movq mm2, mm0 movq mm4, mm0 psrlq mm5, 56 PALIGNR mm2, mm3, 7, mm3 PALIGNR mm5, mm4, 1, mm4 PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4 .do_topright: movq2dq xmm4, mm1 psrlq mm1, 56 movq2dq xmm5, mm1 lea r1, [r0+r3*2] pslldq xmm4, 8 por xmm3, xmm4 movdqa xmm2, xmm3 psrldq xmm2, 1 pslldq xmm5, 15 por xmm2, xmm5 lea r2, [r1+r3*2] movdqa xmm1, xmm3 pslldq xmm1, 1 INIT_XMM PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4 psrldq xmm0, 1 movq [r0+r3*1], xmm0 psrldq xmm0, 1 movq [r0+r3*2], xmm0 psrldq xmm0, 1 lea r0, [r2+r3*2] movq [r1+r3*1], xmm0 psrldq xmm0, 1 movq [r1+r3*2], xmm0 psrldq xmm0, 1 movq [r2+r3*1], xmm0 psrldq xmm0, 1 movq [r2+r3*2], xmm0 psrldq xmm0, 1 movq [r0+r3*1], xmm0 psrldq xmm0, 1 movq [r0+r3*2], xmm0 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_DOWN_LEFT sse2 INIT_MMX %define PALIGNR PALIGNR_SSSE3 PRED8x8L_DOWN_LEFT ssse3 ;----------------------------------------------------------------------------- ;void pred8x8l_down_right_mmxext(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred8x8l_down_right_mmxext, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 ; top_left jz .fix_lt_1 .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 movq mm6, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 ; top_left jz .fix_lt_2 test r2, r2 ; top_right jz .fix_tr_1 .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq mm5, mm4 jmp .body .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 ; top_right jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .body lea r1, [r0+r3*2] movq mm1, mm7 movq mm7, mm5 movq mm5, mm6 movq mm2, mm7 lea r2, [r1+r3*2] PALIGNR mm2, mm6, 1, mm0 movq mm3, mm7 PALIGNR mm3, mm6, 7, mm0 movq mm4, mm7 lea r4, [r2+r3*2] psrlq mm4, 8 PRED4x4_LOWPASS mm0, mm1, mm2, mm5, mm6 PRED4x4_LOWPASS mm1, mm3, mm4, mm7, mm6 movq [r4+r3*2], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r4+r3*1], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r2+r3*2], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r2+r3*1], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r1+r3*2], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r1+r3*1], mm0 movq mm2, mm1 psrlq mm0, 8 psllq mm2, 56 psrlq mm1, 8 por mm0, mm2 movq [r0+r3*2], mm0 psrlq mm0, 8 psllq mm1, 56 por mm0, mm1 movq [r0+r3*1], mm0 RET %macro PRED8x8L_DOWN_RIGHT 1 cglobal pred8x8l_down_right_%1, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jz .fix_lt_1 jmp .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 movq2dq xmm3, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 movq2dq xmm1, mm7 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq2dq xmm4, mm4 lea r1, [r0+r3*2] movdqa xmm0, xmm3 pslldq xmm4, 8 por xmm3, xmm4 lea r2, [r1+r3*2] pslldq xmm4, 1 por xmm1, xmm4 psrldq xmm0, 7 pslldq xmm0, 15 psrldq xmm0, 7 por xmm1, xmm0 lea r0, [r2+r3*2] movdqa xmm2, xmm3 psrldq xmm2, 1 INIT_XMM PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm4 movdqa xmm1, xmm0 psrldq xmm1, 1 movq [r0+r3*2], xmm0 movq [r0+r3*1], xmm1 psrldq xmm0, 2 psrldq xmm1, 2 movq [r2+r3*2], xmm0 movq [r2+r3*1], xmm1 psrldq xmm0, 2 psrldq xmm1, 2 movq [r1+r3*2], xmm0 movq [r1+r3*1], xmm1 psrldq xmm0, 2 psrldq xmm1, 2 movq [r4+r3*2], xmm0 movq [r4+r3*1], xmm1 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_DOWN_RIGHT sse2 INIT_MMX %define PALIGNR PALIGNR_SSSE3 PRED8x8L_DOWN_RIGHT ssse3 ;----------------------------------------------------------------------------- ; void pred8x8l_vertical_right(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred8x8l_vertical_right_mmxext, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jz .fix_lt_1 jmp .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm7, mm2 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .do_top PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5 lea r1, [r0+r3*2] movq mm2, mm6 movq mm3, mm6 PALIGNR mm3, mm7, 7, mm0 PALIGNR mm6, mm7, 6, mm1 movq mm4, mm3 pavgb mm3, mm2 lea r2, [r1+r3*2] PRED4x4_LOWPASS mm0, mm6, mm2, mm4, mm5 movq [r0+r3*1], mm3 movq [r0+r3*2], mm0 movq mm5, mm0 movq mm6, mm3 movq mm1, mm7 movq mm2, mm1 psllq mm2, 8 movq mm3, mm1 psllq mm3, 16 lea r4, [r2+r3*2] PRED4x4_LOWPASS mm0, mm1, mm3, mm2, mm4 PALIGNR mm6, mm0, 7, mm2 movq [r1+r3*1], mm6 psllq mm0, 8 PALIGNR mm5, mm0, 7, mm1 movq [r1+r3*2], mm5 psllq mm0, 8 PALIGNR mm6, mm0, 7, mm2 movq [r2+r3*1], mm6 psllq mm0, 8 PALIGNR mm5, mm0, 7, mm1 movq [r2+r3*2], mm5 psllq mm0, 8 PALIGNR mm6, mm0, 7, mm2 movq [r4+r3*1], mm6 psllq mm0, 8 PALIGNR mm5, mm0, 7, mm1 movq [r4+r3*2], mm5 RET %macro PRED8x8L_VERTICAL_RIGHT 1 cglobal pred8x8l_vertical_right_%1, 4,5,7 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jnz .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq2dq xmm0, mm2 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .do_top PRED4x4_LOWPASS mm6, mm2, mm1, mm3, mm5 lea r1, [r0+r3*2] movq2dq xmm4, mm6 pslldq xmm4, 8 por xmm0, xmm4 movdqa xmm6, [pw_ff00] movdqa xmm1, xmm0 lea r2, [r1+r3*2] movdqa xmm2, xmm0 movdqa xmm3, xmm0 pslldq xmm0, 1 pslldq xmm1, 2 pavgb xmm2, xmm0 INIT_XMM PRED4x4_LOWPASS xmm4, xmm3, xmm1, xmm0, xmm5 pandn xmm6, xmm4 movdqa xmm5, xmm4 psrlw xmm4, 8 packuswb xmm6, xmm4 movhlps xmm4, xmm6 movhps [r0+r3*2], xmm5 movhps [r0+r3*1], xmm2 psrldq xmm5, 4 movss xmm5, xmm6 psrldq xmm2, 4 movss xmm2, xmm4 lea r0, [r2+r3*2] psrldq xmm5, 1 psrldq xmm2, 1 movq [r0+r3*2], xmm5 movq [r0+r3*1], xmm2 psrldq xmm5, 1 psrldq xmm2, 1 movq [r2+r3*2], xmm5 movq [r2+r3*1], xmm2 psrldq xmm5, 1 psrldq xmm2, 1 movq [r1+r3*2], xmm5 movq [r1+r3*1], xmm2 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_VERTICAL_RIGHT sse2 INIT_MMX %define PALIGNR PALIGNR_SSSE3 PRED8x8L_VERTICAL_RIGHT ssse3 ;----------------------------------------------------------------------------- ;void pred8x8l_vertical_left(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_VERTICAL_LEFT 1 cglobal pred8x8l_vertical_left_%1, 4,4 sub r0, r3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 jmp .do_top .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .fix_tr_2: punpckhbw mm3, mm3 pshufw mm1, mm3, 0xFF jmp .do_topright .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq2dq xmm4, mm4 test r2, r2 jz .fix_tr_2 movq mm0, [r0+8] movq mm5, mm0 movq mm2, mm0 movq mm4, mm0 psrlq mm5, 56 PALIGNR mm2, mm3, 7, mm3 PALIGNR mm5, mm4, 1, mm4 PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4 .do_topright: movq2dq xmm3, mm1 lea r1, [r0+r3*2] pslldq xmm3, 8 por xmm4, xmm3 movdqa xmm2, xmm4 movdqa xmm1, xmm4 movdqa xmm3, xmm4 psrldq xmm2, 1 pslldq xmm1, 1 pavgb xmm3, xmm2 lea r2, [r1+r3*2] INIT_XMM PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm4, xmm5 psrldq xmm0, 1 movq [r0+r3*1], xmm3 movq [r0+r3*2], xmm0 lea r0, [r2+r3*2] psrldq xmm3, 1 psrldq xmm0, 1 movq [r1+r3*1], xmm3 movq [r1+r3*2], xmm0 psrldq xmm3, 1 psrldq xmm0, 1 movq [r2+r3*1], xmm3 movq [r2+r3*2], xmm0 psrldq xmm3, 1 psrldq xmm0, 1 movq [r0+r3*1], xmm3 movq [r0+r3*2], xmm0 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_VERTICAL_LEFT sse2 %define PALIGNR PALIGNR_SSSE3 INIT_MMX PRED8x8L_VERTICAL_LEFT ssse3 ;----------------------------------------------------------------------------- ; void pred8x8l_horizontal_up(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- %macro PRED8x8L_HORIZONTAL_UP 1 cglobal pred8x8l_horizontal_up_%1, 4,4 sub r0, r3 lea r2, [r0+r3*2] movq mm0, [r0+r3*1-8] test r1, r1 lea r1, [r0+r3] cmovnz r1, r0 punpckhbw mm0, [r1+r3*0-8] movq mm1, [r2+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r2, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r1+r3*0-8] mov r0, r2 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 lea r1, [r0+r3*2] pshufw mm0, mm7, 00011011b ; l6 l7 l4 l5 l2 l3 l0 l1 psllq mm7, 56 ; l7 .. .. .. .. .. .. .. movq mm2, mm0 psllw mm0, 8 psrlw mm2, 8 por mm2, mm0 ; l7 l6 l5 l4 l3 l2 l1 l0 movq mm3, mm2 movq mm4, mm2 movq mm5, mm2 psrlq mm2, 8 psrlq mm3, 16 lea r2, [r1+r3*2] por mm2, mm7 ; l7 l7 l6 l5 l4 l3 l2 l1 punpckhbw mm7, mm7 por mm3, mm7 ; l7 l7 l7 l6 l5 l4 l3 l2 pavgb mm4, mm2 PRED4x4_LOWPASS mm1, mm3, mm5, mm2, mm6 movq mm5, mm4 punpcklbw mm4, mm1 ; p4 p3 p2 p1 punpckhbw mm5, mm1 ; p8 p7 p6 p5 movq mm6, mm5 movq mm7, mm5 movq mm0, mm5 PALIGNR mm5, mm4, 2, mm1 pshufw mm1, mm6, 11111001b PALIGNR mm6, mm4, 4, mm2 pshufw mm2, mm7, 11111110b PALIGNR mm7, mm4, 6, mm3 pshufw mm3, mm0, 11111111b movq [r0+r3*1], mm4 movq [r0+r3*2], mm5 lea r0, [r2+r3*2] movq [r1+r3*1], mm6 movq [r1+r3*2], mm7 movq [r2+r3*1], mm0 movq [r2+r3*2], mm1 movq [r0+r3*1], mm2 movq [r0+r3*2], mm3 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_HORIZONTAL_UP mmxext %define PALIGNR PALIGNR_SSSE3 PRED8x8L_HORIZONTAL_UP ssse3 ;----------------------------------------------------------------------------- ;void pred8x8l_horizontal_down(uint8_t *src, int has_topleft, int has_topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred8x8l_horizontal_down_mmxext, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jnz .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq mm4, mm0 movq mm7, mm2 movq mm6, mm2 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 psllq mm1, 56 PALIGNR mm7, mm1, 7, mm3 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq mm5, mm4 lea r1, [r0+r3*2] psllq mm7, 56 movq mm2, mm5 movq mm3, mm6 movq mm4, mm2 PALIGNR mm2, mm6, 7, mm5 PALIGNR mm6, mm7, 7, mm0 lea r2, [r1+r3*2] PALIGNR mm4, mm3, 1, mm7 movq mm5, mm3 pavgb mm3, mm6 PRED4x4_LOWPASS mm0, mm4, mm6, mm5, mm7 movq mm4, mm2 movq mm1, mm2 lea r4, [r2+r3*2] psrlq mm4, 16 psrlq mm1, 8 PRED4x4_LOWPASS mm6, mm4, mm2, mm1, mm5 movq mm7, mm3 punpcklbw mm3, mm0 punpckhbw mm7, mm0 movq mm1, mm7 movq mm0, mm7 movq mm4, mm7 movq [r4+r3*2], mm3 PALIGNR mm7, mm3, 2, mm5 movq [r4+r3*1], mm7 PALIGNR mm1, mm3, 4, mm5 movq [r2+r3*2], mm1 PALIGNR mm0, mm3, 6, mm3 movq [r2+r3*1], mm0 movq mm2, mm6 movq mm3, mm6 movq [r1+r3*2], mm4 PALIGNR mm6, mm4, 2, mm5 movq [r1+r3*1], mm6 PALIGNR mm2, mm4, 4, mm5 movq [r0+r3*2], mm2 PALIGNR mm3, mm4, 6, mm4 movq [r0+r3*1], mm3 RET %macro PRED8x8L_HORIZONTAL_DOWN 1 cglobal pred8x8l_horizontal_down_%1, 4,5 sub r0, r3 lea r4, [r0+r3*2] movq mm0, [r0+r3*1-8] punpckhbw mm0, [r0+r3*0-8] movq mm1, [r4+r3*1-8] punpckhbw mm1, [r0+r3*2-8] mov r4, r0 punpckhwd mm1, mm0 lea r0, [r0+r3*4] movq mm2, [r0+r3*1-8] punpckhbw mm2, [r0+r3*0-8] lea r0, [r0+r3*2] movq mm3, [r0+r3*1-8] punpckhbw mm3, [r0+r3*0-8] punpckhwd mm3, mm2 punpckhdq mm3, mm1 lea r0, [r0+r3*2] movq mm0, [r0+r3*0-8] movq mm1, [r4] mov r0, r4 movq mm4, mm3 movq mm2, mm3 PALIGNR mm4, mm0, 7, mm0 PALIGNR mm1, mm2, 1, mm2 test r1, r1 jnz .do_left .fix_lt_1: movq mm5, mm3 pxor mm5, mm4 psrlq mm5, 56 psllq mm5, 48 pxor mm1, mm5 jmp .do_left .fix_lt_2: movq mm5, mm3 pxor mm5, mm2 psllq mm5, 56 psrlq mm5, 56 pxor mm2, mm5 test r2, r2 jnz .do_top .fix_tr_1: movq mm5, mm3 pxor mm5, mm1 psrlq mm5, 56 psllq mm5, 56 pxor mm1, mm5 jmp .do_top .fix_tr_2: punpckhbw mm3, mm3 pshufw mm1, mm3, 0xFF jmp .do_topright .do_left: movq mm0, mm4 PRED4x4_LOWPASS mm2, mm1, mm4, mm3, mm5 movq2dq xmm0, mm2 pslldq xmm0, 8 movq mm4, mm0 PRED4x4_LOWPASS mm1, mm3, mm0, mm4, mm5 movq2dq xmm2, mm1 pslldq xmm2, 15 psrldq xmm2, 8 por xmm0, xmm2 movq mm0, [r0-8] movq mm3, [r0] movq mm1, [r0+8] movq mm2, mm3 movq mm4, mm3 PALIGNR mm2, mm0, 7, mm0 PALIGNR mm1, mm4, 1, mm4 test r1, r1 jz .fix_lt_2 test r2, r2 jz .fix_tr_1 .do_top: PRED4x4_LOWPASS mm4, mm2, mm1, mm3, mm5 movq2dq xmm1, mm4 test r2, r2 jz .fix_tr_2 movq mm0, [r0+8] movq mm5, mm0 movq mm2, mm0 movq mm4, mm0 psrlq mm5, 56 PALIGNR mm2, mm3, 7, mm3 PALIGNR mm5, mm4, 1, mm4 PRED4x4_LOWPASS mm1, mm2, mm5, mm0, mm4 .do_topright: movq2dq xmm5, mm1 pslldq xmm5, 8 por xmm1, xmm5 INIT_XMM lea r2, [r4+r3*2] movdqa xmm2, xmm1 movdqa xmm3, xmm1 PALIGNR xmm1, xmm0, 7, xmm4 PALIGNR xmm2, xmm0, 9, xmm5 lea r1, [r2+r3*2] PALIGNR xmm3, xmm0, 8, xmm0 movdqa xmm4, xmm1 pavgb xmm4, xmm3 lea r0, [r1+r3*2] PRED4x4_LOWPASS xmm0, xmm1, xmm2, xmm3, xmm5 punpcklbw xmm4, xmm0 movhlps xmm0, xmm4 movq [r0+r3*2], xmm4 movq [r2+r3*2], xmm0 psrldq xmm4, 2 psrldq xmm0, 2 movq [r0+r3*1], xmm4 movq [r2+r3*1], xmm0 psrldq xmm4, 2 psrldq xmm0, 2 movq [r1+r3*2], xmm4 movq [r4+r3*2], xmm0 psrldq xmm4, 2 psrldq xmm0, 2 movq [r1+r3*1], xmm4 movq [r4+r3*1], xmm0 RET %endmacro INIT_MMX %define PALIGNR PALIGNR_MMX PRED8x8L_HORIZONTAL_DOWN sse2 INIT_MMX %define PALIGNR PALIGNR_SSSE3 PRED8x8L_HORIZONTAL_DOWN ssse3 ;----------------------------------------------------------------------------- ; void pred4x4_dc_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- cglobal pred4x4_dc_mmxext, 3,5 pxor mm7, mm7 mov r4, r0 sub r0, r2 movd mm0, [r0] psadbw mm0, mm7 movzx r1d, byte [r0+r2*1-1] movd r3d, mm0 add r3d, r1d movzx r1d, byte [r0+r2*2-1] lea r0, [r0+r2*2] add r3d, r1d movzx r1d, byte [r0+r2*1-1] add r3d, r1d movzx r1d, byte [r0+r2*2-1] add r3d, r1d add r3d, 4 shr r3d, 3 imul r3d, 0x01010101 mov [r4+r2*0], r3d mov [r0+r2*0], r3d mov [r0+r2*1], r3d mov [r0+r2*2], r3d RET ;----------------------------------------------------------------------------- ; void pred4x4_tm_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- %macro PRED4x4_TM_MMX 1 cglobal pred4x4_tm_vp8_%1, 3,6 sub r0, r2 pxor mm7, mm7 movd mm0, [r0] punpcklbw mm0, mm7 movzx r4d, byte [r0-1] mov r5d, 2 .loop: movzx r1d, byte [r0+r2*1-1] movzx r3d, byte [r0+r2*2-1] sub r1d, r4d sub r3d, r4d movd mm2, r1d movd mm4, r3d %ifidn %1, mmx punpcklwd mm2, mm2 punpcklwd mm4, mm4 punpckldq mm2, mm2 punpckldq mm4, mm4 %else pshufw mm2, mm2, 0 pshufw mm4, mm4, 0 %endif paddw mm2, mm0 paddw mm4, mm0 packuswb mm2, mm2 packuswb mm4, mm4 movd [r0+r2*1], mm2 movd [r0+r2*2], mm4 lea r0, [r0+r2*2] dec r5d jg .loop REP_RET %endmacro PRED4x4_TM_MMX mmx PRED4x4_TM_MMX mmxext cglobal pred4x4_tm_vp8_ssse3, 3,3 sub r0, r2 movq mm6, [tm_shuf] pxor mm1, mm1 movd mm0, [r0] punpcklbw mm0, mm1 movd mm7, [r0-4] pshufb mm7, mm6 lea r1, [r0+r2*2] movd mm2, [r0+r2*1-4] movd mm3, [r0+r2*2-4] movd mm4, [r1+r2*1-4] movd mm5, [r1+r2*2-4] pshufb mm2, mm6 pshufb mm3, mm6 pshufb mm4, mm6 pshufb mm5, mm6 psubw mm2, mm7 psubw mm3, mm7 psubw mm4, mm7 psubw mm5, mm7 paddw mm2, mm0 paddw mm3, mm0 paddw mm4, mm0 paddw mm5, mm0 packuswb mm2, mm2 packuswb mm3, mm3 packuswb mm4, mm4 packuswb mm5, mm5 movd [r0+r2*1], mm2 movd [r0+r2*2], mm3 movd [r1+r2*1], mm4 movd [r1+r2*2], mm5 RET ;----------------------------------------------------------------------------- ; void pred4x4_vertical_vp8_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred4x4_vertical_vp8_mmxext, 3,3 sub r0, r2 movd m1, [r0-1] movd m0, [r0] mova m2, m0 ;t0 t1 t2 t3 punpckldq m0, [r1] ;t0 t1 t2 t3 t4 t5 t6 t7 lea r1, [r0+r2*2] psrlq m0, 8 ;t1 t2 t3 t4 PRED4x4_LOWPASS m3, m1, m0, m2, m4 movd [r0+r2*1], m3 movd [r0+r2*2], m3 movd [r1+r2*1], m3 movd [r1+r2*2], m3 RET ;----------------------------------------------------------------------------- ; void pred4x4_down_left_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred4x4_down_left_mmxext, 3,3 sub r0, r2 movq m1, [r0] punpckldq m1, [r1] movq m2, m1 movq m3, m1 movq m4, m1 psllq m1, 8 pxor m2, m1 psrlq m2, 8 pxor m3, m2 PRED4x4_LOWPASS m0, m1, m3, m4, m5 lea r1, [r0+r2*2] psrlq m0, 8 movd [r0+r2*1], m0 psrlq m0, 8 movd [r0+r2*2], m0 psrlq m0, 8 movd [r1+r2*1], m0 psrlq m0, 8 movd [r1+r2*2], m0 RET ;----------------------------------------------------------------------------- ; void pred4x4_vertical_left_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred4x4_vertical_left_mmxext, 3,3 sub r0, r2 movq m1, [r0] punpckldq m1, [r1] movq m3, m1 movq m2, m1 psrlq m3, 8 psrlq m2, 16 movq m4, m3 pavgb m4, m1 PRED4x4_LOWPASS m0, m1, m2, m3, m5 lea r1, [r0+r2*2] movh [r0+r2*1], m4 movh [r0+r2*2], m0 psrlq m4, 8 psrlq m0, 8 movh [r1+r2*1], m4 movh [r1+r2*2], m0 RET ;----------------------------------------------------------------------------- ; void pred4x4_horizontal_up_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX cglobal pred4x4_horizontal_up_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movd m0, [r0+r2*1-4] punpcklbw m0, [r0+r2*2-4] movd m1, [r1+r2*1-4] punpcklbw m1, [r1+r2*2-4] punpckhwd m0, m1 movq m1, m0 punpckhbw m1, m1 pshufw m1, m1, 0xFF punpckhdq m0, m1 movq m2, m0 movq m3, m0 movq m7, m0 psrlq m2, 16 psrlq m3, 8 pavgb m7, m3 PRED4x4_LOWPASS m4, m0, m2, m3, m5 punpcklbw m7, m4 movd [r0+r2*1], m7 psrlq m7, 16 movd [r0+r2*2], m7 psrlq m7, 16 movd [r1+r2*1], m7 movd [r1+r2*2], m1 RET ;----------------------------------------------------------------------------- ; void pred4x4_horizontal_down_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred4x4_horizontal_down_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movh m0, [r0-4] ; lt .. punpckldq m0, [r0] ; t3 t2 t1 t0 lt .. .. .. psllq m0, 8 ; t2 t1 t0 lt .. .. .. .. movd m1, [r1+r2*2-4] ; l3 punpcklbw m1, [r1+r2*1-4] ; l2 l3 movd m2, [r0+r2*2-4] ; l1 punpcklbw m2, [r0+r2*1-4] ; l0 l1 punpckhwd m1, m2 ; l0 l1 l2 l3 punpckhdq m1, m0 ; t2 t1 t0 lt l0 l1 l2 l3 movq m0, m1 movq m2, m1 movq m5, m1 psrlq m0, 16 ; .. .. t2 t1 t0 lt l0 l1 psrlq m2, 8 ; .. t2 t1 t0 lt l0 l1 l2 pavgb m5, m2 PRED4x4_LOWPASS m3, m1, m0, m2, m4 punpcklbw m5, m3 psrlq m3, 32 PALIGNR m3, m5, 6, m4 movh [r1+r2*2], m5 psrlq m5, 16 movh [r1+r2*1], m5 psrlq m5, 16 movh [r0+r2*2], m5 movh [r0+r2*1], m3 RET ;----------------------------------------------------------------------------- ; void pred4x4_vertical_right_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred4x4_vertical_right_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movh m0, [r0] ; ........t3t2t1t0 movq m5, m0 PALIGNR m0, [r0-8], 7, m1 ; ......t3t2t1t0lt pavgb m5, m0 PALIGNR m0, [r0+r2*1-8], 7, m1 ; ....t3t2t1t0ltl0 movq m1, m0 PALIGNR m0, [r0+r2*2-8], 7, m2 ; ..t3t2t1t0ltl0l1 movq m2, m0 PALIGNR m0, [r1+r2*1-8], 7, m3 ; t3t2t1t0ltl0l1l2 PRED4x4_LOWPASS m3, m1, m0, m2, m4 movq m1, m3 psrlq m3, 16 psllq m1, 48 movh [r0+r2*1], m5 movh [r0+r2*2], m3 PALIGNR m5, m1, 7, m2 psllq m1, 8 movh [r1+r2*1], m5 PALIGNR m3, m1, 7, m1 movh [r1+r2*2], m3 RET ;----------------------------------------------------------------------------- ; void pred4x4_down_right_mmxext(uint8_t *src, const uint8_t *topright, int stride) ;----------------------------------------------------------------------------- INIT_MMX %define PALIGNR PALIGNR_MMX cglobal pred4x4_down_right_mmxext, 3,3 sub r0, r2 lea r1, [r0+r2*2] movq m1, [r1-8] movq m2, [r0+r2*1-8] punpckhbw m2, [r0-8] movh m3, [r0] punpckhwd m1, m2 PALIGNR m3, m1, 5, m1 movq m1, m3 PALIGNR m3, [r1+r2*1-8], 7, m4 movq m2, m3 PALIGNR m3, [r1+r2*2-8], 7, m4 PRED4x4_LOWPASS m0, m3, m1, m2, m4 movh [r1+r2*2], m0 psrlq m0, 8 movh [r1+r2*1], m0 psrlq m0, 8 movh [r0+r2*2], m0 psrlq m0, 8 movh [r0+r2*1], m0 RET
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1994 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: vgaLoader.asm AUTHOR: Gene Anderson, Feb 24, 1994 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Gene 2/24/94 Initial revision DESCRIPTION: $Id: loader.asm,v 1.1 97/04/04 17:26:35 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ kcode segment para public 'CODE' cgroup group kcode, stack include main.asm include locate.asm include strings.asm include ini.asm include load.asm include heap.asm include path.asm ifndef NO_AUTODETECT include videoDetect.asm ifndef NO_SPLASH_SCREEN include videoDisplay.asm include videoVGA.asm include videoSVGA.asm include videoEGA.asm include videoMCGA.asm include videoCGA.asm include videoHGC.asm include videoSVGAImageLogo.asm include videoSVGAImageLegal.asm endif endif kcode ends end LoadGeos
; A010857: Constant sequence: a(n) = 18. ; 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18 mov $0,18
#include <iostream> int main() { int n; std::cin >> n; int totalNegatives = 0; for (int i=0; i<n; i++) { int temp; std::cin >> temp; if (temp < 0) { totalNegatives++; } } std::cout << totalNegatives; return 0; }
; A169379: Number of reduced words of length n in Coxeter group on 30 generators S_i with relations (S_i)^2 = (S_i S_j)^31 = I. ; 1,30,870,25230,731670,21218430,615334470,17844699630,517496289270,15007392388830,435214379276070,12621216999006030,366015292971174870,10614443496164071230,307818861388758065670,8926746980273983904430 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,29 lpe mov $0,$2 div $0,29
; A159918: Number of ones in binary representation of n^2. ; 0,1,1,2,1,3,2,3,1,3,3,5,2,4,3,4,1,3,3,5,3,6,5,3,2,5,4,6,3,5,4,5,1,3,3,5,3,6,5,7,3,5,6,7,5,8,3,4,2,5,5,5,4,8,6,7,3,6,5,7,4,6,5,6,1,3,3,5,3,6,5,7,3,6,6,9,5,7,7,5,3,6,5,8,6,7,7,7,5,9,8,5,3,6,4,5,2,5,5,6,5,9,5,7,4,6,8,8,6,8,7,4,3,7,6,8,5,9,7,8,4,7,6,8,5,7,6,7,1,3,3,5,3,6,5,7,3,6,6,9,5,8,7,9,3,5,6,7,6,9,9,6,5,9,7,10,7,5,5,6,3,6,6,9,5,8,8,9,6,9,7,8,7,9,7,9,5,8,9,9,8,13,5,6,3,7,6,6,4,7,5,6,2,5,5,6,5,9,6,8,5,9,9,8,5,6,7,8,4,7,6,10,8,8,8,7,6,11,8,10,7,10,4,5,3,7,7,7,6,9,8,7,5,6,9,11,7,10,8,9,4,8,7,9,6,10,8,9,5,8 pow $0,2 mov $1,$0 mov $2,$0 lpb $1 div $2,2 sub $1,$2 lpe
_echo: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 57 push %edi e: 56 push %esi f: 53 push %ebx 10: 51 push %ecx 11: 83 ec 08 sub $0x8,%esp 14: 8b 31 mov (%ecx),%esi 16: 8b 79 04 mov 0x4(%ecx),%edi int i; for(i = 1; i < argc; i++) 19: 83 fe 01 cmp $0x1,%esi 1c: 7e 41 jle 5f <main+0x5f> 1e: bb 01 00 00 00 mov $0x1,%ebx 23: eb 1b jmp 40 <main+0x40> 25: 8d 76 00 lea 0x0(%esi),%esi printf(1, "%s%s", argv[i], i+1 < argc ? " " : "\n"); 28: 68 30 07 00 00 push $0x730 2d: ff 74 9f fc pushl -0x4(%edi,%ebx,4) 31: 68 32 07 00 00 push $0x732 36: 6a 01 push $0x1 38: e8 d3 03 00 00 call 410 <printf> 3d: 83 c4 10 add $0x10,%esp 40: 83 c3 01 add $0x1,%ebx 43: 39 de cmp %ebx,%esi 45: 75 e1 jne 28 <main+0x28> 47: 68 37 07 00 00 push $0x737 4c: ff 74 b7 fc pushl -0x4(%edi,%esi,4) 50: 68 32 07 00 00 push $0x732 55: 6a 01 push $0x1 57: e8 b4 03 00 00 call 410 <printf> 5c: 83 c4 10 add $0x10,%esp exit(); 5f: e8 4e 02 00 00 call 2b2 <exit> 64: 66 90 xchg %ax,%ax 66: 66 90 xchg %ax,%ax 68: 66 90 xchg %ax,%ax 6a: 66 90 xchg %ax,%ax 6c: 66 90 xchg %ax,%ax 6e: 66 90 xchg %ax,%ax 00000070 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 70: 55 push %ebp 71: 89 e5 mov %esp,%ebp 73: 53 push %ebx 74: 8b 45 08 mov 0x8(%ebp),%eax 77: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 7a: 89 c2 mov %eax,%edx 7c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 80: 83 c1 01 add $0x1,%ecx 83: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 87: 83 c2 01 add $0x1,%edx 8a: 84 db test %bl,%bl 8c: 88 5a ff mov %bl,-0x1(%edx) 8f: 75 ef jne 80 <strcpy+0x10> ; return os; } 91: 5b pop %ebx 92: 5d pop %ebp 93: c3 ret 94: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 9a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000a0 <strcmp>: int strcmp(const char *p, const char *q) { a0: 55 push %ebp a1: 89 e5 mov %esp,%ebp a3: 56 push %esi a4: 53 push %ebx a5: 8b 55 08 mov 0x8(%ebp),%edx a8: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) ab: 0f b6 02 movzbl (%edx),%eax ae: 0f b6 19 movzbl (%ecx),%ebx b1: 84 c0 test %al,%al b3: 75 1e jne d3 <strcmp+0x33> b5: eb 29 jmp e0 <strcmp+0x40> b7: 89 f6 mov %esi,%esi b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; c0: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) c3: 0f b6 02 movzbl (%edx),%eax p++, q++; c6: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) c9: 0f b6 59 01 movzbl 0x1(%ecx),%ebx cd: 84 c0 test %al,%al cf: 74 0f je e0 <strcmp+0x40> d1: 89 f1 mov %esi,%ecx d3: 38 d8 cmp %bl,%al d5: 74 e9 je c0 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; d7: 29 d8 sub %ebx,%eax } d9: 5b pop %ebx da: 5e pop %esi db: 5d pop %ebp dc: c3 ret dd: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) e0: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; e2: 29 d8 sub %ebx,%eax } e4: 5b pop %ebx e5: 5e pop %esi e6: 5d pop %ebp e7: c3 ret e8: 90 nop e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 000000f0 <strlen>: uint strlen(const char *s) { f0: 55 push %ebp f1: 89 e5 mov %esp,%ebp f3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) f6: 80 39 00 cmpb $0x0,(%ecx) f9: 74 12 je 10d <strlen+0x1d> fb: 31 d2 xor %edx,%edx fd: 8d 76 00 lea 0x0(%esi),%esi 100: 83 c2 01 add $0x1,%edx 103: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 107: 89 d0 mov %edx,%eax 109: 75 f5 jne 100 <strlen+0x10> ; return n; } 10b: 5d pop %ebp 10c: c3 ret uint strlen(const char *s) { int n; for(n = 0; s[n]; n++) 10d: 31 c0 xor %eax,%eax ; return n; } 10f: 5d pop %ebp 110: c3 ret 111: eb 0d jmp 120 <memset> 113: 90 nop 114: 90 nop 115: 90 nop 116: 90 nop 117: 90 nop 118: 90 nop 119: 90 nop 11a: 90 nop 11b: 90 nop 11c: 90 nop 11d: 90 nop 11e: 90 nop 11f: 90 nop 00000120 <memset>: void* memset(void *dst, int c, uint n) { 120: 55 push %ebp 121: 89 e5 mov %esp,%ebp 123: 57 push %edi 124: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 127: 8b 4d 10 mov 0x10(%ebp),%ecx 12a: 8b 45 0c mov 0xc(%ebp),%eax 12d: 89 d7 mov %edx,%edi 12f: fc cld 130: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 132: 89 d0 mov %edx,%eax 134: 5f pop %edi 135: 5d pop %ebp 136: c3 ret 137: 89 f6 mov %esi,%esi 139: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000140 <strchr>: char* strchr(const char *s, char c) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 53 push %ebx 144: 8b 45 08 mov 0x8(%ebp),%eax 147: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 14a: 0f b6 10 movzbl (%eax),%edx 14d: 84 d2 test %dl,%dl 14f: 74 1d je 16e <strchr+0x2e> if(*s == c) 151: 38 d3 cmp %dl,%bl 153: 89 d9 mov %ebx,%ecx 155: 75 0d jne 164 <strchr+0x24> 157: eb 17 jmp 170 <strchr+0x30> 159: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 160: 38 ca cmp %cl,%dl 162: 74 0c je 170 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 164: 83 c0 01 add $0x1,%eax 167: 0f b6 10 movzbl (%eax),%edx 16a: 84 d2 test %dl,%dl 16c: 75 f2 jne 160 <strchr+0x20> if(*s == c) return (char*)s; return 0; 16e: 31 c0 xor %eax,%eax } 170: 5b pop %ebx 171: 5d pop %ebp 172: c3 ret 173: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 179: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000180 <gets>: char* gets(char *buf, int max) { 180: 55 push %ebp 181: 89 e5 mov %esp,%ebp 183: 57 push %edi 184: 56 push %esi 185: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 186: 31 f6 xor %esi,%esi cc = read(0, &c, 1); 188: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { 18b: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 18e: eb 29 jmp 1b9 <gets+0x39> cc = read(0, &c, 1); 190: 83 ec 04 sub $0x4,%esp 193: 6a 01 push $0x1 195: 57 push %edi 196: 6a 00 push $0x0 198: e8 2d 01 00 00 call 2ca <read> if(cc < 1) 19d: 83 c4 10 add $0x10,%esp 1a0: 85 c0 test %eax,%eax 1a2: 7e 1d jle 1c1 <gets+0x41> break; buf[i++] = c; 1a4: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 1a8: 8b 55 08 mov 0x8(%ebp),%edx 1ab: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') 1ad: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1af: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 1b3: 74 1b je 1d0 <gets+0x50> 1b5: 3c 0d cmp $0xd,%al 1b7: 74 17 je 1d0 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1b9: 8d 5e 01 lea 0x1(%esi),%ebx 1bc: 3b 5d 0c cmp 0xc(%ebp),%ebx 1bf: 7c cf jl 190 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1c1: 8b 45 08 mov 0x8(%ebp),%eax 1c4: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1c8: 8d 65 f4 lea -0xc(%ebp),%esp 1cb: 5b pop %ebx 1cc: 5e pop %esi 1cd: 5f pop %edi 1ce: 5d pop %ebp 1cf: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d0: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1d3: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d5: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1d9: 8d 65 f4 lea -0xc(%ebp),%esp 1dc: 5b pop %ebx 1dd: 5e pop %esi 1de: 5f pop %edi 1df: 5d pop %ebp 1e0: c3 ret 1e1: eb 0d jmp 1f0 <stat> 1e3: 90 nop 1e4: 90 nop 1e5: 90 nop 1e6: 90 nop 1e7: 90 nop 1e8: 90 nop 1e9: 90 nop 1ea: 90 nop 1eb: 90 nop 1ec: 90 nop 1ed: 90 nop 1ee: 90 nop 1ef: 90 nop 000001f0 <stat>: int stat(const char *n, struct stat *st) { 1f0: 55 push %ebp 1f1: 89 e5 mov %esp,%ebp 1f3: 56 push %esi 1f4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1f5: 83 ec 08 sub $0x8,%esp 1f8: 6a 00 push $0x0 1fa: ff 75 08 pushl 0x8(%ebp) 1fd: e8 f0 00 00 00 call 2f2 <open> if(fd < 0) 202: 83 c4 10 add $0x10,%esp 205: 85 c0 test %eax,%eax 207: 78 27 js 230 <stat+0x40> return -1; r = fstat(fd, st); 209: 83 ec 08 sub $0x8,%esp 20c: ff 75 0c pushl 0xc(%ebp) 20f: 89 c3 mov %eax,%ebx 211: 50 push %eax 212: e8 f3 00 00 00 call 30a <fstat> 217: 89 c6 mov %eax,%esi close(fd); 219: 89 1c 24 mov %ebx,(%esp) 21c: e8 b9 00 00 00 call 2da <close> return r; 221: 83 c4 10 add $0x10,%esp 224: 89 f0 mov %esi,%eax } 226: 8d 65 f8 lea -0x8(%ebp),%esp 229: 5b pop %ebx 22a: 5e pop %esi 22b: 5d pop %ebp 22c: c3 ret 22d: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 230: b8 ff ff ff ff mov $0xffffffff,%eax 235: eb ef jmp 226 <stat+0x36> 237: 89 f6 mov %esi,%esi 239: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000240 <atoi>: return r; } int atoi(const char *s) { 240: 55 push %ebp 241: 89 e5 mov %esp,%ebp 243: 53 push %ebx 244: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 247: 0f be 11 movsbl (%ecx),%edx 24a: 8d 42 d0 lea -0x30(%edx),%eax 24d: 3c 09 cmp $0x9,%al 24f: b8 00 00 00 00 mov $0x0,%eax 254: 77 1f ja 275 <atoi+0x35> 256: 8d 76 00 lea 0x0(%esi),%esi 259: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 260: 8d 04 80 lea (%eax,%eax,4),%eax 263: 83 c1 01 add $0x1,%ecx 266: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 26a: 0f be 11 movsbl (%ecx),%edx 26d: 8d 5a d0 lea -0x30(%edx),%ebx 270: 80 fb 09 cmp $0x9,%bl 273: 76 eb jbe 260 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } 275: 5b pop %ebx 276: 5d pop %ebp 277: c3 ret 278: 90 nop 279: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000280 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 280: 55 push %ebp 281: 89 e5 mov %esp,%ebp 283: 56 push %esi 284: 53 push %ebx 285: 8b 5d 10 mov 0x10(%ebp),%ebx 288: 8b 45 08 mov 0x8(%ebp),%eax 28b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 28e: 85 db test %ebx,%ebx 290: 7e 14 jle 2a6 <memmove+0x26> 292: 31 d2 xor %edx,%edx 294: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 298: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 29c: 88 0c 10 mov %cl,(%eax,%edx,1) 29f: 83 c2 01 add $0x1,%edx char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 2a2: 39 da cmp %ebx,%edx 2a4: 75 f2 jne 298 <memmove+0x18> *dst++ = *src++; return vdst; } 2a6: 5b pop %ebx 2a7: 5e pop %esi 2a8: 5d pop %ebp 2a9: c3 ret 000002aa <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2aa: b8 01 00 00 00 mov $0x1,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <exit>: SYSCALL(exit) 2b2: b8 02 00 00 00 mov $0x2,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <wait>: SYSCALL(wait) 2ba: b8 03 00 00 00 mov $0x3,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <pipe>: SYSCALL(pipe) 2c2: b8 04 00 00 00 mov $0x4,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <read>: SYSCALL(read) 2ca: b8 05 00 00 00 mov $0x5,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <write>: SYSCALL(write) 2d2: b8 10 00 00 00 mov $0x10,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <close>: SYSCALL(close) 2da: b8 15 00 00 00 mov $0x15,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <kill>: SYSCALL(kill) 2e2: b8 06 00 00 00 mov $0x6,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <exec>: SYSCALL(exec) 2ea: b8 07 00 00 00 mov $0x7,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <open>: SYSCALL(open) 2f2: b8 0f 00 00 00 mov $0xf,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <mknod>: SYSCALL(mknod) 2fa: b8 11 00 00 00 mov $0x11,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <unlink>: SYSCALL(unlink) 302: b8 12 00 00 00 mov $0x12,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <fstat>: SYSCALL(fstat) 30a: b8 08 00 00 00 mov $0x8,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <link>: SYSCALL(link) 312: b8 13 00 00 00 mov $0x13,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <mkdir>: SYSCALL(mkdir) 31a: b8 14 00 00 00 mov $0x14,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <chdir>: SYSCALL(chdir) 322: b8 09 00 00 00 mov $0x9,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <dup>: SYSCALL(dup) 32a: b8 0a 00 00 00 mov $0xa,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <getpid>: SYSCALL(getpid) 332: b8 0b 00 00 00 mov $0xb,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <sbrk>: SYSCALL(sbrk) 33a: b8 0c 00 00 00 mov $0xc,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <sleep>: SYSCALL(sleep) 342: b8 0d 00 00 00 mov $0xd,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <uptime>: SYSCALL(uptime) 34a: b8 0e 00 00 00 mov $0xe,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <waitx>: SYSCALL(waitx) 352: b8 16 00 00 00 mov $0x16,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <chpr>: SYSCALL(chpr) 35a: b8 17 00 00 00 mov $0x17,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <getpinfo>: SYSCALL(getpinfo) 362: b8 18 00 00 00 mov $0x18,%eax 367: cd 40 int $0x40 369: c3 ret 36a: 66 90 xchg %ax,%ax 36c: 66 90 xchg %ax,%ax 36e: 66 90 xchg %ax,%ax 00000370 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 370: 55 push %ebp 371: 89 e5 mov %esp,%ebp 373: 57 push %edi 374: 56 push %esi 375: 53 push %ebx 376: 89 c6 mov %eax,%esi 378: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 37b: 8b 5d 08 mov 0x8(%ebp),%ebx 37e: 85 db test %ebx,%ebx 380: 74 7e je 400 <printint+0x90> 382: 89 d0 mov %edx,%eax 384: c1 e8 1f shr $0x1f,%eax 387: 84 c0 test %al,%al 389: 74 75 je 400 <printint+0x90> neg = 1; x = -xx; 38b: 89 d0 mov %edx,%eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; 38d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) x = -xx; 394: f7 d8 neg %eax 396: 89 75 c0 mov %esi,-0x40(%ebp) } else { x = xx; } i = 0; 399: 31 ff xor %edi,%edi 39b: 8d 5d d7 lea -0x29(%ebp),%ebx 39e: 89 ce mov %ecx,%esi 3a0: eb 08 jmp 3aa <printint+0x3a> 3a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 3a8: 89 cf mov %ecx,%edi 3aa: 31 d2 xor %edx,%edx 3ac: 8d 4f 01 lea 0x1(%edi),%ecx 3af: f7 f6 div %esi 3b1: 0f b6 92 40 07 00 00 movzbl 0x740(%edx),%edx }while((x /= base) != 0); 3b8: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 3ba: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 3bd: 75 e9 jne 3a8 <printint+0x38> if(neg) 3bf: 8b 45 c4 mov -0x3c(%ebp),%eax 3c2: 8b 75 c0 mov -0x40(%ebp),%esi 3c5: 85 c0 test %eax,%eax 3c7: 74 08 je 3d1 <printint+0x61> buf[i++] = '-'; 3c9: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1) 3ce: 8d 4f 02 lea 0x2(%edi),%ecx 3d1: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi 3d5: 8d 76 00 lea 0x0(%esi),%esi 3d8: 0f b6 07 movzbl (%edi),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 3db: 83 ec 04 sub $0x4,%esp 3de: 83 ef 01 sub $0x1,%edi 3e1: 6a 01 push $0x1 3e3: 53 push %ebx 3e4: 56 push %esi 3e5: 88 45 d7 mov %al,-0x29(%ebp) 3e8: e8 e5 fe ff ff call 2d2 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 3ed: 83 c4 10 add $0x10,%esp 3f0: 39 df cmp %ebx,%edi 3f2: 75 e4 jne 3d8 <printint+0x68> putc(fd, buf[i]); } 3f4: 8d 65 f4 lea -0xc(%ebp),%esp 3f7: 5b pop %ebx 3f8: 5e pop %esi 3f9: 5f pop %edi 3fa: 5d pop %ebp 3fb: c3 ret 3fc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; } else { x = xx; 400: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 402: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 409: eb 8b jmp 396 <printint+0x26> 40b: 90 nop 40c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000410 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 410: 55 push %ebp 411: 89 e5 mov %esp,%ebp 413: 57 push %edi 414: 56 push %esi 415: 53 push %ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 416: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 419: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 41c: 8b 75 0c mov 0xc(%ebp),%esi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 41f: 8b 7d 08 mov 0x8(%ebp),%edi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 422: 89 45 d0 mov %eax,-0x30(%ebp) 425: 0f b6 1e movzbl (%esi),%ebx 428: 83 c6 01 add $0x1,%esi 42b: 84 db test %bl,%bl 42d: 0f 84 b0 00 00 00 je 4e3 <printf+0xd3> 433: 31 d2 xor %edx,%edx 435: eb 39 jmp 470 <printf+0x60> 437: 89 f6 mov %esi,%esi 439: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 440: 83 f8 25 cmp $0x25,%eax 443: 89 55 d4 mov %edx,-0x2c(%ebp) state = '%'; 446: ba 25 00 00 00 mov $0x25,%edx state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 44b: 74 18 je 465 <printf+0x55> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 44d: 8d 45 e2 lea -0x1e(%ebp),%eax 450: 83 ec 04 sub $0x4,%esp 453: 88 5d e2 mov %bl,-0x1e(%ebp) 456: 6a 01 push $0x1 458: 50 push %eax 459: 57 push %edi 45a: e8 73 fe ff ff call 2d2 <write> 45f: 8b 55 d4 mov -0x2c(%ebp),%edx 462: 83 c4 10 add $0x10,%esp 465: 83 c6 01 add $0x1,%esi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 468: 0f b6 5e ff movzbl -0x1(%esi),%ebx 46c: 84 db test %bl,%bl 46e: 74 73 je 4e3 <printf+0xd3> c = fmt[i] & 0xff; if(state == 0){ 470: 85 d2 test %edx,%edx uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; 472: 0f be cb movsbl %bl,%ecx 475: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 478: 74 c6 je 440 <printf+0x30> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 47a: 83 fa 25 cmp $0x25,%edx 47d: 75 e6 jne 465 <printf+0x55> if(c == 'd'){ 47f: 83 f8 64 cmp $0x64,%eax 482: 0f 84 f8 00 00 00 je 580 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 488: 81 e1 f7 00 00 00 and $0xf7,%ecx 48e: 83 f9 70 cmp $0x70,%ecx 491: 74 5d je 4f0 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 493: 83 f8 73 cmp $0x73,%eax 496: 0f 84 84 00 00 00 je 520 <printf+0x110> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 49c: 83 f8 63 cmp $0x63,%eax 49f: 0f 84 ea 00 00 00 je 58f <printf+0x17f> putc(fd, *ap); ap++; } else if(c == '%'){ 4a5: 83 f8 25 cmp $0x25,%eax 4a8: 0f 84 c2 00 00 00 je 570 <printf+0x160> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4ae: 8d 45 e7 lea -0x19(%ebp),%eax 4b1: 83 ec 04 sub $0x4,%esp 4b4: c6 45 e7 25 movb $0x25,-0x19(%ebp) 4b8: 6a 01 push $0x1 4ba: 50 push %eax 4bb: 57 push %edi 4bc: e8 11 fe ff ff call 2d2 <write> 4c1: 83 c4 0c add $0xc,%esp 4c4: 8d 45 e6 lea -0x1a(%ebp),%eax 4c7: 88 5d e6 mov %bl,-0x1a(%ebp) 4ca: 6a 01 push $0x1 4cc: 50 push %eax 4cd: 57 push %edi 4ce: 83 c6 01 add $0x1,%esi 4d1: e8 fc fd ff ff call 2d2 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4d6: 0f b6 5e ff movzbl -0x1(%esi),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4da: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4dd: 31 d2 xor %edx,%edx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4df: 84 db test %bl,%bl 4e1: 75 8d jne 470 <printf+0x60> putc(fd, c); } state = 0; } } } 4e3: 8d 65 f4 lea -0xc(%ebp),%esp 4e6: 5b pop %ebx 4e7: 5e pop %esi 4e8: 5f pop %edi 4e9: 5d pop %ebp 4ea: c3 ret 4eb: 90 nop 4ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 4f0: 83 ec 0c sub $0xc,%esp 4f3: b9 10 00 00 00 mov $0x10,%ecx 4f8: 6a 00 push $0x0 4fa: 8b 5d d0 mov -0x30(%ebp),%ebx 4fd: 89 f8 mov %edi,%eax 4ff: 8b 13 mov (%ebx),%edx 501: e8 6a fe ff ff call 370 <printint> ap++; 506: 89 d8 mov %ebx,%eax 508: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 50b: 31 d2 xor %edx,%edx if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; 50d: 83 c0 04 add $0x4,%eax 510: 89 45 d0 mov %eax,-0x30(%ebp) 513: e9 4d ff ff ff jmp 465 <printf+0x55> 518: 90 nop 519: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; 520: 8b 45 d0 mov -0x30(%ebp),%eax 523: 8b 18 mov (%eax),%ebx ap++; 525: 83 c0 04 add $0x4,%eax 528: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) s = "(null)"; 52b: b8 39 07 00 00 mov $0x739,%eax 530: 85 db test %ebx,%ebx 532: 0f 44 d8 cmove %eax,%ebx while(*s != 0){ 535: 0f b6 03 movzbl (%ebx),%eax 538: 84 c0 test %al,%al 53a: 74 23 je 55f <printf+0x14f> 53c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 540: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 543: 8d 45 e3 lea -0x1d(%ebp),%eax 546: 83 ec 04 sub $0x4,%esp 549: 6a 01 push $0x1 ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; 54b: 83 c3 01 add $0x1,%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 54e: 50 push %eax 54f: 57 push %edi 550: e8 7d fd ff ff call 2d2 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 555: 0f b6 03 movzbl (%ebx),%eax 558: 83 c4 10 add $0x10,%esp 55b: 84 c0 test %al,%al 55d: 75 e1 jne 540 <printf+0x130> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 55f: 31 d2 xor %edx,%edx 561: e9 ff fe ff ff jmp 465 <printf+0x55> 566: 8d 76 00 lea 0x0(%esi),%esi 569: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 570: 83 ec 04 sub $0x4,%esp 573: 88 5d e5 mov %bl,-0x1b(%ebp) 576: 8d 45 e5 lea -0x1b(%ebp),%eax 579: 6a 01 push $0x1 57b: e9 4c ff ff ff jmp 4cc <printf+0xbc> } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 580: 83 ec 0c sub $0xc,%esp 583: b9 0a 00 00 00 mov $0xa,%ecx 588: 6a 01 push $0x1 58a: e9 6b ff ff ff jmp 4fa <printf+0xea> 58f: 8b 5d d0 mov -0x30(%ebp),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 592: 83 ec 04 sub $0x4,%esp 595: 8b 03 mov (%ebx),%eax 597: 6a 01 push $0x1 599: 88 45 e4 mov %al,-0x1c(%ebp) 59c: 8d 45 e4 lea -0x1c(%ebp),%eax 59f: 50 push %eax 5a0: 57 push %edi 5a1: e8 2c fd ff ff call 2d2 <write> 5a6: e9 5b ff ff ff jmp 506 <printf+0xf6> 5ab: 66 90 xchg %ax,%ax 5ad: 66 90 xchg %ax,%ax 5af: 90 nop 000005b0 <free>: static Header base; static Header *freep; void free(void *ap) { 5b0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5b1: a1 e4 09 00 00 mov 0x9e4,%eax static Header base; static Header *freep; void free(void *ap) { 5b6: 89 e5 mov %esp,%ebp 5b8: 57 push %edi 5b9: 56 push %esi 5ba: 53 push %ebx 5bb: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5be: 8b 10 mov (%eax),%edx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 5c0: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5c3: 39 c8 cmp %ecx,%eax 5c5: 73 19 jae 5e0 <free+0x30> 5c7: 89 f6 mov %esi,%esi 5c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 5d0: 39 d1 cmp %edx,%ecx 5d2: 72 1c jb 5f0 <free+0x40> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5d4: 39 d0 cmp %edx,%eax 5d6: 73 18 jae 5f0 <free+0x40> static Header base; static Header *freep; void free(void *ap) { 5d8: 89 d0 mov %edx,%eax Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5da: 39 c8 cmp %ecx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5dc: 8b 10 mov (%eax),%edx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5de: 72 f0 jb 5d0 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5e0: 39 d0 cmp %edx,%eax 5e2: 72 f4 jb 5d8 <free+0x28> 5e4: 39 d1 cmp %edx,%ecx 5e6: 73 f0 jae 5d8 <free+0x28> 5e8: 90 nop 5e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi break; if(bp + bp->s.size == p->s.ptr){ 5f0: 8b 73 fc mov -0x4(%ebx),%esi 5f3: 8d 3c f1 lea (%ecx,%esi,8),%edi 5f6: 39 d7 cmp %edx,%edi 5f8: 74 19 je 613 <free+0x63> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 5fa: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 5fd: 8b 50 04 mov 0x4(%eax),%edx 600: 8d 34 d0 lea (%eax,%edx,8),%esi 603: 39 f1 cmp %esi,%ecx 605: 74 23 je 62a <free+0x7a> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 607: 89 08 mov %ecx,(%eax) freep = p; 609: a3 e4 09 00 00 mov %eax,0x9e4 } 60e: 5b pop %ebx 60f: 5e pop %esi 610: 5f pop %edi 611: 5d pop %ebp 612: c3 ret bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 613: 03 72 04 add 0x4(%edx),%esi 616: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 619: 8b 10 mov (%eax),%edx 61b: 8b 12 mov (%edx),%edx 61d: 89 53 f8 mov %edx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 620: 8b 50 04 mov 0x4(%eax),%edx 623: 8d 34 d0 lea (%eax,%edx,8),%esi 626: 39 f1 cmp %esi,%ecx 628: 75 dd jne 607 <free+0x57> p->s.size += bp->s.size; 62a: 03 53 fc add -0x4(%ebx),%edx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 62d: a3 e4 09 00 00 mov %eax,0x9e4 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 632: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 635: 8b 53 f8 mov -0x8(%ebx),%edx 638: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 63a: 5b pop %ebx 63b: 5e pop %esi 63c: 5f pop %edi 63d: 5d pop %ebp 63e: c3 ret 63f: 90 nop 00000640 <malloc>: return freep; } void* malloc(uint nbytes) { 640: 55 push %ebp 641: 89 e5 mov %esp,%ebp 643: 57 push %edi 644: 56 push %esi 645: 53 push %ebx 646: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 649: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 64c: 8b 15 e4 09 00 00 mov 0x9e4,%edx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 652: 8d 78 07 lea 0x7(%eax),%edi 655: c1 ef 03 shr $0x3,%edi 658: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 65b: 85 d2 test %edx,%edx 65d: 0f 84 a3 00 00 00 je 706 <malloc+0xc6> 663: 8b 02 mov (%edx),%eax 665: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 668: 39 cf cmp %ecx,%edi 66a: 76 74 jbe 6e0 <malloc+0xa0> 66c: 81 ff 00 10 00 00 cmp $0x1000,%edi 672: be 00 10 00 00 mov $0x1000,%esi 677: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx 67e: 0f 43 f7 cmovae %edi,%esi 681: ba 00 80 00 00 mov $0x8000,%edx 686: 81 ff ff 0f 00 00 cmp $0xfff,%edi 68c: 0f 46 da cmovbe %edx,%ebx 68f: eb 10 jmp 6a1 <malloc+0x61> 691: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 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){ 698: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 69a: 8b 48 04 mov 0x4(%eax),%ecx 69d: 39 cf cmp %ecx,%edi 69f: 76 3f jbe 6e0 <malloc+0xa0> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6a1: 39 05 e4 09 00 00 cmp %eax,0x9e4 6a7: 89 c2 mov %eax,%edx 6a9: 75 ed jne 698 <malloc+0x58> char *p; Header *hp; if(nu < 4096) nu = 4096; p = sbrk(nu * sizeof(Header)); 6ab: 83 ec 0c sub $0xc,%esp 6ae: 53 push %ebx 6af: e8 86 fc ff ff call 33a <sbrk> if(p == (char*)-1) 6b4: 83 c4 10 add $0x10,%esp 6b7: 83 f8 ff cmp $0xffffffff,%eax 6ba: 74 1c je 6d8 <malloc+0x98> return 0; hp = (Header*)p; hp->s.size = nu; 6bc: 89 70 04 mov %esi,0x4(%eax) free((void*)(hp + 1)); 6bf: 83 ec 0c sub $0xc,%esp 6c2: 83 c0 08 add $0x8,%eax 6c5: 50 push %eax 6c6: e8 e5 fe ff ff call 5b0 <free> return freep; 6cb: 8b 15 e4 09 00 00 mov 0x9e4,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 6d1: 83 c4 10 add $0x10,%esp 6d4: 85 d2 test %edx,%edx 6d6: 75 c0 jne 698 <malloc+0x58> return 0; 6d8: 31 c0 xor %eax,%eax 6da: eb 1c jmp 6f8 <malloc+0xb8> 6dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) 6e0: 39 cf cmp %ecx,%edi 6e2: 74 1c je 700 <malloc+0xc0> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 6e4: 29 f9 sub %edi,%ecx 6e6: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 6e9: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 6ec: 89 78 04 mov %edi,0x4(%eax) } freep = prevp; 6ef: 89 15 e4 09 00 00 mov %edx,0x9e4 return (void*)(p + 1); 6f5: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 6f8: 8d 65 f4 lea -0xc(%ebp),%esp 6fb: 5b pop %ebx 6fc: 5e pop %esi 6fd: 5f pop %edi 6fe: 5d pop %ebp 6ff: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 700: 8b 08 mov (%eax),%ecx 702: 89 0a mov %ecx,(%edx) 704: eb e9 jmp 6ef <malloc+0xaf> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 706: c7 05 e4 09 00 00 e8 movl $0x9e8,0x9e4 70d: 09 00 00 710: c7 05 e8 09 00 00 e8 movl $0x9e8,0x9e8 717: 09 00 00 base.s.size = 0; 71a: b8 e8 09 00 00 mov $0x9e8,%eax 71f: c7 05 ec 09 00 00 00 movl $0x0,0x9ec 726: 00 00 00 729: e9 3e ff ff ff jmp 66c <malloc+0x2c>
; ---------------------------------------------------------------- ; Z88DK INTERFACE LIBRARY FOR NIRVANA+ ENGINE - by Einar Saukas ; ; See "nirvana+.h" for further details ; ---------------------------------------------------------------- ; void NIRVANAP_drawW(unsigned char tile, unsigned char lin, unsigned char col) SECTION code_clib SECTION code_nirvanap PUBLIC _NIRVANAP_drawW EXTERN asm_NIRVANAP_drawW _NIRVANAP_drawW: ld hl,2 add hl,sp ld a,(hl) ; tile inc hl ld d,(hl) ; lin inc hl ld e,(hl) ; col jp asm_NIRVANAP_drawW
;/*------------------------------------------------------------*/ ;/* filename - tvwrit.asm */ ;/* */ ;/* function(s) */ ;/* TView write member functions */ ;/*------------------------------------------------------------*/ ; ; Turbo Vision - Version 2.0 ; ; Copyright (c) 1994 by Borland International ; All Rights Reserved. ; ifndef __FLAT__ PUBLIC @TView@writeLine$qssssnxv PUBLIC @TView@writeStr$qssnxcuc PUBLIC @TView@writeBuf$qssssnxv else PUBLIC @TView@writeLine$qsssspxv PUBLIC @TView@writeStr$qsspxcuc PUBLIC @TView@writeBuf$qsssspxv endif PUBLIC @TView@writeView$qv PUBLIC @TView@writeChar$qsscucs ifndef __FLAT__ EXTRN @THWMouse@show$qv : FAR EXTRN @THWMouse@hide$qv : FAR EXTRN @TView@mapColor$quc : FAR EXTRN @TEventQueue@mouseIntFlag : BYTE else EXTRN @THWMouse@show$qv : NEAR EXTRN @THWMouse@hide$qv : NEAR EXTRN @TView@mapColor$quc : NEAR EXTRN @THardwareInfo@screenWrite$qususpusul : NEAR endif EXTRN @TEventQueue@curMouse : WORD EXTRN @TScreen@screenBuffer : DWORD EXTRN @TScreen@checkSnow : BYTE EXTRN _shadowSize : WORD EXTRN _shadowAttr : BYTE INCLUDE TV.INC ifndef __FLAT__ Fptr STRUC offs DW ? segm DW ? Fptr ENDS else Fptr STRUC offs DD ? Fptr ENDS endif WriteArgs STRUC Self DD ? Target Fptr ? Buffer Fptr ? wOffset DW ? WriteArgs ENDS DATASEG wArgs WriteArgs ? IFDEF __FLAT__ EXTRN _MONOSEG:WORD EXTRN _COLRSEG:WORD ENDIF CODESEG ; Write to view ; In AX = Y coordinate ; BX = X coordinate ; CX = Count ; ES:(E)DI = Buffer Pointer @TView@writeView$qv PROC near ifndef __FLAT__ MOV [wArgs.wOffset], BX MOV [wArgs.Buffer.offs], DI MOV [wArgs.Buffer.segm], ES ADD CX, BX XOR DX, DX LES DI, [wArgs.Self] OR AX, AX JL @@3 CMP AX, ES:[DI+TViewSizeY] JGE @@3 OR BX, BX JGE @@1 XOR BX, BX @@1: CMP CX, ES:[DI+TViewSizeX] JLE @@2 MOV CX, ES:[DI+TViewSizeX] @@2: CMP BX, CX JL @@10 @@3: RETN @@10: TEST WORD PTR ES:[DI+TViewState], sfVisible JE @@3 CMP WORD PTR ES:[DI+TViewOwner+2], 0 JE @@3 MOV [wArgs.Target.offs], DI MOV [wArgs.Target.segm], ES ADD AX, ES:[DI+TViewOriginY] MOV SI, ES:[DI+TViewOriginX] ADD BX, SI ADD CX, SI ADD [wArgs.wOffset], SI LES DI, ES:[DI+TViewOwner] CMP AX, ES:[DI+TGroupClipAY] JL @@3 CMP AX, ES:[DI+TGroupClipBY] JGE @@3 CMP BX, ES:[DI+TGroupClipAX] JGE @@11 MOV BX, ES:[DI+TGroupClipAX] @@11: CMP CX, ES:[DI+TGroupClipBX] JLE @@12 MOV CX, ES:[DI+TGroupClipBX] @@12: CMP BX, CX JGE @@3 LES DI, ES:[DI+TGroupLast] @@20: LES DI, ES:[DI+TViewNext] CMP DI, [wArgs.Target.offs] JNE @@21 MOV SI, ES CMP SI, [wArgs.Target.segm] JNE @@21 JMP @@40 @@21: TEST WORD PTR ES:[DI+TViewState], sfVisible JE @@20 MOV SI, ES:[DI+TViewOriginY] CMP AX, SI JL @@20 ADD SI, ES:[DI+TViewSizeY] CMP AX, SI JL @@23 TEST WORD PTR ES:[DI+TViewState], sfShadow JE @@20 ADD SI, [_shadowSize+TPointY] CMP AX, SI JGE @@20 MOV SI, ES:[DI+TViewOriginX] ADD SI, [_shadowSize+TPointX] CMP BX, SI JGE @@22 CMP CX, SI JLE @@20 CALL @@30 @@22: ADD SI, ES:[DI+TViewSizeX] JMP @@26 @@23: MOV SI, ES:[DI+TViewOriginX] CMP BX, SI JGE @@24 CMP CX, SI JLE @@20 CALL @@30 @@24: ADD SI, ES:[DI+TViewSizeX] CMP BX, SI JGE @@25 CMP CX, SI JLE @@31 MOV BX, SI @@25: TEST WORD PTR ES:[DI+TViewState], sfShadow JE @@20 PUSH SI MOV SI, ES:[DI+TViewOriginY] ADD SI, [_shadowSize+TPointY] CMP AX, SI POP SI JL @@27 ADD SI, [_shadowSize+TPointX] @@26: CMP BX, SI JGE @@27 INC DX CMP CX, SI JLE @@27 CALL @@30 DEC DX @@27: JMP @@20 @@30: PUSH [wArgs.Target.segm] PUSH [wArgs.Target.offs] PUSH [wArgs.wOffset] PUSH ES PUSH DI PUSH SI PUSH DX PUSH CX PUSH AX MOV CX, SI CALL @@20 POP AX POP CX POP DX POP SI POP DI POP ES POP [wArgs.wOffset] POP [wArgs.Target.offs] POP [wArgs.Target.segm] MOV BX, SI @@31: RETN @@40: LES DI, ES:[DI+TViewOwner] MOV SI, ES:[DI+TGroupBuffer+2] OR SI, SI JE @@44 CMP SI, WORD PTR [@TScreen@screenBuffer+2] JE @@41 CALL @@50 JMP @@44 @@41: CLI CMP AX, WORD PTR [@TEventQueue@curMouse+MsEventWhereY] JNE @@42 CMP BX, WORD PTR [@TEventQueue@curMouse+MsEventWhereX] JA @@42 CMP CX, WORD PTR [@TEventQueue@curMouse+MsEventWhereX] JA @@43 @@42: MOV [@TEventQueue@mouseIntFlag], 0 STI CALL @@50 CMP [@TEventQueue@mouseIntFlag], 0 JE @@44 @@43: STI CALL @THWMouse@hide$qv CALL @@50 CALL @THWMouse@show$qv @@44: CMP BYTE PTR ES:[DI+TGroupLockFlag], 0 JNE @@31 JMP @@10 @@50: PUSH ES PUSH DS PUSH DI PUSH CX PUSH AX MUL BYTE PTR ES:[DI+TViewSizeX] ADD AX, BX SHL AX, 1 ADD AX, ES:[DI+TGroupBuffer] MOV DI, AX MOV ES, SI XOR AL, AL CMP SI, WORD PTR [@TScreen@screenBuffer+2] JNE @@51 MOV AL, [@TScreen@checkSnow] @@51: MOV AH, [_shadowAttr] SUB CX, BX MOV SI, BX SUB SI, [wArgs.wOffset] SHL SI, 1 ADD SI, [wArgs.Buffer.offs] MOV DS, [wArgs.Buffer.segm] CLD OR AL, AL JNE @@60 OR DX, DX JNE @@52 REP MOVSW JMP @@70 @@52: LODSB INC SI STOSW LOOP @@52 JMP @@70 @@60: PUSH DX PUSH BX OR DX, DX MOV DX, 03DAH JNE @@65 @@61: LODSW MOV BX, AX @@62: IN AL, DX TEST AL, 1 JNE @@62 CLI @@63: IN AL, DX TEST AL, 1 JE @@63 MOV AX, BX STOSW STI LOOP @@61 JMP @@68 @@65: LODSB MOV BL, AL INC SI @@66: IN AL, DX TEST AL, 1 JNE @@66 CLI @@67: IN AL, DX TEST AL, 1 JE @@67 MOV AL, BL STOSW STI LOOP @@65 @@68: POP BX POP DX @@70: MOV SI, ES POP AX POP CX POP DI POP DS POP ES RETN else ;;;;;;;;;;;;;;;;;;;;;;;;;; 32-bit version ;;;;;;;;;;;;;;;;;;;;;;;;;;; MOV [wArgs.wOffset], BX MOV [wArgs.Buffer.offs], EDI ADD CX, BX XOR DX, DX MOV EDI, [wArgs.Self] OR AX, AX JL @@3 CMP AX, [EDI+TViewSizeY] JGE @@3 OR BX, BX JGE @@1 XOR BX, BX @@1: CMP CX, [EDI+TViewSizeX] JLE @@2 MOV CX, [EDI+TViewSizeX] @@2: CMP BX, CX JL @@10 @@3: RETN @@10: TEST WORD PTR [EDI+TViewState], sfVisible JE @@3 CMP DWORD PTR [EDI+TViewOwner], 0 JE @@3 MOV [wArgs.Target.offs], EDI ADD AX, [EDI+TViewOriginY] MOV SI, [EDI+TViewOriginX] ADD BX, SI ADD CX, SI ADD [wArgs.wOffset], SI MOV EDI, [EDI+TViewOwner] CMP AX, [EDI+TGroupClipAY] JL @@3 CMP AX, [EDI+TGroupClipBY] JGE @@3 CMP BX, [EDI+TGroupClipAX] JGE @@11 MOV BX, [EDI+TGroupClipAX] @@11: CMP CX, [EDI+TGroupClipBX] JLE @@12 MOV CX, [EDI+TGroupClipBX] @@12: CMP BX, CX JGE @@3 MOV EDI, [EDI+TGroupLast] @@20: MOV EDI, [EDI+TViewNext] CMP EDI, [wArgs.Target.offs] JE @@40 @@21: TEST WORD PTR [EDI+TViewState], sfVisible JE @@20 MOV SI, [EDI+TViewOriginY] CMP AX, SI JL @@20 ADD SI, [EDI+TViewSizeY] CMP AX, SI JL @@23 TEST WORD PTR [EDI+TViewState], sfShadow JE @@20 ADD SI, [LARGE _shadowSize+TPointY] CMP AX, SI JGE @@20 MOV SI, [EDI+TViewOriginX] ADD SI, [LARGE _shadowSize+TPointX] CMP BX, SI JGE @@22 CMP CX, SI JLE @@20 CALL @@30 @@22: ADD SI, [EDI+TViewSizeX] JMP @@26 @@23: MOV SI, [EDI+TViewOriginX] CMP BX, SI JGE @@24 CMP CX, SI JLE @@20 CALL @@30 @@24: ADD SI, [EDI+TViewSizeX] CMP BX, SI JGE @@25 CMP CX, SI JLE @@31 MOV BX, SI @@25: TEST WORD PTR [EDI+TViewState], sfShadow JE @@20 PUSH SI MOV SI, [EDI+TViewOriginY] ADD SI, [LARGE _shadowSize+TPointY] CMP AX, SI POP SI JL @@27 ADD SI, [LARGE _shadowSize+TPointX] @@26: CMP BX, SI JGE @@27 INC DX CMP CX, SI JLE @@27 CALL @@30 DEC DX @@27: JMP @@20 @@30: PUSH [wArgs.Target.offs] PUSH DWORD PTR [wArgs.wOffset] PUSH EDI PUSH ESI PUSH EDX PUSH ECX PUSH EAX MOV CX, SI CALL @@20 POP EAX POP ECX POP EDX POP ESI POP EDI POP DWORD PTR [wArgs.wOffset] POP [wArgs.Target.offs] MOV BX, SI @@31: RETN @@40: MOV EDI, [EDI+TViewOwner] MOV ESI, [EDI+TGroupBuffer] OR ESI, ESI JE @@44 CMP ESI, DWORD PTR [@TScreen@screenBuffer] JE @@41 CALL @@50 JMP @@44 @@41: IFDEF HIDEMOUSE PUSHAD CALL @THWMouse@hide$qv POPAD ENDIF CALL @@50 IFDEF HIDEMOUSE PUSHAD CALL @THWMouse@show$qv POPAD ENDIF @@44: CMP BYTE PTR [EDI+TGroupLockFlag], 0 JNE @@31 JMP @@10 @@50: PUSH ESI PUSH EDI PUSH ECX PUSH EAX PUSH EAX MUL BYTE PTR [EDI+TViewSizeX] ADD AX, BX SHL AX, 1 MOVZX EDI, AX ADD EDI, ESI ; ESI = [EDI+TGroupBuffer] CMP ESI, DWORD PTR [@TScreen@screenBuffer] POP EAX JNE @@60 SUB CX, BX MOV SI, BX SUB SI, [wArgs.wOffset] SHL SI, 1 MOVZX ESI, SI ADD ESI, [wArgs.Buffer.offs] CLD PUSH EAX PUSH ECX PUSH EDI XOR AH, AH OR DX, DX JNE @@52 ;Expand character/attribute pair @@51: LODSB STOSW LODSB STOSW LOOP @@51 JMP @@54 ;Mix in shadow attribute @@52: PUSH EDX MOV DL, [_shadowAttr] @@53: LODSB STOSW MOV AL, DL INC ESI STOSW LOOP @@53 POP EDX @@54: POP EDI POP ECX POP EAX PUSHAD CALL @THardwareInfo@screenWrite$qususpusul, EBX, EAX, EDI, ECX POPAD JMP @@70 @@60: MOV AH, [LARGE _shadowAttr] SUB CX, BX MOV SI, BX SUB SI, [wArgs.wOffset] SHL SI, 1 MOVZX ESI, SI ADD ESI, [wArgs.Buffer.offs] CLD OR DX, DX JNE @@61 MOV EDX, ECX SHR ECX, 1 REP MOVSD MOV ECX, EDX AND ECX, 01H REP MOVSW XOR EDX, EDX JMP @@70 @@61: LODSB INC ESI STOSW LOOP @@61 @@70: POP EAX POP ECX POP EDI POP ESI RETN endif ENDP ifndef __FLAT__ @TView@writeBuf$qssssnxv PROC else @TView@writeBuf$qsssspxv PROC endif ARG thisPtr:PTR, X:ARGINT, Y:ARGINT, W:ARGINT, H:ARGINT, Buf:PTR ifndef __FLAT__ USES SI, DI MOV AX, WORD PTR [thisPtr] MOV WORD PTR [wArgs.Self], AX MOV AX, WORD PTR [thisPtr+2] MOV [(WORD PTR wArgs.Self)+2], AX CMP [H], 0 JLE @@2 @@1: MOV AX, [Y] MOV BX, [X] MOV CX, [W] LES DI, [Buf] CALL @TView@writeView$qv MOV AX, [W] SHL AX, 1 ADD WORD PTR [Buf], AX INC [Y] DEC [H] JNE @@1 @@2: RET else ;;;;;;;;;;;;;;;;;;;;;;;;;; 32-bit version ;;;;;;;;;;;;;;;;;;;;;;;;;;; USES EBX, ESI, EDI XOR EAX, EAX MOV WORD PTR [X+2], AX MOV WORD PTR [Y+2], AX MOV WORD PTR [W+2], AX MOV WORD PTR [H+2], AX MOV EAX, DWORD PTR [thisPtr] MOV [wArgs.Self], EAX CMP [H], 0 JLE @@2 @@1: MOV EAX, [Y] MOV EBX, [X] MOV ECX, [W] MOV EDI, DWORD PTR [Buf] @@4: CALL @TView@writeView$qv MOV EAX, [W] SHL EAX, 1 ADD DWORD PTR [Buf], EAX INC [Y] DEC [H] JNE @@1 @@2: RET endif ENDP @TView@writeChar$qsscucs PROC ARG thisPtr:PTR, X:ARGINT, Y:ARGINT, C:ARGINT, Color:ARGINT, \ Count : ARGINT ifndef __FLAT__ USES SI, DI MOV AX, WORD PTR [thisPtr] MOV WORD PTR [wArgs.Self], AX MOV AX, WORD PTR [thisPtr+2] MOV [(WORD PTR wArgs.Self)+2], AX PUSH WORD PTR [Color] PUSH WORD PTR [thisPtr+2] PUSH WORD PTR [thisPtr] CALL @TView@mapColor$quc ADD SP, 6 MOV AH, AL MOV AL, BYTE PTR [ C] MOV CX, [Count] OR CX, CX JLE @@2 CMP CX, 256 JLE @@1 MOV CX, 256 @@1: MOV DI, CX SHL DI, 1 SUB SP, DI PUSH DI MOV DI, SP ADD DI, 2 PUSH SS POP ES MOV DX, CX CLD REP STOSW MOV CX, DX MOV DI, SP ADD DI, 2 MOV AX, [Y] MOV BX, [X] CALL @TView@writeView$qv POP DI ADD SP, DI @@2: RET else ;;;;;;;;;;;;;;;;;;;;;;;;;; 32-bit version ;;;;;;;;;;;;;;;;;;;;;;;;;;; USES EBX, ESI, EDI XOR EAX, EAX MOV WORD PTR [X+2], AX MOV WORD PTR [Y+2], AX MOV WORD PTR [C+2], AX MOV WORD PTR [Color+2], AX MOV WORD PTR [Count+2], AX MOV EAX, DWORD PTR [thisPtr] MOV [wArgs.Self], EAX CALL @TView@mapColor$quc, [thisPtr], [Color] MOV AH, AL MOV AL, BYTE PTR [C] PUSH AX PUSH AX POP EAX MOV ECX, [Count] OR ECX, ECX JLE @@2 CMP ECX, 256 JLE @@1 MOV ECX, 256 @@1: MOV EDI, ECX SHL EDI, 1 SUB ESP, EDI PUSH EDI MOV EDI, ESP ADD EDI, 4 MOV EDX, ECX CLD SHR ECX, 1 REP STOSD MOV ECX, EDX AND ECX, 01H REP STOSW MOV ECX, EDX MOV EDI, ESP ADD EDI, 4 MOV EAX, [Y] MOV EBX, [X] CALL @TView@writeView$qv POP EDI ADD ESP, EDI @@2: RET endif ENDP ifndef __FLAT__ @TView@writeLine$qssssnxv PROC else @TView@writeLine$qsssspxv PROC endif ARG thisPtr:PTR, X:ARGINT, Y:ARGINT, W:ARGINT, H:ARGINT, \ Buf : PTR ifndef __FLAT__ USES SI, DI MOV AX, WORD PTR [thisPtr] MOV WORD PTR [wArgs.Self], AX MOV AX, WORD PTR [thisPtr+2] MOV [(WORD PTR wArgs.Self)+2], AX CMP [H], 0 JLE @@2 @@1: MOV AX, [Y] MOV BX, [X] MOV CX, [W] LES DI, [Buf] CALL @TView@writeView$qv INC [Y] DEC [H] JNE @@1 @@2: RET else ;;;;;;;;;;;;;;;;;;;;;;;;;; 32-bit version ;;;;;;;;;;;;;;;;;;;;;;;;;;; USES EBX, ESI, EDI XOR EAX, EAX MOV WORD PTR [X+2], AX MOV WORD PTR [Y+2], AX MOV WORD PTR [W+2], AX MOV WORD PTR [H+2], AX MOV EAX, DWORD PTR [thisPtr] MOV [wArgs.Self], EAX CMP [H], 0 JLE @@2 @@1: MOV EAX, [Y] MOV EBX, [X] MOV ECX, [W] MOV EDI, DWORD PTR [Buf] CALL @TView@writeView$qv INC [Y] DEC [H] JNE @@1 @@2: RET endif ENDP ifndef __FLAT__ @TView@writeStr$qssnxcuc PROC else @TView@writeStr$qsspxcuc PROC endif ARG thisPtr:PTR, X:ARGINT, Y:ARGINT, Strng:PTR, Color:ARGINT LOCAL ssize : ARGINT ifndef __FLAT__ USES SI, DI MOV AX, WORD PTR [thisPtr] MOV WORD PTR [wArgs.Self], AX MOV AX, WORD PTR [thisPtr+2] MOV [(WORD PTR wArgs.Self)+2], AX MOV DI, WORD PTR [Strng] OR DI, WORD PTR [Strng+2] JZ @@2 LES DI, [Strng] XOR AX, AX CLD MOV CX, 0FFFFh REPNE SCASB XCHG AX, CX NOT AX DEC AX CMP AX, 0 JE @@2 ; don't write zero length string MOV SI, AX ; save char count SHL AX, 1 SUB SP, AX ; make room for attributed string MOV [ssize], AX PUSH WORD PTR [Color] PUSH WORD PTR [thisPtr+2] PUSH WORD PTR [thisPtr] CALL @TView@mapColor$quc ADD SP, 6 MOV AH, AL ; attribute into AH MOV CX, SI ; char count into CX MOV BX, DS LDS SI, [Strng] MOV DI, SP PUSH SS POP ES MOV DX, CX @@1: LODSB STOSW LOOP @@1 MOV DS, BX MOV CX, DX MOV DI, SP MOV AX, [Y] MOV BX, [X] CALL @TView@writeView$qv ADD SP, [ssize] JMP @@2 @@3: MOV DS, BX @@2: RET else ;;;;;;;;;;;;;;;;;;;;;;;;;; 32-bit version ;;;;;;;;;;;;;;;;;;;;;;;;;;; USES EBX, ESI, EDI XOR EAX, EAX MOV WORD PTR [X+2], AX MOV WORD PTR [Y+2], AX MOV WORD PTR [Color+2], AX MOV WORD PTR [ssize+2], AX MOV EAX, DWORD PTR [thisPtr] MOV DWORD PTR[ wArgs.Self], EAX MOV EDI, DWORD PTR[ Strng] OR EDI, EDI JZ @@2 XOR EAX, EAX CLD MOV ECX, -1 REPNE SCASB XCHG EAX, ECX NOT EAX DEC EAX OR EAX, EAX JZ @@2 ; don't write zero length string MOV ESI, EAX ; save char count INC EAX SHR EAX, 1 SHL EAX, 2 SUB ESP, EAX ; make room for attributed string MOV [ssize], EAX CALL @TView@mapColor$quc, [thisPtr], [Color] MOV AH, AL ; attribute into AH MOV ECX, ESI ; char count into CX MOV ESI, DWORD PTR [Strng] MOV EDI, ESP MOV EDX, ECX @@1: LODSB STOSW LOOP @@1 MOV ECX, EDX MOV EDI, ESP MOV EAX, [Y] MOV EBX, [X] CALL @TView@writeView$qv ADD ESP, [ssize] @@2: RET endif ENDP END
; Q68 Receive data from port  2000 Tony Tebby ;  2017 W. Lenerz ; this just takes a byte out of the hardware FIFO and puts it into ; the SER input queue section spp xdef spp_rxser xref iob_pbyt xref iob_room xref iob_eof include 'dev8_keys_q68' include 'dev8_keys_serparprt' ;+++ ; Receive data from port ; ; d1 c s port number ; ;--- rxregs reg d0/d1/d3/a1/a2/a3 spp_rxser btst #q68..rxmpty,uart_status ; receive buffer empty? bne.s srxp_exit ; yes, done -> move.b uart_rxdata,d1 ; always get data move.l q68_ser_link,a3 tst.b spd_iact(a3) ; is input active? beq.s srxp_exit ; no nothing to get, then : bye -> move.l spd_ibuf(a3),d0 ; input queue ble.s srxp_exit ; there is none -> move.l d0,a2 jsr iob_room ; room left move.l d0,d3 ble.s srxp_noinput ; =0: no room left - disable input cmp.l #15,d3 ; not more than 16 bytes a pop blt.s srxp_loop moveq #14,d3 bra.s rx_chk srxp_loop move.b uart_rxdata,d1 ; get data ; now check for CTRL Z etc rx_chk move.b spb_fz(a2),d0 ; <FF> or CTRL Z subq.b #1,d0 ble.s srxp_ckcr ; ... not CTRL Z move.b d1,d0 tst.b spb_prty(a2) ; parity? beq.s srxp_ckcz ; ... no bclr #7,d0 ; ... ignore it srxp_ckcz cmp.b #26,d0 ; is it CTRL Z? bne.s srxp_ckcr jsr iob_eof ; mark end of file st spd_ibuf(a3) ; no input buffer pointer now bra.s srxp_noinput srxp_ckcr move.b spb_cr(a2),d0 ; cr to lf? beq.s srxp_pbyt ; ... no cmp.b d0,d1 ; cr? bne.s srxp_pbyt ; ... no move.b spb_lf(a2),d1 ; ... yes beq.s srxp_eloop ; cr ignored srxp_pbyt jsr iob_pbyt ; put byte in buffer srxp_eloop move.b uart_status,d1 ; ser port status andi.b #q68.rxand,d1 ; receive buffer empty ? bne.s srxp_exit dbf d3,srxp_loop srxp_exit rts srxp_noinput sf spd_iact(a3) ; inactivate input rts spp_rxend end
;=========================================================================== ; Print.asm ;--------------------------------------------------------------------------- ; Assembly x86 library ; ; ; Author: Ahmed Hussein ; Created: ; ; ; This file provide some Procedures for printing text on the screen ; All procedures provided works on top of Interrupt 10H ; ; Procedures included: ; * PrintString ; * PrintStringVGA ; ;=========================================================================== ;----------------------------------------------------- ; PrintString ;----------------------------------------------------- ; Prints a string with a certain color in text mode ; Prints new line whenever it reaches screen limit, where the ; new line starts from the same X-coordinate. ; ; @param BH = Display page ; @param DH = Row position where string is to be written ; @param DL = Column position where string is to be written ; @param SI = Offset of the string ; @param CX = Length of the string ; @param BL = Pixel Color ; ; BL = |7|6|5|4|3|2|1|0| ; | | | | | | | |___ B Foreground ; | | | | | | |_____ G Foreground ; | | | | | |_______ R Foreground ; | | | | |_________ Intensity Foreground ; | | | |___________ B Background ; | | |_____________ G Background ; | |_______________ R Background ; |_________________ Blinking Background ; ; Examples: 00FH --> White on black background ; 0FAH --> Green on white blinking ; ; ;----------------------------------------------------- PrintString PROC PUSHA MOV DI, DX CMP CX, 00 JE @@PrintStringRet @@PrintChar: PUSH CX MOV AH,2 INT 10H ;Setting cursor MOV AL, [SI] INC SI MOV CX, 1 ;Print character once MOV AH, 9 INT 10H ;Printing character INC DL ;Increment cursor position CMP DL, GX_TEXT_MODE_COL JB @@SameLine MOV DX, DI INC DH MOV DI, DX @@SameLine: POP CX DEC CX JNZ @@PrintChar @@PrintStringRet:POPA RET PrintString ENDP ;----------------------------------------------------- ; PrintStringVGA ;----------------------------------------------------- ; Prints a string with a certain color on graphics mode. ; This procedure translate coordinates from graphics mode to text mode ; to print string in the intented position. ; The resulted coordinates may not be as accurate as needed. ; ; @param BH = Display page ; @param SI = Offset of the string ; @param AX = Length of the string ; @param CX = X-coordinate ; @param DX = Y-coordinate ; @param BL = Pixel Color ; ;----------------------------------------------------- PrintStringVGA PROC PUSH AX ; Translating coordinates from graphics mode to text mode TranslateNumber_M DX, GX_ScreenHeight, GX_TEXT_MODE_ROW MOV DH, AL TranslateNumber_M CX, GX_ScreenWidth, GX_TEXT_MODE_COL MOV DL, AL POP CX ;Pop string length in CX CALL PrintString RET PrintStringVGA ENDP ;=========================================================================== ; Macro wrappers ;=========================================================================== PrintString_M MACRO DispPage, StringLength, RowPos, ColumnPos, Color, PointerToString PUSHA MOV BH, DispPage MOV CX, StringLength MOV DL, ColumnPos MOV DH, RowPos MOV BL, Color MOV SI, PointerToString CALL PrintString POPA ENDM PrintString_M PrintStringVGA_M MACRO DispPage, StringLength, Xcoordinate, Ycoordinate, Color, PointerToString PUSHA MOV BH, DispPage MOV CX, Xcoordinate MOV DX, Ycoordinate MOV AX, StringLength MOV BL, Color MOV SI, PointerToString CALL PrintStringVGA POPA ENDM PrintStringVGA_M
; A288707: 0-limiting word of the mapping 00->1000, 10->00, starting with 00. ; 0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0 mov $2,$0 mov $4,2 lpb $4 mov $0,$2 sub $4,1 add $0,$4 sub $0,1 div $0,2 max $0,0 seq $0,189663 ; Partial sums of A189661. mov $3,$0 mov $5,$4 mul $5,$0 add $1,$5 lpe min $2,1 mul $2,$3 sub $1,$2 mov $0,$1
; *************************************************************************** ; *************************************************************************** ; ; lzsa2_6502.s ; ; NMOS 6502 decompressor for data stored in Emmanuel Marty's LZSA2 format. ; ; This code is written for the ACME assembler. ; ; The code is 241 bytes for the small version, and 256 bytes for the normal. ; ; Copyright John Brandwood 2021. ; ; 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) ; ; *************************************************************************** ; *************************************************************************** ; *************************************************************************** ; *************************************************************************** ; ; Decompression Options & Macros ; ; ; Choose size over decompression speed (within sane limits)? ; LZSA_SMALL_SIZE = 0 ; *************************************************************************** ; *************************************************************************** ; ; Data usage is last 11 bytes of zero-page. ; lzsa_length = lzsa_winptr ; 1 word. lzsa_cmdbuf = $F5 ; 1 byte. lzsa_nibflg = $F6 ; 1 byte. lzsa_nibble = $F7 ; 1 byte. lzsa_offset = $F8 ; 1 word. lzsa_winptr = $FA ; 1 word. lzsa_srcptr = $FC ; 1 word. lzsa_dstptr = $FE ; 1 word. lzsa_length = lzsa_winptr ; 1 word. LZSA_SRC_LO = $FC LZSA_SRC_HI = $FD LZSA_DST_LO = $FE LZSA_DST_HI = $FF ; *************************************************************************** ; *************************************************************************** ; ; lzsa2_unpack - Decompress data stored in Emmanuel Marty's LZSA2 format. ; ; Args: lzsa_srcptr = ptr to compessed data ; Args: lzsa_dstptr = ptr to output buffer ; DECOMPRESS_LZSA2_FAST: lzsa2_unpack: ldx #$00 ; Hi-byte of length or offset. ldy #$00 ; Initialize source index. sty <lzsa_nibflg ; Initialize nibble buffer. ; ; Copy bytes from compressed source data. ; ; N.B. X=0 is expected and guaranteed when we get here. ; .cp_length: !if LZSA_SMALL_SIZE { jsr .get_byte } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 bne .cp_skip0 inc <lzsa_srcptr + 1 } .cp_skip0: sta <lzsa_cmdbuf ; Preserve this for later. and #$18 ; Extract literal length. beq .lz_offset ; Skip directly to match? lsr ; Get 2-bit literal length. lsr lsr cmp #$03 ; Extended length? bcc .cp_got_len jsr .get_length ; X=0 for literals, returns CC. stx .cp_npages + 1 ; Hi-byte of length. .cp_got_len: tax ; Lo-byte of length. .cp_byte: lda (lzsa_srcptr),y ; CC throughout the execution of sta (lzsa_dstptr),y ; of this .cp_page loop. inc <lzsa_srcptr + 0 bne .cp_skip1 inc <lzsa_srcptr + 1 .cp_skip1: inc <lzsa_dstptr + 0 bne .cp_skip2 inc <lzsa_dstptr + 1 .cp_skip2: dex bne .cp_byte .cp_npages: lda #0 ; Any full pages left to copy? beq .lz_offset dec .cp_npages + 1 ; Unlikely, so can be slow. bcc .cp_byte ; Always true! ; ; Copy bytes from decompressed window. ; ; N.B. X=0 is expected and guaranteed when we get here. ; ; xyz ; =========================== ; 00z 5-bit offset ; 01z 9-bit offset ; 10z 13-bit offset ; 110 16-bit offset ; 111 repeat offset ; .lz_offset: lda <lzsa_cmdbuf asl bcs .get_13_16_rep .get_5_9_bits: dex ; X=$FF for a 5-bit offset. asl bcs .get_9_bits ; Fall through if 5-bit. .get_13_bits: asl ; Both 5-bit and 13-bit read php ; a nibble. jsr .get_nibble plp rol ; Shift into position, clr C. eor #$E1 cpx #$00 ; X=$FF for a 5-bit offset. bne .set_offset sbc #2 ; 13-bit offset from $FE00. bne .set_hi_8 ; Always NZ from previous SBC. .get_9_bits: asl ; X=$FF if CC, X=$FE if CS. bcc .get_lo_8 dex bcs .get_lo_8 ; Always CS from previous BCC. .get_13_16_rep: asl bcc .get_13_bits ; Shares code with 5-bit path. .get_16_rep: bmi .lz_length ; Repeat previous offset. .get_16_bits: jsr .get_byte ; Get hi-byte of offset. .set_hi_8: tax .get_lo_8: !if LZSA_SMALL_SIZE { jsr .get_byte ; Get lo-byte of offset. } else { lda (lzsa_srcptr),y ; Get lo-byte of offset. inc <lzsa_srcptr + 0 bne .set_offset inc <lzsa_srcptr + 1 } .set_offset: sta <lzsa_offset + 0 ; Save new offset. stx <lzsa_offset + 1 .lz_length: ldx #1 ; Hi-byte of length+256. lda <lzsa_cmdbuf and #$07 clc adc #$02 cmp #$09 ; Extended length? bcc .got_lz_len jsr .get_length ; X=1 for match, returns CC. inx ; Hi-byte of length+256. .got_lz_len: eor #$FF ; Negate the lo-byte of length. tay eor #$FF .get_lz_dst: adc <lzsa_dstptr + 0 ; Calc address of partial page. sta <lzsa_dstptr + 0 ; Always CC from previous CMP. iny bcs .get_lz_win beq .get_lz_win ; Is lo-byte of length zero? dec <lzsa_dstptr + 1 .get_lz_win: clc ; Calc address of match. adc <lzsa_offset + 0 ; N.B. Offset is negative! sta <lzsa_winptr + 0 lda <lzsa_dstptr + 1 adc <lzsa_offset + 1 sta <lzsa_winptr + 1 .lz_byte: lda (lzsa_winptr),y sta (lzsa_dstptr),y iny bne .lz_byte inc <lzsa_dstptr + 1 dex ; Any full pages left to copy? bne .lz_more jmp .cp_length ; Loop around to the beginning. .lz_more: inc <lzsa_winptr + 1 ; Unlikely, so can be slow. bne .lz_byte ; Always true! ; ; Lookup tables to differentiate literal and match lengths. ; .nibl_len_tbl: !byte 3 ; 0+3 (for literal). !byte 9 ; 2+7 (for match). .byte_len_tbl: !byte 18 - 1 ; 0+3+15 - CS (for literal). !byte 24 - 1 ; 2+7+15 - CS (for match). ; ; Get 16-bit length in X:A register pair, return with CC. ; .get_length: jsr .get_nibble cmp #$0F ; Extended length? bcs .byte_length adc .nibl_len_tbl,x ; Always CC from previous CMP. .got_length: ldx #$00 ; Set hi-byte of 4 & 8 bit rts ; lengths. .byte_length: jsr .get_byte ; So rare, this can be slow! adc .byte_len_tbl,x ; Always CS from previous CMP. bcc .got_length beq .finished .word_length: clc ; MUST return CC! jsr .get_byte ; So rare, this can be slow! pha jsr .get_byte ; So rare, this can be slow! tax pla bne .got_word ; Check for zero lo-byte. dex ; Do one less page loop if so. .got_word: rts .get_byte: lda (lzsa_srcptr),y ; Subroutine version for when inc <lzsa_srcptr + 0 ; inlining isn't advantageous. bne .got_byte inc <lzsa_srcptr + 1 .got_byte: rts .finished: pla ; Decompression completed, pop pla ; return address. rts ; ; Get a nibble value from compressed data in A. ; .get_nibble: lsr <lzsa_nibflg ; Is there a nibble waiting? lda <lzsa_nibble ; Extract the lo-nibble. bcs .got_nibble inc <lzsa_nibflg ; Reset the flag. !if LZSA_SMALL_SIZE { jsr .get_byte } else { lda (lzsa_srcptr),y inc <lzsa_srcptr + 0 bne .set_nibble inc <lzsa_srcptr + 1 } .set_nibble: sta <lzsa_nibble ; Preserve for next time. lsr ; Extract the hi-nibble. lsr lsr lsr .got_nibble: and #$0F rts
text_config: .db "CFG",$FE,$FE .db "BPM:",$FE,$FE .db "SYNC:",$FE,$FE .db "LFO TO:",$FE, .db "LFO RESET:",$FE,$FE .db "SYNTH:",$FE .db "DRUMS:",$FE,$FE .db "PATTERN",$FE .db "OVERRIDES:",$FF text_yes: .db "YES",$FF text_no: .db "NO ",$FF text_memdef: .db ": ",$FF text_confirm: .db "ARE YOU SURE ?",$FE .db " NO YES",$FE .db " ",$FF textptr_yesno: .dw text_no .dw text_yes text_syncnone: .db "NONE ",$FF text_synclsdjs: .db "LSDJ SLAVE ",$FF text_synclsdjmidi: .db "LSDJ MIDI-IN",$FF text_syncnano: .db "NANO MASTER ",$FF text_syncfmidi: .db "FULL MIDI ",$FF textptr_sync: .dw text_syncnone .dw text_synclsdjs .dw text_synclsdjmidi .dw text_syncnano .dw text_syncfmidi text_lfon: .db "NOTHING ",$FF text_lforc: .db "CUTOFF ",$FF text_lforr: .db "RESONANCE",$FF text_lforp: .db "PITCH ",$FF textptr_lfor: .dw text_lfon .dw text_lforc .dw text_lforr .dw text_lforp text_l: .db "L-",$FF text_r: .db "-R",$FF text_lr: .db "LR",$FF text_stop: .db "ST",$FF textptr_lr: .dw text_l .dw text_r .dw text_lr text_piano: .db "PRL",$FF text_xy: .db "X/Y",$FE .db " CUTOFF",$FE,$FE,$FE,$FE .db "R",$FE,"E",$FE,"S",$FE,"O",$FE,"N",$FE,"A",$FE,"N",$FE,"C",$FE,"E",$FF text_live: .db "LIV",$FE,$FE .db " P1 P2 P3",$FE,$FE,$FE .db " CUTF CUTF CUTF",$FE .db " RESO RESO RESO",$FE .db " PITC PITC PITC",$FE .db " SLID SLID SLID",$FE .db " LFOS LFOS LFOS",$FE .db " LFOA LFOA LFOA",$FE,$FE .db " DIST: OSC:",$FE,$FE .db " " .db T_LFOSHAPES+4+TXT_NORMAL,T_LFOSHAPES+5+TXT_NORMAL .db T_LFOSHAPES+2+TXT_NORMAL,T_LFOSHAPES+3+TXT_NORMAL .db $FE .db " " .db T_LFOSHAPES+10+TXT_NORMAL,T_LFOSHAPES+11+TXT_NORMAL .db T_LFOSHAPES+8+TXT_NORMAL,T_LFOSHAPES+9+TXT_NORMAL .db $FF text_loadsave: .db "MEM",$FE,$FE .db "CURRENT",$FE .db " SONG:",$FE .db " PATT:",$FE,$FE .db $FE .db " SAVE PATTERN",$FE .db " LOAD PATTERN",$FE,$FE .db $FE .db " SAVE SONG",$FE .db " LOAD SONG",$FE,$FE .db "DUMP",$FE .db "FORMAT",$FE .db "CREDITS",$FF text_seq: .db "TRK",$FF text_seqhelp: .db " N A S O RR DRUMS ",$FF text_table: .db "SNG",$FF text_eos: .db "()",$FF text_free: .db "FREE SLOT",$FF text_used: .db "USED SLOT",$FF text_nosaves: .db " EEPROM ERROR",$FE,$FE,$FE .db "SAVING AND LOADING",$FE .db " DISABLED",$FF text_nopots: .db " HW ERROR",$FE,$FE,$FE .db "POT CONTROLS",$FE .db " DISABLED",$FF text_credits: ; 0123456789ABCDEF0123 .db "CODE, GFX AND",$FE .db "HARDWARE:",$FE .db " FURRTEK",$FE,$FE .db "THANKS:",$FE .db "MRMEGAHERTZ 2080",$FE .db "2XAA JANKENPOPP",$FE .db "ULTRASYD CYBERIC",$FE .db "DJPIE SABREPULSE",$FE .db "NITRO2K01 KEFF",$FE .db "CHIPMUSIC FORUMS",$FE,$FE .db "SW V1,0 WT V1,0",$FF text_clearname: .db " ",$FF text_noteempty: .db "---",$FF text_notecorrupt: .db "???",$FF note_names: .db "C-2",$FF .db "C#2",$FF .db "D-2",$FF .db "D#2",$FF .db "E-2",$FF .db "F-2",$FF .db "F#2",$FF .db "G-2",$FF .db "G#2",$FF .db "A-2",$FF .db "A#2",$FF .db "B-2",$FF .db "C-3",$FF .db "C#3",$FF .db "D-3",$FF .db "D#3",$FF .db "E-3",$FF .db "F-3",$FF .db "F#3",$FF .db "G-3",$FF .db "G#3",$FF .db "A-3",$FF .db "A#3",$FF .db "B-3",$FF .db "C-4",$FF .db "C#4",$FF .db "D-4",$FF .db "D#4",$FF .db "E-4",$FF .db "F-4",$FF .db "F#4",$FF .db "G-4",$FF .db "G#4",$FF .db "A-4",$FF .db "A#4",$FF .db "B-4",$FF .db "OFF",$FF
# $Id: e_inc_2.asm,v 1.1 2001/03/14 16:57:28 ellard Exp $ #@ tests for illegal register in inc. inc r0, 1 inc r1, 1 inc r2, 1 inc r3, 1 inc r4, 1 inc r5, 1 inc r6, 1 inc r7, 1 inc r8, 1 inc r9, 1 inc r10, 1 inc r11, 1 inc r12, 1 inc r13, 1 inc r14, 1 inc r15, 1 inc r16, 1 # Not OK
// ImGui Win32 + DirectX9 binding // Implemented features: // [X] User texture binding. Use 'LPDIRECT3DTEXTURE9' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2018-05-07: Render: Saving/restoring Transform because they don't seem to be included in the StateBlock. Setting shading mode to Gouraud. // 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors and ImGuiBackendFlags_HasSetMousePos flags + honor ImGuiConfigFlags_NoMouseCursorChange flag. // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX9_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Honoring the io.WantSetMousePos by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavEnableSetMousePos is set). // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. #include "../imgui.h" #include "imgui_impl_dx9.h" // DirectX #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> // Win32 data static HWND g_hWnd = 0; static INT64 g_Time = 0; static INT64 g_TicksPerSecond = 0; static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_COUNT; // DirectX data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static LPDIRECT3DVERTEXBUFFER9 g_pVB = NULL; static LPDIRECT3DINDEXBUFFER9 g_pIB = NULL; static LPDIRECT3DTEXTURE9 g_FontTexture = NULL; static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; static IDirect3DStateBlock9* d3d9_state_block = NULL; struct CUSTOMVERTEX { float pos[3]; D3DCOLOR col; float uv[2]; }; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1) // Render function. // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX9_RenderDrawData(ImDrawData* draw_data) { // Avoid rendering when minimized ImGuiIO& io = ImGui::GetIO(); if (io.DisplaySize.x <= 0.0f || io.DisplaySize.y <= 0.0f) return; // Create and grow buffers if needed if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) { if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } g_VertexBufferSize = draw_data->TotalVtxCount + 5000; if (g_pd3dDevice->CreateVertexBuffer(g_VertexBufferSize * sizeof(CUSTOMVERTEX), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL) < 0) return; } if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) { if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } g_IndexBufferSize = draw_data->TotalIdxCount + 10000; if (g_pd3dDevice->CreateIndexBuffer(g_IndexBufferSize * sizeof(ImDrawIdx), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, sizeof(ImDrawIdx) == 2 ? D3DFMT_INDEX16 : D3DFMT_INDEX32, D3DPOOL_DEFAULT, &g_pIB, NULL) < 0) return; } // Backup the DX9 state //IDirect3DStateBlock9* d3d9_state_block = NULL; if (g_pd3dDevice->CreateStateBlock(D3DSBT_PIXELSTATE, &d3d9_state_block) < 0) return; IDirect3DVertexDeclaration9* vertDec; IDirect3DVertexShader9* vertShader; g_pd3dDevice->GetVertexDeclaration(&vertDec); g_pd3dDevice->GetVertexShader(&vertShader); // Backup the DX9 transform (DX9 documentation suggests that it is included in the StateBlock but it doesn't appear to) D3DMATRIX last_world, last_view, last_projection; g_pd3dDevice->GetTransform(D3DTS_WORLD, &last_world); g_pd3dDevice->GetTransform(D3DTS_VIEW, &last_view); g_pd3dDevice->GetTransform(D3DTS_PROJECTION, &last_projection); // Copy and convert all vertices into a single contiguous buffer, convert colors to DX9 default format. // FIXME-OPT: This is a waste of resource, the ideal is to use imconfig.h and // 1) to avoid repacking colors: #define IMGUI_USE_BGRA_PACKED_COLOR // 2) to avoid repacking vertices: #define IMGUI_OVERRIDE_DRAWVERT_STRUCT_LAYOUT struct ImDrawVert { ImVec2 pos; float z; ImU32 col; ImVec2 uv; } CUSTOMVERTEX* vtx_dst; ImDrawIdx* idx_dst; if (g_pVB->Lock(0, (UINT)(draw_data->TotalVtxCount * sizeof(CUSTOMVERTEX)), (void**)&vtx_dst, D3DLOCK_DISCARD) < 0) return; if (g_pIB->Lock(0, (UINT)(draw_data->TotalIdxCount * sizeof(ImDrawIdx)), (void**)&idx_dst, D3DLOCK_DISCARD) < 0) return; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; const ImDrawVert* vtx_src = cmd_list->VtxBuffer.Data; for (int i = 0; i < cmd_list->VtxBuffer.Size; i++) { vtx_dst->pos[0] = vtx_src->pos.x; vtx_dst->pos[1] = vtx_src->pos.y; vtx_dst->pos[2] = 0.0f; vtx_dst->col = (vtx_src->col & 0xFF00FF00) | ((vtx_src->col & 0xFF0000) >> 16) | ((vtx_src->col & 0xFF) << 16); // RGBA --> ARGB for DirectX9 vtx_dst->uv[0] = vtx_src->uv.x; vtx_dst->uv[1] = vtx_src->uv.y; vtx_dst++; vtx_src++; } memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); idx_dst += cmd_list->IdxBuffer.Size; } g_pVB->Unlock(); g_pIB->Unlock(); g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX)); g_pd3dDevice->SetIndices(g_pIB); g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX); // Setup viewport D3DVIEWPORT9 vp; vp.X = vp.Y = 0; vp.Width = (DWORD)io.DisplaySize.x; vp.Height = (DWORD)io.DisplaySize.y; vp.MinZ = 0.0f; vp.MaxZ = 1.0f; g_pd3dDevice->SetViewport(&vp); // Setup render state: fixed-pipeline, alpha-blending, no face culling, no depth testing, shade mode (for gradient) g_pd3dDevice->SetPixelShader(NULL); g_pd3dDevice->SetVertexShader(NULL); g_pd3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, false); g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true); g_pd3dDevice->SetRenderState(D3DRS_ALPHATESTENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD); g_pd3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); g_pd3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, true); g_pd3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE); g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); g_pd3dDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); // Setup orthographic projection matrix // Being agnostic of whether <d3dx9.h> or <DirectXMath.h> can be used, we aren't relying on D3DXMatrixIdentity()/D3DXMatrixOrthoOffCenterLH() or DirectX::XMMatrixIdentity()/DirectX::XMMatrixOrthographicOffCenterLH() { const float L = 0.5f, R = io.DisplaySize.x + 0.5f, T = 0.5f, B = io.DisplaySize.y + 0.5f; D3DMATRIX mat_identity = { { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; D3DMATRIX mat_projection = { 2.0f / (R - L), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (T - B), 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, (L + R) / (L - R), (T + B) / (B - T), 0.5f, 1.0f, }; g_pd3dDevice->SetTransform(D3DTS_WORLD, &mat_identity); g_pd3dDevice->SetTransform(D3DTS_VIEW, &mat_identity); g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &mat_projection); } // Render command lists int vtx_offset = 0; int idx_offset = 0; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { const RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w }; g_pd3dDevice->SetTexture(0, (LPDIRECT3DTEXTURE9)pcmd->TextureId); g_pd3dDevice->SetScissorRect(&r); g_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, vtx_offset, 0, (UINT)cmd_list->VtxBuffer.Size, idx_offset, pcmd->ElemCount / 3); } idx_offset += pcmd->ElemCount; } vtx_offset += cmd_list->VtxBuffer.Size; } // Restore the DX9 transform g_pd3dDevice->SetTransform(D3DTS_WORLD, &last_world); g_pd3dDevice->SetTransform(D3DTS_VIEW, &last_view); g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &last_projection); // Restore the DX9 state d3d9_state_block->Apply(); d3d9_state_block->Release(); d3d9_state_block = NULL; g_pd3dDevice->SetVertexDeclaration(vertDec); g_pd3dDevice->SetVertexShader(vertShader); } static bool ImGui_ImplWin32_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange) return false; ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor(); if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor ::SetCursor(NULL); } else { // Show OS mouse cursor LPTSTR win32_cursor = IDC_ARROW; switch (imgui_cursor) { case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; } ::SetCursor(::LoadCursor(NULL, win32_cursor)); } return true; } // Allow compilation with old Windows SDK. MinGW doesn't have default _WIN32_WINNT/WINVER versions. #ifndef WM_MOUSEHWHEEL #define WM_MOUSEHWHEEL 0x020E #endif // Process Win32 mouse/keyboard inputs. // 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. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui::GetCurrentContext() == NULL) return 0; ImGuiIO& io = ImGui::GetIO(); switch (msg) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: case WM_XBUTTONDOWN: case WM_XBUTTONDBLCLK: { int button = 0; if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0; if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1; if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2; if (msg == WM_XBUTTONDOWN || msg == WM_XBUTTONDBLCLK) button = (HIWORD(wParam) == XBUTTON1) ? 3 : 4; if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL) ::SetCapture(hwnd); io.MouseDown[button] = true; return 1; } case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: case WM_XBUTTONUP: { int button = 0; if (msg == WM_LBUTTONUP) button = 0; if (msg == WM_RBUTTONUP) button = 1; if (msg == WM_MBUTTONUP) button = 2; if (msg == WM_XBUTTONUP) button = (HIWORD(wParam) == XBUTTON1) ? 3 : 4; io.MouseDown[button] = false; if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd) ::ReleaseCapture(); return 1; } case WM_MOUSEWHEEL: io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f; return 1; case WM_MOUSEMOVE: io.MousePos.x = (signed short)(lParam); io.MousePos.y = (signed short)(lParam >> 16); return 1; case WM_KEYDOWN: case WM_SYSKEYDOWN: if (wParam < 256) io.KeysDown[wParam] = 1; return 1; case WM_KEYUP: case WM_SYSKEYUP: if (wParam < 256) io.KeysDown[wParam] = 0; return 1; case WM_CHAR: // You can also use ToAscii()+GetKeyboardState() to retrieve characters. if (wParam > 0 && wParam < 0x10000) io.AddInputCharacter((unsigned short)wParam); return 1; } return 0; } bool ImGui_ImplDX9_Init(void* hwnd, IDirect3DDevice9* device) { g_hWnd = (HWND)hwnd; g_pd3dDevice = device; if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond)) return false; if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time)) return false; // Setup back-end capabilities flags ImGuiIO& io = ImGui::GetIO(); io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional) io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used) // Keyboard mapping. ImGui will use those indices to peek into the io.KeysDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_Tab] = VK_TAB; io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR; io.KeyMap[ImGuiKey_PageDown] = VK_NEXT; io.KeyMap[ImGuiKey_Home] = VK_HOME; io.KeyMap[ImGuiKey_End] = VK_END; io.KeyMap[ImGuiKey_Insert] = VK_INSERT; io.KeyMap[ImGuiKey_Delete] = VK_DELETE; io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Space] = VK_SPACE; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; io.ImeWindowHandle = g_hWnd; return true; } void ImGui_ImplDX9_Shutdown() { ImGui_ImplDX9_InvalidateDeviceObjects(); g_pd3dDevice = NULL; g_hWnd = 0; } static bool ImGui_ImplDX9_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height, bytes_per_pixel; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height, &bytes_per_pixel); // Upload texture to graphics system g_FontTexture = NULL; if (g_pd3dDevice->CreateTexture(width, height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_FontTexture, NULL) < 0) return false; D3DLOCKED_RECT tex_locked_rect; if (g_FontTexture->LockRect(0, &tex_locked_rect, NULL, 0) != D3D_OK) return false; for (int y = 0; y < height; y++) memcpy((unsigned char *)tex_locked_rect.pBits + tex_locked_rect.Pitch * y, pixels + (width * bytes_per_pixel) * y, (width * bytes_per_pixel)); g_FontTexture->UnlockRect(0); // Store our identifier io.Fonts->TexID = (void *)g_FontTexture; return true; } bool ImGui_ImplDX9_CreateDeviceObjects() { if (!g_pd3dDevice) return false; if (!ImGui_ImplDX9_CreateFontsTexture()) return false; return true; } void ImGui_ImplDX9_InvalidateDeviceObjects() { //if (!g_pd3dDevice) // return; if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } if (d3d9_state_block) { d3d9_state_block->Release(); d3d9_state_block = NULL; } // At this point note that we set ImGui::GetIO().Fonts->TexID to be == g_FontTexture, so clear both. ImGuiIO& io = ImGui::GetIO(); IM_ASSERT(g_FontTexture == io.Fonts->TexID); if (g_FontTexture) g_FontTexture->Release(); g_FontTexture = NULL; io.Fonts->TexID = NULL; } void ImGui_ImplDX9_NewFrame() { if (!g_FontTexture) ImGui_ImplDX9_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) RECT rect; GetClientRect(g_hWnd, &rect); io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Setup time step INT64 current_time; QueryPerformanceCounter((LARGE_INTEGER *)&current_time); io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; g_Time = current_time; // Read keyboard modifiers inputs io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0; io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0; io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0; io.KeySuper = false; // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events // io.MousePos : filled by WM_MOUSEMOVE events // io.MouseDown : filled by WM_*BUTTON* events // io.MouseWheel : filled by WM_MOUSEWHEEL events // Set OS mouse position if requested (only used when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user) if (io.WantSetMousePos) { POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; ClientToScreen(g_hWnd, &pos); SetCursorPos(pos.x, pos.y); } // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); if (g_LastMouseCursor != mouse_cursor) { g_LastMouseCursor = mouse_cursor; ImGui_ImplWin32_UpdateMouseCursor(); } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); }
; CRT0 for the VG5000 ; ; Joaopa Jun. 2014 ; Stefano Bodrato Lug. 2014 ; ; $Id: vg5k_crt0.asm,v 1.15 2016/07/15 21:03:25 dom Exp $ ; MODULE vg5k_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- EXTERN _main ;main() is always external to crt0 code PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) ; Now, getting to the real stuff now! IF !DEFINED_CRT_ORG_CODE defc CRT_ORG_CODE = 20480 ENDIF org CRT_ORG_CODE start: xor a ld (18434), a ;default character will be normal and black ex de,hl ; preserve HL ld (start1+1),sp ;Save entry stack ld hl,-64 add hl,sp ld sp,hl call crt0_init_bss ld (exitsp),sp push de ; save HL ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "amalloc.def" ENDIF di call _main ei cleanup: ; ; Deallocate memory which has been allocated here! ; IF !DEFINED_nostreams EXTERN closeall call closeall ENDIF pop hl ; ..let's restore them ! ld ix,$47FA start1: ld sp,0 ret l_dcal: jp (hl) ;Used for function pointer calls ; defm "Small C+ VG5000" ; defb 0 INCLUDE "crt0_runtime_selection.asm" INCLUDE "crt0_section.asm" SECTION code_crt_init ld hl,$4000 ld (base_graphics),hl
;; @file ; Provide FSP API entry points. ; ; Copyright (c) 2016, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ;; SECTION .text %include "SaveRestoreSseNasm.inc" %include "MicrocodeLoadNasm.inc" ; ; Following are fixed PCDs ; extern ASM_PFX(PcdGet32 (PcdTemporaryRamBase)) extern ASM_PFX(PcdGet32 (PcdTemporaryRamSize)) extern ASM_PFX(PcdGet32 (PcdFspReservedBufferSize)) ; ; Following functions will be provided in PlatformSecLib ; extern ASM_PFX(AsmGetFspBaseAddress) extern ASM_PFX(AsmGetFspInfoHeader) ;extern ASM_PFX(LoadMicrocode) ; @todo: needs a weak implementation extern ASM_PFX(SecPlatformInit) ; @todo: needs a weak implementation extern ASM_PFX(SecCarInit) ; ; Define the data length that we saved on the stack top ; DATA_LEN_OF_PER0 EQU 18h DATA_LEN_OF_MCUD EQU 18h DATA_LEN_AT_STACK_TOP EQU (DATA_LEN_OF_PER0 + DATA_LEN_OF_MCUD + 4) ; ; @todo: These structures are moved from MicrocodeLoadNasm.inc to avoid ; build error. This needs to be fixed later on. ; struc MicrocodeHdr .MicrocodeHdrVersion: resd 1 .MicrocodeHdrRevision: resd 1 .MicrocodeHdrDate: resd 1 .MicrocodeHdrProcessor: resd 1 .MicrocodeHdrChecksum: resd 1 .MicrocodeHdrLoader: resd 1 .MicrocodeHdrFlags: resd 1 .MicrocodeHdrDataSize: resd 1 .MicrocodeHdrTotalSize: resd 1 .MicrocodeHdrRsvd: resd 3 .size: endstruc struc ExtSigHdr .ExtSigHdrCount: resd 1 .ExtSigHdrChecksum: resd 1 .ExtSigHdrRsvd: resd 3 .size: endstruc struc ExtSig .ExtSigProcessor: resd 1 .ExtSigFlags: resd 1 .ExtSigChecksum: resd 1 .size: endstruc struc LoadMicrocodeParams ; FSP_UPD_HEADER { .FspUpdHeader: resd 8 ; } ; FSPT_CORE_UPD { .MicrocodeCodeAddr: resd 1 .MicrocodeCodeSize: resd 1 .CodeRegionBase: resd 1 .CodeRegionSize: resd 1 ; } .size: endstruc ; ; Define SSE macros ; ; ;args 1: ReturnAddress 2:MmxRegister ; %macro LOAD_MMX_EXT 2 mov esi, %1 movd %2, esi ; save ReturnAddress into MMX %endmacro ; ;args 1: RoutineLabel 2:MmxRegister ; %macro CALL_MMX_EXT 2 mov esi, %%ReturnAddress movd %2, esi ; save ReturnAddress into MMX jmp %1 %%ReturnAddress: %endmacro ; ;arg 1:MmxRegister ; %macro RET_ESI_EXT 1 movd esi, %1 ; move ReturnAddress from MMX to ESI jmp esi %endmacro ; ;arg 1:RoutineLabel ; %macro CALL_MMX 1 CALL_MMX_EXT %1, mm7 %endmacro %macro RET_ESI 0 RET_ESI_EXT mm7 %endmacro ; ; @todo: The strong/weak implementation does not work. ; This needs to be reviewed later. ; ;------------------------------------------------------------------------------ ; ;;global ASM_PFX(SecPlatformInitDefault) ;ASM_PFX(SecPlatformInitDefault): ; ; Inputs: ; ; mm7 -> Return address ; ; Outputs: ; ; eax -> 0 - Successful, Non-zero - Failed. ; ; Register Usage: ; ; eax is cleared and ebp is used for return address. ; ; All others reserved. ; ; ; Save return address to EBP ; movd ebp, mm7 ; ; xor eax, eax ;Exit1: ; jmp ebp ;------------------------------------------------------------------------------ global ASM_PFX(LoadMicrocodeDefault) ASM_PFX(LoadMicrocodeDefault): ; Inputs: ; esp -> LoadMicrocodeParams pointer ; Register Usage: ; esp Preserved ; All others destroyed ; Assumptions: ; No memory available, stack is hard-coded and used for return address ; Executed by SBSP and NBSP ; Beginning of microcode update region starts on paragraph boundary ; ; ; Save return address to EBP movd ebp, mm7 cmp esp, 0 jz ParamError mov eax, dword [esp + 4] ; Parameter pointer cmp eax, 0 jz ParamError mov esp, eax ; skip loading Microcode if the MicrocodeCodeSize is zero ; and report error if size is less than 2k mov eax, dword [esp + LoadMicrocodeParams.MicrocodeCodeSize] cmp eax, 0 jz Exit2 cmp eax, 0800h jl ParamError mov esi, dword [esp + LoadMicrocodeParams.MicrocodeCodeAddr] cmp esi, 0 jnz CheckMainHeader ParamError: mov eax, 080000002h jmp Exit2 CheckMainHeader: ; Get processor signature and platform ID from the installed processor ; and save into registers for later use ; ebx = processor signature ; edx = platform ID mov eax, 1 cpuid mov ebx, eax mov ecx, MSR_IA32_PLATFORM_ID rdmsr mov ecx, edx shr ecx, 50-32 ; shift (50d-32d=18d=0x12) bits and ecx, 7h ; platform id at bit[52..50] mov edx, 1 shl edx, cl ; Current register usage ; esp -> stack with parameters ; esi -> microcode update to check ; ebx = processor signature ; edx = platform ID ; Check for valid microcode header ; Minimal test checking for header version and loader version as 1 mov eax, dword 1 cmp dword [esi + MicrocodeHdr.MicrocodeHdrVersion], eax jne AdvanceFixedSize cmp dword [esi + MicrocodeHdr.MicrocodeHdrLoader], eax jne AdvanceFixedSize ; Check if signature and plaform ID match cmp ebx, dword [esi + MicrocodeHdr.MicrocodeHdrProcessor] jne LoadMicrocodeDefault1 test edx, dword [esi + MicrocodeHdr.MicrocodeHdrFlags ] jnz LoadCheck ; Jif signature and platform ID match LoadMicrocodeDefault1: ; Check if extended header exists ; First check if MicrocodeHdrTotalSize and MicrocodeHdrDataSize are valid xor eax, eax cmp dword [esi + MicrocodeHdr.MicrocodeHdrTotalSize], eax je NextMicrocode cmp dword [esi + MicrocodeHdr.MicrocodeHdrDataSize], eax je NextMicrocode ; Then verify total size - sizeof header > data size mov ecx, dword [esi + MicrocodeHdr.MicrocodeHdrTotalSize] sub ecx, MicrocodeHdr.size cmp ecx, dword [esi + MicrocodeHdr.MicrocodeHdrDataSize] jng NextMicrocode ; Jif extended header does not exist ; Set edi -> extended header mov edi, esi add edi, MicrocodeHdr.size add edi, dword [esi + MicrocodeHdr.MicrocodeHdrDataSize] ; Get count of extended structures mov ecx, dword [edi + ExtSigHdr.ExtSigHdrCount] ; Move pointer to first signature structure add edi, ExtSigHdr.size CheckExtSig: ; Check if extended signature and platform ID match cmp dword [edi + ExtSig.ExtSigProcessor], ebx jne LoadMicrocodeDefault2 test dword [edi + ExtSig.ExtSigFlags], edx jnz LoadCheck ; Jif signature and platform ID match LoadMicrocodeDefault2: ; Check if any more extended signatures exist add edi, ExtSig.size loop CheckExtSig NextMicrocode: ; Advance just after end of this microcode xor eax, eax cmp dword [esi + MicrocodeHdr.MicrocodeHdrTotalSize], eax je LoadMicrocodeDefault3 add esi, dword [esi + MicrocodeHdr.MicrocodeHdrTotalSize] jmp CheckAddress LoadMicrocodeDefault3: add esi, dword 2048 jmp CheckAddress AdvanceFixedSize: ; Advance by 4X dwords add esi, dword 1024 CheckAddress: ; Is valid Microcode start point ? cmp dword [esi + MicrocodeHdr.MicrocodeHdrVersion], 0ffffffffh jz Done ; Is automatic size detection ? mov eax, dword [esp + LoadMicrocodeParams.MicrocodeCodeSize] cmp eax, 0ffffffffh jz LoadMicrocodeDefault4 ; Address >= microcode region address + microcode region size? add eax, dword [esp + LoadMicrocodeParams.MicrocodeCodeAddr] cmp esi, eax jae Done ;Jif address is outside of microcode region jmp CheckMainHeader LoadMicrocodeDefault4: LoadCheck: ; Get the revision of the current microcode update loaded mov ecx, MSR_IA32_BIOS_SIGN_ID xor eax, eax ; Clear EAX xor edx, edx ; Clear EDX wrmsr ; Load 0 to MSR at 8Bh mov eax, 1 cpuid mov ecx, MSR_IA32_BIOS_SIGN_ID rdmsr ; Get current microcode signature ; Verify this microcode update is not already loaded cmp dword [esi + MicrocodeHdr.MicrocodeHdrRevision], edx je Continue LoadMicrocode: ; EAX contains the linear address of the start of the Update Data ; EDX contains zero ; ECX contains 79h (IA32_BIOS_UPDT_TRIG) ; Start microcode load with wrmsr mov eax, esi add eax, MicrocodeHdr.size xor edx, edx mov ecx, MSR_IA32_BIOS_UPDT_TRIG wrmsr mov eax, 1 cpuid Continue: jmp NextMicrocode Done: mov eax, 1 cpuid mov ecx, MSR_IA32_BIOS_SIGN_ID rdmsr ; Get current microcode signature xor eax, eax cmp edx, 0 jnz Exit2 mov eax, 08000000Eh Exit2: jmp ebp global ASM_PFX(EstablishStackFsp) ASM_PFX(EstablishStackFsp): ; ; Save parameter pointer in edx ; mov edx, dword [esp + 4] ; ; Enable FSP STACK ; mov esp, DWORD [ASM_PFX(PcdGet32 (PcdTemporaryRamBase))] add esp, DWORD [ASM_PFX(PcdGet32 (PcdTemporaryRamSize))] push DATA_LEN_OF_MCUD ; Size of the data region push 4455434Dh ; Signature of the data region 'MCUD' push dword [edx + 2Ch] ; Code size sizeof(FSPT_UPD_COMMON) + 12 push dword [edx + 28h] ; Code base sizeof(FSPT_UPD_COMMON) + 8 push dword [edx + 24h] ; Microcode size sizeof(FSPT_UPD_COMMON) + 4 push dword [edx + 20h] ; Microcode base sizeof(FSPT_UPD_COMMON) + 0 ; ; Save API entry/exit timestamp into stack ; push DATA_LEN_OF_PER0 ; Size of the data region push 30524550h ; Signature of the data region 'PER0' rdtsc push edx push eax LOAD_EDX push edx LOAD_EAX push eax ; ; Terminator for the data on stack ; push 0 ; ; Set ECX/EDX to the BootLoader temporary memory range ; mov ecx, [ASM_PFX(PcdGet32 (PcdTemporaryRamBase))] mov edx, ecx add edx, [ASM_PFX(PcdGet32 (PcdTemporaryRamSize))] sub edx, [ASM_PFX(PcdGet32 (PcdFspReservedBufferSize))] cmp ecx, edx ;If PcdFspReservedBufferSize >= PcdTemporaryRamSize, then error. jb EstablishStackFspSuccess mov eax, 80000003h ;EFI_UNSUPPORTED jmp EstablishStackFspExit EstablishStackFspSuccess: xor eax, eax EstablishStackFspExit: RET_ESI ;---------------------------------------------------------------------------- ; TempRamInit API ; ; This FSP API will load the microcode update, enable code caching for the ; region specified by the boot loader and also setup a temporary stack to be ; used till main memory is initialized. ; ;---------------------------------------------------------------------------- global ASM_PFX(TempRamInitApi) ASM_PFX(TempRamInitApi): ; ; Ensure SSE is enabled ; ENABLE_SSE ; ; Save EBP, EBX, ESI, EDI & ESP in XMM7 & XMM6 ; SAVE_REGS ; ; Save timestamp into XMM6 ; rdtsc SAVE_EAX SAVE_EDX ; ; Check Parameter ; mov eax, dword [esp + 4] cmp eax, 0 mov eax, 80000002h jz TempRamInitExit ; ; Sec Platform Init ; CALL_MMX ASM_PFX(SecPlatformInit) cmp eax, 0 jnz TempRamInitExit ; Load microcode LOAD_ESP CALL_MMX ASM_PFX(LoadMicrocodeDefault) SXMMN xmm6, 3, eax ;Save microcode return status in ECX-SLOT 3 in xmm6. ;@note If return value eax is not 0, microcode did not load, but continue and attempt to boot. ; Call Sec CAR Init LOAD_ESP CALL_MMX ASM_PFX(SecCarInit) cmp eax, 0 jnz TempRamInitExit LOAD_ESP CALL_MMX ASM_PFX(EstablishStackFsp) cmp eax, 0 jnz TempRamInitExit LXMMN xmm6, eax, 3 ;Restore microcode status if no CAR init error from ECX-SLOT 3 in xmm6. TempRamInitExit: mov bl, al ; save al data in bl mov al, 07Fh ; API exit postcode 7f out 080h, al mov al, bl ; restore al data from bl ; ; Load EBP, EBX, ESI, EDI & ESP from XMM7 & XMM6 ; LOAD_REGS ret ;---------------------------------------------------------------------------- ; Module Entrypoint API ;---------------------------------------------------------------------------- global ASM_PFX(_ModuleEntryPoint) ASM_PFX(_ModuleEntryPoint): jmp $
; sccz80 crt0 library - 8080 version SECTION code_clib SECTION code_l_sccz80 PUBLIC l_long_eq EXTERN l_long_ucmp .l_long_eq call l_long_ucmp ld hl,1 scf ret Z dec hl and a ret
Name: kart-enemy-back.asm Type: file Size: 13223 Last-Modified: '1992-02-13T07:48:12Z' SHA-1: 7CFA5FA7F497D3CD4A72CA18DE3D92CEBA5EDC89 Description: null
;channel 1 menuChannelOne:: ;mesure 1 db $00, $80, $87, $14, $87, MQUAVER * 2 ; DO#2 db $00, $80, $87, $F7, $86, MQUAVER ; SI1 db $00, $80, $87, $D6, $86, MQUAVER ; LA1 db $00, $80, $87, $C4, $86, MQUAVER * 2 ; SOL#1 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 2 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER / 2 ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 + MQUAVER / 2 ; NO SOUND ;mesure 3 db $00, $80, $87, $9E, $86, MQUAVER ; FA#1 db $00, $80, $87, $C4, $86, MQUAVER ; SOL#1 db $00, $80, $87, $D6, $86, MQUAVER ; LA1 db $00, $80, $87, $F7, $86, MQUAVER ; SI1 db $00, $80, $87, $C4, $86, MQUAVER * 2 ; SOL#1 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 4 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND ;mesure 5 db $00, $80, $87, $9E, $86, MQUAVER ; FA#1 db $00, $80, $87, $C4, $86, MQUAVER ; SOL#1 db $00, $80, $87, $D6, $86, MQUAVER ; LA1 db $00, $80, $87, $F7, $86, MQUAVER ; SI1 db $00, $80, $87, $C4, $86, MQUAVER * 2 ; SOL#1 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 6 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 3 ; NO SOUND db $00, $80, $87, $5C, $86, MQUAVER ; RE#1 db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 7 db $00, $80, $87, $9E, $86, MQUAVER * 2 ; FA#1 db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $87, $5C, $86, MQUAVER ; RE#1 db $00, $80, $87, $29, $86, MQUAVER * 2 ; DO#1 db $00, $80, $87, $C4, $86, MQUAVER ; SOL#1 db $00, $80, $87, $9E, $86, MQUAVER ; FA#1 ;mesure 8 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $5C, $86, MQUAVER ; RE#1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND ;mesure 9 db $00, $80, $87, $8A, $87, MQUAVER * 2 ; DO#3 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 db $00, $80, $87, $6B, $87, MQUAVER ; LA2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 10 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND ;mesure 11 db $00, $80, $87, $4F, $87, MQUAVER ; FA#2 db $00, $80, $87, $62, $87, MQUAVER ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER ; LA2 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 12 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND ;mesure 13 db $00, $80, $87, $4F, $87, MQUAVER ; FA#2 db $00, $80, $87, $62, $87, MQUAVER ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER ; LA2 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $00, $D6, $86, MQUAVER ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 ;mesure 14 db $00, $80, $00, $D6, $86, MQUAVER * 2 ; NO SOUND db $00, $80, $87, $73, $86, MQUAVER ; MI1 db $00, $80, $00, $D6, $86, MQUAVER * 3 ; NO SOUND db $00, $80, $87, $2E, $87, MQUAVER ; RE#2 db $00, $80, $87, $39, $87, MQUAVER ; MI2 ;mesure 15 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $39, $87, MQUAVER ; MI2 db $00, $80, $87, $2E, $87, MQUAVER ; RE#2 db $00, $80, $87, $39, $87, MQUAVER * 2 ; MI2 db $00, $80, $87, $14, $87, MQUAVER * 6 ; DO#2 ;mesure 16 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 ;mesure 17 db $00, $80, $87, $39, $87, MQUAVER * 4 ; MI2 db $00, $80, $87, $2E, $87, MQUAVER * 4 ; RE#2 ;mesure 18 db $00, $80, $87, $39, $87, MQUAVER * 2 ; MI2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $39, $87, MQUAVER * 2 ; MI2 ;mesure 19 db $00, $80, $87, $2E, $87, MQUAVER * 4 ; RE#2 db $00, $80, $87, $2E, $87, MQUAVER * 2 ; RE#2 db $00, $80, $87, $14, $87, MQUAVER * 2 ; DO#2 ;mesure 20 - 21 db $00, $80, $87, $14, $87, MQUAVER * 12 ; DO#2 db $00, $80, $87, $5C, $86, MQUAVER * 4 ; RE#1 ;mesure 22 db $00, $80, $87, $73, $86, MQUAVER * 2 ; MI1 db $00, $80, $87, $9E, $86, MQUAVER * 2 ; FA#1 db $00, $80, $87, $9E, $86, MQUAVER * 2 ; FA#1 db $00, $80, $87, $73, $86, MQUAVER * 2 ; MI1 ;mesure 23 db $00, $80, $87, $5C, $86, MQUAVER * 4 ; RE#1 db $00, $80, $87, $73, $86, MQUAVER * 2 ; MI1 db $00, $80, $87, $9E, $86, MQUAVER * 2 ; FA#1 ;mesure 24 db $00, $80, $87, $C4, $86, MQUAVER * 4 ; SOL#1 db $00, $80, $00, $D6, $86, MQUAVER * 4 ; NO SOUND ;mesure 25 db $00, $80, $00, $D6, $86, MQUAVER * 4 ; NO SOUND db $00, $80, $87, $4F, $87, MQUAVER * 4 ; FA#2 ;mesure 26 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 ;mesure 27 db $00, $80, $87, $4F, $87, MQUAVER * 4 ; FA#2 db $00, $80, $87, $62, $87, MQUAVER * 4 ; SOL#2 ;mesure 28 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 ;mesure 29 db $00, $80, $87, $62, $87, MQUAVER * 4 ; SOL#2 db $00, $80, $87, $73, $87, MQUAVER * 4 ; LA#2 ;mesure 30 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 db $00, $80, $87, $8A, $87, MQUAVER * 2 ; DO#3 db $00, $80, $87, $8A, $87, MQUAVER * 2 ; DO#3 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 ;mesure 31 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 db $00, $80, $87, $73, $87, MQUAVER * 2 ; LA#2 db $00, $80, $87, $C4, $86, MQUAVER / 2 ; SOL#1 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $B1, $87, MQUAVER / 2 ; SOL#3 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 ;mesure 32 db $00, $80, $87, $C4, $86, MQUAVER / 2 ; SOL#1 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $B1, $87, MQUAVER / 2 ; SOL#3 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $C4, $86, MQUAVER / 2 ; SOL#1 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $B1, $87, MQUAVER / 2 ; SOL#3 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 ;mesure 33 db $00, $80, $87, $C4, $86, MQUAVER / 2 ; SOL#1 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $B1, $87, MQUAVER / 2 ; SOL#3 db $00, $80, $87, $97, $87, MQUAVER / 2 ; RE#3 db $00, $80, $87, $62, $87, MQUAVER / 2 ; SOL#2 db $00, $80, $87, $2E, $87, MQUAVER / 2 ; RE#2 db $00, $80, $87, $4F, $87, MQUAVER ; FA#2 db $00, $80, $87, $62, $87, MQUAVER ; SOL#2 db $00, $80, $87, $73, $87, MQUAVER ; LA#2 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 ;mesure 34 db $00, $80, $87, $8A, $87, MQUAVER ; DO#3 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 db $00, $80, $87, $8A, $87, MQUAVER ; DO#3 db $00, $80, $87, $97, $87, MQUAVER ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER ; MI3 db $00, $80, $87, $97, $87, MQUAVER ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER ; MI3 db $00, $80, $87, $A7, $87, MQUAVER ; FA#3 ;mesure 35 db $00, $80, $87, $B1, $87, MQUAVER ; SOL#3 db $00, $80, $87, $BA, $87, MQUAVER ; LA#3 db $00, $80, $87, $BE, $87, MQUAVER ; SI3 db $00, $80, $87, $C1, $87, MQUAVER ; DO4 db $00, $80, $87, $C5, $87, MQUAVER * 4 ; DO#4 ;mesure 36 db $00, $80, $87, $C5, $87, MQUAVER * 2 ; DO#4 db $00, $80, $87, $C1, $87, MQUAVER * 2 ; DO4 db $00, $80, $87, $C5, $87, MQUAVER * 2 ; DO#4 db $00, $80, $87, $C1, $87, MQUAVER * 2 ; DO4 ;mesure 37 db $00, $80, $87, $C5, $87, MQUAVER * 4 ; DO#4 db $00, $80, $87, $4F, $87, MQUAVER ; FA#2 db $00, $80, $87, $62, $87, MQUAVER ; SOL#2 db $00, $80, $87, $73, $87, MQUAVER ; LA#2 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 ;mesure 38 db $00, $80, $87, $8A, $87, MQUAVER ; DO#3 db $00, $80, $87, $7C, $87, MQUAVER ; SI2 db $00, $80, $87, $8A, $87, MQUAVER ; DO#3 db $00, $80, $87, $97, $87, MQUAVER ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER ; MI3 db $00, $80, $87, $97, $87, MQUAVER ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER ; MI3 db $00, $80, $87, $A7, $87, MQUAVER ; FA#3 ;mesure 39 db $00, $80, $87, $B1, $87, MQUAVER ; SOL#3 db $00, $80, $87, $BA, $87, MQUAVER ; LA#3 db $00, $80, $87, $BE, $87, MQUAVER ; SI3 db $00, $80, $87, $C1, $87, MQUAVER ; DO4 db $00, $80, $87, $8A, $87, MQUAVER * 4 ; DO#3 ;mesure 40 - 41 db $00, $80, $87, $97, $87, MQUAVER * 2 ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER * 2 ; MI3 db $00, $80, $87, $A7, $87, MQUAVER * 8 ; FA#3 db $00, $80, $87, $62, $87, MQUAVER * 4 ; SOL#2 ;mesure 42 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 ;mesure 43 db $00, $80, $87, $39, $87, MQUAVER * 4 ; MI2 db $00, $80, $87, $7C, $87, MQUAVER * 4 ; SI2 ;mesure 44 db $00, $80, $87, $7C, $87, MQUAVER * 2 ; SI2 db $00, $80, $87, $8A, $87, MQUAVER * 2 ; DO#3 db $00, $80, $87, $7C, $87, MQUAVER * 4 ; SI2 ;mesure 45 db $00, $80, $87, $6B, $87, MQUAVER * 2 ; LA2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER * 4 ; LA2 ;mesure 46 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $6B, $87, MQUAVER * 4 ; LA2 ;mesure 47 db $00, $80, $87, $62, $87, MQUAVER * 2 ; SOL#2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $4F, $87, MQUAVER * 2 ; FA#2 db $00, $80, $87, $39, $87, MQUAVER * 2 ; MI2 ;mesure 48 db $00, $80, $87, $62, $87, MQUAVER * 8 ; SOL#2 ;mesure 49 db $00, $80, $87, $6B, $87, MQUAVER / 3 * 2 ; LA2 db $00, $80, $87, $7C, $87, MQUAVER / 3 * 2 ; SI2 db $00, $80, $87, $8A, $87, MQUAVER / 3 * 2 ; DO#3 db $00, $80, $87, $97, $87, MQUAVER / 3 * 2 ; RE#3 db $00, $80, $87, $9D, $87, MQUAVER / 3 * 2 ; MI3 db $00, $80, $87, $A7, $87, MQUAVER / 3 * 2 ; FA#3 db $00, $80, $87, $B1, $87, MQUAVER * 4 ; SOL#3 ;mesure 50 db $00, $80, $87, $B1, $87, MQUAVER * 2 ; SOL#3 db $00, $80, $87, $B6, $87, MQUAVER * 2 ; LA3 db $00, $80, $87, $B1, $87, MQUAVER * 2 ; SOL#3 db $00, $80, $87, $A7, $87, MQUAVER * 2 ; FA#3 ;mesure 51 db $00, $80, $87, $9D, $87, MQUAVER * 4 ; MI3 db $00, $80, $87, $BE, $87, MQUAVER * 4 ; SI3 ;mesure 52 db $00, $80, $87, $BE, $87, MQUAVER * 2 ; SI3 db $00, $80, $87, $C5, $87, MQUAVER * 2 ; DO#4 db $00, $80, $87, $BE, $87, MQUAVER * 4 ; SI3 ;mesure 53 db $00, $80, $87, $B6, $87, MQUAVER * 2 ; LA3 db $00, $80, $87, $B1, $87, MQUAVER * 2 ; SOL#3 db $00, $80, $87, $B6, $87, MQUAVER * 4 ; LA3 ;mesure 54 db $00, $80, $87, $A7, $87, MQUAVER * 2 ; FA#3 db $00, $80, $87, $B1, $87, MQUAVER * 2 ; SOL#3 db $00, $80, $87, $B6, $87, MQUAVER * 4 ; LA3 ;mesure 55 - 56 db $00, $80, $87, $B1, $87, MQUAVER * 2 ; SOL#3 db $00, $80, $87, $A7, $87, MQUAVER * 2 ; FA#3 db $00, $80, $87, $9D, $87, MQUAVER * 8 ; MI3 db $00, $80, $87, $7C, $87, MQUAVER / 3 * 4 ; SI2 db $00, $80, $00, $7C, $87, MQUAVER / 3 * 8 ; NO SOUND db $00, $80, $00, $7C, $87, $FF ; LOOP
; A219680: Number of n X 2 arrays of the minimum value of corresponding elements and their horizontal, vertical or antidiagonal neighbors in a random, but sorted with lexicographically nondecreasing rows and nonincreasing columns, 0..2 n X 2 array. ; 3,4,9,19,35,60,98,154,234,345,495,693,949,1274,1680,2180,2788,3519,4389,5415,6615,8008,9614,11454,13550,15925,18603,21609,24969,28710,32860,37448,42504,48059,54145,60795,68043,75924,84474,93730,103730,114513 mov $2,$0 cmp $2,0 mov $3,1 mov $4,$0 add $0,$2 mov $1,$0 div $3,$0 cal $1,55417 ; Number of points in N^n of norm <= 2. add $3,$1 sub $3,1 mov $1,$3 mov $5,$4 mul $5,$4 add $1,$5
INCLUDE Irvine32.inc .data score SDWORD ?,0 titleScore BYTE "Score:",0 titleGrade BYTE " Grade:",0 grade BYTE ?,0 grA BYTE "A",0 grB BYTE "B",0 grC BYTE "C",0 grD BYTE "D",0 grF BYTE "F",0 out_of_range BYTE "The integer is not <= 100 and >= 0",0 .code main PROC call Randomize mov eax,101 ;set random range from 0 to 100 mov edx,OFFSET titleScore call WriteString call RandomRange mov score, eax mov edx, score call writeDec mov edx,OFFSET titleGrade call WriteString call GradeCalc mov edx,0 mov grade,al mov edx, OFFSET grade call WriteChar exit main ENDP GradeCalc PROC cmp eax,100 jl Check1 jnle Error1 Check1: cmp eax,80 jl Check2 mov al,grA ret Check2: cmp eax,70 jl Check3 mov al,grB ret Check3: cmp eax,60 jl Check4 mov al,grC ret Check4: cmp eax,50 jl Check5 mov al,grD ret Check5: cmp eax,0 jl Error1 mov al,grF ret Error1: mov edx,OFFSET out_of_range call WriteString call Crlf ret GradeCalc ENDP END main
; ; Copyright (c) 2020 Phillip Stevens ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ; feilipu, August 2020 ; ;------------------------------------------------------------------------- ; asm_am9511_ladd - am9511 long add ;------------------------------------------------------------------------- SECTION code_clib SECTION code_fp_am9511 IFDEF __CLASSIC INCLUDE "../../_DEVELOPMENT/target/am9511/config_am9511_private.inc" ELSE INCLUDE "target/am9511/config_am9511_private.inc" ENDIF EXTERN asm_am9511_pushl EXTERN asm_am9511_pushl_fastcall EXTERN asm_am9511_popl PUBLIC asm_am9511_ladd, asm_am9511_ladd_callee ; enter here for long add, x+y, x on stack, y in dehl, result in dehl .asm_am9511_ladd call asm_am9511_pushl ; x call asm_am9511_pushl_fastcall ; y ld a,__IO_APU_OP_DADD out (__IO_APU_CONTROL),a ; x + y jp asm_am9511_popl ; enter here for long add callee, x+y, x on stack, y in dehl .asm_am9511_ladd_callee call asm_am9511_pushl ; x call asm_am9511_pushl_fastcall ; y ld a,__IO_APU_OP_DADD out (__IO_APU_CONTROL),a ; x + y pop hl ; ret pop de ex (sp),hl ; ret back on stack jp asm_am9511_popl ; result in dehl
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// #include "tink/subtle/aes_gcm_hkdf_stream_segment_decrypter.h" #include <string> #include <utility> #include <vector> #include "gtest/gtest.h" #include "absl/strings/str_cat.h" #include "tink/subtle/aes_gcm_hkdf_stream_segment_encrypter.h" #include "tink/subtle/common_enums.h" #include "tink/subtle/hkdf.h" #include "tink/subtle/random.h" #include "tink/subtle/stream_segment_encrypter.h" #include "tink/util/status.h" #include "tink/util/statusor.h" #include "tink/util/test_util.h" namespace crypto { namespace tink { namespace subtle { namespace { util::StatusOr<std::unique_ptr<StreamSegmentEncrypter>> GetEncrypter( const util::SecretData& ikm, HashType hkdf_hash, int derived_key_size, int ciphertext_offset, int ciphertext_segment_size, absl::string_view associated_data) { AesGcmHkdfStreamSegmentEncrypter::Params params; params.salt = Random::GetRandomBytes(derived_key_size); auto hkdf_result = Hkdf::ComputeHkdf( hkdf_hash, ikm, params.salt, associated_data, derived_key_size); if (!hkdf_result.ok()) return hkdf_result.status(); params.key = hkdf_result.ValueOrDie(); params.ciphertext_offset = ciphertext_offset; params.ciphertext_segment_size = ciphertext_segment_size; return AesGcmHkdfStreamSegmentEncrypter::New(params); } TEST(AesGcmHkdfStreamSegmentDecrypterTest, testBasic) { for (int ikm_size : {16, 32}) { for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) { for (int derived_key_size = 16; derived_key_size <= ikm_size; derived_key_size += 16) { for (int ciphertext_offset : {0, 5, 10}) { for (int ct_segment_size : {80, 128, 200}) { for (std::string associated_data : {"associated data", "42", ""}) { SCOPED_TRACE(absl::StrCat( "hkdf_hash = ", EnumToString(hkdf_hash), ", ikm_size = ", ikm_size, ", associated_data = '", associated_data, "'", ", derived_key_size = ", derived_key_size, ", ciphertext_offset = ", ciphertext_offset, ", ciphertext_segment_size = ", ct_segment_size)); // Construct a decrypter. AesGcmHkdfStreamSegmentDecrypter::Params params; params.ikm = Random::GetRandomKeyBytes(ikm_size); params.hkdf_hash = hkdf_hash; params.derived_key_size = derived_key_size; params.ciphertext_offset = ciphertext_offset; params.ciphertext_segment_size = ct_segment_size; params.associated_data = associated_data; auto result = AesGcmHkdfStreamSegmentDecrypter::New(params); EXPECT_TRUE(result.ok()) << result.status(); auto dec = std::move(result.ValueOrDie()); // Try to use the decrypter. std::vector<uint8_t> pt; auto status = dec->DecryptSegment(pt, 42, false, nullptr); EXPECT_FALSE(status.ok()); EXPECT_EQ(absl::StatusCode::kFailedPrecondition, status.code()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "not initialized", std::string(status.message())); // Get an encrypter and initialize the decrypter. auto enc = std::move( GetEncrypter(params.ikm, hkdf_hash, derived_key_size, ciphertext_offset, ct_segment_size, associated_data).ValueOrDie()); status = dec->Init(enc->get_header()); EXPECT_TRUE(status.ok()) << status; // Use the constructed decrypter. int header_size = derived_key_size + /* nonce_prefix_size = */ 7 + 1; EXPECT_EQ(header_size, dec->get_header_size()); EXPECT_EQ(enc->get_header().size(), dec->get_header_size()); EXPECT_EQ(ct_segment_size, dec->get_ciphertext_segment_size()); EXPECT_EQ(ct_segment_size - /* tag_size = */ 16, dec->get_plaintext_segment_size()); EXPECT_EQ(ciphertext_offset, dec->get_ciphertext_offset()); int segment_number = 0; for (int pt_size : {1, 10, dec->get_plaintext_segment_size()}) { for (bool is_last_segment : {false, true}) { SCOPED_TRACE(absl::StrCat( "plaintext_size = ", pt_size, ", is_last_segment = ", is_last_segment)); std::vector<uint8_t> pt(pt_size, 'p'); std::vector<uint8_t> ct; std::vector<uint8_t> decrypted; auto status = enc->EncryptSegment(pt, is_last_segment, &ct); EXPECT_TRUE(status.ok()) << status; status = dec->DecryptSegment(ct, segment_number, is_last_segment, &decrypted); EXPECT_TRUE(status.ok()) << status; EXPECT_EQ(pt, decrypted); segment_number++; EXPECT_EQ(segment_number, enc->get_segment_number()); } } // Try decryption with wrong params. std::vector<uint8_t> ct( dec->get_ciphertext_segment_size() + 1, 'c'); status = dec->DecryptSegment(ct, 42, true, nullptr); EXPECT_FALSE(status.ok()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "ciphertext too long", std::string(status.message())); ct.resize(dec->get_plaintext_segment_size()); status = dec->DecryptSegment(ct, 42, true, nullptr); EXPECT_FALSE(status.ok()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be non-null", std::string(status.message())); } } } } } } } TEST(AesGcmHkdfStreamSegmentDecrypterTest, testWrongDerivedKeySize) { for (int derived_key_size : {12, 24, 64}) { for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) { for (int ct_segment_size : {128, 200}) { SCOPED_TRACE(absl::StrCat( "derived_key_size = ", derived_key_size, ", hkdf_hash = ", EnumToString(hkdf_hash), ", ciphertext_segment_size = ", ct_segment_size)); AesGcmHkdfStreamSegmentDecrypter::Params params; params.ikm = Random::GetRandomKeyBytes(derived_key_size); params.hkdf_hash = hkdf_hash; params.derived_key_size = derived_key_size; params.ciphertext_offset = 0; params.ciphertext_segment_size = ct_segment_size; params.associated_data = "associated data"; auto result = AesGcmHkdfStreamSegmentDecrypter::New(params); EXPECT_FALSE(result.ok()); EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be 16 or 32", std::string(result.status().message())); } } } } TEST(AesGcmHkdfStreamSegmentDecrypterTest, testWrongIkmSize) { for (int derived_key_size : {16, 32}) { for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) { for (int ikm_size_delta : {-8, -4, -2, -1}) { SCOPED_TRACE(absl::StrCat( "derived_key_size = ", derived_key_size, ", hkdf_hash = ", EnumToString(hkdf_hash), ", ikm_size_delta = ", ikm_size_delta)); AesGcmHkdfStreamSegmentDecrypter::Params params; params.ikm = Random::GetRandomKeyBytes(derived_key_size + ikm_size_delta); params.hkdf_hash = hkdf_hash; params.derived_key_size = derived_key_size; params.ciphertext_offset = 0; params.ciphertext_segment_size = 128; params.associated_data = "associated data"; auto result = AesGcmHkdfStreamSegmentDecrypter::New(params); EXPECT_FALSE(result.ok()); EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small", std::string(result.status().message())); } } } } TEST(AesGcmHkdfStreamSegmentDecrypterTest, testWrongCiphertextOffset) { for (int derived_key_size : {16, 32}) { for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) { for (int ciphertext_offset : {-16, -10, -3, -1}) { SCOPED_TRACE(absl::StrCat( "derived_key_size = ", derived_key_size, ", hkdf_hash = ", EnumToString(hkdf_hash), ", ciphertext_offset = ", ciphertext_offset)); AesGcmHkdfStreamSegmentDecrypter::Params params; params.ikm = Random::GetRandomKeyBytes(derived_key_size); params.hkdf_hash = hkdf_hash; params.derived_key_size = derived_key_size; params.ciphertext_offset = ciphertext_offset; params.ciphertext_segment_size = 128; params.associated_data = "associated data"; auto result = AesGcmHkdfStreamSegmentDecrypter::New(params); EXPECT_FALSE(result.ok()); EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be non-negative", std::string(result.status().message())); } } } } TEST(AesGcmHkdfStreamSegmentDecrypterTest, testWrongCiphertextSegmentSize) { for (int derived_key_size : {16, 32}) { for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) { for (int ciphertext_offset : {0, 1, 5, 10}) { int min_ct_segment_size = derived_key_size + ciphertext_offset + 8 + // nonce_prefix_size + 1 16 + // tag_size 1; for (int ct_segment_size : {min_ct_segment_size - 5, min_ct_segment_size - 1, min_ct_segment_size, min_ct_segment_size + 1, min_ct_segment_size + 10}) { SCOPED_TRACE(absl::StrCat( "derived_key_size = ", derived_key_size, ", ciphertext_offset = ", ciphertext_offset, ", ciphertext_segment_size = ", ct_segment_size)); AesGcmHkdfStreamSegmentDecrypter::Params params; params.ikm = Random::GetRandomKeyBytes(derived_key_size); params.hkdf_hash = hkdf_hash; params.derived_key_size = derived_key_size; params.ciphertext_offset = ciphertext_offset; params.ciphertext_segment_size = ct_segment_size; auto result = AesGcmHkdfStreamSegmentDecrypter::New(params); if (ct_segment_size < min_ct_segment_size) { EXPECT_FALSE(result.ok()); EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code()); EXPECT_PRED_FORMAT2(testing::IsSubstring, "too small", std::string(result.status().message())); } else { EXPECT_TRUE(result.ok()) << result.status(); } } } } } } } // namespace } // namespace subtle } // namespace tink } // namespace crypto
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =========================================================================== // File: CEELOAD.CPP // // // CEELOAD reads in the PE file format using LoadLibrary // =========================================================================== #include "common.h" #include "array.h" #include "ceeload.h" #include "hash.h" #include "vars.hpp" #include "reflectclasswriter.h" #include "method.hpp" #include "stublink.h" #include "cgensys.h" #include "excep.h" #include "dbginterface.h" #include "dllimport.h" #include "eeprofinterfaces.h" #include "perfcounters.h" #include "encee.h" #include "jitinterface.h" #include "eeconfig.h" #include "dllimportcallback.h" #include "contractimpl.h" #include "typehash.h" #include "instmethhash.h" #include "virtualcallstub.h" #include "typestring.h" #include "stringliteralmap.h" #include <formattype.h> #include "fieldmarshaler.h" #include "sigbuilder.h" #include "metadataexports.h" #include "inlinetracking.h" #ifdef FEATURE_PREJIT #include "exceptionhandling.h" #include "corcompile.h" #include "compile.h" #include "nibblestream.h" #include "zapsig.h" #endif //FEATURE_PREJIT #ifdef FEATURE_COMINTEROP #include "runtimecallablewrapper.h" #include "comcallablewrapper.h" #endif //FEATURE_COMINTEROP #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4724) #endif // _MSC_VER #include "ngenhash.inl" #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER #include "perflog.h" #include "ecall.h" #include "../md/compiler/custattr.h" #include "typekey.h" #include "peimagelayout.inl" #include "ildbsymlib.h" #if defined(PROFILING_SUPPORTED) #include "profilermetadataemitvalidator.h" #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4244) #endif // _MSC_VER #ifdef _TARGET_64BIT_ #define COR_VTABLE_PTRSIZED COR_VTABLE_64BIT #define COR_VTABLE_NOT_PTRSIZED COR_VTABLE_32BIT #else // !_TARGET_64BIT_ #define COR_VTABLE_PTRSIZED COR_VTABLE_32BIT #define COR_VTABLE_NOT_PTRSIZED COR_VTABLE_64BIT #endif // !_TARGET_64BIT_ #define CEE_FILE_GEN_GROWTH_COLLECTIBLE 2048 #define NGEN_STATICS_ALLCLASSES_WERE_LOADED -1 BOOL Module::HasInlineTrackingMap() { LIMITED_METHOD_DAC_CONTRACT; #ifdef FEATURE_READYTORUN if (IsReadyToRun() && GetReadyToRunInfo()->GetInlineTrackingMap() != NULL) { return TRUE; } #endif return (m_pPersistentInlineTrackingMapNGen != NULL); } COUNT_T Module::GetInliners(PTR_Module inlineeOwnerMod, mdMethodDef inlineeTkn, COUNT_T inlinersSize, MethodInModule inliners[], BOOL *incompleteData) { WRAPPER_NO_CONTRACT; #ifdef FEATURE_READYTORUN if(IsReadyToRun() && GetReadyToRunInfo()->GetInlineTrackingMap() != NULL) { return GetReadyToRunInfo()->GetInlineTrackingMap()->GetInliners(inlineeOwnerMod, inlineeTkn, inlinersSize, inliners, incompleteData); } #endif if(m_pPersistentInlineTrackingMapNGen != NULL) { return m_pPersistentInlineTrackingMapNGen->GetInliners(inlineeOwnerMod, inlineeTkn, inlinersSize, inliners, incompleteData); } return 0; } #ifndef DACCESS_COMPILE // =========================================================================== // Module // =========================================================================== //--------------------------------------------------------------------------------------------------- // This wrapper just invokes the real initialization inside a try/hook. // szName is not null only for dynamic modules //--------------------------------------------------------------------------------------------------- void Module::DoInit(AllocMemTracker *pamTracker, LPCWSTR szName) { CONTRACTL { INSTANCE_CHECK; STANDARD_VM_CHECK; } CONTRACTL_END; #ifdef PROFILING_SUPPORTED { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); GCX_COOP(); g_profControlBlock.pProfInterface->ModuleLoadStarted((ModuleID) this); END_PIN_PROFILER(); } // Need TRY/HOOK instead of holder so we can get HR of exception thrown for profiler callback EX_TRY #endif { Initialize(pamTracker, szName); } #ifdef PROFILING_SUPPORTED EX_HOOK { { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); g_profControlBlock.pProfInterface->ModuleLoadFinished((ModuleID) this, GET_EXCEPTION()->GetHR()); END_PIN_PROFILER(); } } EX_END_HOOK; #endif } // Set the given bit on m_dwTransientFlags. Return true if we won the race to set the bit. BOOL Module::SetTransientFlagInterlocked(DWORD dwFlag) { LIMITED_METHOD_CONTRACT; for (;;) { DWORD dwTransientFlags = m_dwTransientFlags; if ((dwTransientFlags & dwFlag) != 0) return FALSE; if ((DWORD)FastInterlockCompareExchange((LONG*)&m_dwTransientFlags, dwTransientFlags | dwFlag, dwTransientFlags) == dwTransientFlags) return TRUE; } } #if PROFILING_SUPPORTED void Module::NotifyProfilerLoadFinished(HRESULT hr) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM()); MODE_ANY; } CONTRACTL_END; // Note that in general we wil reuse shared modules. So we need to make sure we only notify // the profiler once. if (SetTransientFlagInterlocked(IS_PROFILER_NOTIFIED)) { // Record how many types are already present DWORD countTypesOrig = 0; DWORD countExportedTypesOrig = 0; if (!IsResource()) { countTypesOrig = GetMDImport()->GetCountWithTokenKind(mdtTypeDef); countExportedTypesOrig = GetMDImport()->GetCountWithTokenKind(mdtExportedType); } // Notify the profiler, this may cause metadata to be updated { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); { GCX_PREEMP(); g_profControlBlock.pProfInterface->ModuleLoadFinished((ModuleID) this, hr); if (SUCCEEDED(hr)) { g_profControlBlock.pProfInterface->ModuleAttachedToAssembly((ModuleID) this, (AssemblyID)m_pAssembly); } } END_PIN_PROFILER(); } // If there are more types than before, add these new types to the // assembly if (!IsResource()) { DWORD countTypesAfterProfilerUpdate = GetMDImport()->GetCountWithTokenKind(mdtTypeDef); DWORD countExportedTypesAfterProfilerUpdate = GetMDImport()->GetCountWithTokenKind(mdtExportedType); // typeDefs rids 0 and 1 aren't included in the count, thus X typeDefs before means rid X+1 was valid and our incremental addition should start at X+2 for (DWORD typeDefRid = countTypesOrig + 2; typeDefRid < countTypesAfterProfilerUpdate + 2; typeDefRid++) { GetAssembly()->AddType(this, TokenFromRid(typeDefRid, mdtTypeDef)); } // exportedType rid 0 isn't included in the count, thus X exportedTypes before means rid X was valid and our incremental addition should start at X+1 for (DWORD exportedTypeDef = countExportedTypesOrig + 1; exportedTypeDef < countExportedTypesAfterProfilerUpdate + 1; exportedTypeDef++) { GetAssembly()->AddExportedType(TokenFromRid(exportedTypeDef, mdtExportedType)); } } { BEGIN_PIN_PROFILER(CORProfilerTrackAssemblyLoads()); if (IsManifest()) { GCX_COOP(); g_profControlBlock.pProfInterface->AssemblyLoadFinished((AssemblyID) m_pAssembly, hr); } END_PIN_PROFILER(); } } } #ifndef CROSSGEN_COMPILE IMetaDataEmit *Module::GetValidatedEmitter() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM()); MODE_ANY; } CONTRACTL_END; if (m_pValidatedEmitter.Load() == NULL) { // In the past profilers could call any API they wanted on the the IMetaDataEmit interface and we didn't // verify anything. To ensure we don't break back-compat the verifications are not enabled by default. // Right now I have only added verifications for NGEN images, but in the future we might want verifications // for all modules. IMetaDataEmit* pEmit = NULL; if (CLRConfig::GetConfigValue(CLRConfig::UNSUPPORTED_ProfAPI_ValidateNGENInstrumentation) && HasNativeImage()) { ProfilerMetadataEmitValidator* pValidator = new ProfilerMetadataEmitValidator(GetEmitter()); pValidator->QueryInterface(IID_IMetaDataEmit, (void**)&pEmit); } else { pEmit = GetEmitter(); pEmit->AddRef(); } // Atomically swap it into the field (release it if we lose the race) if (FastInterlockCompareExchangePointer(&m_pValidatedEmitter, pEmit, NULL) != NULL) { pEmit->Release(); } } return m_pValidatedEmitter.Load(); } #endif // CROSSGEN_COMPILE #endif // PROFILING_SUPPORTED void Module::NotifyEtwLoadFinished(HRESULT hr) { CONTRACTL { NOTHROW; GC_TRIGGERS; } CONTRACTL_END // we report only successful loads if (SUCCEEDED(hr) && ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_Context, TRACE_LEVEL_INFORMATION, KEYWORDZERO)) { BOOL fSharedModule = !SetTransientFlagInterlocked(IS_ETW_NOTIFIED); ETW::LoaderLog::ModuleLoad(this, fSharedModule); } } // Module initialization occurs in two phases: the constructor phase and the Initialize phase. // // The constructor phase initializes just enough so that Destruct() can be safely called. // It cannot throw or fail. // Module::Module(Assembly *pAssembly, mdFile moduleRef, PEFile *file) { CONTRACTL { NOTHROW; GC_TRIGGERS; FORBID_FAULT; } CONTRACTL_END PREFIX_ASSUME(pAssembly != NULL); m_pAssembly = pAssembly; m_moduleRef = moduleRef; m_file = file; m_dwTransientFlags = CLASSES_FREED; if (!m_file->HasNativeImage()) { // Memory allocated on LoaderHeap is zero-filled. Spot-check it here. _ASSERTE(m_pBinder == NULL); _ASSERTE(m_symbolFormat == eSymbolFormatNone); } file->AddRef(); } void Module::InitializeForProfiling() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; PRECONDITION(HasNativeOrReadyToRunImage()); } CONTRACTL_END; COUNT_T cbProfileList = 0; m_nativeImageProfiling = FALSE; if (HasNativeImage()) { PEImageLayout * pNativeImage = GetNativeImage(); CORCOMPILE_VERSION_INFO * pNativeVersionInfo = pNativeImage->GetNativeVersionInfoMaybeNull(); if ((pNativeVersionInfo != NULL) && (pNativeVersionInfo->wConfigFlags & CORCOMPILE_CONFIG_INSTRUMENTATION)) { m_nativeImageProfiling = GetAssembly()->IsInstrumented(); } // Link the module to the profile data list if available. m_methodProfileList = pNativeImage->GetNativeProfileDataList(&cbProfileList); } else // ReadyToRun image { #ifdef FEATURE_READYTORUN // We already setup the m_methodProfileList in the ReadyToRunInfo constructor if (m_methodProfileList != nullptr) { ReadyToRunInfo * pInfo = GetReadyToRunInfo(); PEImageLayout * pImage = pInfo->GetImage(); // Enable profiling if the ZapBBInstr value says to m_nativeImageProfiling = GetAssembly()->IsInstrumented(); } #endif } #ifdef FEATURE_LAZY_COW_PAGES // When running a IBC tuning image to gather profile data // we increment the block counts contained in this area. // if (cbProfileList) EnsureWritablePages(m_methodProfileList, cbProfileList); #endif } #ifdef FEATURE_PREJIT void Module::InitializeNativeImage(AllocMemTracker* pamTracker) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; PRECONDITION(HasNativeImage()); } CONTRACTL_END; PEImageLayout * pNativeImage = GetNativeImage(); ExecutionManager::AddNativeImageRange(dac_cast<TADDR>(pNativeImage->GetBase()), pNativeImage->GetVirtualSize(), this); #ifndef CROSSGEN_COMPILE LoadTokenTables(); LoadHelperTable(); #endif // CROSSGEN_COMPILE #if defined(HAVE_GCCOVER) if (GCStress<cfg_instr_ngen>::IsEnabled()) { // Setting up gc coverage requires the base system classes // to be initialized. So we must defer this for mscorlib. if(!IsSystem()) { SetupGcCoverageForNativeImage(this); } } #endif // defined(HAVE_GCCOVER) } void Module::SetNativeMetadataAssemblyRefInCache(DWORD rid, PTR_Assembly pAssembly) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (m_NativeMetadataAssemblyRefMap == NULL) { IMDInternalImport* pImport = GetNativeAssemblyImport(); DWORD dwMaxRid = pImport->GetCountWithTokenKind(mdtAssemblyRef); _ASSERTE(dwMaxRid > 0); S_SIZE_T dwAllocSize = S_SIZE_T(sizeof(PTR_Assembly)) * S_SIZE_T(dwMaxRid); AllocMemTracker amTracker; PTR_Assembly * NativeMetadataAssemblyRefMap = (PTR_Assembly *) amTracker.Track( GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(dwAllocSize) ); // Note: Memory allocated on loader heap is zero filled if (InterlockedCompareExchangeT<PTR_Assembly *>(&m_NativeMetadataAssemblyRefMap, NativeMetadataAssemblyRefMap, NULL) == NULL) amTracker.SuppressRelease(); } _ASSERTE(m_NativeMetadataAssemblyRefMap != NULL); _ASSERTE(rid <= GetNativeAssemblyImport()->GetCountWithTokenKind(mdtAssemblyRef)); m_NativeMetadataAssemblyRefMap[rid-1] = pAssembly; } #else // FEATURE_PREJIT BOOL Module::IsPersistedObject(void *address) { LIMITED_METHOD_CONTRACT; return FALSE; } #endif // FEATURE_PREJIT // Module initialization occurs in two phases: the constructor phase and the Initialize phase. // // The Initialize() phase completes the initialization after the constructor has run. // It can throw exceptions but whether it throws or succeeds, it must leave the Module // in a state where Destruct() can be safely called. // // szName is only used by dynamic modules, see ReflectionModule::Initialize // // void Module::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName) { CONTRACTL { INSTANCE_CHECK; STANDARD_VM_CHECK; PRECONDITION(szName == NULL); } CONTRACTL_END; m_pSimpleName = m_file->GetSimpleName(); m_Crst.Init(CrstModule); m_LookupTableCrst.Init(CrstModuleLookupTable, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD)); m_FixupCrst.Init(CrstModuleFixup, (CrstFlags)(CRST_HOST_BREAKABLE|CRST_REENTRANCY)); m_InstMethodHashTableCrst.Init(CrstInstMethodHashTable, CRST_REENTRANCY); m_ISymUnmanagedReaderCrst.Init(CrstISymUnmanagedReader, CRST_DEBUGGER_THREAD); if (!m_file->HasNativeImage()) { AllocateMaps(); if (IsSystem() || (strcmp(m_pSimpleName, "System") == 0) || (strcmp(m_pSimpleName, "System.Core") == 0) || (strcmp(m_pSimpleName, "Windows.Foundation") == 0)) { FastInterlockOr(&m_dwPersistedFlags, LOW_LEVEL_SYSTEM_ASSEMBLY_BY_NAME); } } m_dwTransientFlags &= ~((DWORD)CLASSES_FREED); // Set flag indicating LookupMaps are now in a consistent and destructable state #ifdef FEATURE_READYTORUN if (!HasNativeImage() && !IsResource()) m_pReadyToRunInfo = ReadyToRunInfo::Initialize(this, pamTracker); #endif // Initialize the instance fields that we need for all non-Resource Modules if (!IsResource()) { if (m_pAvailableClasses == NULL && !IsReadyToRun()) { m_pAvailableClasses = EEClassHashTable::Create(this, GetAssembly()->IsCollectible() ? AVAILABLE_CLASSES_HASH_BUCKETS_COLLECTIBLE : AVAILABLE_CLASSES_HASH_BUCKETS, FALSE /* bCaseInsensitive */, pamTracker); } if (m_pAvailableParamTypes == NULL) { m_pAvailableParamTypes = EETypeHashTable::Create(GetLoaderAllocator(), this, PARAMTYPES_HASH_BUCKETS, pamTracker); } if (m_pInstMethodHashTable == NULL) { m_pInstMethodHashTable = InstMethodHashTable::Create(GetLoaderAllocator(), this, PARAMMETHODS_HASH_BUCKETS, pamTracker); } if(m_pMemberRefToDescHashTable == NULL) { if (IsReflection()) { m_pMemberRefToDescHashTable = MemberRefToDescHashTable::Create(this, MEMBERREF_MAP_INITIAL_SIZE, pamTracker); } else { IMDInternalImport * pImport = GetMDImport(); // Get #MemberRefs and create memberrefToDesc hash table m_pMemberRefToDescHashTable = MemberRefToDescHashTable::Create(this, pImport->GetCountWithTokenKind(mdtMemberRef)+1, pamTracker); } } #ifdef FEATURE_COMINTEROP if (IsCompilationProcess() && m_pGuidToTypeHash == NULL) { // only allocate this during NGEN-ing m_pGuidToTypeHash = GuidToMethodTableHashTable::Create(this, GUID_TO_TYPE_HASH_BUCKETS, pamTracker); } #endif // FEATURE_COMINTEROP } if (GetAssembly()->IsDomainNeutral() && !IsSingleAppDomain()) { m_ModuleIndex = Module::AllocateModuleIndex(); m_ModuleID = (DomainLocalModule*)Module::IndexToID(m_ModuleIndex); } else { // this will be initialized a bit later. m_ModuleID = NULL; m_ModuleIndex.m_dwIndex = (SIZE_T)-1; } #ifdef FEATURE_COLLECTIBLE_TYPES if (GetAssembly()->IsCollectible()) { FastInterlockOr(&m_dwPersistedFlags, COLLECTIBLE_MODULE); } #endif // FEATURE_COLLECTIBLE_TYPES // Prepare statics that are known at module load time AllocateStatics(pamTracker); #ifdef FEATURE_PREJIT // Set up native image if (HasNativeImage()) { InitializeNativeImage(pamTracker); } #endif // FEATURE_PREJIT if (HasNativeOrReadyToRunImage()) { InitializeForProfiling(); } #ifdef FEATURE_NATIVE_IMAGE_GENERATION if (g_CorCompileVerboseLevel) m_pNgenStats = new NgenStats(); #endif if (!IsResource() && (m_AssemblyRefByNameTable == NULL)) { Module::CreateAssemblyRefByNameTable(pamTracker); } // If the program has the "ForceEnc" env variable set we ensure every eligible // module has EnC turned on. if (g_pConfig->ForceEnc() && IsEditAndContinueCapable()) EnableEditAndContinue(); LOG((LF_CLASSLOADER, LL_INFO10, "Loaded pModule: \"%ws\".\n", GetDebugName())); } #endif // DACCESS_COMPILE #ifdef FEATURE_COMINTEROP #ifndef DACCESS_COMPILE // static GuidToMethodTableHashTable* GuidToMethodTableHashTable::Create(Module* pModule, DWORD cInitialBuckets, AllocMemTracker *pamTracker) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED()); } CONTRACTL_END; LoaderHeap *pHeap = pModule->GetAssembly()->GetLowFrequencyHeap(); GuidToMethodTableHashTable *pThis = (GuidToMethodTableHashTable*)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(GuidToMethodTableHashTable))); // The base class get initialized through chaining of constructors. We allocated the hash instance via the // loader heap instead of new so use an in-place new to call the constructors now. new (pThis) GuidToMethodTableHashTable(pModule, pHeap, cInitialBuckets); return pThis; } GuidToMethodTableEntry *GuidToMethodTableHashTable::InsertValue(PTR_GUID pGuid, PTR_MethodTable pMT, BOOL bReplaceIfFound, AllocMemTracker *pamTracker) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED()); } CONTRACTL_END; GuidToMethodTableEntry *pEntry = NULL; if (bReplaceIfFound) { pEntry = FindItem(pGuid, NULL); } if (pEntry != NULL) { pEntry->m_pMT = pMT; } else { pEntry = BaseAllocateEntry(pamTracker); pEntry->m_Guid = pGuid; pEntry->m_pMT = pMT; DWORD hash = Hash(pGuid); BaseInsertEntry(hash, pEntry); } return pEntry; } #endif // !DACCESS_COMPILE PTR_MethodTable GuidToMethodTableHashTable::GetValue(const GUID * pGuid, LookupContext *pContext) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; PRECONDITION(CheckPointer(pGuid)); } CONTRACTL_END; GuidToMethodTableEntry * pEntry = FindItem(pGuid, pContext); if (pEntry != NULL) { return pEntry->m_pMT; } return NULL; } GuidToMethodTableEntry *GuidToMethodTableHashTable::FindItem(const GUID * pGuid, LookupContext *pContext) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; PRECONDITION(CheckPointer(pGuid)); } CONTRACTL_END; // It's legal for the caller not to pass us a LookupContext, but we might need to iterate // internally (since we lookup via hash and hashes may collide). So substitute our own // private context if one was not provided. LookupContext sAltContext; if (pContext == NULL) pContext = &sAltContext; // The base class provides the ability to enumerate all entries with the same hash code. // We further check which of these entries actually match the full key. PTR_GuidToMethodTableEntry pSearch = BaseFindFirstEntryByHash(Hash(pGuid), pContext); while (pSearch) { if (CompareKeys(pSearch, pGuid)) { return pSearch; } pSearch = BaseFindNextEntryByHash(pContext); } return NULL; } BOOL GuidToMethodTableHashTable::CompareKeys(PTR_GuidToMethodTableEntry pEntry, const GUID * pGuid) { LIMITED_METHOD_DAC_CONTRACT; return *pGuid == *(pEntry->m_Guid); } DWORD GuidToMethodTableHashTable::Hash(const GUID * pGuid) { LIMITED_METHOD_DAC_CONTRACT; static_assert_no_msg(sizeof(GUID) % sizeof(DWORD) == 0); static_assert_no_msg(sizeof(GUID) / sizeof(DWORD) == 4); DWORD * pSlice = (DWORD*) pGuid; return pSlice[0] ^ pSlice[1] ^ pSlice[2] ^ pSlice[3]; } BOOL GuidToMethodTableHashTable::FindNext(Iterator *it, GuidToMethodTableEntry **ppEntry) { LIMITED_METHOD_DAC_CONTRACT; if (!it->m_fIterating) { BaseInitIterator(&it->m_sIterator); it->m_fIterating = true; } *ppEntry = it->m_sIterator.Next(); return *ppEntry ? TRUE : FALSE; } DWORD GuidToMethodTableHashTable::GetCount() { LIMITED_METHOD_DAC_CONTRACT; return BaseGetElementCount(); } #if defined(FEATURE_NATIVE_IMAGE_GENERATION) && !defined(DACCESS_COMPILE) void GuidToMethodTableHashTable::Save(DataImage *pImage, CorProfileData *pProfileData) { WRAPPER_NO_CONTRACT; Base_t::BaseSave(pImage, pProfileData); } void GuidToMethodTableHashTable::Fixup(DataImage *pImage) { WRAPPER_NO_CONTRACT; Base_t::BaseFixup(pImage); } bool GuidToMethodTableHashTable::SaveEntry(DataImage *pImage, CorProfileData *pProfileData, GuidToMethodTableEntry *pOldEntry, GuidToMethodTableEntry *pNewEntry, EntryMappingTable *pMap) { LIMITED_METHOD_CONTRACT; return false; } void GuidToMethodTableHashTable::FixupEntry(DataImage *pImage, GuidToMethodTableEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset) { WRAPPER_NO_CONTRACT; pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_pMT), pEntry->m_pMT); pImage->FixupField(pFixupBase, cbFixupOffset + offsetof(GuidToMethodTableEntry, m_Guid), pEntry->m_Guid); } #endif // FEATURE_NATIVE_IMAGE_GENERATION && !DACCESS_COMPILE #ifdef FEATURE_PREJIT #ifndef DACCESS_COMPILE BOOL Module::CanCacheWinRTTypeByGuid(MethodTable *pMT) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; PRECONDITION(IsCompilationProcess()); } CONTRACTL_END; // Don't cache mscorlib-internal declarations of WinRT types. if (IsSystem() && pMT->IsProjectedFromWinRT()) return FALSE; // Don't cache redirected WinRT types. if (WinRTTypeNameConverter::IsRedirectedWinRTSourceType(pMT)) return FALSE; #ifdef FEATURE_NATIVE_IMAGE_GENERATION // Don't cache in a module that's not the NGen target, since the result // won't be saved, and since the such a module might be read-only. if (GetAppDomain()->ToCompilationDomain()->GetTargetModule() != this) return FALSE; #endif return TRUE; } void Module::CacheWinRTTypeByGuid(PTR_MethodTable pMT, PTR_GuidInfo pgi /*= NULL*/) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pMT)); PRECONDITION(pMT->IsLegalNonArrayWinRTType()); PRECONDITION(pgi != NULL || pMT->GetGuidInfo() != NULL); PRECONDITION(IsCompilationProcess()); } CONTRACTL_END; if (pgi == NULL) { pgi = pMT->GetGuidInfo(); } AllocMemTracker amt; m_pGuidToTypeHash->InsertValue(&pgi->m_Guid, pMT, TRUE, &amt); amt.SuppressRelease(); } #endif // !DACCESS_COMPILE PTR_MethodTable Module::LookupTypeByGuid(const GUID & guid) { WRAPPER_NO_CONTRACT; // Triton ni images do not have this hash. if (m_pGuidToTypeHash != NULL) return m_pGuidToTypeHash->GetValue(&guid, NULL); else return NULL; } void Module::GetCachedWinRTTypes(SArray<PTR_MethodTable> * pTypes, SArray<GUID> * pGuids) { CONTRACTL { STANDARD_VM_CHECK; SUPPORTS_DAC; } CONTRACTL_END; // Triton ni images do not have this hash. if (m_pGuidToTypeHash != NULL) { GuidToMethodTableHashTable::Iterator it(m_pGuidToTypeHash); GuidToMethodTableEntry *pEntry; while (m_pGuidToTypeHash->FindNext(&it, &pEntry)) { pTypes->Append(pEntry->m_pMT); pGuids->Append(*pEntry->m_Guid); } } } #endif // FEATURE_PREJIT #endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE MemberRefToDescHashTable* MemberRefToDescHashTable::Create(Module *pModule, DWORD cInitialBuckets, AllocMemTracker *pamTracker) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED()); } CONTRACTL_END; LoaderHeap *pHeap = pModule->GetAssembly()->GetLowFrequencyHeap(); MemberRefToDescHashTable *pThis = (MemberRefToDescHashTable*)pamTracker->Track(pHeap->AllocMem((S_SIZE_T)sizeof(MemberRefToDescHashTable))); // The base class get initialized through chaining of constructors. We allocated the hash instance via the // loader heap instead of new so use an in-place new to call the constructors now. new (pThis) MemberRefToDescHashTable(pModule, pHeap, cInitialBuckets); return pThis; } //Inserts FieldRef MemberRefToDescHashEntry* MemberRefToDescHashTable::Insert(mdMemberRef token , FieldDesc *value) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED()); } CONTRACTL_END; LookupContext sAltContext; _ASSERTE((dac_cast<TADDR>(value) & IS_FIELD_MEMBER_REF) == 0); MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(token), &sAltContext); if (pEntry != NULL) { // If memberRef is hot token in that case entry for memberref is already persisted in ngen image. So entry for it will already be present in hash table. // However its value will be null. We need to set its actual value. if(pEntry->m_value == dac_cast<TADDR>(NULL)) { EnsureWritablePages(&(pEntry->m_value)); pEntry->m_value = dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF; } _ASSERTE(pEntry->m_value == (dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF)); return pEntry; } // For non hot tokens insert new entry in hashtable pEntry = BaseAllocateEntry(NULL); pEntry->m_value = dac_cast<TADDR>(value)|IS_FIELD_MEMBER_REF; BaseInsertEntry(RidFromToken(token), pEntry); return pEntry; } // Insert MethodRef MemberRefToDescHashEntry* MemberRefToDescHashTable::Insert(mdMemberRef token , MethodDesc *value) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); PRECONDITION(!FORBIDGC_LOADER_USE_ENABLED()); } CONTRACTL_END; LookupContext sAltContext; MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(token), &sAltContext); if (pEntry != NULL) { // If memberRef is hot token in that case entry for memberref is already persisted in ngen image. So entry for it will already be present in hash table. // However its value will be null. We need to set its actual value. if(pEntry->m_value == dac_cast<TADDR>(NULL)) { EnsureWritablePages(&(pEntry->m_value)); pEntry->m_value = dac_cast<TADDR>(value); } _ASSERTE(pEntry->m_value == dac_cast<TADDR>(value)); return pEntry; } // For non hot tokens insert new entry in hashtable pEntry = BaseAllocateEntry(NULL); pEntry->m_value = dac_cast<TADDR>(value); BaseInsertEntry(RidFromToken(token), pEntry); return pEntry; } #if defined(FEATURE_NATIVE_IMAGE_GENERATION) void MemberRefToDescHashTable::Save(DataImage *pImage, CorProfileData *pProfileData) { STANDARD_VM_CONTRACT; // Mark if the tokens are hot if (pProfileData) { DWORD numInTokenList = pProfileData->GetHotTokens(mdtMemberRef>>24, 1<<RidMap, 1<<RidMap, NULL, 0); if (numInTokenList > 0) { LookupContext sAltContext; mdToken *tokenList = (mdToken*)(void*)pImage->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(mdToken)) * S_SIZE_T(numInTokenList)); pProfileData->GetHotTokens(mdtMemberRef>>24, 1<<RidMap, 1<<RidMap, tokenList, numInTokenList); for (DWORD i = 0; i < numInTokenList; i++) { DWORD rid = RidFromToken(tokenList[i]); MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(tokenList[i]), &sAltContext); if (pEntry != NULL) { _ASSERTE((pEntry->m_value & 0x1) == 0); pEntry->m_value |= 0x1; } } } } BaseSave(pImage, pProfileData); } void MemberRefToDescHashTable::FixupEntry(DataImage *pImage, MemberRefToDescHashEntry *pEntry, void *pFixupBase, DWORD cbFixupOffset) { //As there is no more hard binding initialize MemberRef* to NULL pImage->ZeroPointerField(pFixupBase, cbFixupOffset + offsetof(MemberRefToDescHashEntry, m_value)); } #endif // FEATURE_NATIVE_IMAGE_GENERATION #endif // !DACCESS_COMPILE PTR_MemberRef MemberRefToDescHashTable::GetValue(mdMemberRef token, BOOL *pfIsMethod) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; LookupContext sAltContext; MemberRefToDescHashEntry *pEntry = (PTR_MemberRefToDescHashEntry) BaseFindFirstEntryByHash(RidFromToken(token), &sAltContext); if (pEntry != NULL) { if(pEntry->m_value & IS_FIELD_MEMBER_REF) *pfIsMethod = FALSE; else *pfIsMethod = TRUE; return (PTR_MemberRef)(pEntry->m_value & (~MEMBER_REF_MAP_ALL_FLAGS)); } return NULL; } void Module::SetDebuggerInfoBits(DebuggerAssemblyControlFlags newBits) { LIMITED_METHOD_CONTRACT; SUPPORTS_DAC; _ASSERTE(((newBits << DEBUGGER_INFO_SHIFT_PRIV) & ~DEBUGGER_INFO_MASK_PRIV) == 0); m_dwTransientFlags &= ~DEBUGGER_INFO_MASK_PRIV; m_dwTransientFlags |= (newBits << DEBUGGER_INFO_SHIFT_PRIV); #ifdef DEBUGGING_SUPPORTED BOOL setEnC = ((newBits & DACF_ENC_ENABLED) != 0) && IsEditAndContinueCapable(); // IsEditAndContinueCapable should already check !GetAssembly()->IsDomainNeutral _ASSERTE(!setEnC || !GetAssembly()->IsDomainNeutral()); // The only way can change Enc is through debugger override. if (setEnC) { EnableEditAndContinue(); } else { if (!g_pConfig->ForceEnc()) DisableEditAndContinue(); } #endif // DEBUGGING_SUPPORTED #if defined(DACCESS_COMPILE) // Now that we've changed m_dwTransientFlags, update that in the target too. // This will fail for read-only target. // If this fails, it will throw an exception. // @dbgtodo dac write: finalize on plans for how DAC writes to the target. HRESULT hrDac; hrDac = DacWriteHostInstance(this, true); _ASSERTE(SUCCEEDED(hrDac)); // would throw if there was an error. #endif // DACCESS_COMPILE } #ifndef DACCESS_COMPILE /* static */ Module *Module::Create(Assembly *pAssembly, mdFile moduleRef, PEFile *file, AllocMemTracker *pamTracker) { CONTRACT(Module *) { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pAssembly)); PRECONDITION(CheckPointer(file)); PRECONDITION(!IsNilToken(moduleRef) || file->IsAssembly()); POSTCONDITION(CheckPointer(RETVAL)); POSTCONDITION(RETVAL->GetFile() == file); } CONTRACT_END; // Hoist CONTRACT into separate routine because of EX incompatibility Module *pModule = NULL; // Create the module #ifdef FEATURE_PREJIT if (file->HasNativeImage()) { pModule = file->GetLoadedNative()->GetPersistedModuleImage(); PREFIX_ASSUME(pModule != NULL); CONSISTENCY_CHECK_MSG(pModule->m_pAssembly == NULL || !pModule->IsTenured(), // if the module is not tenured it could be our previous attempt "Native image can only be used once per process\n"); EnsureWritablePages(pModule); pModule = new ((void*) pModule) Module(pAssembly, moduleRef, file); PREFIX_ASSUME(pModule != NULL); } #endif // FEATURE_PREJIT if (pModule == NULL) { #ifdef EnC_SUPPORTED if (IsEditAndContinueCapable(pAssembly, file)) { // IsEditAndContinueCapable should already check !pAssembly->IsDomainNeutral _ASSERTE(!pAssembly->IsDomainNeutral()); // if file is EnCCapable, always create an EnC-module, but EnC won't necessarily be enabled. // Debugger enables this by calling SetJITCompilerFlags on LoadModule callback. void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(EditAndContinueModule)))); pModule = new (pMemory) EditAndContinueModule(pAssembly, moduleRef, file); } else #endif // EnC_SUPPORTED { void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(Module)))); pModule = new (pMemory) Module(pAssembly, moduleRef, file); } } PREFIX_ASSUME(pModule != NULL); ModuleHolder pModuleSafe(pModule); pModuleSafe->DoInit(pamTracker, NULL); RETURN pModuleSafe.Extract(); } void Module::ApplyMetaData() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; LOG((LF_CLASSLOADER, LL_INFO100, "Module::ApplyNewMetaData %x\n", this)); HRESULT hr = S_OK; ULONG ulCount; // Ensure for TypeRef ulCount = GetMDImport()->GetCountWithTokenKind(mdtTypeRef) + 1; EnsureTypeRefCanBeStored(TokenFromRid(ulCount, mdtTypeRef)); // Ensure for AssemblyRef ulCount = GetMDImport()->GetCountWithTokenKind(mdtAssemblyRef) + 1; EnsureAssemblyRefCanBeStored(TokenFromRid(ulCount, mdtAssemblyRef)); } // // Destructor for Module // void Module::Destruct() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; LOG((LF_EEMEM, INFO3, "Deleting module %x\n", this)); #ifdef PROFILING_SUPPORTED { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); if (!IsBeingUnloaded()) { // Profiler is causing some peripheral class loads. Probably this just needs // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler. EX_TRY { GCX_PREEMP(); g_profControlBlock.pProfInterface->ModuleUnloadStarted((ModuleID) this); } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); } END_PIN_PROFILER(); } #endif // PROFILING_SUPPORTED DACNotify::DoModuleUnloadNotification(this); // Free classes in the class table FreeClassTables(); #ifdef DEBUGGING_SUPPORTED if (g_pDebugInterface) { GCX_PREEMP(); g_pDebugInterface->DestructModule(this); } #endif // DEBUGGING_SUPPORTED ReleaseISymUnmanagedReader(); // Clean up sig cookies VASigCookieBlock *pVASigCookieBlock = m_pVASigCookieBlock; while (pVASigCookieBlock) { VASigCookieBlock *pNext = pVASigCookieBlock->m_Next; delete pVASigCookieBlock; pVASigCookieBlock = pNext; } // Clean up the IL stub cache if (m_pILStubCache != NULL) { delete m_pILStubCache; } #ifdef PROFILING_SUPPORTED { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); // Profiler is causing some peripheral class loads. Probably this just needs // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler. EX_TRY { GCX_PREEMP(); g_profControlBlock.pProfInterface->ModuleUnloadFinished((ModuleID) this, S_OK); } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); END_PIN_PROFILER(); } if (m_pValidatedEmitter.Load() != NULL) { m_pValidatedEmitter->Release(); } #endif // PROFILING_SUPPORTED // // Warning - deleting the zap file will cause the module to be unmapped // ClearInMemorySymbolStream(); m_Crst.Destroy(); m_FixupCrst.Destroy(); m_LookupTableCrst.Destroy(); m_InstMethodHashTableCrst.Destroy(); m_ISymUnmanagedReaderCrst.Destroy(); if (m_debuggerSpecificData.m_pDynamicILCrst) { delete m_debuggerSpecificData.m_pDynamicILCrst; } if (m_debuggerSpecificData.m_pDynamicILBlobTable) { delete m_debuggerSpecificData.m_pDynamicILBlobTable; } if (m_debuggerSpecificData.m_pTemporaryILBlobTable) { delete m_debuggerSpecificData.m_pTemporaryILBlobTable; } if (m_debuggerSpecificData.m_pILOffsetMappingTable) { for (ILOffsetMappingTable::Iterator pCurElem = m_debuggerSpecificData.m_pILOffsetMappingTable->Begin(), pEndElem = m_debuggerSpecificData.m_pILOffsetMappingTable->End(); pCurElem != pEndElem; pCurElem++) { ILOffsetMappingEntry entry = *pCurElem; entry.m_mapping.Clear(); } delete m_debuggerSpecificData.m_pILOffsetMappingTable; } #ifdef FEATURE_PREJIT if (HasNativeImage()) { m_file->Release(); } else #endif // FEATURE_PREJIT { m_file->Release(); } // If this module was loaded as domain-specific, then // we must free its ModuleIndex so that it can be reused FreeModuleIndex(); } #ifdef FEATURE_PREJIT void Module::DeleteNativeCodeRanges() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_PREEMPTIVE; FORBID_FAULT; } CONTRACTL_END; if (HasNativeImage()) { PEImageLayout * pNativeImage = GetNativeImage(); ExecutionManager::DeleteRange(dac_cast<TADDR>(pNativeImage->GetBase())); } } #endif bool Module::NeedsGlobalMethodTable() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; IMDInternalImport * pImport = GetMDImport(); if (!IsResource() && pImport->IsValidToken(COR_GLOBAL_PARENT_TOKEN)) { { HENUMInternalHolder funcEnum(pImport); funcEnum.EnumGlobalFunctionsInit(); if (pImport->EnumGetCount(&funcEnum) != 0) return true; } { HENUMInternalHolder fieldEnum(pImport); fieldEnum.EnumGlobalFieldsInit(); if (pImport->EnumGetCount(&fieldEnum) != 0) return true; } } // resource module or no global statics nor global functions return false; } MethodTable *Module::GetGlobalMethodTable() { CONTRACT (MethodTable *) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(CONTRACT_RETURN NULL;); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; if ((m_dwPersistedFlags & COMPUTED_GLOBAL_CLASS) == 0) { MethodTable *pMT = NULL; if (NeedsGlobalMethodTable()) { pMT = ClassLoader::LoadTypeDefThrowing(this, COR_GLOBAL_PARENT_TOKEN, ClassLoader::ThrowIfNotFound, ClassLoader::FailIfUninstDefOrRef).AsMethodTable(); } FastInterlockOr(&m_dwPersistedFlags, COMPUTED_GLOBAL_CLASS); RETURN pMT; } else { RETURN LookupTypeDef(COR_GLOBAL_PARENT_TOKEN).AsMethodTable(); } } #endif // !DACCESS_COMPILE #ifdef FEATURE_PREJIT /*static*/ BOOL Module::IsAlwaysSavedInPreferredZapModule(Instantiation classInst, // the type arguments to the type (if any) Instantiation methodInst) // the type arguments to the method (if any) { LIMITED_METHOD_CONTRACT; return ClassLoader::IsTypicalSharedInstantiation(classInst) && ClassLoader::IsTypicalSharedInstantiation(methodInst); } //this gets called recursively for generics, so do a probe. PTR_Module Module::ComputePreferredZapModule(Module * pDefinitionModule, Instantiation classInst, Instantiation methodInst) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; } CONTRACTL_END; PTR_Module ret = NULL; INTERIOR_STACK_PROBE_NOTHROW_CHECK_THREAD(DontCallDirectlyForceStackOverflow()); ret = Module::ComputePreferredZapModuleHelper( pDefinitionModule, classInst, methodInst ); END_INTERIOR_STACK_PROBE; return ret; } // // Is pModule likely a dependency of pOtherModule? Heuristic used by preffered zap module algorithm. // It can return both false positives and negatives. // static bool IsLikelyDependencyOf(Module * pModule, Module * pOtherModule) { CONTRACTL { NOTHROW; GC_NOTRIGGER; FORBID_FAULT; MODE_ANY; SUPPORTS_DAC; PRECONDITION(CheckPointer(pOtherModule)); } CONTRACTL_END // Every module has a dependency with itself if (pModule == pOtherModule) return true; // // Explicit check for low level system assemblies is working around Win8P facades introducing extra layer between low level system assemblies // (System.dll or System.Core.dll) and the app assemblies. Because of this extra layer, the check below won't see the direct // reference between these low level system assemblies and the app assemblies. The prefererred zap module for instantiations of generic // collections from these low level system assemblies (like LinkedList<AppType>) should be module of AppType. It would be module of the generic // collection without this check. On desktop (FEATURE_FULL_NGEN defined), it would result into inefficient code because of the instantiations // would be speculative. On CoreCLR (FEATURE_FULL_NGEN not defined), it would result into the instantiations not getting saved into native // image at all. // // Similar problem exists for Windows.Foundation.winmd. There is a cycle between Windows.Foundation.winmd and Windows.Storage.winmd. This cycle // would cause prefererred zap module for instantiations of foundation types (like IAsyncOperation<StorageFolder>) to be Windows.Foundation.winmd. // It is a bad choice. It should be Windows.Storage.winmd instead. We explicitly push Windows.Foundation to lower level by treating it as // low level system assembly to avoid this problem. // if (pModule->IsLowLevelSystemAssemblyByName()) { if (!pOtherModule->IsLowLevelSystemAssemblyByName()) return true; // Every module depends upon mscorlib if (pModule->IsSystem()) return true; // mscorlib does not depend upon any other module if (pOtherModule->IsSystem()) return false; } else { if (pOtherModule->IsLowLevelSystemAssemblyByName()) return false; } // At this point neither pModule or pOtherModule is mscorlib #ifndef DACCESS_COMPILE // // We will check to see if the pOtherModule has a reference to pModule // // If we can match the assembly ref in the ManifestModuleReferencesMap we can early out. // This early out kicks in less than half of the time. It hurts performance on average. // if (!IsNilToken(pOtherModule->FindAssemblyRef(pModule->GetAssembly()))) // return true; if (pOtherModule->HasReferenceByName(pModule->GetSimpleName())) return true; #endif // DACCESS_COMPILE return false; } // Determine the "preferred ngen home" for an instantiated type or method // * This is the first ngen module that the loader will look in; // * Also, we only hard bind to a type or method that lives in its preferred module // The following properties must hold of the preferred module: // - it must be one of the component type's declaring modules // - if the type or method is open then the preferred module must be that of one of the type parameters // (this ensures that we can always hard bind to open types and methods created during ngen) // - for always-saved instantiations it must be the declaring module of the generic definition // Otherwise, we try to pick a module that is likely to reference the type or method // /* static */ PTR_Module Module::ComputePreferredZapModuleHelper( Module * pDefinitionModule, // the module that declares the generic type or method Instantiation classInst, // the type arguments to the type (if any) Instantiation methodInst) // the type arguments to the method (if any) { CONTRACT(PTR_Module) { NOTHROW; GC_NOTRIGGER; FORBID_FAULT; MODE_ANY; PRECONDITION(CheckPointer(pDefinitionModule, NULL_OK)); // One of them will be non-null... Note we don't use CheckPointer // because that raises a breakpoint in the debugger PRECONDITION(pDefinitionModule != NULL || !classInst.IsEmpty() || !methodInst.IsEmpty()); POSTCONDITION(CheckPointer(RETVAL)); SUPPORTS_DAC; } CONTRACT_END DWORD totalArgs = classInst.GetNumArgs() + methodInst.GetNumArgs(); // The open type parameters takes precendence over closed type parameters since // we always hardbind to open types. for (DWORD i = 0; i < totalArgs; i++) { TypeHandle thArg = (i < classInst.GetNumArgs()) ? classInst[i] : methodInst[i - classInst.GetNumArgs()]; // Encoded types are never open _ASSERTE(!thArg.IsEncodedFixup()); Module * pOpenModule = thArg.GetDefiningModuleForOpenType(); if (pOpenModule != NULL) RETURN dac_cast<PTR_Module>(pOpenModule); } // The initial value of pCurrentPZM is the pDefinitionModule or mscorlib Module* pCurrentPZM = (pDefinitionModule != NULL) ? pDefinitionModule : MscorlibBinder::GetModule(); bool preferredZapModuleBasedOnValueType = false; for (DWORD i = 0; i < totalArgs; i++) { TypeHandle pTypeParam = (i < classInst.GetNumArgs()) ? classInst[i] : methodInst[i - classInst.GetNumArgs()]; _ASSERTE(pTypeParam != NULL); _ASSERTE(!pTypeParam.IsEncodedFixup()); Module * pParamPZM = GetPreferredZapModuleForTypeHandle(pTypeParam); // // If pCurrentPZM is not a dependency of pParamPZM // then we aren't going to update pCurrentPZM // if (IsLikelyDependencyOf(pCurrentPZM, pParamPZM)) { // If we have a type parameter that is a value type // and we don't yet have a value type based pCurrentPZM // then we will select it's module as the new pCurrentPZM. // if (pTypeParam.IsValueType() && !preferredZapModuleBasedOnValueType) { pCurrentPZM = pParamPZM; preferredZapModuleBasedOnValueType = true; } else { // The normal rule is to replace the pCurrentPZM only when // both of the following are true: // pCurrentPZM is a dependency of pParamPZM // and pParamPZM is not a dependency of pCurrentPZM // // note that the second condition is alway true when pCurrentPZM is mscorlib // if (!IsLikelyDependencyOf(pParamPZM, pCurrentPZM)) { pCurrentPZM = pParamPZM; } } } } RETURN dac_cast<PTR_Module>(pCurrentPZM); } PTR_Module Module::ComputePreferredZapModule(TypeKey *pKey) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; if (pKey->GetKind() == ELEMENT_TYPE_CLASS) { return Module::ComputePreferredZapModule(pKey->GetModule(), pKey->GetInstantiation()); } else if (pKey->GetKind() != ELEMENT_TYPE_FNPTR) return Module::GetPreferredZapModuleForTypeHandle(pKey->GetElementType()); else return NULL; } /* see code:Module::ComputePreferredZapModuleHelper for more */ /*static*/ PTR_Module Module::GetPreferredZapModuleForMethodTable(MethodTable *pMT) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; PTR_Module pRet=NULL; INTERIOR_STACK_PROBE_FOR_NOTHROW_CHECK_THREAD(10, NO_FORBIDGC_LOADER_USE_ThrowSO();); if (pMT->IsArray()) { TypeHandle elemTH = pMT->GetApproxArrayElementTypeHandle(); pRet= ComputePreferredZapModule(NULL, Instantiation(&elemTH, 1)); } else if (pMT->HasInstantiation() && !pMT->IsGenericTypeDefinition()) { pRet= ComputePreferredZapModule(pMT->GetModule(), pMT->GetInstantiation()); } else { // If it is uninstantiated or it is the generic type definition itself // then its loader module is simply the module containing its TypeDef pRet= pMT->GetModule(); } END_INTERIOR_STACK_PROBE; return pRet; } /*static*/ PTR_Module Module::GetPreferredZapModuleForTypeDesc(PTR_TypeDesc pTD) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; } CONTRACTL_END; SUPPORTS_DAC; if (pTD->HasTypeParam()) return GetPreferredZapModuleForTypeHandle(pTD->GetTypeParam()); else if (pTD->IsGenericVariable()) return pTD->GetModule(); _ASSERTE(pTD->GetInternalCorElementType() == ELEMENT_TYPE_FNPTR); PTR_FnPtrTypeDesc pFnPtrTD = dac_cast<PTR_FnPtrTypeDesc>(pTD); // Result type of function type is used for preferred zap module return GetPreferredZapModuleForTypeHandle(pFnPtrTD->GetRetAndArgTypesPointer()[0]); } /*static*/ PTR_Module Module::GetPreferredZapModuleForTypeHandle(TypeHandle t) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; } CONTRACTL_END; SUPPORTS_DAC; if (t.IsTypeDesc()) return GetPreferredZapModuleForTypeDesc(t.AsTypeDesc()); else return GetPreferredZapModuleForMethodTable(t.AsMethodTable()); } /*static*/ PTR_Module Module::GetPreferredZapModuleForMethodDesc(const MethodDesc *pMD) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; } CONTRACTL_END; if (pMD->IsTypicalMethodDefinition()) { return PTR_Module(pMD->GetModule()); } else if (pMD->IsGenericMethodDefinition()) { return GetPreferredZapModuleForMethodTable(pMD->GetMethodTable()); } else { return ComputePreferredZapModule(pMD->GetModule(), pMD->GetClassInstantiation(), pMD->GetMethodInstantiation()); } } /* see code:Module::ComputePreferredZapModuleHelper for more */ /*static*/ PTR_Module Module::GetPreferredZapModuleForFieldDesc(FieldDesc * pFD) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; } CONTRACTL_END; // The approx MT is sufficient: it's always the one that owns the FieldDesc // data structure return GetPreferredZapModuleForMethodTable(pFD->GetApproxEnclosingMethodTable()); } #endif // FEATURE_PREJIT /*static*/ BOOL Module::IsEditAndContinueCapable(Assembly *pAssembly, PEFile *file) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; _ASSERTE(pAssembly != NULL && file != NULL); // Some modules are never EnC-capable return ! (pAssembly->GetDebuggerInfoBits() & DACF_ALLOW_JIT_OPTS || pAssembly->IsDomainNeutral() || file->IsSystem() || file->IsResource() || file->HasNativeImage() || file->IsDynamic()); } BOOL Module::IsManifest() { WRAPPER_NO_CONTRACT; return dac_cast<TADDR>(GetAssembly()->GetManifestModule()) == dac_cast<TADDR>(this); } DomainAssembly* Module::GetDomainAssembly(AppDomain *pDomain) { CONTRACT(DomainAssembly *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain, NULL_OK)); POSTCONDITION(CheckPointer(RETVAL)); THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACT_END; if (IsManifest()) RETURN (DomainAssembly *) GetDomainFile(pDomain); else RETURN (DomainAssembly *) m_pAssembly->GetDomainAssembly(pDomain); } DomainFile *Module::GetDomainFile(AppDomain *pDomain) { CONTRACT(DomainFile *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain)); POSTCONDITION(CheckPointer(RETVAL)); GC_TRIGGERS; THROWS; MODE_ANY; SUPPORTS_DAC; } CONTRACT_END; if (Module::IsEncodedModuleIndex(GetModuleID())) { DomainLocalBlock *pLocalBlock = pDomain->GetDomainLocalBlock(); DomainFile *pDomainFile = pLocalBlock->TryGetDomainFile(GetModuleIndex()); #if !defined(DACCESS_COMPILE) && defined(FEATURE_LOADER_OPTIMIZATION) if (pDomainFile == NULL) pDomainFile = pDomain->LoadDomainNeutralModuleDependency(this, FILE_LOADED); #endif // !DACCESS_COMPILE RETURN (PTR_DomainFile) pDomainFile; } else { CONSISTENCY_CHECK(dac_cast<TADDR>(pDomain) == dac_cast<TADDR>(GetDomain()) || IsSingleAppDomain()); RETURN dac_cast<PTR_DomainFile>(m_ModuleID->GetDomainFile()); } } DomainAssembly* Module::FindDomainAssembly(AppDomain *pDomain) { CONTRACT(DomainAssembly *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain)); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; } CONTRACT_END; if (IsManifest()) RETURN dac_cast<PTR_DomainAssembly>(FindDomainFile(pDomain)); else RETURN m_pAssembly->FindDomainAssembly(pDomain); } DomainModule *Module::GetDomainModule(AppDomain *pDomain) { CONTRACT(DomainModule *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain)); PRECONDITION(!IsManifest()); POSTCONDITION(CheckPointer(RETVAL)); THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACT_END; RETURN (DomainModule *) GetDomainFile(pDomain); } DomainFile *Module::FindDomainFile(AppDomain *pDomain) { CONTRACT(DomainFile *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain)); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; } CONTRACT_END; if (Module::IsEncodedModuleIndex(GetModuleID())) { DomainLocalBlock *pLocalBlock = pDomain->GetDomainLocalBlock(); RETURN pLocalBlock->TryGetDomainFile(GetModuleIndex()); } else { if (dac_cast<TADDR>(pDomain) == dac_cast<TADDR>(GetDomain()) || IsSingleAppDomain()) RETURN m_ModuleID->GetDomainFile(); else RETURN NULL; } } DomainModule *Module::FindDomainModule(AppDomain *pDomain) { CONTRACT(DomainModule *) { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomain)); PRECONDITION(!IsManifest()); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); GC_NOTRIGGER; NOTHROW; MODE_ANY; } CONTRACT_END; RETURN (DomainModule *) FindDomainFile(pDomain); } #ifndef DACCESS_COMPILE #include "staticallocationhelpers.inl" // Parses metadata and initializes offsets of per-class static blocks. void Module::BuildStaticsOffsets(AllocMemTracker *pamTracker) { STANDARD_VM_CONTRACT; // Trade off here. We want a slot for each type. That way we can get to 2 bits per class and // index directly and not need a mapping from ClassID to MethodTable (we will use the RID // as the mapping) IMDInternalImport *pImport = GetMDImport(); DWORD * pRegularStaticOffsets = NULL; DWORD * pThreadStaticOffsets = NULL; // Get the number of types/classes defined in this module. Add 1 to count the module itself DWORD dwNumTypes = pImport->GetCountWithTokenKind(mdtTypeDef) + 1; // +1 for module type // [0] covers regular statics, [1] covers thread statics DWORD dwGCHandles[2] = { 0, 0 }; // Organization in memory of the static block // // // | GC Statics | // | // | // | Class Data (one byte per class) | pointer to gc statics | primitive type statics | // // #ifndef CROSSBITNESS_COMPILE // The assertions must hold in every non-crossbitness scenario _ASSERTE(OFFSETOF__DomainLocalModule__m_pDataBlob_ == DomainLocalModule::OffsetOfDataBlob()); _ASSERTE(OFFSETOF__ThreadLocalModule__m_pDataBlob == ThreadLocalModule::OffsetOfDataBlob()); #endif DWORD dwNonGCBytes[2] = { DomainLocalModule::OffsetOfDataBlob() + sizeof(BYTE)*dwNumTypes, ThreadLocalModule::OffsetOfDataBlob() + sizeof(BYTE)*dwNumTypes }; HENUMInternalHolder hTypeEnum(pImport); hTypeEnum.EnumAllInit(mdtTypeDef); mdTypeDef type; // Parse each type of the class while (pImport->EnumNext(&hTypeEnum, &type)) { // Set offset for this type DWORD dwIndex = RidFromToken(type) - 1; // [0] covers regular statics, [1] covers thread statics DWORD dwAlignment[2] = { 1, 1 }; DWORD dwClassNonGCBytes[2] = { 0, 0 }; DWORD dwClassGCHandles[2] = { 0, 0 }; // need to check if the type is generic and if so exclude it from iteration as we don't know the size HENUMInternalHolder hGenericEnum(pImport); hGenericEnum.EnumInit(mdtGenericParam, type); ULONG cGenericParams = pImport->EnumGetCount(&hGenericEnum); if (cGenericParams == 0) { HENUMInternalHolder hFieldEnum(pImport); hFieldEnum.EnumInit(mdtFieldDef, type); mdFieldDef field; // Parse each field of the type while (pImport->EnumNext(&hFieldEnum, &field)) { BOOL fSkip = FALSE; CorElementType ElementType = ELEMENT_TYPE_END; mdToken tkValueTypeToken = 0; int kk; // Use one set of variables for regular statics, and the other set for thread statics fSkip = GetStaticFieldElementTypeForFieldDef(this, pImport, field, &ElementType, &tkValueTypeToken, &kk); if (fSkip) continue; // We account for "regular statics" and "thread statics" separately. // Currently we are lumping RVA and context statics into "regular statics", // but we probably shouldn't. switch (ElementType) { case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_BOOLEAN: dwClassNonGCBytes[kk] += 1; break; case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_CHAR: dwAlignment[kk] = max(2, dwAlignment[kk]); dwClassNonGCBytes[kk] += 2; break; case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: dwAlignment[kk] = max(4, dwAlignment[kk]); dwClassNonGCBytes[kk] += 4; break; case ELEMENT_TYPE_FNPTR: case ELEMENT_TYPE_PTR: case ELEMENT_TYPE_I: case ELEMENT_TYPE_U: dwAlignment[kk] = max((1 << LOG2_PTRSIZE), dwAlignment[kk]); dwClassNonGCBytes[kk] += (1 << LOG2_PTRSIZE); break; case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: dwAlignment[kk] = max(8, dwAlignment[kk]); dwClassNonGCBytes[kk] += 8; break; case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_MVAR: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_SZARRAY: case ELEMENT_TYPE_ARRAY: case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_OBJECT: dwClassGCHandles[kk] += 1; break; case ELEMENT_TYPE_VALUETYPE: // Statics for valuetypes where the valuetype is defined in this module are handled here. Other valuetype statics utilize the pessimistic model below. dwClassGCHandles[kk] += 1; break; case ELEMENT_TYPE_END: default: // The actual element type was ELEMENT_TYPE_VALUETYPE, but the as we don't want to load additional assemblies // to determine these static offsets, we've fallen back to a pessimistic model. if (tkValueTypeToken != 0) { // We'll have to be pessimistic here dwClassNonGCBytes[kk] += MAX_PRIMITIVE_FIELD_SIZE; dwAlignment[kk] = max(MAX_PRIMITIVE_FIELD_SIZE, dwAlignment[kk]); dwClassGCHandles[kk] += 1; break; } else { // field has an unexpected type ThrowHR(VER_E_FIELD_SIG); break; } } } if (pRegularStaticOffsets == NULL && (dwClassGCHandles[0] != 0 || dwClassNonGCBytes[0] != 0)) { // Lazily allocate table for offsets. We need offsets for GC and non GC areas. We add +1 to use as a sentinel. pRegularStaticOffsets = (PTR_DWORD)pamTracker->Track( GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem( (S_SIZE_T(2 * sizeof(DWORD))*(S_SIZE_T(dwNumTypes)+S_SIZE_T(1))))); for (DWORD i = 0; i < dwIndex; i++) { pRegularStaticOffsets[i * 2 ] = dwGCHandles[0]*TARGET_POINTER_SIZE; pRegularStaticOffsets[i * 2 + 1] = dwNonGCBytes[0]; } } if (pThreadStaticOffsets == NULL && (dwClassGCHandles[1] != 0 || dwClassNonGCBytes[1] != 0)) { // Lazily allocate table for offsets. We need offsets for GC and non GC areas. We add +1 to use as a sentinel. pThreadStaticOffsets = (PTR_DWORD)pamTracker->Track( GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem( (S_SIZE_T(2 * sizeof(DWORD))*(S_SIZE_T(dwNumTypes)+S_SIZE_T(1))))); for (DWORD i = 0; i < dwIndex; i++) { pThreadStaticOffsets[i * 2 ] = dwGCHandles[1]*TARGET_POINTER_SIZE; pThreadStaticOffsets[i * 2 + 1] = dwNonGCBytes[1]; } } } if (pRegularStaticOffsets != NULL) { // Align the offset of non gc statics dwNonGCBytes[0] = (DWORD) ALIGN_UP(dwNonGCBytes[0], dwAlignment[0]); // Save current offsets pRegularStaticOffsets[dwIndex*2] = dwGCHandles[0]*TARGET_POINTER_SIZE; pRegularStaticOffsets[dwIndex*2 + 1] = dwNonGCBytes[0]; // Increment for next class dwGCHandles[0] += dwClassGCHandles[0]; dwNonGCBytes[0] += dwClassNonGCBytes[0]; } if (pThreadStaticOffsets != NULL) { // Align the offset of non gc statics dwNonGCBytes[1] = (DWORD) ALIGN_UP(dwNonGCBytes[1], dwAlignment[1]); // Save current offsets pThreadStaticOffsets[dwIndex*2] = dwGCHandles[1]*TARGET_POINTER_SIZE; pThreadStaticOffsets[dwIndex*2 + 1] = dwNonGCBytes[1]; // Increment for next class dwGCHandles[1] += dwClassGCHandles[1]; dwNonGCBytes[1] += dwClassNonGCBytes[1]; } } m_maxTypeRidStaticsAllocated = dwNumTypes; if (pRegularStaticOffsets != NULL) { pRegularStaticOffsets[dwNumTypes*2] = dwGCHandles[0]*TARGET_POINTER_SIZE; pRegularStaticOffsets[dwNumTypes*2 + 1] = dwNonGCBytes[0]; } if (pThreadStaticOffsets != NULL) { pThreadStaticOffsets[dwNumTypes*2] = dwGCHandles[1]*TARGET_POINTER_SIZE; pThreadStaticOffsets[dwNumTypes*2 + 1] = dwNonGCBytes[1]; } m_pRegularStaticOffsets = pRegularStaticOffsets; m_pThreadStaticOffsets = pThreadStaticOffsets; m_dwMaxGCRegularStaticHandles = dwGCHandles[0]; m_dwMaxGCThreadStaticHandles = dwGCHandles[1]; m_dwRegularStaticsBlockSize = dwNonGCBytes[0]; m_dwThreadStaticsBlockSize = dwNonGCBytes[1]; } void Module::GetOffsetsForRegularStaticData( mdToken cl, BOOL bDynamic, DWORD dwGCStaticHandles, DWORD dwNonGCStaticBytes, DWORD * pOutStaticHandleOffset, DWORD * pOutNonGCStaticOffset) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END *pOutStaticHandleOffset = 0; *pOutNonGCStaticOffset = 0; if (!dwGCStaticHandles && !dwNonGCStaticBytes) { return; } #ifndef CROSSBITNESS_COMPILE _ASSERTE(OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob == DomainLocalModule::DynamicEntry::GetOffsetOfDataBlob()); #endif // Statics for instantiated types are allocated dynamically per-instantiation if (bDynamic) { // Non GC statics are embedded in the Dynamic Entry. *pOutNonGCStaticOffset = OFFSETOF__DomainLocalModule__NormalDynamicEntry__m_pDataBlob; return; } if (m_pRegularStaticOffsets == NULL) { THROW_BAD_FORMAT(BFA_METADATA_CORRUPT, this); } _ASSERTE(m_pRegularStaticOffsets != (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED); // We allocate in the big blob. DWORD index = RidFromToken(cl) - 1; *pOutStaticHandleOffset = m_pRegularStaticOffsets[index*2]; *pOutNonGCStaticOffset = m_pRegularStaticOffsets[index*2 + 1]; #ifdef CROSSBITNESS_COMPILE *pOutNonGCStaticOffset += OFFSETOF__DomainLocalModule__m_pDataBlob_ - DomainLocalModule::OffsetOfDataBlob(); #endif // Check we didnt go out of what we predicted we would need for the class if (*pOutStaticHandleOffset + TARGET_POINTER_SIZE*dwGCStaticHandles > m_pRegularStaticOffsets[(index+1)*2] || *pOutNonGCStaticOffset + dwNonGCStaticBytes > m_pRegularStaticOffsets[(index+1)*2 + 1]) { // It's most likely that this is due to bad metadata, thus the exception. However, the // previous comments for this bit of code mentioned that this could be a corner case bug // with static field size estimation, though this is entirely unlikely since the code has // been this way for at least two releases. THROW_BAD_FORMAT(BFA_METADATA_CORRUPT, this); } } void Module::GetOffsetsForThreadStaticData( mdToken cl, BOOL bDynamic, DWORD dwGCStaticHandles, DWORD dwNonGCStaticBytes, DWORD * pOutStaticHandleOffset, DWORD * pOutNonGCStaticOffset) { CONTRACTL { THROWS; GC_TRIGGERS; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END *pOutStaticHandleOffset = 0; *pOutNonGCStaticOffset = 0; if (!dwGCStaticHandles && !dwNonGCStaticBytes) { return; } #ifndef CROSSBITNESS_COMPILE _ASSERTE(OFFSETOF__ThreadLocalModule__DynamicEntry__m_pDataBlob == ThreadLocalModule::DynamicEntry::GetOffsetOfDataBlob()); #endif // Statics for instantiated types are allocated dynamically per-instantiation if (bDynamic) { // Non GC thread statics are embedded in the Dynamic Entry. *pOutNonGCStaticOffset = OFFSETOF__ThreadLocalModule__DynamicEntry__m_pDataBlob; return; } if (m_pThreadStaticOffsets == NULL) { THROW_BAD_FORMAT(BFA_METADATA_CORRUPT, this); } _ASSERTE(m_pThreadStaticOffsets != (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED); // We allocate in the big blob. DWORD index = RidFromToken(cl) - 1; *pOutStaticHandleOffset = m_pThreadStaticOffsets[index*2]; *pOutNonGCStaticOffset = m_pThreadStaticOffsets[index*2 + 1]; #ifdef CROSSBITNESS_COMPILE *pOutNonGCStaticOffset += OFFSETOF__ThreadLocalModule__m_pDataBlob - ThreadLocalModule::GetOffsetOfDataBlob(); #endif // Check we didnt go out of what we predicted we would need for the class if (*pOutStaticHandleOffset + TARGET_POINTER_SIZE*dwGCStaticHandles > m_pThreadStaticOffsets[(index+1)*2] || *pOutNonGCStaticOffset + dwNonGCStaticBytes > m_pThreadStaticOffsets[(index+1)*2 + 1]) { // It's most likely that this is due to bad metadata, thus the exception. However, the // previous comments for this bit of code mentioned that this could be a corner case bug // with static field size estimation, though this is entirely unlikely since the code has // been this way for at least two releases. THROW_BAD_FORMAT(BFA_METADATA_CORRUPT, this); } } // initialize Crst controlling the Dynamic IL hashtable void Module::InitializeDynamicILCrst() { Crst * pCrst = new Crst(CrstDynamicIL, CrstFlags(CRST_UNSAFE_ANYMODE | CRST_DEBUGGER_THREAD)); if (InterlockedCompareExchangeT( &m_debuggerSpecificData.m_pDynamicILCrst, pCrst, NULL) != NULL) { delete pCrst; } } // Add a (token, address) pair to the table of IL blobs for reflection/dynamics // Arguments: // Input: // token method token // blobAddress address of the start of the IL blob address, including the header // fTemporaryOverride // is this a permanent override that should go in the // DynamicILBlobTable, or a temporary one? // Output: not explicit, but if the pair was not already in the table it will be added. // Does not add duplicate tokens to the table. void Module::SetDynamicIL(mdToken token, TADDR blobAddress, BOOL fTemporaryOverride) { DynamicILBlobEntry entry = {mdToken(token), TADDR(blobAddress)}; // Lazily allocate a Crst to serialize update access to the info structure. // Carefully synchronize to ensure we don't leak a Crst in race conditions. if (m_debuggerSpecificData.m_pDynamicILCrst == NULL) { InitializeDynamicILCrst(); } CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst); // Figure out which table to fill in PTR_DynamicILBlobTable &table(fTemporaryOverride ? m_debuggerSpecificData.m_pTemporaryILBlobTable : m_debuggerSpecificData.m_pDynamicILBlobTable); // Lazily allocate the hash table. if (table == NULL) { table = PTR_DynamicILBlobTable(new DynamicILBlobTable); } table->AddOrReplace(entry); } #endif // !DACCESS_COMPILE // Get the stored address of the IL blob for reflection/dynamics // Arguments: // Input: // token method token // fAllowTemporary also check the temporary overrides // Return Value: starting (target) address of the IL blob corresponding to the input token TADDR Module::GetDynamicIL(mdToken token, BOOL fAllowTemporary) { SUPPORTS_DAC; #ifndef DACCESS_COMPILE // The Crst to serialize update access to the info structure is lazily allocated. // If it hasn't been allocated yet, then we don't have any IL blobs (temporary or otherwise) if (m_debuggerSpecificData.m_pDynamicILCrst == NULL) { return TADDR(NULL); } CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst); #endif // Both hash tables are lazily allocated, so if they're NULL // then we have no IL blobs if (fAllowTemporary && m_debuggerSpecificData.m_pTemporaryILBlobTable != NULL) { DynamicILBlobEntry entry = m_debuggerSpecificData.m_pTemporaryILBlobTable->Lookup(token); // Only return a value if the lookup succeeded if (!DynamicILBlobTraits::IsNull(entry)) { return entry.m_il; } } if (m_debuggerSpecificData.m_pDynamicILBlobTable == NULL) { return TADDR(NULL); } DynamicILBlobEntry entry = m_debuggerSpecificData.m_pDynamicILBlobTable->Lookup(token); // If the lookup fails, it returns the 'NULL' entry // The 'NULL' entry has m_il set to NULL, so either way we're safe return entry.m_il; } #if !defined(DACCESS_COMPILE) //--------------------------------------------------------------------------------------- // // Add instrumented IL offset mapping for the specified method. // // Arguments: // token - the MethodDef token of the method in question // mapping - the mapping information between original IL offsets and instrumented IL offsets // // Notes: // * Once added, the mapping stays valid until the Module containing the method is destructed. // * The profiler may potentially update the mapping more than once. // void Module::SetInstrumentedILOffsetMapping(mdMethodDef token, InstrumentedILOffsetMapping mapping) { ILOffsetMappingEntry entry(token, mapping); // Lazily allocate a Crst to serialize update access to the hash table. // Carefully synchronize to ensure we don't leak a Crst in race conditions. if (m_debuggerSpecificData.m_pDynamicILCrst == NULL) { InitializeDynamicILCrst(); } CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst); // Lazily allocate the hash table. if (m_debuggerSpecificData.m_pILOffsetMappingTable == NULL) { m_debuggerSpecificData.m_pILOffsetMappingTable = PTR_ILOffsetMappingTable(new ILOffsetMappingTable); } ILOffsetMappingEntry currentEntry = m_debuggerSpecificData.m_pILOffsetMappingTable->Lookup(ILOffsetMappingTraits::GetKey(entry)); if (!ILOffsetMappingTraits::IsNull(currentEntry)) currentEntry.m_mapping.Clear(); m_debuggerSpecificData.m_pILOffsetMappingTable->AddOrReplace(entry); } #endif // DACCESS_COMPILE //--------------------------------------------------------------------------------------- // // Retrieve the instrumented IL offset mapping for the specified method. // // Arguments: // token - the MethodDef token of the method in question // // Return Value: // Return the mapping information between original IL offsets and instrumented IL offsets. // Check InstrumentedILOffsetMapping::IsNull() to see if any mapping is available. // // Notes: // * Once added, the mapping stays valid until the Module containing the method is destructed. // * The profiler may potentially update the mapping more than once. // InstrumentedILOffsetMapping Module::GetInstrumentedILOffsetMapping(mdMethodDef token) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; // Lazily allocate a Crst to serialize update access to the hash table. // If the Crst is NULL, then we couldn't possibly have added any mapping yet, so just return NULL. if (m_debuggerSpecificData.m_pDynamicILCrst == NULL) { InstrumentedILOffsetMapping emptyMapping; return emptyMapping; } CrstHolder ch(m_debuggerSpecificData.m_pDynamicILCrst); // If the hash table hasn't been created, then we couldn't possibly have added any mapping yet, // so just return NULL. if (m_debuggerSpecificData.m_pILOffsetMappingTable == NULL) { InstrumentedILOffsetMapping emptyMapping; return emptyMapping; } ILOffsetMappingEntry entry = m_debuggerSpecificData.m_pILOffsetMappingTable->Lookup(token); return entry.m_mapping; } #undef DECODE_TYPEID #undef ENCODE_TYPEID #undef IS_ENCODED_TYPEID #ifndef DACCESS_COMPILE BOOL Module::IsNoStringInterning() { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END if (!(m_dwPersistedFlags & COMPUTED_STRING_INTERNING)) { // The flags should be precomputed in native images _ASSERTE(!HasNativeImage()); // Default is string interning BOOL fNoStringInterning = FALSE; HRESULT hr; // This flag applies to assembly, but it is stored on module so it can be cached in ngen image // Thus, we should ever need it for manifest module only. IMDInternalImport *mdImport = GetAssembly()->GetManifestImport(); _ASSERTE(mdImport); mdToken token; IfFailThrow(mdImport->GetAssemblyFromScope(&token)); const BYTE *pVal; ULONG cbVal; hr = mdImport->GetCustomAttributeByName(token, COMPILATIONRELAXATIONS_TYPE, (const void**)&pVal, &cbVal); // Parse the attribute if (hr == S_OK) { CustomAttributeParser cap(pVal, cbVal); IfFailThrow(cap.SkipProlog()); // Get Flags UINT32 flags; IfFailThrow(cap.GetU4(&flags)); if (flags & CompilationRelaxations_NoStringInterning) { fNoStringInterning = TRUE; } } #ifdef _DEBUG static ConfigDWORD g_NoStringInterning; DWORD dwOverride = g_NoStringInterning.val(CLRConfig::INTERNAL_NoStringInterning); if (dwOverride == 0) { // Disabled fNoStringInterning = FALSE; } else if (dwOverride == 2) { // Always true (testing) fNoStringInterning = TRUE; } #endif // _DEBUG FastInterlockOr(&m_dwPersistedFlags, COMPUTED_STRING_INTERNING | (fNoStringInterning ? NO_STRING_INTERNING : 0)); } return !!(m_dwPersistedFlags & NO_STRING_INTERNING); } BOOL Module::GetNeutralResourcesLanguage(LPCUTF8 * cultureName, ULONG * cultureNameLength, INT16 * fallbackLocation, BOOL cacheAttribute) { STANDARD_VM_CONTRACT; BOOL retVal = FALSE; if (!(m_dwPersistedFlags & NEUTRAL_RESOURCES_LANGUAGE_IS_CACHED)) { const BYTE *pVal = NULL; ULONG cbVal = 0; // This flag applies to assembly, but it is stored on module so it can be cached in ngen image // Thus, we should ever need it for manifest module only. IMDInternalImport *mdImport = GetAssembly()->GetManifestImport(); _ASSERTE(mdImport); mdToken token; IfFailThrow(mdImport->GetAssemblyFromScope(&token)); // Check for the existance of the attribute. HRESULT hr = mdImport->GetCustomAttributeByName(token,"System.Resources.NeutralResourcesLanguageAttribute",(const void **)&pVal, &cbVal); if (hr == S_OK) { // we should not have a native image (it would have been cached at ngen time) _ASSERTE(!HasNativeImage()); CustomAttributeParser cap(pVal, cbVal); IfFailThrow(cap.SkipProlog()); IfFailThrow(cap.GetString(cultureName, cultureNameLength)); IfFailThrow(cap.GetI2(fallbackLocation)); // Should only be true on Module.Save(). Update flag to show we have the attribute cached if (cacheAttribute) FastInterlockOr(&m_dwPersistedFlags, NEUTRAL_RESOURCES_LANGUAGE_IS_CACHED); retVal = TRUE; } } else { *cultureName = m_pszCultureName; *cultureNameLength = m_CultureNameLength; *fallbackLocation = m_FallbackLocation; retVal = TRUE; #ifdef _DEBUG // confirm that the NGENed attribute is correct LPCUTF8 pszCultureNameCheck = NULL; ULONG cultureNameLengthCheck = 0; INT16 fallbackLocationCheck = 0; const BYTE *pVal = NULL; ULONG cbVal = 0; IMDInternalImport *mdImport = GetAssembly()->GetManifestImport(); _ASSERTE(mdImport); mdToken token; IfFailThrow(mdImport->GetAssemblyFromScope(&token)); // Confirm that the attribute exists, and has the save value as when we ngen'd it HRESULT hr = mdImport->GetCustomAttributeByName(token,"System.Resources.NeutralResourcesLanguageAttribute",(const void **)&pVal, &cbVal); _ASSERTE(hr == S_OK); CustomAttributeParser cap(pVal, cbVal); IfFailThrow(cap.SkipProlog()); IfFailThrow(cap.GetString(&pszCultureNameCheck, &cultureNameLengthCheck)); IfFailThrow(cap.GetI2(&fallbackLocationCheck)); _ASSERTE(cultureNameLengthCheck == m_CultureNameLength); _ASSERTE(fallbackLocationCheck == m_FallbackLocation); _ASSERTE(strncmp(pszCultureNameCheck,m_pszCultureName,m_CultureNameLength) == 0); #endif // _DEBUG } return retVal; } BOOL Module::HasDefaultDllImportSearchPathsAttribute() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if(IsDefaultDllImportSearchPathsAttributeCached()) { return (m_dwPersistedFlags & DEFAULT_DLL_IMPORT_SEARCH_PATHS_STATUS) != 0 ; } IMDInternalImport *mdImport = GetAssembly()->GetManifestImport(); BOOL attributeIsFound = FALSE; attributeIsFound = GetDefaultDllImportSearchPathsAttributeValue(mdImport, TokenFromRid(1, mdtAssembly),&m_DefaultDllImportSearchPathsAttributeValue); if(attributeIsFound) { FastInterlockOr(&m_dwPersistedFlags, DEFAULT_DLL_IMPORT_SEARCH_PATHS_IS_CACHED | DEFAULT_DLL_IMPORT_SEARCH_PATHS_STATUS); } else { FastInterlockOr(&m_dwPersistedFlags, DEFAULT_DLL_IMPORT_SEARCH_PATHS_IS_CACHED); } return (m_dwPersistedFlags & DEFAULT_DLL_IMPORT_SEARCH_PATHS_STATUS) != 0 ; } // Returns a BOOL to indicate if we have computed whether compiler has instructed us to // wrap the non-CLS compliant exceptions or not. BOOL Module::IsRuntimeWrapExceptionsStatusComputed() { LIMITED_METHOD_CONTRACT; return (m_dwPersistedFlags & COMPUTED_WRAP_EXCEPTIONS); } BOOL Module::IsRuntimeWrapExceptions() { CONTRACTL { THROWS; if (IsRuntimeWrapExceptionsStatusComputed()) GC_NOTRIGGER; else GC_TRIGGERS; MODE_ANY; } CONTRACTL_END if (!(IsRuntimeWrapExceptionsStatusComputed())) { // The flags should be precomputed in native images _ASSERTE(!HasNativeImage()); HRESULT hr; BOOL fRuntimeWrapExceptions = FALSE; // This flag applies to assembly, but it is stored on module so it can be cached in ngen image // Thus, we should ever need it for manifest module only. IMDInternalImport *mdImport = GetAssembly()->GetManifestImport(); mdToken token; IfFailGo(mdImport->GetAssemblyFromScope(&token)); const BYTE *pVal; ULONG cbVal; hr = mdImport->GetCustomAttributeByName(token, RUNTIMECOMPATIBILITY_TYPE, (const void**)&pVal, &cbVal); // Parse the attribute if (hr == S_OK) { CustomAttributeParser ca(pVal, cbVal); CaNamedArg namedArgs[1] = {{0}}; // First, the void constructor: IfFailGo(ParseKnownCaArgs(ca, NULL, 0)); // Then, find the named argument namedArgs[0].InitBoolField("WrapNonExceptionThrows"); IfFailGo(ParseKnownCaNamedArgs(ca, namedArgs, lengthof(namedArgs))); if (namedArgs[0].val.boolean) fRuntimeWrapExceptions = TRUE; } ErrExit: FastInterlockOr(&m_dwPersistedFlags, COMPUTED_WRAP_EXCEPTIONS | (fRuntimeWrapExceptions ? WRAP_EXCEPTIONS : 0)); } return !!(m_dwPersistedFlags & WRAP_EXCEPTIONS); } BOOL Module::IsPreV4Assembly() { CONTRACTL { THROWS; GC_NOTRIGGER; SO_TOLERANT; } CONTRACTL_END if (!(m_dwPersistedFlags & COMPUTED_IS_PRE_V4_ASSEMBLY)) { // The flags should be precomputed in native images _ASSERTE(!HasNativeImage()); IMDInternalImport *pImport = GetAssembly()->GetManifestImport(); _ASSERTE(pImport); BOOL fIsPreV4Assembly = FALSE; LPCSTR szVersion = NULL; if (SUCCEEDED(pImport->GetVersionString(&szVersion))) { if (szVersion != NULL && strlen(szVersion) > 2) { fIsPreV4Assembly = (szVersion[0] == 'v' || szVersion[0] == 'V') && (szVersion[1] == '1' || szVersion[1] == '2'); } } FastInterlockOr(&m_dwPersistedFlags, COMPUTED_IS_PRE_V4_ASSEMBLY | (fIsPreV4Assembly ? IS_PRE_V4_ASSEMBLY : 0)); } return !!(m_dwPersistedFlags & IS_PRE_V4_ASSEMBLY); } ArrayDPTR(RelativeFixupPointer<PTR_MethodTable>) ModuleCtorInfo::GetGCStaticMTs(DWORD index) { LIMITED_METHOD_CONTRACT; if (index < numHotGCStaticsMTs) { _ASSERTE(ppHotGCStaticsMTs != NULL); return ppHotGCStaticsMTs + index; } else { _ASSERTE(ppColdGCStaticsMTs != NULL); // shift the start of the cold table because all cold offsets are also shifted return ppColdGCStaticsMTs + (index - numHotGCStaticsMTs); } } DWORD Module::AllocateDynamicEntry(MethodTable *pMT) { CONTRACTL { THROWS; GC_TRIGGERS; PRECONDITION(pMT->GetModuleForStatics() == this); PRECONDITION(pMT->IsDynamicStatics()); PRECONDITION(!pMT->ContainsGenericVariables()); } CONTRACTL_END; DWORD newId = FastInterlockExchangeAdd((LONG*)&m_cDynamicEntries, 1); if (newId >= m_maxDynamicEntries) { CrstHolder ch(&m_Crst); if (newId >= m_maxDynamicEntries) { SIZE_T maxDynamicEntries = max(16, m_maxDynamicEntries); while (maxDynamicEntries <= newId) { maxDynamicEntries *= 2; } DynamicStaticsInfo* pNewDynamicStaticsInfo = (DynamicStaticsInfo*) (void*)GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(DynamicStaticsInfo)) * S_SIZE_T(maxDynamicEntries)); if (m_pDynamicStaticsInfo) memcpy(pNewDynamicStaticsInfo, m_pDynamicStaticsInfo, sizeof(DynamicStaticsInfo) * m_maxDynamicEntries); m_pDynamicStaticsInfo = pNewDynamicStaticsInfo; m_maxDynamicEntries = maxDynamicEntries; } } EnsureWritablePages(&(m_pDynamicStaticsInfo[newId]))->pEnclosingMT = pMT; LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Assigned dynamic ID %d to %s\n", newId, pMT->GetDebugClassName())); return newId; } void Module::FreeModuleIndex() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; if (GetAssembly()->IsDomainNeutral()) { // We do not recycle ModuleIndexes used by domain neutral Modules. } else { if (m_ModuleID != NULL) { // Module's m_ModuleID should not contain the ID, it should // contain a pointer to the DLM _ASSERTE(!Module::IsEncodedModuleIndex((SIZE_T)m_ModuleID)); _ASSERTE(m_ModuleIndex == m_ModuleID->GetModuleIndex()); // Get the ModuleIndex from the DLM and free it Module::FreeModuleIndex(m_ModuleIndex); } else { // This was an empty, short-lived Module object that // was never assigned a ModuleIndex... } } } ModuleIndex Module::AllocateModuleIndex() { DWORD val; g_pModuleIndexDispenser->NewId(NULL, val); // For various reasons, the IDs issued by the IdDispenser start at 1. // Domain neutral module IDs have historically started at 0, and we // have always assigned ID 0 to mscorlib. Thus, to make it so that // domain neutral module IDs start at 0, we will subtract 1 from the // ID that we got back from the ID dispenser. ModuleIndex index((SIZE_T)(val-1)); return index; } void Module::FreeModuleIndex(ModuleIndex index) { WRAPPER_NO_CONTRACT; // We subtracted 1 after we allocated this ID, so we need to // add 1 before we free it. DWORD val = index.m_dwIndex + 1; g_pModuleIndexDispenser->DisposeId(val); } void Module::AllocateRegularStaticHandles(AppDomain* pDomain) { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; #ifndef CROSSGEN_COMPILE if (NingenEnabled()) return; // Allocate the handles we will need. Note that AllocateStaticFieldObjRefPtrs will only // allocate if pModuleData->GetGCStaticsBasePointerAddress(pMT) != 0, avoiding creating // handles more than once for a given MT or module DomainLocalModule *pModuleData = GetDomainLocalModule(pDomain); _ASSERTE(pModuleData->GetPrecomputedGCStaticsBasePointerAddress() != NULL); if (this->m_dwMaxGCRegularStaticHandles > 0) { // If we're setting up a non-default domain, we want the allocation to look like it's // coming from the created domain. // REVISIT_TODO: The comparison "pDomain != GetDomain()" will always be true for domain-neutral // modules, since GetDomain() will return the SharedDomain, which is NOT an AppDomain. // Was this intended? If so, there should be a clarifying comment. If not, then we should // probably do "pDomain != GetAppDomain()" instead. if (pDomain != GetDomain() && pDomain != SystemDomain::System()->DefaultDomain() && IsSystem()) { pDomain->AllocateStaticFieldObjRefPtrsCrossDomain(this->m_dwMaxGCRegularStaticHandles, pModuleData->GetPrecomputedGCStaticsBasePointerAddress()); } else { pDomain->AllocateStaticFieldObjRefPtrs(this->m_dwMaxGCRegularStaticHandles, pModuleData->GetPrecomputedGCStaticsBasePointerAddress()); } // We should throw if we fail to allocate and never hit this assert _ASSERTE(pModuleData->GetPrecomputedGCStaticsBasePointer() != NULL); } #endif // CROSSGEN_COMPILE } BOOL Module::IsStaticStoragePrepared(mdTypeDef tkType) { LIMITED_METHOD_CONTRACT; // Right now the design is that we do one static allocation pass during NGEN, // and a 2nd pass for it at module init time for modules that weren't NGENed or the NGEN // pass was unsucessful. If we are loading types after that then we must use dynamic // static storage. These dynamic statics require an additional indirection so they // don't perform quite as well. // // This check was created for the scenario where a profiler adds additional types // however it seems likely this check would also accurately handle other dynamic // scenarios such as ref.emit and EnC as long as they are adding new types and // not new statics to existing types. _ASSERTE(TypeFromToken(tkType) == mdtTypeDef); return m_maxTypeRidStaticsAllocated >= RidFromToken(tkType); } void Module::AllocateStatics(AllocMemTracker *pamTracker) { STANDARD_VM_CONTRACT; if (IsResource()) { m_dwRegularStaticsBlockSize = DomainLocalModule::OffsetOfDataBlob(); m_dwThreadStaticsBlockSize = ThreadLocalModule::OffsetOfDataBlob(); // If it has no code, we don't have to allocate anything LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Resource module %s. No statics neeeded\n", GetSimpleName())); _ASSERTE(m_maxTypeRidStaticsAllocated == 0); return; } #ifdef FEATURE_PREJIT if (m_pRegularStaticOffsets == (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED) { _ASSERTE(HasNativeImage()); // This is an ngen image and all the classes were loaded at ngen time, so we're done. LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: 'Complete' Native image found, no statics parsing needed for module %s.\n", GetSimpleName())); // typeDefs rids 0 and 1 aren't included in the count, thus X typeDefs means rid X+1 is valid _ASSERTE(m_maxTypeRidStaticsAllocated == GetMDImport()->GetCountWithTokenKind(mdtTypeDef) + 1); return; } #endif LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Allocating statics for module %s\n", GetSimpleName())); // Build the offset table, which will tell us what the offsets for the statics of each class are (one offset for gc handles, one offset // for non gc types) BuildStaticsOffsets(pamTracker); } // This method will report GC static refs of the module. It doesn't have to be complete (ie, it's // currently used to opportunistically get more concurrency in the marking of statics), so it currently // ignores any statics that are not preallocated (ie: won't report statics from IsDynamicStatics() MT) // The reason this function is in Module and not in DomainFile (together with DomainLocalModule is because // for shared modules we need a very fast way of getting to the DomainLocalModule. For that we use // a table in DomainLocalBlock that's indexed with a module ID // // This method is a secondary way for the GC to find statics, and it is only used when we are on // a multiproc machine and we are using the ServerHeap. The primary way used by the GC to find // statics is through the handle table. Module::AllocateRegularStaticHandles() allocates a GC handle // from the handle table, and the GC will trace this handle and find the statics. void Module::EnumRegularStaticGCRefs(AppDomain* pAppDomain, promote_func* fn, ScanContext* sc) { CONTRACT_VOID { NOTHROW; GC_NOTRIGGER; } CONTRACT_END; _ASSERTE(GCHeapUtilities::IsGCInProgress() && GCHeapUtilities::IsServerHeap() && IsGCSpecialThread()); DomainLocalModule *pModuleData = GetDomainLocalModule(pAppDomain); DWORD dwHandles = m_dwMaxGCRegularStaticHandles; if (IsResource()) { RETURN; } LOG((LF_GC, LL_INFO100, "Scanning statics for module %s\n", GetSimpleName())); OBJECTREF* ppObjectRefs = pModuleData->GetPrecomputedGCStaticsBasePointer(); for (DWORD i = 0 ; i < dwHandles ; i++) { // Handles are allocated in SetDomainFile (except for bootstrapped mscorlib). In any // case, we shouldnt get called if the module hasn't had it's handles allocated (as we // only get here if IsActive() is true, which only happens after SetDomainFile(), which // is were we allocate handles. _ASSERTE(ppObjectRefs); fn((Object **)(ppObjectRefs+i), sc, 0); } LOG((LF_GC, LL_INFO100, "Done scanning statics for module %s\n", GetSimpleName())); RETURN; } void Module::SetDomainFile(DomainFile *pDomainFile) { CONTRACTL { INSTANCE_CHECK; PRECONDITION(CheckPointer(pDomainFile)); PRECONDITION(IsManifest() == pDomainFile->IsAssembly()); THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; DomainLocalModule* pModuleData = 0; // Do we need to allocate memory for the non GC statics? if ((GetAssembly()->IsDomainNeutral() && !IsSingleAppDomain())|| m_ModuleID == NULL) { // Allocate memory for the module statics. LoaderAllocator *pLoaderAllocator = NULL; if (GetAssembly()->IsCollectible()) { pLoaderAllocator = GetAssembly()->GetLoaderAllocator(); } else { pLoaderAllocator = pDomainFile->GetAppDomain()->GetLoaderAllocator(); } SIZE_T size = GetDomainLocalModuleSize(); LOG((LF_CLASSLOADER, LL_INFO10, "STATICS: Allocating %i bytes for precomputed statics in module %S in LoaderAllocator %p\n", size, this->GetDebugName(), pLoaderAllocator)); // We guarantee alignment for 64-bit regular statics on 32-bit platforms even without FEATURE_64BIT_ALIGNMENT for performance reasons. _ASSERTE(size >= DomainLocalModule::OffsetOfDataBlob()); pModuleData = (DomainLocalModule*)(void*) pLoaderAllocator->GetHighFrequencyHeap()->AllocAlignedMem( size, MAX_PRIMITIVE_FIELD_SIZE); // Note: Memory allocated on loader heap is zero filled // memset(pModuleData, 0, size); // Verify that the space is really zero initialized _ASSERTE(pModuleData->GetPrecomputedGCStaticsBasePointer() == NULL); // Make sure that the newly allocated DomainLocalModule gets // a copy of the domain-neutral module ID. if (GetAssembly()->IsDomainNeutral() && !IsSingleAppDomain()) { // If the module was loaded as domain-neutral, we can find the ID by // casting 'm_ModuleID'. _ASSERTE(Module::IDToIndex((SIZE_T)m_ModuleID) == this->m_ModuleIndex); pModuleData->m_ModuleIndex = Module::IDToIndex((SIZE_T)m_ModuleID); // Eventually I want to just do this instead... //pModuleData->m_ModuleIndex = this->m_ModuleIndex; } else { // If the module was loaded as domain-specific, then we need to assign // this module a domain-neutral module ID. pModuleData->m_ModuleIndex = Module::AllocateModuleIndex(); m_ModuleIndex = pModuleData->m_ModuleIndex; } } else { pModuleData = this->m_ModuleID; LOG((LF_CLASSLOADER, LL_INFO10, "STATICS: Allocation not needed for ngened non shared module %s in Appdomain %08x\n")); } if (GetAssembly()->IsDomainNeutral() && !IsSingleAppDomain()) { DomainLocalBlock *pLocalBlock; { pLocalBlock = pDomainFile->GetAppDomain()->GetDomainLocalBlock(); pLocalBlock->SetModuleSlot(GetModuleIndex(), pModuleData); } pLocalBlock->SetDomainFile(GetModuleIndex(), pDomainFile); } else { // Non shared case, module points directly to the statics. In ngen case // m_pDomainModule is already set for the non shared case if (m_ModuleID == NULL) { m_ModuleID = pModuleData; } m_ModuleID->SetDomainFile(pDomainFile); } // Allocate static handles now. // NOTE: Bootstrapping issue with mscorlib - we will manually allocate later // If the assembly is collectible, we don't initialize static handles for them // as it is currently initialized through the DomainLocalModule::PopulateClass in MethodTable::CheckRunClassInitThrowing // (If we don't do this, it would allocate here unused regular static handles that will be overridden later) if (g_pPredefinedArrayTypes[ELEMENT_TYPE_OBJECT] != NULL && !GetAssembly()->IsCollectible()) AllocateRegularStaticHandles(pDomainFile->GetAppDomain()); } #ifndef CROSSGEN_COMPILE OBJECTREF Module::GetExposedObject() { CONTRACT(OBJECTREF) { INSTANCE_CHECK; POSTCONDITION(RETVAL != NULL); THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACT_END; RETURN GetDomainFile()->GetExposedModuleObject(); } #endif // CROSSGEN_COMPILE // // AllocateMap allocates the RID maps based on the size of the current // metadata (if any) // void Module::AllocateMaps() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; enum { TYPEDEF_MAP_INITIAL_SIZE = 5, TYPEREF_MAP_INITIAL_SIZE = 5, MEMBERDEF_MAP_INITIAL_SIZE = 10, GENERICPARAM_MAP_INITIAL_SIZE = 5, GENERICTYPEDEF_MAP_INITIAL_SIZE = 5, FILEREFERENCES_MAP_INITIAL_SIZE = 5, ASSEMBLYREFERENCES_MAP_INITIAL_SIZE = 5, }; PTR_TADDR pTable = NULL; if (IsResource()) return; if (IsReflection()) { // For dynamic modules, it is essential that we at least have a TypeDefToMethodTable // map with an initial block. Otherwise, all the iterators will abort on an // initial empty table and we will e.g. corrupt the backpatching chains during // an appdomain unload. m_TypeDefToMethodTableMap.dwCount = TYPEDEF_MAP_INITIAL_SIZE; // The above is essential. The following ones are precautionary. m_TypeRefToMethodTableMap.dwCount = TYPEREF_MAP_INITIAL_SIZE; m_MethodDefToDescMap.dwCount = MEMBERDEF_MAP_INITIAL_SIZE; m_FieldDefToDescMap.dwCount = MEMBERDEF_MAP_INITIAL_SIZE; m_GenericParamToDescMap.dwCount = GENERICPARAM_MAP_INITIAL_SIZE; m_GenericTypeDefToCanonMethodTableMap.dwCount = TYPEDEF_MAP_INITIAL_SIZE; m_FileReferencesMap.dwCount = FILEREFERENCES_MAP_INITIAL_SIZE; m_ManifestModuleReferencesMap.dwCount = ASSEMBLYREFERENCES_MAP_INITIAL_SIZE; m_MethodDefToPropertyInfoMap.dwCount = MEMBERDEF_MAP_INITIAL_SIZE; } else { IMDInternalImport * pImport = GetMDImport(); // Get # TypeDefs (add 1 for COR_GLOBAL_PARENT_TOKEN) m_TypeDefToMethodTableMap.dwCount = pImport->GetCountWithTokenKind(mdtTypeDef)+2; // Get # TypeRefs m_TypeRefToMethodTableMap.dwCount = pImport->GetCountWithTokenKind(mdtTypeRef)+1; // Get # MethodDefs m_MethodDefToDescMap.dwCount = pImport->GetCountWithTokenKind(mdtMethodDef)+1; // Get # FieldDefs m_FieldDefToDescMap.dwCount = pImport->GetCountWithTokenKind(mdtFieldDef)+1; // Get # GenericParams m_GenericParamToDescMap.dwCount = pImport->GetCountWithTokenKind(mdtGenericParam)+1; // Get the number of FileReferences in the map m_FileReferencesMap.dwCount = pImport->GetCountWithTokenKind(mdtFile)+1; // Get the number of AssemblyReferences in the map m_ManifestModuleReferencesMap.dwCount = pImport->GetCountWithTokenKind(mdtAssemblyRef)+1; // These maps are only added to during NGen, so for other scenarios leave them empty if (IsCompilationProcess()) { m_GenericTypeDefToCanonMethodTableMap.dwCount = m_TypeDefToMethodTableMap.dwCount; m_MethodDefToPropertyInfoMap.dwCount = m_MethodDefToDescMap.dwCount; } else { m_GenericTypeDefToCanonMethodTableMap.dwCount = 0; m_MethodDefToPropertyInfoMap.dwCount = 0; } } S_SIZE_T nTotal; nTotal += m_TypeDefToMethodTableMap.dwCount; nTotal += m_TypeRefToMethodTableMap.dwCount; nTotal += m_MethodDefToDescMap.dwCount; nTotal += m_FieldDefToDescMap.dwCount; nTotal += m_GenericParamToDescMap.dwCount; nTotal += m_GenericTypeDefToCanonMethodTableMap.dwCount; nTotal += m_FileReferencesMap.dwCount; nTotal += m_ManifestModuleReferencesMap.dwCount; nTotal += m_MethodDefToPropertyInfoMap.dwCount; _ASSERTE (m_pAssembly && m_pAssembly->GetLowFrequencyHeap()); pTable = (PTR_TADDR)(void*)m_pAssembly->GetLowFrequencyHeap()->AllocMem(nTotal * S_SIZE_T(sizeof(TADDR))); // Note: Memory allocated on loader heap is zero filled // memset(pTable, 0, nTotal * sizeof(void*)); m_TypeDefToMethodTableMap.pNext = NULL; m_TypeDefToMethodTableMap.supportedFlags = TYPE_DEF_MAP_ALL_FLAGS; m_TypeDefToMethodTableMap.pTable = pTable; m_TypeRefToMethodTableMap.pNext = NULL; m_TypeRefToMethodTableMap.supportedFlags = TYPE_REF_MAP_ALL_FLAGS; m_TypeRefToMethodTableMap.pTable = &pTable[m_TypeDefToMethodTableMap.dwCount]; m_MethodDefToDescMap.pNext = NULL; m_MethodDefToDescMap.supportedFlags = METHOD_DEF_MAP_ALL_FLAGS; m_MethodDefToDescMap.pTable = &m_TypeRefToMethodTableMap.pTable[m_TypeRefToMethodTableMap.dwCount]; m_FieldDefToDescMap.pNext = NULL; m_FieldDefToDescMap.supportedFlags = FIELD_DEF_MAP_ALL_FLAGS; m_FieldDefToDescMap.pTable = &m_MethodDefToDescMap.pTable[m_MethodDefToDescMap.dwCount]; m_GenericParamToDescMap.pNext = NULL; m_GenericParamToDescMap.supportedFlags = GENERIC_PARAM_MAP_ALL_FLAGS; m_GenericParamToDescMap.pTable = &m_FieldDefToDescMap.pTable[m_FieldDefToDescMap.dwCount]; m_GenericTypeDefToCanonMethodTableMap.pNext = NULL; m_GenericTypeDefToCanonMethodTableMap.supportedFlags = GENERIC_TYPE_DEF_MAP_ALL_FLAGS; m_GenericTypeDefToCanonMethodTableMap.pTable = &m_GenericParamToDescMap.pTable[m_GenericParamToDescMap.dwCount]; m_FileReferencesMap.pNext = NULL; m_FileReferencesMap.supportedFlags = FILE_REF_MAP_ALL_FLAGS; m_FileReferencesMap.pTable = &m_GenericTypeDefToCanonMethodTableMap.pTable[m_GenericTypeDefToCanonMethodTableMap.dwCount]; m_ManifestModuleReferencesMap.pNext = NULL; m_ManifestModuleReferencesMap.supportedFlags = MANIFEST_MODULE_MAP_ALL_FLAGS; m_ManifestModuleReferencesMap.pTable = &m_FileReferencesMap.pTable[m_FileReferencesMap.dwCount]; m_MethodDefToPropertyInfoMap.pNext = NULL; m_MethodDefToPropertyInfoMap.supportedFlags = PROPERTY_INFO_MAP_ALL_FLAGS; m_MethodDefToPropertyInfoMap.pTable = &m_ManifestModuleReferencesMap.pTable[m_ManifestModuleReferencesMap.dwCount]; } // // FreeClassTables frees the classes in the module // void Module::FreeClassTables() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (m_dwTransientFlags & CLASSES_FREED) return; FastInterlockOr(&m_dwTransientFlags, CLASSES_FREED); // disable ibc here because it can cause errors during the destruction of classes IBCLoggingDisabler disableLogging; #if _DEBUG DebugLogRidMapOccupancy(); #endif // // Free the types filled out in the TypeDefToEEClass map // // Go through each linked block LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT != NULL && pMT->IsRestored()) { pMT->GetClass()->Destruct(pMT); } } // Now do the same for constructed types (arrays and instantiated generic types) if (IsTenured()) // If we're destructing because of an error during the module's creation, we'll play it safe and not touch this table as its memory is freed by a { // separate AllocMemTracker. Though you're supposed to destruct everything else before destructing the AllocMemTracker, this is an easy invariant to break so // we'll play extra safe on this end. if (m_pAvailableParamTypes != NULL) { EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle th = pEntry->GetTypeHandle(); if (!th.IsRestored()) continue; #ifdef FEATURE_COMINTEROP // Some MethodTables/TypeDescs have COM interop goo attached to them which must be released if (!th.IsTypeDesc()) { MethodTable *pMT = th.AsMethodTable(); if (pMT->HasCCWTemplate() && (!pMT->IsZapped() || pMT->GetZapModule() == this)) { // code:MethodTable::GetComCallWrapperTemplate() may go through canonical methodtable indirection cell. // The module load could be aborted before completing code:FILE_LOAD_EAGER_FIXUPS phase that's responsible // for resolving pre-restored indirection cells, so we have to check for it here explicitly. if (CORCOMPILE_IS_POINTER_TAGGED(pMT->GetCanonicalMethodTableFixup())) continue; ComCallWrapperTemplate *pTemplate = pMT->GetComCallWrapperTemplate(); if (pTemplate != NULL) { pTemplate->Release(); } } } else if (th.IsArray()) { ComCallWrapperTemplate *pTemplate = th.AsArray()->GetComCallWrapperTemplate(); if (pTemplate != NULL) { pTemplate->Release(); } } #endif // FEATURE_COMINTEROP // We need to call destruct on instances of EEClass whose "canonical" dependent lives in this table // There is nothing interesting to destruct on array EEClass if (!th.IsTypeDesc()) { MethodTable * pMT = th.AsMethodTable(); if (pMT->IsCanonicalMethodTable() && (!pMT->IsZapped() || pMT->GetZapModule() == this)) pMT->GetClass()->Destruct(pMT); } } } } } #endif // !DACCESS_COMPILE ClassLoader *Module::GetClassLoader() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; _ASSERTE(m_pAssembly != NULL); return m_pAssembly->GetLoader(); } PTR_BaseDomain Module::GetDomain() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; _ASSERTE(m_pAssembly != NULL); return m_pAssembly->GetDomain(); } #ifndef DACCESS_COMPILE #ifndef CROSSGEN_COMPILE void Module::StartUnload() { WRAPPER_NO_CONTRACT; #ifdef PROFILING_SUPPORTED { BEGIN_PIN_PROFILER(CORProfilerTrackModuleLoads()); if (!IsBeingUnloaded()) { // Profiler is causing some peripheral class loads. Probably this just needs // to be turned into a Fault_not_fatal and moved to a specific place inside the profiler. EX_TRY { GCX_PREEMP(); g_profControlBlock.pProfInterface->ModuleUnloadStarted((ModuleID) this); } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); } END_PIN_PROFILER(); } #endif // PROFILING_SUPPORTED #ifdef FEATURE_PREJIT if (g_IBCLogger.InstrEnabled()) { Thread * pThread = GetThread(); ThreadLocalIBCInfo* pInfo = pThread->GetIBCInfo(); // Acquire the Crst lock before creating the IBCLoggingDisabler object. // Only one thread at a time can be processing an IBC logging event. CrstHolder lock(g_IBCLogger.GetSync()); { IBCLoggingDisabler disableLogging( pInfo ); // runs IBCLoggingDisabler::DisableLogging // Write out the method profile data /*hr=*/WriteMethodProfileDataLogFile(true); } } #endif // FEATURE_PREJIT SetBeingUnloaded(); } #endif // CROSSGEN_COMPILE void Module::ReleaseILData(void) { WRAPPER_NO_CONTRACT; ReleaseISymUnmanagedReader(); } //--------------------------------------------------------------------------------------- // // Simple wrapper around calling IsAfContentType_WindowsRuntime() against the flags // returned from the PEAssembly's GetFlagsNoTrigger() // // Return Value: // nonzero iff we successfully determined pModule is a WinMD. FALSE if pModule is not // a WinMD, or we fail trying to find out. // BOOL Module::IsWindowsRuntimeModule() { CONTRACTL { NOTHROW; GC_NOTRIGGER; CAN_TAKE_LOCK; // Accesses metadata directly, which takes locks MODE_ANY; } CONTRACTL_END; BOOL fRet = FALSE; DWORD dwFlags; if (FAILED(GetAssembly()->GetManifestFile()->GetFlagsNoTrigger(&dwFlags))) return FALSE; return IsAfContentType_WindowsRuntime(dwFlags); } BOOL Module::IsInCurrentVersionBubble() { LIMITED_METHOD_CONTRACT; #ifdef FEATURE_NATIVE_IMAGE_GENERATION if (!IsCompilationProcess()) return TRUE; // The module being compiled is always part of the current version bubble AppDomain * pAppDomain = GetAppDomain(); if (pAppDomain->IsCompilationDomain() && pAppDomain->ToCompilationDomain()->GetTargetModule() == this) return TRUE; if (IsReadyToRunCompilation()) return FALSE; #ifdef FEATURE_COMINTEROP if (g_fNGenWinMDResilient) return !GetAssembly()->IsWinMD(); #endif return TRUE; #else // FEATURE_NATIVE_IMAGE_GENERATION return TRUE; #endif // FEATURE_NATIVE_IMAGE_GENERATION } //--------------------------------------------------------------------------------------- // // WinMD-aware helper to grab a readable public metadata interface. Any place that thinks // it wants to use Module::GetRWImporter + QI now should use this wrapper instead. // // Arguments: // * dwOpenFlags - Combo from CorOpenFlags. Better not contain ofWrite! // * riid - Public IID requested // * ppvInterface - [out] Requested interface. On success, *ppvInterface is returned // refcounted; caller responsible for Release. // // Return Value: // HRESULT indicating success or failure. // HRESULT Module::GetReadablePublicMetaDataInterface(DWORD dwOpenFlags, REFIID riid, LPVOID * ppvInterface) { CONTRACTL { NOTHROW; GC_NOTRIGGER; CAN_TAKE_LOCK; // IsWindowsRuntimeModule accesses metadata directly, which takes locks MODE_ANY; } CONTRACTL_END; _ASSERTE((dwOpenFlags & ofWrite) == 0); // Temporary place to store public, AddRef'd interface pointers ReleaseHolder<IUnknown> pIUnkPublic; // Temporary place to store the IUnknown from which we'll do the final QI to get the // requested public interface. Any assignment to pIUnk assumes pIUnk does not need // to do a Release() (either the interface was internal and not AddRef'd, or was // public and will be released by the above holder). IUnknown * pIUnk = NULL; HRESULT hr = S_OK; // Normally, we just get an RWImporter to do the QI on, and we're on our way. EX_TRY { pIUnk = GetRWImporter(); } EX_CATCH_HRESULT_NO_ERRORINFO(hr); if (FAILED(hr) && IsWindowsRuntimeModule()) { // WinMD modules don't like creating RW importers. They also (currently) // have no plumbing to get to their public metadata interfaces from the // Module. So we actually have to start from scratch at the dispenser. // To start with, get a dispenser, and get the metadata memory blob we've // already loaded. If either of these fail, just return the error HRESULT // from the above GetRWImporter() call. // We'll get an addref'd IMetaDataDispenser, so use a holder to release it ReleaseHolder<IMetaDataDispenser> pDispenser; if (FAILED(InternalCreateMetaDataDispenser(IID_IMetaDataDispenser, &pDispenser))) { _ASSERTE(FAILED(hr)); return hr; } COUNT_T cbMetadata = 0; PTR_CVOID pvMetadata = GetAssembly()->GetManifestFile()->GetLoadedMetadata(&cbMetadata); if ((pvMetadata == NULL) || (cbMetadata == 0)) { _ASSERTE(FAILED(hr)); return hr; } // Now that the pieces are ready, we can use the riid specified by the // profiler in this call to the dispenser to get the requested interface. If // this fails, then this is the interesting HRESULT for the caller to see. // // We'll get an AddRef'd public interface, so use a holder to release it hr = pDispenser->OpenScopeOnMemory( pvMetadata, cbMetadata, (dwOpenFlags | ofReadOnly), // Force ofReadOnly on behalf of the profiler riid, &pIUnkPublic); if (FAILED(hr)) return hr; // Set pIUnk so we can do the final QI from it below as we do in the other // cases. pIUnk = pIUnkPublic; } // Get the requested interface if (SUCCEEDED(hr) && (ppvInterface != NULL)) { _ASSERTE(pIUnk != NULL); hr = pIUnk->QueryInterface(riid, (void **) ppvInterface); } return hr; } // a special token that indicates no reader could be created - don't try again static ISymUnmanagedReader* const k_pInvalidSymReader = (ISymUnmanagedReader*)0x1; #if defined(FEATURE_ISYM_READER) && !defined(CROSSGEN_COMPILE) ISymUnmanagedReader *Module::GetISymUnmanagedReaderNoThrow(void) { CONTRACT(ISymUnmanagedReader *) { INSTANCE_CHECK; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); NOTHROW; WRAPPER(GC_TRIGGERS); MODE_ANY; } CONTRACT_END; ISymUnmanagedReader *ret = NULL; EX_TRY { ret = GetISymUnmanagedReader(); } EX_CATCH { // We swallow any exception and say that we simply couldn't get a reader by returning NULL. // The only type of error that should be possible here is OOM. /* DISABLED due to Dev10 bug 619495 CONSISTENCY_CHECK_MSG( GET_EXCEPTION()->GetHR() == E_OUTOFMEMORY, "Exception from GetISymUnmanagedReader"); */ } EX_END_CATCH(RethrowTerminalExceptions); RETURN (ret); } ISymUnmanagedReader *Module::GetISymUnmanagedReader(void) { CONTRACT(ISymUnmanagedReader *) { INSTANCE_CHECK; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); THROWS; WRAPPER(GC_TRIGGERS); MODE_ANY; } CONTRACT_END; // No symbols for resource modules if (IsResource()) RETURN NULL; if (g_fEEShutDown) RETURN NULL; // Verify that symbol reading is permitted for this module. // If we know we've already created a symbol reader, don't bother checking. There is // no advantage to allowing symbol reading to be turned off if we've already created the reader. // Note that we can't just put this code in the creation block below because we might have to // call managed code to resolve security policy, and we can't do that while holding a lock. // There is no disadvantage other than a minor perf cost to calling this unnecessarily, so the // race on m_pISymUnmanagedReader here is OK. The perf cost is minor because the only real // work is done by the security system which caches the result. if( m_pISymUnmanagedReader == NULL && !IsSymbolReadingEnabled() ) RETURN NULL; // Take the lock for the m_pISymUnmanagedReader // This ensures that we'll only ever attempt to create one reader at a time, and we won't // create a reader if we're in the middle of destroying one that has become stale. // Actual access to the reader can safely occur outside the lock as long as it has its own // AddRef which we take inside the lock at the bottom of this method. CrstHolder holder(&m_ISymUnmanagedReaderCrst); UINT lastErrorMode = 0; // If we haven't created a reader yet, do so now if (m_pISymUnmanagedReader == NULL) { // Mark our reader as invalid so that if we fail to create the reader // (including if an exception is thrown), we won't keep trying. m_pISymUnmanagedReader = k_pInvalidSymReader; // There are 4 main cases here: // 1. Assembly is on disk and we'll get the symbols from a file next to the assembly // 2. Assembly is provided by the host and we'll get the symbols from the host // 3. Assembly was loaded in-memory (by byte array or ref-emit), and symbols were // provided along with it. // 4. Assembly was loaded in-memory but no symbols were provided. // Determine whether we should be looking in memory for the symbols (cases 2 & 3) bool fInMemorySymbols = ( m_file->IsIStream() || GetInMemorySymbolStream() ); if( !fInMemorySymbols && m_file->GetPath().IsEmpty() ) { // Case 4. We don't have a module path, an IStream or an in memory symbol stream, // so there is no-where to try and get symbols from. RETURN (NULL); } // Create a binder to find the reader. // // <REVISIT_TODO>@perf: this is slow, creating and destroying the binder every // time. We should cache this somewhere, but I'm not 100% sure // where right now...</REVISIT_TODO> HRESULT hr = S_OK; SafeComHolder<ISymUnmanagedBinder> pBinder; if (g_pDebugInterface == NULL) { // @TODO: this is reachable when debugging! UNREACHABLE_MSG("About to CoCreateInstance! This code should not be " "reachable or needs to be reimplemented for CoreCLR!"); } if (this->GetInMemorySymbolStreamFormat() == eSymbolFormatILDB) { // We've got in-memory ILDB symbols, create the ILDB symbol binder // Note that in this case, we must be very careful not to use diasymreader.dll // at all - we don't trust it, and shouldn't run any code in it IfFailThrow(IldbSymbolsCreateInstance(CLSID_CorSymBinder_SxS, IID_ISymUnmanagedBinder, (void**)&pBinder)); } else { // We're going to be working with Windows PDB format symbols. Attempt to CoCreate the symbol binder. // CoreCLR supports not having a symbol reader installed, so CoCreate searches the PATH env var // and then tries coreclr dll location. // On desktop, the framework installer is supposed to install diasymreader.dll as well // and so this shouldn't happen. hr = FakeCoCreateInstanceEx(CLSID_CorSymBinder_SxS, NATIVE_SYMBOL_READER_DLL, IID_ISymUnmanagedBinder, (void**)&pBinder, NULL); if (FAILED(hr)) { PathString symbolReaderPath; hr = GetHModuleDirectory(GetModuleInst(), symbolReaderPath); if (FAILED(hr)) { RETURN (NULL); } symbolReaderPath.Append(NATIVE_SYMBOL_READER_DLL); hr = FakeCoCreateInstanceEx(CLSID_CorSymBinder_SxS, symbolReaderPath.GetUnicode(), IID_ISymUnmanagedBinder, (void**)&pBinder, NULL); if (FAILED(hr)) { RETURN (NULL); } } } LOG((LF_CORDB, LL_INFO10, "M::GISUR: Created binder\n")); // Note: we change the error mode here so we don't get any popups as the PDB symbol reader attempts to search the // hard disk for files. lastErrorMode = SetErrorMode(SEM_NOOPENFILEERRORBOX|SEM_FAILCRITICALERRORS); SafeComHolder<ISymUnmanagedReader> pReader; if (fInMemorySymbols) { SafeComHolder<IStream> pIStream( NULL ); // If debug stream is already specified, don't bother to go through fusion // This is the common case for case 2 (hosted modules) and case 3 (Ref.Emit). if (GetInMemorySymbolStream() ) { if( IsReflection() ) { // If this is Reflection.Emit, we must clone the stream because another thread may // update it when someone is using the reader we create here leading to AVs. // Note that the symbol stream should be up to date since we flush the writer // after every addition in Module::AddClass. IfFailThrow(GetInMemorySymbolStream()->Clone(&pIStream)); } else { // The stream is not changing. Just add-ref to it. pIStream = GetInMemorySymbolStream(); pIStream->AddRef(); } } if (SUCCEEDED(hr)) { hr = pBinder->GetReaderFromStream(GetRWImporter(), pIStream, &pReader); } } else { // The assembly is on disk, so try and load symbols based on the path to the assembly (case 1) const SString &path = m_file->GetPath(); // Call Fusion to ensure that any PDB's are shadow copied before // trying to get a symbol reader. This has to be done once per // Assembly. // for this to work with winmds we cannot simply call GetRWImporter() as winmds are RO // and thus don't implement the RW interface. so we call this wrapper function which knows // how to get a IMetaDataImport interface regardless of the underlying module type. ReleaseHolder<IUnknown> pUnk = NULL; hr = GetReadablePublicMetaDataInterface(ofReadOnly, IID_IMetaDataImport, &pUnk); if (SUCCEEDED(hr)) hr = pBinder->GetReaderForFile(pUnk, path, NULL, &pReader); } SetErrorMode(lastErrorMode); if (SUCCEEDED(hr)) { m_pISymUnmanagedReader = pReader.Extract(); LOG((LF_CORDB, LL_INFO10, "M::GISUR: Loaded symbols for module %S\n", GetDebugName())); } else { // We failed to create the reader, don't try again next time LOG((LF_CORDB, LL_INFO10, "M::GISUR: Failed to load symbols for module %S\n", GetDebugName())); _ASSERTE( m_pISymUnmanagedReader == k_pInvalidSymReader ); } } // if( m_pISymUnmanagedReader == NULL ) // If we previously failed to create the reader, return NULL if (m_pISymUnmanagedReader == k_pInvalidSymReader) { RETURN (NULL); } // Success - return an AddRef'd copy of the reader m_pISymUnmanagedReader->AddRef(); RETURN (m_pISymUnmanagedReader); } #endif // FEATURE_ISYM_READER && !CROSSGEN_COMPILE BOOL Module::IsSymbolReadingEnabled() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; // The only time we need symbols available is for debugging and taking stack traces, // neither of which can be done if the assembly can't run. The advantage of being strict // is that there is a perf penalty adding types to a module if you must support reading // symbols at any time. If symbols don't need to be accesible then we can // optimize by only commiting symbols when the assembly is saved to disk. See DDB 671107. if(!GetAssembly()->HasRunAccess()) { return FALSE; } // If the module has symbols in-memory (eg. RefEmit) that are in ILDB // format, then there isn't any reason not to supply them. The reader // code is always available, and we trust it's security. if (this->GetInMemorySymbolStreamFormat() == eSymbolFormatILDB) { return TRUE; } #ifdef DEBUGGING_SUPPORTED if (!g_pDebugInterface) { // if debugging is disabled (no debug pack installed), do not load symbols // This is done for two reasons. We don't completely trust the security of // the diasymreader.dll code, so we don't want to use it in mainline scenarios. // Secondly, there's not reason that diasymreader.dll will even necssarily be // be on the machine if the debug pack isn't installed. return FALSE; } #endif // DEBUGGING_SUPPORTED return TRUE; } // At this point, this is only called when we're creating an appdomain // out of an array of bytes, so we'll keep the IStream that we create // around in case the debugger attaches later (including detach & re-attach!) void Module::SetSymbolBytes(LPCBYTE pbSyms, DWORD cbSyms) { STANDARD_VM_CONTRACT; // Create a IStream from the memory for the syms. SafeComHolder<CGrowableStream> pStream(new CGrowableStream()); // Do not need to AddRef the CGrowableStream because the constructor set it to 1 // ref count already. The Module will keep a copy for its own use. // Make sure to set the symbol stream on the module before // attempting to send UpdateModuleSyms messages up for it. SetInMemorySymbolStream(pStream, eSymbolFormatPDB); // This can only be called when the module is being created. No-one should have // tried to use the symbols yet, and so there should not be a reader. // If instead, we wanted to call this when a reader could have been created, we need to // serialize access by taking the reader lock, and flush the old reader by calling // code:Module.ReleaseISymUnmanagedReader _ASSERTE( m_pISymUnmanagedReader == NULL ); #ifdef LOGGING LPCWSTR pName = NULL; pName = GetDebugName(); #endif // LOGGING ULONG cbWritten; DWORD dwError = pStream->Write((const void *)pbSyms, (ULONG)cbSyms, &cbWritten); IfFailThrow(HRESULT_FROM_WIN32(dwError)); #if PROFILING_SUPPORTED && !defined(CROSSGEN_COMPILE) BEGIN_PIN_PROFILER(CORProfilerInMemorySymbolsUpdatesEnabled()); { g_profControlBlock.pProfInterface->ModuleInMemorySymbolsUpdated((ModuleID) this); } END_PIN_PROFILER(); #endif //PROFILING_SUPPORTED && !defined(CROSSGEN_COMPILE) ETW::CodeSymbolLog::EmitCodeSymbols(this); // Tell the debugger that symbols have been loaded for this // module. We iterate through all domains which contain this // module's assembly, and send a debugger notify for each one. // <REVISIT_TODO>@perf: it would scale better if we directly knew which domains // the assembly was loaded in.</REVISIT_TODO> if (CORDebuggerAttached()) { AppDomainIterator i(FALSE); while (i.Next()) { AppDomain *pDomain = i.GetDomain(); if (pDomain->IsDebuggerAttached() && (GetDomain() == SystemDomain::System() || pDomain->ContainsAssembly(m_pAssembly))) { g_pDebugInterface->SendUpdateModuleSymsEventAndBlock(this, pDomain); } } } } // Clear any cached symbol reader void Module::ReleaseISymUnmanagedReader(void) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; } CONTRACTL_END; // Caller is responsible for taking the reader lock if the call could occur when // other threads are using or creating the reader if( m_pISymUnmanagedReader != NULL ) { // If we previously failed to create a reader, don't attempt to release it // but do clear it out so that we can try again (eg. symbols may have changed) if( m_pISymUnmanagedReader != k_pInvalidSymReader ) { m_pISymUnmanagedReader->Release(); } m_pISymUnmanagedReader = NULL; } } // Lazily creates a new IL stub cache for this module. ILStubCache* Module::GetILStubCache() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END; // Use per-AD cache for domain specific modules when not NGENing BaseDomain *pDomain = GetDomain(); if (!pDomain->IsSharedDomain() && !pDomain->AsAppDomain()->IsCompilationDomain()) return pDomain->AsAppDomain()->GetILStubCache(); if (m_pILStubCache == NULL) { ILStubCache *pILStubCache = new ILStubCache(GetLoaderAllocator()->GetHighFrequencyHeap()); if (FastInterlockCompareExchangePointer(&m_pILStubCache, pILStubCache, NULL) != NULL) { // some thread swooped in and set the field delete pILStubCache; } } _ASSERTE(m_pILStubCache != NULL); return m_pILStubCache; } // Called to finish the process of adding a new class with Reflection.Emit void Module::AddClass(mdTypeDef classdef) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_PREEMPTIVE; PRECONDITION(!IsResource()); } CONTRACTL_END; // The fake class associated with the module (global fields & functions) needs to be initialized here // Normal classes are added to the available class hash when their typedef is first created. if (RidFromToken(classdef) == 0) { BuildClassForModule(); } // Since the module is being modified, the in-memory symbol stream // (if any) has probably also been modified. If we support reading the symbols // then we need to commit the changes to the writer and flush any old readers // However if we don't support reading then we can skip this which will give // a substantial perf improvement. See DDB 671107. if(IsSymbolReadingEnabled()) { CONSISTENCY_CHECK(IsReflection()); // this is only used for dynamic modules ISymUnmanagedWriter * pWriter = GetReflectionModule()->GetISymUnmanagedWriter(); if (pWriter != NULL) { // Serialize with any concurrent reader creations // Specifically, if we started creating a reader on one thread, and then updated the // symbols on another thread, we need to wait until the initial reader creation has // completed and release it so we don't get stuck with a stale reader. // Also, if we commit to the stream while we're in the process of creating a reader, // the reader will get corrupted/incomplete data. // Note that we must also be in co-operative mode here to ensure the debugger helper // thread can't be simultaneously reading this stream while the process is synchronized // (code:Debugger::GetSymbolBytes) CrstHolder holder(&m_ISymUnmanagedReaderCrst); // Flush writes to the symbol store to the symbol stream // Note that we do this when finishing the addition of the class, instead of // on-demand in GetISymUnmanagedReader because the writer is not thread-safe. // Here, we're inside the lock of TypeBuilder.CreateType, and so it's safe to // manipulate the writer. SafeComHolderPreemp<ISymUnmanagedWriter3> pWriter3; HRESULT thr = pWriter->QueryInterface(IID_ISymUnmanagedWriter3, (void**)&pWriter3); CONSISTENCY_CHECK(SUCCEEDED(thr)); if (SUCCEEDED(thr)) { thr = pWriter3->Commit(); if (SUCCEEDED(thr)) { // Flush any cached symbol reader to ensure we pick up any new symbols ReleaseISymUnmanagedReader(); } } // If either the QI or Commit failed if (FAILED(thr)) { // The only way we expect this might fail is out-of-memory. In that // case we silently fail to update the symbol stream with new data, but // we leave the existing reader intact. CONSISTENCY_CHECK(thr==E_OUTOFMEMORY); } } } } //--------------------------------------------------------------------------- // For the global class this builds the table of MethodDescs an adds the rids // to the MethodDef map. //--------------------------------------------------------------------------- void Module::BuildClassForModule() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; IMDInternalImport * pImport = GetMDImport(); DWORD cFunctions, cFields; { // Obtain count of global functions HENUMInternalHolder hEnum(pImport); hEnum.EnumGlobalFunctionsInit(); cFunctions = pImport->EnumGetCount(&hEnum); } { // Obtain count of global fields HENUMInternalHolder hEnum(pImport); hEnum.EnumGlobalFieldsInit(); cFields = pImport->EnumGetCount(&hEnum); } // If we have any work to do... if (cFunctions > 0 || cFields > 0) { COUNTER_ONLY(size_t _HeapSize = 0); TypeKey typeKey(this, COR_GLOBAL_PARENT_TOKEN); TypeHandle typeHnd = GetClassLoader()->LoadTypeHandleForTypeKeyNoLock(&typeKey); #ifdef ENABLE_PERF_COUNTERS _HeapSize = GetLoaderAllocator()->GetHighFrequencyHeap()->GetSize(); GetPerfCounters().m_Loading.cbLoaderHeapSize = _HeapSize; #endif // ENABLE_PERF_COUNTERS } } #endif // !DACCESS_COMPILE // Returns true iff the debugger should be notified about this module // // Notes: // Debugger doesn't need to be notified about modules that can't be executed, // like inspection and resource only. These are just pure data. // // This should be immutable for an instance of a module. That ensures that the debugger gets consistent // notifications about it. It this value mutates, than the debugger may miss relevant notifications. BOOL Module::IsVisibleToDebugger() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; if (IsResource()) { return FALSE; } // If for whatever other reason, we can't run it, then don't notify the debugger about it. Assembly * pAssembly = GetAssembly(); if (!pAssembly->HasRunAccess()) { return FALSE; } return TRUE; } BOOL Module::HasNativeOrReadyToRunImage() { #ifdef FEATURE_READYTORUN if (IsReadyToRun()) return TRUE; #endif return HasNativeImage(); } PEImageLayout * Module::GetNativeOrReadyToRunImage() { LIMITED_METHOD_CONTRACT; #ifdef FEATURE_READYTORUN if (IsReadyToRun()) return GetReadyToRunInfo()->GetImage(); #endif return GetNativeImage(); } PTR_CORCOMPILE_IMPORT_SECTION Module::GetImportSections(COUNT_T *pCount) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; #ifdef FEATURE_READYTORUN if (IsReadyToRun()) return GetReadyToRunInfo()->GetImportSections(pCount); #endif return GetNativeImage()->GetNativeImportSections(pCount); } PTR_CORCOMPILE_IMPORT_SECTION Module::GetImportSectionFromIndex(COUNT_T index) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; #ifdef FEATURE_READYTORUN if (IsReadyToRun()) return GetReadyToRunInfo()->GetImportSectionFromIndex(index); #endif return GetNativeImage()->GetNativeImportSectionFromIndex(index); } PTR_CORCOMPILE_IMPORT_SECTION Module::GetImportSectionForRVA(RVA rva) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; #ifdef FEATURE_READYTORUN if (IsReadyToRun()) return GetReadyToRunInfo()->GetImportSectionForRVA(rva); #endif return GetNativeImage()->GetNativeImportSectionForRVA(rva); } TADDR Module::GetIL(DWORD target) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; if (target == 0) return NULL; return m_file->GetIL(target); } PTR_VOID Module::GetRvaField(DWORD rva, BOOL fZapped) { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; #ifdef FEATURE_PREJIT if (fZapped && m_file->IsILOnly()) { return dac_cast<PTR_VOID>(m_file->GetLoadedNative()->GetRvaData(rva,NULL_OK)); } #endif // FEATURE_PREJIT return m_file->GetRvaField(rva); } #ifndef DACCESS_COMPILE CHECK Module::CheckRvaField(RVA field) { WRAPPER_NO_CONTRACT; if (!IsReflection()) CHECK(m_file->CheckRvaField(field)); CHECK_OK; } CHECK Module::CheckRvaField(RVA field, COUNT_T size) { CONTRACTL { STANDARD_VM_CHECK; CAN_TAKE_LOCK; } CONTRACTL_END; if (!IsReflection()) CHECK(m_file->CheckRvaField(field, size)); CHECK_OK; } #endif // !DACCESS_COMPILE BOOL Module::HasTls() { WRAPPER_NO_CONTRACT; return m_file->HasTls(); } BOOL Module::IsRvaFieldTls(DWORD rva) { WRAPPER_NO_CONTRACT; return m_file->IsRvaFieldTls(rva); } UINT32 Module::GetFieldTlsOffset(DWORD rva) { WRAPPER_NO_CONTRACT; return m_file->GetFieldTlsOffset(rva); } UINT32 Module::GetTlsIndex() { WRAPPER_NO_CONTRACT; return m_file->GetTlsIndex(); } // In DAC builds this function was being called on host addresses which may or may not // have been marshalled from the target. Such addresses can't be reliably mapped back to // target addresses, which means we can't tell whether they came from the IL or not // // Security note: Any security which you might wish to gain by verifying the origin of // a signature isn't available in DAC. The attacker can provide a dump which spoofs all // module ranges. In other words the attacker can make the signature appear to come from // anywhere, but still violate all the rules that a signature from that location would // otherwise follow. I am removing this function from DAC in order to prevent anyone from // getting a false sense of security (in addition to its functional shortcomings) #ifndef DACCESS_COMPILE BOOL Module::IsSigInIL(PCCOR_SIGNATURE signature) { CONTRACTL { INSTANCE_CHECK; FORBID_FAULT; MODE_ANY; NOTHROW; SO_TOLERANT; GC_NOTRIGGER; } CONTRACTL_END; return m_file->IsPtrInILImage(signature); } #ifdef FEATURE_PREJIT StubMethodHashTable *Module::GetStubMethodHashTable() { CONTRACTL { THROWS; GC_NOTRIGGER; } CONTRACTL_END if (m_pStubMethodHashTable == NULL && SystemDomain::GetCurrentDomain()->IsCompilationDomain()) { // we only need to create the hash table when NGENing, it is read-only at run-time AllocMemTracker amTracker; m_pStubMethodHashTable = StubMethodHashTable::Create(GetLoaderAllocator(), this, METHOD_STUBS_HASH_BUCKETS, &amTracker); amTracker.SuppressRelease(); } return m_pStubMethodHashTable; } #endif // FEATURE_PREJIT void Module::InitializeStringData(DWORD token, EEStringData *pstrData, CQuickBytes *pqb) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(TypeFromToken(token) == mdtString); } CONTRACTL_END; BOOL fIs80Plus; DWORD dwCharCount; LPCWSTR pString; if (FAILED(GetMDImport()->GetUserString(token, &dwCharCount, &fIs80Plus, &pString)) || (pString == NULL)) { THROW_BAD_FORMAT(BFA_BAD_STRING_TOKEN_RANGE, this); } #if !BIGENDIAN pstrData->SetStringBuffer(pString); #else // !!BIGENDIAN _ASSERTE(pqb != NULL); LPWSTR pSwapped; pSwapped = (LPWSTR) pqb->AllocThrows(dwCharCount * sizeof(WCHAR)); memcpy((void*)pSwapped, (void*)pString, dwCharCount*sizeof(WCHAR)); SwapStringLength(pSwapped, dwCharCount); pstrData->SetStringBuffer(pSwapped); #endif // !!BIGENDIAN // MD and String look at this bit in opposite ways. Here's where we'll do the conversion. // MD sets the bit to true if the string contains characters greater than 80. // String sets the bit to true if the string doesn't contain characters greater than 80. pstrData->SetCharCount(dwCharCount); pstrData->SetIsOnlyLowChars(!fIs80Plus); } #ifndef CROSSGEN_COMPILE #ifdef FEATURE_PREJIT OBJECTHANDLE Module::ResolveStringRefHelper(DWORD token, BaseDomain *pDomain, PTR_CORCOMPILE_IMPORT_SECTION pSection, EEStringData *pStrData) { PEImageLayout *pNativeImage = GetNativeImage(); // Get the table COUNT_T tableSize; TADDR tableBase = pNativeImage->GetDirectoryData(&pSection->Section, &tableSize); // Walk the handle table. // @TODO: If we ever care about the perf of this function, we could sort the tokens // using as a key the string they point to, so we could do a binary search for (SIZE_T * pEntry = (SIZE_T *)tableBase ; pEntry < (SIZE_T *)(tableBase + tableSize); pEntry++) { // Ensure that the compiler won't fetch the value twice SIZE_T entry = VolatileLoadWithoutBarrier(pEntry); if (CORCOMPILE_IS_POINTER_TAGGED(entry)) { BYTE * pBlob = (BYTE *) pNativeImage->GetRvaData(CORCOMPILE_UNTAG_TOKEN(entry)); // Note that we only care about strings from current module, and so we do not check ENCODE_MODULE_OVERRIDE if (*pBlob++ == ENCODE_STRING_HANDLE && TokenFromRid(CorSigUncompressData((PCCOR_SIGNATURE&) pBlob), mdtString) == token) { EnsureWritablePages(pEntry); // This string hasn't been fixed up. Synchronize the update with the normal // fixup logic { CrstHolder ch(this->GetFixupCrst()); if (!CORCOMPILE_IS_POINTER_TAGGED(*pEntry)) { // We lost the race, just return current entry } else { *pEntry = (SIZE_T) ResolveStringRef(token, pDomain, false); } } return (OBJECTHANDLE) *pEntry; } } else { OBJECTREF* pRef = (OBJECTREF*) entry; _ASSERTE((*pRef)->GetMethodTable() == g_pStringClass); STRINGREF stringRef = (STRINGREF) *pRef; // Is this the string we are trying to resolve? if (pStrData->GetCharCount() == stringRef->GetStringLength() && memcmp((void*)pStrData->GetStringBuffer(), (void*) stringRef->GetBuffer(), pStrData->GetCharCount()*sizeof(WCHAR)) == 0) { // We found it, so we just have to return this instance return (OBJECTHANDLE) entry; } } } return NULL; } #endif // FEATURE_PREJIT OBJECTHANDLE Module::ResolveStringRef(DWORD token, BaseDomain *pDomain, bool bNeedToSyncWithFixups) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(TypeFromToken(token) == mdtString); } CONTRACTL_END; EEStringData strData; OBJECTHANDLE string = NULL; #if !BIGENDIAN InitializeStringData(token, &strData, NULL); #else // !!BIGENDIAN CQuickBytes qb; InitializeStringData(token, &strData, &qb); #endif // !!BIGENDIAN GCX_COOP(); // We can only do this for native images as they guarantee that resolvestringref will be // called only once per string from this module. @TODO: We really dont have any way of asserting // this, which would be nice... (and is needed to guarantee correctness) #ifdef FEATURE_PREJIT if (HasNativeImage() && IsNoStringInterning()) { if (bNeedToSyncWithFixups) { // In an ngen image, it is possible that we get here but not be coming from a fixup, // (FixupNativeEntry case). In that unfortunate case (ngen partial images, dynamic methods, // lazy string inits) we will have to troll through the fixup list, and in the case the string is there, // reuse it, if it's there but hasn't been fixed up, fix it up now, and in the case it isn't // there at all, then go to our old style string interning. Going through this code path is // guaranteed to be slow. If necessary, we can further optimize it by sorting the token table, // Another way of solving this would be having a token to string table (would require knowing // all our posible stings in the ngen case (this is possible by looking at the IL)) PEImageLayout * pNativeImage = GetNativeImage(); COUNT_T nSections; PTR_CORCOMPILE_IMPORT_SECTION pSections = pNativeImage->GetNativeImportSections(&nSections); for (COUNT_T iSection = 0; iSection < nSections; iSection++) { PTR_CORCOMPILE_IMPORT_SECTION pSection = pSections + iSection; if (pSection->Type != CORCOMPILE_IMPORT_TYPE_STRING_HANDLE) continue; OBJECTHANDLE oh = ResolveStringRefHelper(token, pDomain, pSection, &strData); if (oh != NULL) return oh; } // The string is not in our fixup list, so just intern it old style (using hashtable) goto INTERN_OLD_STYLE; } /* Unfortunately, this assert won't work in some cases of generics, consider the following scenario: 1) Generic type in mscorlib. 2) Instantiation of generic (1) (via valuetype) in another module 3) other module now holds a copy of the code of the generic for that particular instantiation however, it is resolving the string literals against mscorlib, which breaks the invariant this assert was based on (no string fixups against other modules). In fact, with NoStringInterning, our behavior is not very intuitive. */ /* _ASSERTE(pDomain == GetAssembly()->GetDomain() && "If your are doing ldstr for a string" "in another module, either the JIT is very smart or you have a bug, check INLINE_NO_CALLEE_LDSTR"); */ /* Dev10 804385 bugfix - We should be using appdomain that the string token lives in (GetAssembly->GetDomain()) to allocate the System.String object instead of the appdomain that first uses the ldstr <token> (pDomain). Otherwise, it is possible to get into the situation that pDomain is unloaded but GetAssembly->GetDomain() is still kicking around. Anything else that is still using that string will now be pointing to an object that will be freed when the next GC happens. */ pDomain = GetAssembly()->GetDomain(); // The caller is going to update an ngen fixup entry. The fixup entry // is used to reference the string and to ensure that the string is // allocated only once. Hence, this operation needs to be done under a lock. _ASSERTE(GetFixupCrst()->OwnedByCurrentThread()); // Allocate handle OBJECTREF* pRef = pDomain->AllocateObjRefPtrsInLargeTable(1); STRINGREF str = AllocateStringObject(&strData); SetObjectReference(pRef, str, NULL); #ifdef LOGGING int length = strData.GetCharCount(); length = min(length, 100); WCHAR *szString = (WCHAR *)_alloca((length + 1) * sizeof(WCHAR)); memcpyNoGCRefs((void*)szString, (void*)strData.GetStringBuffer(), length * sizeof(WCHAR)); szString[length] = '\0'; LOG((LF_APPDOMAIN, LL_INFO10000, "String literal \"%S\" won't be interned due to NoInterningAttribute\n", szString)); #endif // LOGGING return (OBJECTHANDLE) pRef; } INTERN_OLD_STYLE: #endif // Retrieve the string from the either the appropriate LoaderAllocator LoaderAllocator *pLoaderAllocator; if (this->IsCollectible()) pLoaderAllocator = this->GetLoaderAllocator(); else pLoaderAllocator = pDomain->GetLoaderAllocator(); string = (OBJECTHANDLE)pLoaderAllocator->GetStringObjRefPtrFromUnicodeString(&strData); return string; } #endif // CROSSGEN_COMPILE // // Used by the verifier. Returns whether this stringref is valid. // CHECK Module::CheckStringRef(DWORD token) { LIMITED_METHOD_CONTRACT; CHECK(TypeFromToken(token)==mdtString); CHECK(!IsNilToken(token)); CHECK(GetMDImport()->IsValidToken(token)); CHECK_OK; } mdToken Module::GetEntryPointToken() { WRAPPER_NO_CONTRACT; return m_file->GetEntryPointToken(); } BYTE *Module::GetProfilerBase() { CONTRACT(BYTE*) { NOTHROW; GC_NOTRIGGER; CANNOT_TAKE_LOCK; } CONTRACT_END; if (m_file == NULL) // I'd rather assert this is not the case... { RETURN NULL; } else if (HasNativeImage()) { RETURN (BYTE*)(GetNativeImage()->GetBase()); } else if (m_file->IsLoaded()) { RETURN (BYTE*)(m_file->GetLoadedIL()->GetBase()); } else { RETURN NULL; } } void Module::AddActiveDependency(Module *pModule, BOOL unconditional) { CONTRACT_VOID { THROWS; GC_TRIGGERS; PRECONDITION(CheckPointer(pModule)); PRECONDITION(pModule != this); PRECONDITION(!IsSystem()); PRECONDITION(!GetAssembly()->IsDomainNeutral() || pModule->GetAssembly()->IsDomainNeutral() || GetAppDomain()->IsDefaultDomain()); POSTCONDITION(IsSingleAppDomain() || HasActiveDependency(pModule)); POSTCONDITION(IsSingleAppDomain() || !unconditional || HasUnconditionalActiveDependency(pModule)); // Postcondition about activation } CONTRACT_END; // Activation tracking is not require in single domain mode. Activate the target immediately. if (IsSingleAppDomain()) { pModule->EnsureActive(); RETURN; } // In the default AppDomain we delay a closure walk until a sharing attempt has been made // This might result in a situation where a domain neutral assembly from the default AppDomain // depends on something resolved by assembly resolve event (even Ref.Emit assemblies) // Since we won't actually share such assemblies, and the default AD itself cannot go away we // do not need to assert for such assemblies, thus " || GetAppDomain()->IsDefaultDomain()" CONSISTENCY_CHECK_MSG(!GetAssembly()->IsDomainNeutral() || pModule->GetAssembly()->IsDomainNeutral() || GetAppDomain()->IsDefaultDomain(), "Active dependency from domain neutral to domain bound is illegal"); // We must track this dependency for multiple domains' use STRESS_LOG2(LF_CLASSLOADER, LL_INFO100000," %p -> %p\n",this,pModule); _ASSERTE(!unconditional || pModule->HasNativeImage()); _ASSERTE(!unconditional || HasNativeImage()); COUNT_T index; // this function can run in parallel with DomainFile::Activate and sychronizes via GetNumberOfActivations() // because we expose dependency only in the end Domain::Activate might miss it, but it will increment a counter module // so we can realize we have to additionally propagate a dependency into that appdomain. // currently we do it just by rescanning al appdomains. // needless to say, updating the counter and checking counter+adding dependency to the list should be atomic BOOL propagate = FALSE; ULONG startCounter=0; ULONG endCounter=0; do { // First, add the dependency to the physical dependency list { #ifdef _DEBUG CHECK check; if (unconditional) check=DomainFile::CheckUnactivatedInAllDomains(this); #endif // _DEBUG CrstHolder lock(&m_Crst); startCounter=GetNumberOfActivations(); index = m_activeDependencies.FindElement(0, pModule); if (index == (COUNT_T) ArrayList::NOT_FOUND) { propagate = TRUE; STRESS_LOG3(LF_CLASSLOADER, LL_INFO100,"Adding new module dependency %p -> %p, unconditional=%i\n",this,pModule,unconditional); } if (unconditional) { if (propagate) { CONSISTENCY_CHECK_MSG(check, "Unconditional dependency cannot be added after module has already been activated"); index = m_activeDependencies.GetCount(); m_activeDependencies.Append(pModule); m_unconditionalDependencies.SetBit(index); STRESS_LOG2(LF_CLASSLOADER, LL_INFO100," Unconditional module dependency propagated %p -> %p\n",this,pModule); // Now other threads can skip this dependency without propagating. } RETURN; } } // Now we have to propagate any module activations in the loader if (propagate) { _ASSERTE(!unconditional); DomainFile::PropagateNewActivation(this, pModule); CrstHolder lock(&m_Crst); STRESS_LOG2(LF_CLASSLOADER, LL_INFO100," Conditional module dependency propagated %p -> %p\n",this,pModule); // Now other threads can skip this dependency without propagating. endCounter=GetNumberOfActivations(); if(startCounter==endCounter) m_activeDependencies.Append(pModule); } }while(propagate && startCounter!=endCounter); //need to retry if someone was activated in parallel RETURN; } BOOL Module::HasActiveDependency(Module *pModule) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(CheckPointer(pModule)); } CONTRACTL_END; if (pModule == this) return TRUE; DependencyIterator i = IterateActiveDependencies(); while (i.Next()) { if (i.GetDependency() == pModule) return TRUE; } return FALSE; } BOOL Module::HasUnconditionalActiveDependency(Module *pModule) { CONTRACTL { NOTHROW; CAN_TAKE_LOCK; MODE_ANY; PRECONDITION(CheckPointer(pModule)); } CONTRACTL_END; if (pModule == this) return TRUE; DependencyIterator i = IterateActiveDependencies(); while (i.Next()) { if (i.GetDependency() == pModule && i.IsUnconditional()) return TRUE; } return FALSE; } void Module::EnableModuleFailureTriggers(Module *pModuleTo, AppDomain *pDomain) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; // At this point we need to enable failure triggers we have placed in the code for this module. However, // the failure trigger codegen logic is NYI. To keep correctness, we just allow the exception to propagate // here. Note that in general this will enforce the failure invariants, but will also result in some rude // behavior as these failures will be propagated too widely rather than constrained to the appropriate // assemblies/app domains. // // This should throw. STRESS_LOG2(LF_CLASSLOADER, LL_INFO100,"EnableModuleFailureTriggers for module %p in AppDomain %i\n",pModuleTo,pDomain->GetId().m_dwId); DomainFile *pDomainFileTo = pModuleTo->GetDomainFile(pDomain); pDomainFileTo->EnsureActive(); // @NYI: shouldn't get here yet since we propagate failures UNREACHABLE_MSG("Module failure triggers NYI"); } #endif //!DACCESS_COMPILE // // an GetAssemblyIfLoadedAppDomainIterator is used to iterate over all domains that // are known to be walkable at the time GetAssemblyIfLoaded is executed. // // The iteration is guaranteed to include all domains that exist at the // start & end of the iteration that are safely accessible. This class is logically part // of GetAssemblyIfLoaded and logically has the same set of contracts. // class GetAssemblyIfLoadedAppDomainIterator { enum IteratorType { StackwalkingThreadIterator, AllAppDomainWalkingIterator, CurrentAppDomainIterator } m_iterType; public: GetAssemblyIfLoadedAppDomainIterator() : m_adIteratorAll(TRUE), m_appDomainCurrent(NULL), m_pFrame(NULL), m_fNextCalledForCurrentADIterator(FALSE) { LIMITED_METHOD_CONTRACT; #ifndef DACCESS_COMPILE if (IsStackWalkerThread()) { Thread * pThread = (Thread *)ClrFlsGetValue(TlsIdx_StackWalkerWalkingThread); m_iterType = StackwalkingThreadIterator; m_pFrame = pThread->GetFrame(); m_appDomainCurrent = pThread->GetDomain(); } else if (IsGCThread()) { m_iterType = AllAppDomainWalkingIterator; m_adIteratorAll.Init(); } else { _ASSERTE(::GetAppDomain() != NULL); m_appDomainCurrent = ::GetAppDomain(); m_iterType = CurrentAppDomainIterator; } #else //!DACCESS_COMPILE // We have to walk all AppDomains in debugger m_iterType = AllAppDomainWalkingIterator; m_adIteratorAll.Init(); #endif //!DACCESS_COMPILE } BOOL Next() { WRAPPER_NO_CONTRACT; switch (m_iterType) { #ifndef DACCESS_COMPILE case StackwalkingThreadIterator: if (!m_fNextCalledForCurrentADIterator) { m_fNextCalledForCurrentADIterator = TRUE; // Try searching frame chain if the current domain is NULL if (m_appDomainCurrent == NULL) return Next(); return TRUE; } else { while (m_pFrame != FRAME_TOP) { AppDomain * pDomain = m_pFrame->GetReturnDomain(); if ((pDomain != NULL) && (pDomain != m_appDomainCurrent)) { m_appDomainCurrent = pDomain; return TRUE; } m_pFrame = m_pFrame->PtrNextFrame(); } return FALSE; } #endif //!DACCESS_COMPILE case AllAppDomainWalkingIterator: { BOOL fSuccess = m_adIteratorAll.Next(); if (fSuccess) m_appDomainCurrent = m_adIteratorAll.GetDomain(); return fSuccess; } #ifndef DACCESS_COMPILE case CurrentAppDomainIterator: { BOOL retVal; retVal = !m_fNextCalledForCurrentADIterator; m_fNextCalledForCurrentADIterator = TRUE; return retVal; } #endif //!DACCESS_COMPILE default: _ASSERTE(FALSE); return FALSE; } } AppDomain * GetDomain() { LIMITED_METHOD_CONTRACT; return m_appDomainCurrent; } BOOL UsingCurrentAD() { LIMITED_METHOD_CONTRACT; return m_iterType == CurrentAppDomainIterator; } private: UnsafeAppDomainIterator m_adIteratorAll; AppDomain * m_appDomainCurrent; Frame * m_pFrame; BOOL m_fNextCalledForCurrentADIterator; }; // class GetAssemblyIfLoadedAppDomainIterator #if !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) // This function, given an AssemblyRef into the ngen generated native metadata section, will find the assembly referenced if // 1. The Assembly is defined with a different name than the AssemblyRef provides // 2. The Assembly has reached the stage of being loaded. // This function is used as a helper function to assist GetAssemblyIfLoaded with its tasks in the conditions // where GetAssemblyIfLoaded must succeed (or we violate various invariants in the system required for // correct implementation of GC, Stackwalking, and generic type loading. Assembly * Module::GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(mdAssemblyRef kAssemblyRef, BOOL *pfDiscoveredAssemblyRefMatchesTargetDefExactly) { CONTRACT(Assembly *) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; FORBID_FAULT; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; _ASSERTE(HasNativeImage()); Assembly *pAssembly = NULL; IMDInternalImport *pImportFoundNativeImage = this->GetNativeAssemblyImport(FALSE); if (!pImportFoundNativeImage) { RETURN NULL; } if (kAssemblyRef != mdAssemblyRefNil) { // Scan CORCOMPILE_DEPENDENCIES tables PEImageLayout* pNativeLayout = this->GetNativeImage(); COUNT_T dependencyCount; CORCOMPILE_DEPENDENCY *pDependencies = pNativeLayout->GetNativeDependencies(&dependencyCount); // Find the assemblyDef that defines the exact target mdAssemblyRef foundAssemblyDef = mdAssemblyRefNil; for (COUNT_T i = 0; i < dependencyCount; ++i) { CORCOMPILE_DEPENDENCY* pDependency = &(pDependencies[i]); if (pDependency->dwAssemblyRef == kAssemblyRef) { foundAssemblyDef = pDependency->dwAssemblyDef; break; } } // In this case we know there is no assembly redirection involved. Skip any additional work. if (kAssemblyRef == foundAssemblyDef) { *pfDiscoveredAssemblyRefMatchesTargetDefExactly = true; RETURN NULL; } if (foundAssemblyDef != mdAssemblyRefNil) { // Find out if THIS reference is satisfied // Specify fDoNotUtilizeExtraChecks to prevent recursion Assembly *pAssemblyCandidate = this->GetAssemblyIfLoaded(foundAssemblyDef, NULL, NULL, pImportFoundNativeImage, TRUE /*fDoNotUtilizeExtraChecks*/); // This extended check is designed only to find assemblies loaded via an AssemblySpecBindingCache based binder. Verify that's what we found. if(pAssemblyCandidate != NULL) { if (!pAssemblyCandidate->GetManifestFile()->HasHostAssembly()) { pAssembly = pAssemblyCandidate; } else { DWORD binderFlags = 0; ICLRPrivAssembly * pPrivBinder = pAssemblyCandidate->GetManifestFile()->GetHostAssembly(); HRESULT hrBinderFlagCheck = pPrivBinder->GetBinderFlags(&binderFlags); if (SUCCEEDED(hrBinderFlagCheck) && (binderFlags & BINDER_FINDASSEMBLYBYSPEC_REQUIRES_EXACT_MATCH)) { pAssembly = pAssemblyCandidate; } else { // This should only happen in the generic instantiation case when multiple threads are racing and // the assembly found is one which we will determine is the wrong assembly. // // We can't assert that (as its possible under stress); however it shouldn't happen in the stack walk or GC case, so we assert in those cases. _ASSERTE("Non-AssemblySpecBindingCache based assembly found with extended search" && !(IsStackWalkerThread() || IsGCThread()) && IsGenericInstantiationLookupCompareThread()); } } } } } RETURN pAssembly; } #endif // !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) // Fills ppContainingWinRtAppDomain only if WinRT type name is passed and if the assembly is found (return value != NULL). Assembly * Module::GetAssemblyIfLoaded( mdAssemblyRef kAssemblyRef, LPCSTR szWinRtNamespace, // = NULL LPCSTR szWinRtClassName, // = NULL IMDInternalImport * pMDImportOverride, // = NULL BOOL fDoNotUtilizeExtraChecks, // = FALSE ICLRPrivBinder *pBindingContextForLoadedAssembly // = NULL ) { CONTRACT(Assembly *) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; FORBID_FAULT; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); SUPPORTS_DAC; } CONTRACT_END; Assembly * pAssembly = NULL; BOOL fCanUseRidMap = ((pMDImportOverride == NULL) && (szWinRtNamespace == NULL)); #ifdef _DEBUG fCanUseRidMap = fCanUseRidMap && (CLRConfig::GetConfigValue(CLRConfig::INTERNAL_GetAssemblyIfLoadedIgnoreRidMap) == 0); #endif // If we're here due to a generic instantiation, then we should only be querying information from the ngen image we're finding the generic instantiation in. #if !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) _ASSERTE(!IsGenericInstantiationLookupCompareThread() || HasNativeImage()); #endif // Don't do a lookup if an override IMDInternalImport is provided, since the lookup is for the // standard IMDInternalImport and might result in an incorrect result. // WinRT references also do not update RID map, so don't try to look it up if (fCanUseRidMap) { pAssembly = LookupAssemblyRef(kAssemblyRef); } #ifndef DACCESS_COMPILE // Check if actually loaded, unless a GC is in progress or the current thread is // walking the stack (either its own stack, or another thread's stack) as that works // only with loaded assemblies // // NOTE: The case where the current thread is walking a stack can be problematic for // other reasons, as the remaining code of this function uses "GetAppDomain()", when // in fact the right AppDomain to use is the one corresponding to the frame being // traversed on the walked thread. Dev10 TFS bug# 762348 tracks that issue. if ((pAssembly != NULL) && !IsGCThread() && !IsStackWalkerThread()) { _ASSERTE(::GetAppDomain() != NULL); DomainAssembly * pDomainAssembly = pAssembly->FindDomainAssembly(::GetAppDomain()); if ((pDomainAssembly == NULL) || !pDomainAssembly->IsLoaded()) pAssembly = NULL; } #endif //!DACCESS_COMPILE if (pAssembly == NULL) { // If in stackwalking or gc mode // For each AppDomain that is on the stack being walked... // For each AppDomain in the process... if gc'ing // For the current AppDomain ... if none of the above GetAssemblyIfLoadedAppDomainIterator appDomainIter; while (appDomainIter.Next()) { AppDomain * pAppDomainExamine = appDomainIter.GetDomain(); DomainAssembly * pCurAssemblyInExamineDomain = GetAssembly()->FindDomainAssembly(pAppDomainExamine); if (pCurAssemblyInExamineDomain == NULL) { continue; } #ifdef FEATURE_COMINTEROP if (szWinRtNamespace != NULL) { _ASSERTE(szWinRtClassName != NULL); CLRPrivBinderWinRT * pWinRtBinder = pAppDomainExamine->GetWinRtBinder(); if (pWinRtBinder == nullptr) { // We are most likely in AppX mode (calling AppX::IsAppXProcess() for verification is painful in DACCESS) #ifndef DACCESS_COMPILE // Note: We should also look // Check designer binding context present (only in AppXDesignMode) ICLRPrivBinder * pCurrentBinder = pAppDomainExamine->GetLoadContextHostBinder(); if (pCurrentBinder != nullptr) { // We have designer binding context, look for the type in it ReleaseHolder<ICLRPrivWinRtTypeBinder> pCurrentWinRtTypeBinder; HRESULT hr = pCurrentBinder->QueryInterface(__uuidof(ICLRPrivWinRtTypeBinder), (void **)&pCurrentWinRtTypeBinder); // The binder should be an instance of code:CLRPrivBinderAppX class that implements the interface _ASSERTE(SUCCEEDED(hr) && (pCurrentWinRtTypeBinder != nullptr)); if (SUCCEEDED(hr)) { ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); pAssembly = (Assembly *)pCurrentWinRtTypeBinder->FindAssemblyForWinRtTypeIfLoaded( (void *)pAppDomainExamine, szWinRtNamespace, szWinRtClassName); } } #endif //!DACCESS_COMPILE if (pAssembly == nullptr) { } } if (pWinRtBinder != nullptr) { ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); pAssembly = pWinRtBinder->FindAssemblyForTypeIfLoaded( dac_cast<PTR_AppDomain>(pAppDomainExamine), szWinRtNamespace, szWinRtClassName); } // Never store WinMD AssemblyRefs into the rid map. if (pAssembly != NULL) { break; } // Never attemt to search the assembly spec binding cache for this form of WinRT assembly reference. continue; } #endif // FEATURE_COMINTEROP #ifndef DACCESS_COMPILE { IMDInternalImport * pMDImport = (pMDImportOverride == NULL) ? (GetMDImport()) : (pMDImportOverride); //we have to be very careful here. //we are using InitializeSpecInternal so we need to make sure that under no condition //the data we pass to it can outlive the assembly spec. AssemblySpec spec; if (FAILED(spec.InitializeSpecInternal(kAssemblyRef, pMDImport, pCurAssemblyInExamineDomain, FALSE /*fAllowAllocation*/))) { continue; } // If we have been passed the binding context for the loaded assembly that is being looked up in the // cache, then set it up in the AssemblySpec for the cache lookup to use it below. if (pBindingContextForLoadedAssembly != NULL) { _ASSERTE(spec.GetBindingContext() == NULL); spec.SetBindingContext(pBindingContextForLoadedAssembly); } DomainAssembly * pDomainAssembly = nullptr; { pDomainAssembly = pAppDomainExamine->FindCachedAssembly(&spec, FALSE /*fThrow*/); } if (pDomainAssembly && pDomainAssembly->IsLoaded()) pAssembly = pDomainAssembly->GetCurrentAssembly(); // <NOTE> Do not use GetAssembly - that may force the completion of a load // Only store in the rid map if working with the current AppDomain. if (fCanUseRidMap && pAssembly && appDomainIter.UsingCurrentAD()) StoreAssemblyRef(kAssemblyRef, pAssembly); if (pAssembly != NULL) break; } #endif //!DACCESS_COMPILE } } #if !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) if (pAssembly == NULL && (IsStackWalkerThread() || IsGCThread() || IsGenericInstantiationLookupCompareThread()) && !fDoNotUtilizeExtraChecks) { // The GetAssemblyIfLoaded function must succeed in finding assemblies which have already been loaded in a series of interesting cases // (GC, Stackwalking, GenericInstantiationLookup). This logic is used to handle cases where the normal lookup done above // may fail, and more extensive (and slow) lookups are necessary. This logic is gated by a long series of checks to ensure it doesn't // run in cases which are not known to be problematic, or would not benefit from the logic here. // // This is logic which tries extra possibilities to find an assembly. It is believed this logic can only be hit in cases where an ngen // image depends on an assembly through some sort of binding version/public key token adjustment (due to binding policy, unification, or portability rules) // and the assembly depended on was loaded through a binder that utilizes the AssemblySpecBindingCache for binder caching. (The cache's in the other // binder's successfully answer the GetAssemblyIfLoaded question in the case of non-exact matches where the match was discovered during // ngen resolution.) // This restricts the scenario to a somewhat restricted case. BOOL eligibleForAdditionalChecks = TRUE; if (szWinRtNamespace != NULL) eligibleForAdditionalChecks = FALSE; // WinRT binds do not support this scan else if (this->GetAssembly()->GetManifestFile()->IsDesignerBindingContext()) { eligibleForAdditionalChecks = FALSE; // assemblies loaded into leaf designer binding contexts cannot be ngen images, or be depended on by ngen assemblies that bind to different versions of assemblies. // However, in the shared designer binding context assemblies can be loaded with ngen images, and therefore can depend on assemblies in a designer binding context. (the shared context) // A more correct version of this check would probably allow assemblies loaded into the shared designer binding context to be eligibleForAdditionalChecks; however // there are problems. In particular, the logic below which scans through all native images is not strictly correct for scenarios involving a shared assembly context // as the shared assembly context may have different binding rules as compared to the root context. At this time, we prefer to not fix this scenario until // there is customer need for a fix. } AssemblySpec specSearchAssemblyRef; // Get the assembly ref information that we are attempting to satisfy. if (eligibleForAdditionalChecks) { IMDInternalImport * pMDImport = (pMDImportOverride == NULL) ? (GetMDImport()) : (pMDImportOverride); if (FAILED(specSearchAssemblyRef.InitializeSpecInternal(kAssemblyRef, pMDImport, NULL, FALSE /*fAllowAllocation*/))) { eligibleForAdditionalChecks = FALSE; // If an assemblySpec can't be constructed then we're not going to succeed // This should not ever happen, due to the above checks, but this logic // is intended to be defensive against unexpected behavior. } else if (specSearchAssemblyRef.IsContentType_WindowsRuntime()) { eligibleForAdditionalChecks = FALSE; // WinRT binds do not support this scan } } if (eligibleForAdditionalChecks) { BOOL abortAdditionalChecks = false; // When working with an ngenn'd assembly, as an optimization we can scan only that module for dependency info. bool onlyScanCurrentModule = HasNativeImage() && GetFile()->IsAssembly(); mdAssemblyRef foundAssemblyRef = mdAssemblyRefNil; GetAssemblyIfLoadedAppDomainIterator appDomainIter; // In each AppDomain that might be interesting, scan for an ngen image that is loaded that has a dependency on the same // assembly that is now being looked up. If that ngen image has the same dependency, then we can use the CORCOMPILE_DEPENDENCIES // table to find the exact AssemblyDef that defines the assembly, and attempt a load based on that information. // As this logic is expected to be used only in exceedingly rare situations, this code has not been tuned for performance // in any way. while (!abortAdditionalChecks && appDomainIter.Next()) { AppDomain * pAppDomainExamine = appDomainIter.GetDomain(); DomainAssembly * pCurAssemblyInExamineDomain = GetAssembly()->FindDomainAssembly(pAppDomainExamine); if (pCurAssemblyInExamineDomain == NULL) { continue; } DomainFile *pDomainFileNativeImage; if (onlyScanCurrentModule) { pDomainFileNativeImage = pCurAssemblyInExamineDomain; // Do not reset foundAssemblyRef. // This will allow us to avoid scanning for foundAssemblyRef in each domain we iterate through } else { foundAssemblyRef = mdAssemblyRefNil; pDomainFileNativeImage = pAppDomainExamine->GetDomainFilesWithNativeImagesList(); } while (!abortAdditionalChecks && (pDomainFileNativeImage != NULL) && (pAssembly == NULL)) { Module *pNativeImageModule = pDomainFileNativeImage->GetCurrentModule(); _ASSERTE(pNativeImageModule->HasNativeImage()); IMDInternalImport *pImportFoundNativeImage = pNativeImageModule->GetNativeAssemblyImport(FALSE); if (pImportFoundNativeImage != NULL) { if (IsNilToken(foundAssemblyRef)) { // Enumerate assembly refs in nmd space, and compare against held ref. HENUMInternalHolder hAssemblyRefEnum(pImportFoundNativeImage); if (FAILED(hAssemblyRefEnum.EnumInitNoThrow(mdtAssemblyRef, mdAssemblyRefNil))) { continue; } mdAssemblyRef assemblyRef = mdAssemblyRefNil; // Find if the native image has a matching assembly ref in its compile dependencies. while (pImportFoundNativeImage->EnumNext(&hAssemblyRefEnum, &assemblyRef) && (pAssembly == NULL)) { AssemblySpec specFoundAssemblyRef; if (FAILED(specFoundAssemblyRef.InitializeSpecInternal(assemblyRef, pImportFoundNativeImage, NULL, FALSE /*fAllowAllocation*/))) { continue; // If the spec cannot be loaded, it isn't the one we're looking for } // Check for AssemblyRef equality if (specSearchAssemblyRef.CompareEx(&specFoundAssemblyRef)) { foundAssemblyRef = assemblyRef; break; } } } pAssembly = pNativeImageModule->GetAssemblyIfLoadedFromNativeAssemblyRefWithRefDefMismatch(foundAssemblyRef, &abortAdditionalChecks); if (fCanUseRidMap && pAssembly && appDomainIter.UsingCurrentAD()) StoreAssemblyRef(kAssemblyRef, pAssembly); } // If we're only scanning one module for accurate dependency information, break the loop here. if (onlyScanCurrentModule) break; pDomainFileNativeImage = pDomainFileNativeImage->FindNextDomainFileWithNativeImage(); } } } } #endif // !defined(DACCESS_COMPILE) && defined(FEATURE_PREJIT) // When walking the stack or computing GC information this function should never fail. _ASSERTE((pAssembly != NULL) || !(IsStackWalkerThread() || IsGCThread())); #ifdef DACCESS_COMPILE // Note: In rare cases when debugger walks the stack, we could actually have pAssembly=NULL here. // To fix that we should DACize the AppDomain-iteration code above (especially AssemblySpec). _ASSERTE(pAssembly != NULL); #endif //DACCESS_COMPILE RETURN pAssembly; } // Module::GetAssemblyIfLoaded DWORD Module::GetAssemblyRefFlags( mdAssemblyRef tkAssemblyRef) { CONTRACTL { if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; _ASSERTE(TypeFromToken(tkAssemblyRef) == mdtAssemblyRef); LPCSTR pszAssemblyName; const void *pbPublicKeyOrToken; DWORD cbPublicKeyOrToken; DWORD dwAssemblyRefFlags; IfFailThrow(GetMDImport()->GetAssemblyRefProps( tkAssemblyRef, &pbPublicKeyOrToken, &cbPublicKeyOrToken, &pszAssemblyName, NULL, NULL, NULL, &dwAssemblyRefFlags)); return dwAssemblyRefFlags; } // Module::GetAssemblyRefFlags #ifndef DACCESS_COMPILE // Arguments: // szWinRtTypeNamespace ... Namespace of WinRT type. // szWinRtTypeClassName ... Name of WinRT type, NULL for non-WinRT (classic) types. DomainAssembly * Module::LoadAssembly( AppDomain * pDomain, mdAssemblyRef kAssemblyRef, LPCUTF8 szWinRtTypeNamespace, LPCUTF8 szWinRtTypeClassName) { CONTRACT(DomainAssembly *) { INSTANCE_CHECK; if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS; if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM();); } MODE_ANY; PRECONDITION(CheckPointer(pDomain)); POSTCONDITION(CheckPointer(RETVAL, NULL_NOT_OK)); //POSTCONDITION((CheckPointer(GetAssemblyIfLoaded(kAssemblyRef, szWinRtTypeNamespace, szWinRtTypeClassName)), NULL_NOT_OK)); } CONTRACT_END; ETWOnStartup (LoaderCatchCall_V1, LoaderCatchCallEnd_V1); DomainAssembly * pDomainAssembly; // // Early out quickly if the result is cached // Assembly * pAssembly = LookupAssemblyRef(kAssemblyRef); if (pAssembly != NULL) { _ASSERTE(HasBindableIdentity(kAssemblyRef)); pDomainAssembly = pAssembly->FindDomainAssembly(pDomain); if (pDomainAssembly == NULL) pDomainAssembly = pAssembly->GetDomainAssembly(pDomain); pDomain->LoadDomainFile(pDomainAssembly, FILE_LOADED); RETURN pDomainAssembly; } bool fHasBindableIdentity = HasBindableIdentity(kAssemblyRef); { PEAssemblyHolder pFile = GetDomainFile(GetAppDomain())->GetFile()->LoadAssembly( kAssemblyRef, NULL, szWinRtTypeNamespace, szWinRtTypeClassName); AssemblySpec spec; spec.InitializeSpec(kAssemblyRef, GetMDImport(), GetDomainFile(GetAppDomain())->GetDomainAssembly()); // Set the binding context in the AssemblySpec if one is available. This can happen if the LoadAssembly ended up // invoking the custom AssemblyLoadContext implementation that returned a reference to an assembly bound to a different // AssemblyLoadContext implementation. ICLRPrivBinder *pBindingContext = pFile->GetBindingContext(); if (pBindingContext != NULL) { spec.SetBindingContext(pBindingContext); } if (szWinRtTypeClassName != NULL) { spec.SetWindowsRuntimeType(szWinRtTypeNamespace, szWinRtTypeClassName); } pDomainAssembly = GetAppDomain()->LoadDomainAssembly(&spec, pFile, FILE_LOADED); } if (pDomainAssembly != NULL) { _ASSERTE( !fHasBindableIdentity || // GetAssemblyIfLoaded will not find non-bindable assemblies pDomainAssembly->IsSystem() || // GetAssemblyIfLoaded will not find mscorlib (see AppDomain::FindCachedFile) !pDomainAssembly->IsLoaded() || // GetAssemblyIfLoaded will not find not-yet-loaded assemblies GetAssemblyIfLoaded(kAssemblyRef, NULL, NULL, NULL, FALSE, pDomainAssembly->GetFile()->GetHostAssembly()) != NULL); // GetAssemblyIfLoaded should find all remaining cases // Note: We cannot cache WinRT AssemblyRef, because it is meaningless without the TypeRef context if (pDomainAssembly->GetCurrentAssembly() != NULL) { if (fHasBindableIdentity) { StoreAssemblyRef(kAssemblyRef, pDomainAssembly->GetCurrentAssembly()); } } } RETURN pDomainAssembly; } #endif // !DACCESS_COMPILE Module *Module::GetModuleIfLoaded(mdFile kFile, BOOL onlyLoadedInAppDomain, BOOL permitResources) { CONTRACT(Module *) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(TypeFromToken(kFile) == mdtFile || TypeFromToken(kFile) == mdtModuleRef); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); FORBID_FAULT; SUPPORTS_DAC; } CONTRACT_END; ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); // Handle the module ref case if (TypeFromToken(kFile) == mdtModuleRef) { LPCSTR moduleName; if (FAILED(GetMDImport()->GetModuleRefProps(kFile, &moduleName))) { RETURN NULL; } // This is required only because of some lower casing on the name kFile = GetAssembly()->GetManifestFileToken(moduleName); if (kFile == mdTokenNil) RETURN NULL; RETURN GetAssembly()->GetManifestModule()->GetModuleIfLoaded(kFile, onlyLoadedInAppDomain, permitResources); } Module *pModule = LookupFile(kFile); if (pModule == NULL) { if (IsManifest()) { if (kFile == mdFileNil) pModule = GetAssembly()->GetManifestModule(); } else { // If we didn't find it there, look at the "master rid map" in the manifest file Assembly *pAssembly = GetAssembly(); mdFile kMatch; // This is required only because of some lower casing on the name kMatch = pAssembly->GetManifestFileToken(GetMDImport(), kFile); if (IsNilToken(kMatch)) { if (kMatch == mdFileNil) { pModule = pAssembly->GetManifestModule(); } else { RETURN NULL; } } else pModule = pAssembly->GetManifestModule()->LookupFile(kMatch); } #ifndef DACCESS_COMPILE if (pModule != NULL) StoreFileNoThrow(kFile, pModule); #endif } // We may not want to return a resource module if (!permitResources && pModule && pModule->IsResource()) pModule = NULL; #ifndef DACCESS_COMPILE #endif // !DACCESS_COMPILE RETURN pModule; } #ifndef DACCESS_COMPILE DomainFile *Module::LoadModule(AppDomain *pDomain, mdFile kFile, BOOL permitResources/*=TRUE*/, BOOL bindOnly/*=FALSE*/) { CONTRACT(DomainFile *) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(TypeFromToken(kFile) == mdtFile || TypeFromToken(kFile) == mdtModuleRef); POSTCONDITION(CheckPointer(RETVAL, !permitResources || bindOnly ? NULL_OK : NULL_NOT_OK)); } CONTRACT_END; if (bindOnly) { RETURN NULL; } else { LPCSTR psModuleName=NULL; if (TypeFromToken(kFile) == mdtModuleRef) { // This is a moduleRef IfFailThrow(GetMDImport()->GetModuleRefProps(kFile, &psModuleName)); } else { // This is mdtFile IfFailThrow(GetAssembly()->GetManifestImport()->GetFileProps(kFile, &psModuleName, NULL, NULL, NULL)); } SString name(SString::Utf8, psModuleName); EEFileLoadException::Throw(name, COR_E_MULTIMODULEASSEMBLIESDIALLOWED, NULL); } } #endif // !DACCESS_COMPILE PTR_Module Module::LookupModule(mdToken kFile,BOOL permitResources/*=TRUE*/) { CONTRACT(PTR_Module) { INSTANCE_CHECK; if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS; if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); } MODE_ANY; PRECONDITION(TypeFromToken(kFile) == mdtFile || TypeFromToken(kFile) == mdtModuleRef); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); SUPPORTS_DAC; } CONTRACT_END; if (TypeFromToken(kFile) == mdtModuleRef) { LPCSTR moduleName; IfFailThrow(GetMDImport()->GetModuleRefProps(kFile, &moduleName)); mdFile kFileLocal = GetAssembly()->GetManifestFileToken(moduleName); if (kFileLocal == mdTokenNil) COMPlusThrowHR(COR_E_BADIMAGEFORMAT); RETURN GetAssembly()->GetManifestModule()->LookupModule(kFileLocal, permitResources); } PTR_Module pModule = LookupFile(kFile); if (pModule == NULL && !IsManifest()) { // If we didn't find it there, look at the "master rid map" in the manifest file Assembly *pAssembly = GetAssembly(); mdFile kMatch = pAssembly->GetManifestFileToken(GetMDImport(), kFile); if (IsNilToken(kMatch)) { if (kMatch == mdFileNil) pModule = pAssembly->GetManifestModule(); else COMPlusThrowHR(COR_E_BADIMAGEFORMAT); } else pModule = pAssembly->GetManifestModule()->LookupFile(kMatch); } RETURN pModule; } TypeHandle Module::LookupTypeRef(mdTypeRef token) { STATIC_CONTRACT_NOTHROW; STATIC_CONTRACT_GC_NOTRIGGER; STATIC_CONTRACT_FORBID_FAULT; SUPPORTS_DAC; _ASSERTE(TypeFromToken(token) == mdtTypeRef); g_IBCLogger.LogRidMapAccess( MakePair( this, token ) ); TypeHandle entry = TypeHandle::FromTAddr(dac_cast<TADDR>(m_TypeRefToMethodTableMap.GetElement(RidFromToken(token)))); if (entry.IsNull()) return TypeHandle(); // Cannot do this in a NOTHROW function. // Note that this could be called while doing GC from the prestub of // a method to resolve typerefs in a signature. We cannot THROW // during GC. // @PERF: Enable this so that we do not need to touch metadata // to resolve typerefs #ifdef FIXUPS_ALL_TYPEREFS if (CORCOMPILE_IS_POINTER_TAGGED((SIZE_T) entry.AsPtr())) { #ifndef DACCESS_COMPILE Module::RestoreTypeHandlePointer(&entry, TRUE); m_TypeRefToMethodTableMap.SetElement(RidFromToken(token), dac_cast<PTR_TypeRef>(value.AsTAddr())); #else // DACCESS_COMPILE DacNotImpl(); #endif // DACCESS_COMPILE } #endif // FIXUPS_ALL_TYPEREFS return entry; } #ifdef FEATURE_NATIVE_IMAGE_GENERATION mdTypeRef Module::LookupTypeRefByMethodTable(MethodTable *pMT) { STANDARD_VM_CONTRACT; HENUMInternalHolder hEnumTypeRefs(GetMDImport()); mdTypeRef token; hEnumTypeRefs.EnumAllInit(mdtTypeRef); while (hEnumTypeRefs.EnumNext(&token)) { TypeHandle thRef = LookupTypeRef(token); if (thRef.IsNull() || thRef.IsTypeDesc()) { continue; } MethodTable *pMTRef = thRef.AsMethodTable(); if (pMT->HasSameTypeDefAs(pMTRef)) { _ASSERTE(pMTRef->IsTypicalTypeDefinition()); return token; } } #ifdef FEATURE_READYTORUN_COMPILER if (IsReadyToRunCompilation()) { if (pMT->GetClass()->IsEquivalentType()) { GetSvcLogger()->Log(W("ReadyToRun: Type reference to equivalent type cannot be encoded\n")); ThrowHR(E_NOTIMPL); } // FUTURE: Encoding of new cross-module references for ReadyToRun // This warning is hit for recursive cross-module inlining. It is commented out to avoid noise. // GetSvcLogger()->Log(W("ReadyToRun: Type reference outside of current version bubble cannot be encoded\n")); } else #endif // FEATURE_READYTORUN_COMPILER { // FUTURE TODO: Version resilience _ASSERTE(!"Cross module type reference not found"); } ThrowHR(E_FAIL); } mdMemberRef Module::LookupMemberRefByMethodDesc(MethodDesc *pMD) { STANDARD_VM_CONTRACT; HENUMInternalHolder hEnumMemberRefs(GetMDImport()); mdMemberRef token; hEnumMemberRefs.EnumAllInit(mdtMemberRef); while (hEnumMemberRefs.EnumNext(&token)) { BOOL fIsMethod = FALSE; TADDR addr = LookupMemberRef(token, &fIsMethod); if (fIsMethod) { MethodDesc *pCurMD = dac_cast<PTR_MethodDesc>(addr); if (pCurMD == pMD) { return token; } } } // FUTURE TODO: Version resilience _ASSERTE(!"Cross module method reference not found"); ThrowHR(E_FAIL); } #endif // FEATURE_NATIVE_IMAGE_GENERATION #ifndef DACCESS_COMPILE // // Increase the size of one of the maps, such that it can handle a RID of at least "rid". // // This function must also check that another thread didn't already add a LookupMap capable // of containing the same RID. // PTR_TADDR LookupMapBase::GrowMap(Module * pModule, DWORD rid) { CONTRACT(PTR_TADDR) { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(ThrowOutOfMemory();); POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END; LookupMapBase *pMap = this; LookupMapBase *pPrev = NULL; LookupMapBase *pNewMap = NULL; // Initial block size DWORD dwIndex = rid; DWORD dwBlockSize = 16; { CrstHolder ch(pModule->GetLookupTableCrst()); // Check whether we can already handle this RID index do { if (dwIndex < pMap->dwCount) { // Already there - some other thread must have added it RETURN pMap->GetIndexPtr(dwIndex); } dwBlockSize *= 2; dwIndex -= pMap->dwCount; pPrev = pMap; pMap = pMap->pNext; } while (pMap != NULL); _ASSERTE(pPrev != NULL); // should never happen, because there's always at least one map DWORD dwSizeToAllocate = max(dwIndex + 1, dwBlockSize); pNewMap = (LookupMapBase *) (void*)pModule->GetLoaderAllocator()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(LookupMapBase)) + S_SIZE_T(dwSizeToAllocate)*S_SIZE_T(sizeof(TADDR))); // Note: Memory allocated on loader heap is zero filled // memset(pNewMap, 0, sizeof(LookupMap) + dwSizeToAllocate*sizeof(void*)); pNewMap->pNext = NULL; pNewMap->dwCount = dwSizeToAllocate; pNewMap->pTable = dac_cast<ArrayDPTR(TADDR)>(pNewMap + 1); // Link ourselves in VolatileStore<LookupMapBase*>(&(pPrev->pNext), pNewMap); } RETURN pNewMap->GetIndexPtr(dwIndex); } #endif // DACCESS_COMPILE PTR_TADDR LookupMapBase::GetElementPtr(DWORD rid) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; } CONTRACTL_END; LookupMapBase * pMap = this; #ifdef FEATURE_PREJIT if (pMap->dwNumHotItems > 0) { #ifdef _DEBUG_IMPL static DWORD counter = 0; counter++; if (counter >= pMap->dwNumHotItems) { CheckConsistentHotItemList(); counter = 0; } #endif // _DEBUG_IMPL PTR_TADDR pHotItemValue = pMap->FindHotItemValuePtr(rid); if (pHotItemValue) { return pHotItemValue; } } #endif // FEATURE_PREJIT DWORD dwIndex = rid; do { if (dwIndex < pMap->dwCount) { return pMap->GetIndexPtr(dwIndex); } dwIndex -= pMap->dwCount; pMap = pMap->pNext; } while (pMap != NULL); return NULL; } #ifdef FEATURE_PREJIT // This method can only be called on a compressed map (MapIsCompressed() == true). Compressed rid maps store // the array of values as packed deltas (each value is based on the accumulated of all the previous entries). // So this method takes the bit stream of compressed data we're navigating and the value of the last entry // retrieved allowing us to calculate the full value of the next entry. Note that the values passed in and out // here aren't the final values the top-level caller sees. In order to avoid having to touch the compressed // data on image base relocations we actually store a form of RVA (though relative to the map base rather than // the module base). INT32 LookupMapBase::GetNextCompressedEntry(BitStreamReader *pTableStream, INT32 iLastValue) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; PRECONDITION(MapIsCompressed()); } CONTRACTL_END; // The next kLookupMapLengthBits bits in the stream are an index into a per-map table that tells us the // length of the encoded delta. DWORD dwValueLength = rgEncodingLengths[pTableStream->Read(kLookupMapLengthBits)]; // Then follows a single bit that indicates whether the delta should be added (1) or subtracted (0) from // the previous entry value to recover the current entry value. // Once we've read that bit we read the delta (encoded as an unsigned integer using the number of bits // that we read from the encoding lengths table above). if (pTableStream->ReadOneFast()) return iLastValue + (INT32)(pTableStream->Read(dwValueLength)); else return iLastValue - (INT32)(pTableStream->Read(dwValueLength)); } // This method can only be called on a compressed map (MapIsCompressed() == true). Retrieves the final value // (e.g. MethodTable*, MethodDesc* etc. based on map type) given the rid of the entry. TADDR LookupMapBase::GetValueFromCompressedMap(DWORD rid) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; SUPPORTS_DAC; PRECONDITION(MapIsCompressed()); } CONTRACTL_END; // Normally to extract the nth entry in the table we have to linearly parse all (n - 1) preceding entries // (since entries are stored as the delta from the previous entry). Obviously this can yield exceptionally // poor performance for the later entries in large tables. So we also build an index of the compressed // stream. This index has an entry for every kLookupMapIndexStride entries in the compressed table. Each // index entry contains the full RVA (relative to the map) of the corresponding table entry plus the bit // offset in the stream from which to start parsing the next entry's data. // In this fashion we can get to within kLookupMapIndexStride entries of our target entry and then decode // our way to the final target. // Ensure that index does not go beyond end of the saved table if (rid >= dwCount) return 0; // Calculate the nearest entry in the index that is lower than our target index in the full table. DWORD dwIndexEntry = rid / kLookupMapIndexStride; // Then calculate how many additional entries we'll need to decode from the compressed streams to recover // the target entry. DWORD dwSubIndex = rid % kLookupMapIndexStride; // Open a bit stream reader on the index and skip all the entries prior to the one we're interested in. BitStreamReader sIndexStream(pIndex); sIndexStream.Skip(dwIndexEntry * cIndexEntryBits); // The first kBitsPerRVA of the index entry contain the RVA of the corresponding entry in the compressed // table. If this is exactly the entry we want (dwSubIndex == 0) then we can use this RVA to recover the // value the caller wants. Our RVAs are based on the map address rather than the module base (simply // because we don't record the module base in LookupMapBase). A delta of zero encodes a null value, // otherwise we simply add the RVA to the our map address to recover the full pointer. // Note that most LookupMaps are embedded structures (in Module) so we can't directly dac_cast<TADDR> our // "this" pointer for DAC builds. Instead we have to use the slightly slower (in DAC) but more flexible // PTR_HOST_INT_TO_TADDR() which copes with interior host pointers. INT32 iValue = (INT32)sIndexStream.Read(kBitsPerRVA); if (dwSubIndex == 0) return iValue ? PTR_HOST_INT_TO_TADDR(this) + iValue : 0; // Otherwise we must parse one or more entries in the compressed table to accumulate more deltas to the // base RVA we read above. The remaining portion of the index entry has the bit offset into the compressed // table at which to begin parsing. BitStreamReader sTableStream(dac_cast<PTR_CBYTE>(pTable)); sTableStream.Skip(sIndexStream.Read(cIndexEntryBits - kBitsPerRVA)); // Parse all the entries up to our target entry. Each step takes the RVA from the previous cycle (or from // the index entry we read above) and applies the compressed delta of the next table entry to it. for (DWORD i = 0; i < dwSubIndex; i++) iValue = GetNextCompressedEntry(&sTableStream, iValue); // We have the final RVA so recover the actual pointer from it (a zero RVA encodes a NULL pointer). Note // the use of PTR_HOST_INT_TO_TADDR() rather than dac_cast<TADDR>, see previous comment on // PTR_HOST_INT_TO_TADDR for an explanation. return iValue ? PTR_HOST_INT_TO_TADDR(this) + iValue : 0; } PTR_TADDR LookupMapBase::FindHotItemValuePtr(DWORD rid) { LIMITED_METHOD_DAC_CONTRACT; if (dwNumHotItems < 5) { // do simple linear search if there are only a few hot items for (DWORD i = 0; i < dwNumHotItems; i++) { if (hotItemList[i].rid == rid) return dac_cast<PTR_TADDR>( dac_cast<TADDR>(hotItemList) + i * sizeof(HotItem) + offsetof(HotItem, value)); } } else { // otherwise do binary search if (hotItemList[0].rid <= rid && rid <= hotItemList[dwNumHotItems-1].rid) { DWORD l = 0; DWORD r = dwNumHotItems; while (l + 1 < r) { // loop invariant: _ASSERTE(hotItemList[l].rid <= rid && (r >= dwNumHotItems || rid < hotItemList[r].rid)); DWORD m = (l + r)/2; // loop condition implies l < m < r, hence interval shrinks every iteration, hence loop terminates _ASSERTE(l < m && m < r); if (rid < hotItemList[m].rid) r = m; else l = m; } // now we know l + 1 == r && hotItemList[l].rid <= rid < hotItemList[r].rid // loop invariant: _ASSERTE(hotItemList[l].rid <= rid && (r >= dwNumHotItems || rid < hotItemList[r].rid)); if (hotItemList[l].rid == rid) return dac_cast<PTR_TADDR>( dac_cast<TADDR>(hotItemList) + l * sizeof(HotItem) + offsetof(HotItem, value)); } } return NULL; } #ifdef _DEBUG void LookupMapBase::CheckConsistentHotItemList() { LIMITED_METHOD_DAC_CONTRACT; for (DWORD i = 0; i < dwNumHotItems; i++) { DWORD rid = hotItemList[i].rid; PTR_TADDR pHotValue = dac_cast<PTR_TADDR>( dac_cast<TADDR>(hotItemList) + i * sizeof(HotItem) + offsetof(HotItem, value)); TADDR hotValue = RelativePointer<TADDR>::GetValueMaybeNullAtPtr(dac_cast<TADDR>(pHotValue)); TADDR value; if (MapIsCompressed()) { value = GetValueFromCompressedMap(rid); } else { PTR_TADDR pValue = GetIndexPtr(rid); value = RelativePointer<TADDR>::GetValueMaybeNullAtPtr(dac_cast<TADDR>(pValue)); } _ASSERTE(hotValue == value || value == NULL); } } #endif // _DEBUG #endif // FEATURE_PREJIT // Get number of RIDs that this table can store DWORD LookupMapBase::GetSize() { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; LookupMapBase * pMap = this; DWORD dwSize = 0; do { dwSize += pMap->dwCount; pMap = pMap->pNext; } while (pMap != NULL); return dwSize; } #ifndef DACCESS_COMPILE #ifdef _DEBUG void LookupMapBase::DebugGetRidMapOccupancy(DWORD *pdwOccupied, DWORD *pdwSize) { LIMITED_METHOD_CONTRACT; *pdwOccupied = 0; *pdwSize = 0; LookupMapBase * pMap = this; // Go through each linked block for (; pMap != NULL; pMap = pMap->pNext) { DWORD dwIterCount = pMap->dwCount; for (DWORD i = 0; i < dwIterCount; i++) { #ifdef FEATURE_PREJIT if (pMap->MapIsCompressed()) { if (pMap->GetValueFromCompressedMap(i)) (*pdwOccupied)++; } else #endif // FEATURE_PREJIT if (pMap->pTable[i] != NULL) (*pdwOccupied)++; } (*pdwSize) += dwIterCount; } } void Module::DebugLogRidMapOccupancy() { WRAPPER_NO_CONTRACT; #define COMPUTE_RID_MAP_OCCUPANCY(var_suffix, map) \ DWORD dwOccupied##var_suffix, dwSize##var_suffix, dwPercent##var_suffix; \ map.DebugGetRidMapOccupancy(&dwOccupied##var_suffix, &dwSize##var_suffix); \ dwPercent##var_suffix = dwOccupied##var_suffix ? ((dwOccupied##var_suffix * 100) / dwSize##var_suffix) : 0; COMPUTE_RID_MAP_OCCUPANCY(1, m_TypeDefToMethodTableMap); COMPUTE_RID_MAP_OCCUPANCY(2, m_TypeRefToMethodTableMap); COMPUTE_RID_MAP_OCCUPANCY(3, m_MethodDefToDescMap); COMPUTE_RID_MAP_OCCUPANCY(4, m_FieldDefToDescMap); COMPUTE_RID_MAP_OCCUPANCY(5, m_GenericParamToDescMap); COMPUTE_RID_MAP_OCCUPANCY(6, m_GenericTypeDefToCanonMethodTableMap); COMPUTE_RID_MAP_OCCUPANCY(7, m_FileReferencesMap); COMPUTE_RID_MAP_OCCUPANCY(8, m_ManifestModuleReferencesMap); COMPUTE_RID_MAP_OCCUPANCY(9, m_MethodDefToPropertyInfoMap); LOG(( LF_EEMEM, INFO3, " Map occupancy:\n" " TypeDefToMethodTable map: %4d/%4d (%2d %%)\n" " TypeRefToMethodTable map: %4d/%4d (%2d %%)\n" " MethodDefToDesc map: %4d/%4d (%2d %%)\n" " FieldDefToDesc map: %4d/%4d (%2d %%)\n" " GenericParamToDesc map: %4d/%4d (%2d %%)\n" " GenericTypeDefToCanonMethodTable map: %4d/%4d (%2d %%)\n" " FileReferences map: %4d/%4d (%2d %%)\n" " AssemblyReferences map: %4d/%4d (%2d %%)\n" " MethodDefToPropInfo map: %4d/%4d (%2d %%)\n" , dwOccupied1, dwSize1, dwPercent1, dwOccupied2, dwSize2, dwPercent2, dwOccupied3, dwSize3, dwPercent3, dwOccupied4, dwSize4, dwPercent4, dwOccupied5, dwSize5, dwPercent5, dwOccupied6, dwSize6, dwPercent6, dwOccupied7, dwSize7, dwPercent7, dwOccupied8, dwSize8, dwPercent8, dwOccupied9, dwSize9, dwPercent9 )); #undef COMPUTE_RID_MAP_OCCUPANCY } #endif // _DEBUG BOOL Module::CanExecuteCode() { WRAPPER_NO_CONTRACT; #ifdef FEATURE_PREJIT // In a passive domain, we lock down which assemblies can run code if (!GetAppDomain()->IsPassiveDomain()) return TRUE; Assembly * pAssembly = GetAssembly(); PEAssembly * pPEAssembly = pAssembly->GetManifestFile(); // Only mscorlib is allowed to execute code in an ngen passive domain if (IsCompilationProcess()) return pPEAssembly->IsSystem(); // ExecuteDLLForAttach does not run the managed entry point in // a passive domain to avoid loader-lock deadlocks. // Hence, it is not safe to execute any code from this assembly. if (pPEAssembly->GetEntryPointToken(INDEBUG(TRUE)) != mdTokenNil) return FALSE; // EXEs loaded using LoadAssembly() may not be loaded at their // preferred base address. If they have any relocs, these may // not have been fixed up. if (!pPEAssembly->IsDll() && !pPEAssembly->IsILOnly()) return FALSE; #endif // FEATURE_PREJIT return TRUE; } // // FindMethod finds a MethodDesc for a global function methoddef or ref // MethodDesc *Module::FindMethodThrowing(mdToken pMethod) { CONTRACT (MethodDesc *) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END SigTypeContext typeContext; /* empty type context: methods will not be generic */ RETURN MemberLoader::GetMethodDescFromMemberDefOrRefOrSpec(this, pMethod, &typeContext, TRUE, /* strictMetadataChecks */ FALSE /* dont get code shared between generic instantiations */); } // // FindMethod finds a MethodDesc for a global function methoddef or ref // MethodDesc *Module::FindMethod(mdToken pMethod) { CONTRACT (MethodDesc *) { INSTANCE_CHECK; NOTHROW; GC_TRIGGERS; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; MethodDesc *pMDRet = NULL; EX_TRY { pMDRet = FindMethodThrowing(pMethod); } EX_CATCH { #ifdef _DEBUG CONTRACT_VIOLATION(ThrowsViolation); char szMethodName [MAX_CLASSNAME_LENGTH]; CEEInfo::findNameOfToken(this, pMethod, szMethodName, COUNTOF (szMethodName)); // This used to be IJW, but changed to LW_INTEROP to reclaim a bit in our log facilities LOG((LF_INTEROP, LL_INFO10, "Failed to find Method: %s for Vtable Fixup\n", szMethodName)); #endif // _DEBUG } EX_END_CATCH(SwallowAllExceptions) RETURN pMDRet; } // // PopulatePropertyInfoMap precomputes property information during NGen // that is expensive to look up from metadata at runtime. // void Module::PopulatePropertyInfoMap() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; PRECONDITION(IsCompilationProcess()); } CONTRACTL_END; IMDInternalImport* mdImport = GetMDImport(); HENUMInternalHolder hEnum(mdImport); hEnum.EnumAllInit(mdtMethodDef); mdMethodDef md; while (hEnum.EnumNext(&md)) { mdProperty prop = 0; ULONG semantic = 0; if (mdImport->GetPropertyInfoForMethodDef(md, &prop, NULL, &semantic) == S_OK) { // Store the Rid in the lower 24 bits and the semantic in the upper 8 _ASSERTE((semantic & 0xFFFFFF00) == 0); SIZE_T value = RidFromToken(prop) | (semantic << 24); // We need to make sure a value of zero indicates an empty LookupMap entry // Fortunately the semantic will prevent value from being zero _ASSERTE(value != 0); m_MethodDefToPropertyInfoMap.AddElement(this, RidFromToken(md), value); } } FastInterlockOr(&m_dwPersistedFlags, COMPUTED_METHODDEF_TO_PROPERTYINFO_MAP); } // // GetPropertyInfoForMethodDef wraps the metadata function of the same name, // first trying to use the information stored in m_MethodDefToPropertyInfoMap. // HRESULT Module::GetPropertyInfoForMethodDef(mdMethodDef md, mdProperty *ppd, LPCSTR *pName, ULONG *pSemantic) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; } CONTRACTL_END; HRESULT hr; if ((m_dwPersistedFlags & COMPUTED_METHODDEF_TO_PROPERTYINFO_MAP) != 0) { SIZE_T value = m_MethodDefToPropertyInfoMap.GetElement(RidFromToken(md)); if (value == 0) { _ASSERTE(GetMDImport()->GetPropertyInfoForMethodDef(md, ppd, pName, pSemantic) == S_FALSE); return S_FALSE; } else { // Decode the value into semantic and mdProperty as described in PopulatePropertyInfoMap ULONG semantic = (value & 0xFF000000) >> 24; mdProperty prop = TokenFromRid(value & 0x00FFFFFF, mdtProperty); #ifdef _DEBUG mdProperty dbgPd; LPCSTR dbgName; ULONG dbgSemantic; _ASSERTE(GetMDImport()->GetPropertyInfoForMethodDef(md, &dbgPd, &dbgName, &dbgSemantic) == S_OK); #endif if (ppd != NULL) { *ppd = prop; _ASSERTE(*ppd == dbgPd); } if (pSemantic != NULL) { *pSemantic = semantic; _ASSERTE(*pSemantic == dbgSemantic); } if (pName != NULL) { IfFailRet(GetMDImport()->GetPropertyProps(prop, pName, NULL, NULL, NULL)); #ifdef _DEBUG HRESULT hr = GetMDImport()->GetPropertyProps(prop, pName, NULL, NULL, NULL); _ASSERTE(hr == S_OK); _ASSERTE(strcmp(*pName, dbgName) == 0); #endif } return S_OK; } } return GetMDImport()->GetPropertyInfoForMethodDef(md, ppd, pName, pSemantic); } #ifdef FEATURE_NATIVE_IMAGE_GENERATION // Fill the m_propertyNameSet hash filter with data that represents every // property and its name in the module. void Module::PrecomputeMatchingProperties(DataImage *image) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(IsCompilationProcess()); } CONTRACTL_END; IMDInternalImport* mdImport = GetMDImport(); m_nPropertyNameSet = mdImport->GetCountWithTokenKind(mdtProperty); if (m_nPropertyNameSet == 0) { return; } m_propertyNameSet = new (image->GetHeap()) BYTE[m_nPropertyNameSet]; DWORD nEnumeratedProperties = 0; HENUMInternalHolder hEnumTypes(mdImport); hEnumTypes.EnumAllInit(mdtTypeDef); // Enumerate all properties of all types mdTypeDef tkType; while (hEnumTypes.EnumNext(&tkType)) { HENUMInternalHolder hEnumPropertiesForType(mdImport); hEnumPropertiesForType.EnumInit(mdtProperty, tkType); mdProperty tkProperty; while (hEnumPropertiesForType.EnumNext(&tkProperty)) { LPCSTR name; HRESULT hr = GetMDImport()->GetPropertyProps(tkProperty, &name, NULL, NULL, NULL); IfFailThrow(hr); ++nEnumeratedProperties; // Use a case-insensitive hash so that we can use this value for // both case-sensitive and case-insensitive name lookups SString ssName(SString::Utf8Literal, name); ULONG nameHashValue = ssName.HashCaseInsensitive(); // Set one bit in m_propertyNameSet per iteration // This will allow lookup to ensure that the bit from each iteration is set // and if any are not set, know that the (tkProperty,name) pair is not valid for (DWORD i = 0; i < NUM_PROPERTY_SET_HASHES; ++i) { DWORD currentHashValue = HashThreeToOne(tkProperty, nameHashValue, i); DWORD bitPos = currentHashValue % (m_nPropertyNameSet * 8); m_propertyNameSet[bitPos / 8] |= (1 << bitPos % 8); } } } _ASSERTE(nEnumeratedProperties == m_nPropertyNameSet); } #endif // FEATURE_NATIVE_IMAGE_GENERATION // Check whether the module might possibly have a property with a name with // the passed hash value without accessing the property's name. This is done // by consulting a hash filter populated at NGen time. BOOL Module::MightContainMatchingProperty(mdProperty tkProperty, ULONG nameHash) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; MODE_ANY; } CONTRACTL_END; if (m_propertyNameSet) { _ASSERTE(HasNativeImage()); // if this property was added after the name set was computed, conservatively // assume we might have it. This is known to occur in scenarios where a profiler // injects additional metadata at module load time for an NGEN'ed module. In the // future other dynamic additions to the module might produce a similar result. if (RidFromToken(tkProperty) > m_nPropertyNameSet) return TRUE; // Check one bit per iteration, failing if any are not set // We know that all will have been set for any valid (tkProperty,name) pair for (DWORD i = 0; i < NUM_PROPERTY_SET_HASHES; ++i) { DWORD currentHashValue = HashThreeToOne(tkProperty, nameHash, i); DWORD bitPos = currentHashValue % (m_nPropertyNameSet * 8); if ((m_propertyNameSet[bitPos / 8] & (1 << bitPos % 8)) == 0) { return FALSE; } } } return TRUE; } #ifdef FEATURE_NATIVE_IMAGE_GENERATION // Ensure that all elements and flags that we want persisted in the LookupMaps are present void Module::FinalizeLookupMapsPreSave(DataImage *image) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(IsCompilationProcess()); } CONTRACTL_END; // For each typedef, if it does not need a restore, add the ZAPPED_TYPE_NEEDS_NO_RESTORE flag { LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT != NULL && !pMT->NeedsRestore(image)) { m_TypeDefToMethodTableMap.AddFlag(RidFromToken(pMT->GetCl()), ZAPPED_TYPE_NEEDS_NO_RESTORE); } } } // For each canonical instantiation of a generic type def, if it does not need a restore, add the ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE flag { LookupMap<PTR_MethodTable>::Iterator genericTypeDefIter(&m_GenericTypeDefToCanonMethodTableMap); while (genericTypeDefIter.Next()) { MethodTable * pMT = genericTypeDefIter.GetElement(); if (pMT != NULL && !pMT->NeedsRestore(image)) { m_GenericTypeDefToCanonMethodTableMap.AddFlag(RidFromToken(pMT->GetCl()), ZAPPED_GENERIC_TYPE_NEEDS_NO_RESTORE); } } } } #endif // FEATURE_NATIVE_IMAGE_GENERATION // Return true if this module has any live (jitted) JMC functions. // If a module has no jitted JMC functions, then it's as if it's a // non-user module. bool Module::HasAnyJMCFunctions() { LIMITED_METHOD_CONTRACT; // If we have any live JMC funcs in us, then we're a JMC module. // We count JMC functions when we either explicitly toggle their status // or when we get the code:DebuggerMethodInfo for them (which happens in a jit-complete). // Since we don't get the jit-completes for ngen modules, we also check the module's // "default" status. This means we may err on the side of believing we have // JMC methods. return ((m_debuggerSpecificData.m_cTotalJMCFuncs > 0) || m_debuggerSpecificData.m_fDefaultJMCStatus); } // Alter our module's count of JMC functions. // Since these may be called on multiple threads (say 2 threads are jitting // methods within a module), make it thread safe. void Module::IncJMCFuncCount() { LIMITED_METHOD_CONTRACT; InterlockedIncrement(&m_debuggerSpecificData.m_cTotalJMCFuncs); } void Module::DecJMCFuncCount() { LIMITED_METHOD_CONTRACT; InterlockedDecrement(&m_debuggerSpecificData.m_cTotalJMCFuncs); } // code:DebuggerMethodInfo are lazily created. Let them lookup what the default is. bool Module::GetJMCStatus() { LIMITED_METHOD_CONTRACT; return m_debuggerSpecificData.m_fDefaultJMCStatus; } // Set the default JMC status of this module. void Module::SetJMCStatus(bool fStatus) { LIMITED_METHOD_CONTRACT; m_debuggerSpecificData.m_fDefaultJMCStatus = fStatus; } // Update the dynamic metadata if needed. Nop for non-dynamic modules void Module::UpdateDynamicMetadataIfNeeded() { CONTRACTL { NOTHROW; GC_TRIGGERS; } CONTRACTL_END; // Only need to serializing metadata for dynamic modules. For non-dynamic modules, metadata is already available. if (!IsReflection()) { return; } // Since serializing metadata to an auxillary buffer is only needed by the debugger, // we should only be doing this for modules that the debugger can see. if (!IsVisibleToDebugger()) { return; } HRESULT hr = S_OK; EX_TRY { GetReflectionModule()->CaptureModuleMetaDataToMemory(); } EX_CATCH_HRESULT(hr); // This Metadata buffer is only used for the debugger, so it's a non-fatal exception for regular CLR execution. // Just swallow it and keep going. However, with the exception of out-of-memory, we do expect it to // succeed, so assert on failures. if (hr != E_OUTOFMEMORY) { SIMPLIFYING_ASSUMPTION_SUCCEEDED(hr); } } #ifdef DEBUGGING_SUPPORTED #endif // DEBUGGING_SUPPORTED BOOL Module::NotifyDebuggerLoad(AppDomain *pDomain, DomainFile * pDomainFile, int flags, BOOL attaching) { WRAPPER_NO_CONTRACT; // We don't notify the debugger about modules that don't contain any code. if (!IsVisibleToDebugger()) return FALSE; // Always capture metadata, even if no debugger is attached. If a debugger later attaches, it will use // this data. { Module * pModule = pDomainFile->GetModule(); pModule->UpdateDynamicMetadataIfNeeded(); } // // Remaining work is only needed if a debugger is attached // if (!attaching && !pDomain->IsDebuggerAttached()) return FALSE; BOOL result = FALSE; if (flags & ATTACH_MODULE_LOAD) { g_pDebugInterface->LoadModule(this, m_file->GetPath(), m_file->GetPath().GetCount(), GetAssembly(), pDomain, pDomainFile, attaching); result = TRUE; } if (flags & ATTACH_CLASS_LOAD) { LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT != NULL && pMT->IsRestored()) { result = TypeHandle(pMT).NotifyDebuggerLoad(pDomain, attaching) || result; } } } return result; } void Module::NotifyDebuggerUnload(AppDomain *pDomain) { LIMITED_METHOD_CONTRACT; if (!pDomain->IsDebuggerAttached()) return; // We don't notify the debugger about modules that don't contain any code. if (!IsVisibleToDebugger()) return; LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT != NULL && pMT->IsRestored()) { TypeHandle(pMT).NotifyDebuggerUnload(pDomain); } } g_pDebugInterface->UnloadModule(this, pDomain); } #if !defined(CROSSGEN_COMPILE) //================================================================================= mdToken GetTokenForVTableEntry(HINSTANCE hInst, BYTE **ppVTEntry) { CONTRACTL{ NOTHROW; } CONTRACTL_END; mdToken tok =(mdToken)(UINT_PTR)*ppVTEntry; _ASSERTE(TypeFromToken(tok) == mdtMethodDef || TypeFromToken(tok) == mdtMemberRef); return tok; } //================================================================================= void SetTargetForVTableEntry(HINSTANCE hInst, BYTE **ppVTEntry, BYTE *pTarget) { CONTRACTL{ THROWS; } CONTRACTL_END; DWORD oldProtect; if (!ClrVirtualProtect(ppVTEntry, sizeof(BYTE*), PAGE_READWRITE, &oldProtect)) { // This is very bad. We are not going to be able to update header. _ASSERTE(!"SetTargetForVTableEntry(): VirtualProtect() changing IJW thunk vtable to R/W failed.\n"); ThrowLastError(); } *ppVTEntry = pTarget; DWORD ignore; if (!ClrVirtualProtect(ppVTEntry, sizeof(BYTE*), oldProtect, &ignore)) { // This is not so bad, we're already done the update, we just didn't return the thunk table to read only _ASSERTE(!"SetTargetForVTableEntry(): VirtualProtect() changing IJW thunk vtable back to RO failed.\n"); } } //================================================================================= BYTE * GetTargetForVTableEntry(HINSTANCE hInst, BYTE **ppVTEntry) { CONTRACTL{ NOTHROW; } CONTRACTL_END; return *ppVTEntry; } //====================================================================================== // Fixup vtables stored in the header to contain pointers to method desc // prestubs rather than metadata method tokens. void Module::FixupVTables() { CONTRACTL{ INSTANCE_CHECK; STANDARD_VM_CHECK; } CONTRACTL_END; // If we've already fixed up, or this is not an IJW module, just return. // NOTE: This relies on ILOnly files not having fixups. If this changes, // we need to change this conditional. if (IsIJWFixedUp() || m_file->IsILOnly()) { return; } HINSTANCE hInstThis = GetFile()->GetIJWBase(); // <REVISIT_TODO>@todo: workaround!</REVISIT_TODO> // If we are compiling in-process, we don't want to fixup the vtables - as it // will have side effects on the other copy of the module! if (SystemDomain::GetCurrentDomain()->IsPassiveDomain()) { return; } #ifdef FEATURE_PREJIT // We delayed filling in this value until the LoadLibrary occurred if (HasTls() && HasNativeImage()) { CORCOMPILE_EE_INFO_TABLE *pEEInfo = GetNativeImage()->GetNativeEEInfoTable(); pEEInfo->rvaStaticTlsIndex = GetTlsIndex(); } #endif // Get vtable fixup data COUNT_T cFixupRecords; IMAGE_COR_VTABLEFIXUP *pFixupTable = m_file->GetVTableFixups(&cFixupRecords); // No records then return if (cFixupRecords == 0) { return; } // Now, we need to take a lock to serialize fixup. PEImage::IJWFixupData *pData = PEImage::GetIJWData(m_file->GetIJWBase()); // If it's already been fixed (in some other appdomain), record the fact and return if (pData->IsFixedUp()) { SetIsIJWFixedUp(); return; } ////////////////////////////////////////////////////// // // This is done in three stages: // 1. We enumerate the types we'll need to load // 2. We load the types // 3. We create and install the thunks // COUNT_T cVtableThunks = 0; struct MethodLoadData { mdToken token; MethodDesc *pMD; }; MethodLoadData *rgMethodsToLoad = NULL; COUNT_T cMethodsToLoad = 0; // // Stage 1 // // Each fixup entry describes a vtable, so iterate the vtables and sum their counts { DWORD iFixup; for (iFixup = 0; iFixup < cFixupRecords; iFixup++) cVtableThunks += pFixupTable[iFixup].Count; } Thread *pThread = GetThread(); StackingAllocator *pAlloc = &pThread->m_MarshalAlloc; CheckPointHolder cph(pAlloc->GetCheckpoint()); // Allocate the working array of tokens. cMethodsToLoad = cVtableThunks; rgMethodsToLoad = new (pAlloc) MethodLoadData[cMethodsToLoad]; memset(rgMethodsToLoad, 0, cMethodsToLoad * sizeof(MethodLoadData)); // Now take the IJW module lock and get all the tokens { // Take the lock CrstHolder lockHolder(pData->GetLock()); // If someone has beaten us, just return if (pData->IsFixedUp()) { SetIsIJWFixedUp(); return; } COUNT_T iCurMethod = 0; if (cFixupRecords != 0) { for (COUNT_T iFixup = 0; iFixup < cFixupRecords; iFixup++) { // Vtables can be 32 or 64 bit. if ((pFixupTable[iFixup].Type == (COR_VTABLE_PTRSIZED)) || (pFixupTable[iFixup].Type == (COR_VTABLE_PTRSIZED | COR_VTABLE_FROM_UNMANAGED)) || (pFixupTable[iFixup].Type == (COR_VTABLE_PTRSIZED | COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN))) { const BYTE** pPointers = (const BYTE **)m_file->GetVTable(pFixupTable[iFixup].RVA); for (int iMethod = 0; iMethod < pFixupTable[iFixup].Count; iMethod++) { if (pData->IsMethodFixedUp(iFixup, iMethod)) continue; mdToken mdTok = GetTokenForVTableEntry(hInstThis, (BYTE **)(pPointers + iMethod)); CONSISTENCY_CHECK(mdTok != mdTokenNil); rgMethodsToLoad[iCurMethod++].token = mdTok; } } } } } // // Stage 2 - Load the types // { for (COUNT_T iCurMethod = 0; iCurMethod < cMethodsToLoad; iCurMethod++) { mdToken curTok = rgMethodsToLoad[iCurMethod].token; if (!GetMDImport()->IsValidToken(curTok)) { _ASSERTE(!"Invalid token in v-table fix-up table"); ThrowHR(COR_E_BADIMAGEFORMAT); } // Find the method desc MethodDesc *pMD; { CONTRACT_VIOLATION(LoadsTypeViolation); pMD = FindMethodThrowing(curTok); } CONSISTENCY_CHECK(CheckPointer(pMD)); rgMethodsToLoad[iCurMethod].pMD = pMD; } } // // Stage 3 - Create the thunk data // { // Take the lock CrstHolder lockHolder(pData->GetLock()); // If someone has beaten us, just return if (pData->IsFixedUp()) { SetIsIJWFixedUp(); return; } // This phase assumes there is only one AppDomain and that thunks // can all safely point directly to the method in the current AppDomain AppDomain *pAppDomain = GetAppDomain(); // Used to index into rgMethodsToLoad COUNT_T iCurMethod = 0; // Each fixup entry describes a vtable (each slot contains a metadata token // at this stage). DWORD iFixup; for (iFixup = 0; iFixup < cFixupRecords; iFixup++) cVtableThunks += pFixupTable[iFixup].Count; DWORD dwIndex = 0; DWORD dwThunkIndex = 0; // Now to fill in the thunk table. for (iFixup = 0; iFixup < cFixupRecords; iFixup++) { // Tables may contain zero fixups, in which case the RVA is null, which triggers an assert if (pFixupTable[iFixup].Count == 0) continue; const BYTE** pPointers = (const BYTE **) m_file->GetVTable(pFixupTable[iFixup].RVA); // Vtables can be 32 or 64 bit. if (pFixupTable[iFixup].Type == COR_VTABLE_PTRSIZED) { for (int iMethod = 0; iMethod < pFixupTable[iFixup].Count; iMethod++) { if (pData->IsMethodFixedUp(iFixup, iMethod)) continue; mdToken mdTok = rgMethodsToLoad[iCurMethod].token; MethodDesc *pMD = rgMethodsToLoad[iCurMethod].pMD; iCurMethod++; #ifdef _DEBUG if (pMD->IsNDirect()) { LOG((LF_INTEROP, LL_INFO10, "[0x%lx] <-- PINV thunk for \"%s\" (target = 0x%lx)\n", (size_t)&(pPointers[iMethod]), pMD->m_pszDebugMethodName, (size_t)(((NDirectMethodDesc*)pMD)->GetNDirectTarget()))); } #endif // _DEBUG CONSISTENCY_CHECK(dwThunkIndex < cVtableThunks); // Point the local vtable slot to the thunk we created SetTargetForVTableEntry(hInstThis, (BYTE **)&pPointers[iMethod], (BYTE *)pMD->GetMultiCallableAddrOfCode()); pData->MarkMethodFixedUp(iFixup, iMethod); dwThunkIndex++; } } else if (pFixupTable[iFixup].Type == (COR_VTABLE_PTRSIZED | COR_VTABLE_FROM_UNMANAGED) || (pFixupTable[iFixup].Type == (COR_VTABLE_PTRSIZED | COR_VTABLE_FROM_UNMANAGED_RETAIN_APPDOMAIN))) { for (int iMethod = 0; iMethod < pFixupTable[iFixup].Count; iMethod++) { if (pData->IsMethodFixedUp(iFixup, iMethod)) continue; mdToken mdTok = rgMethodsToLoad[iCurMethod].token; MethodDesc *pMD = rgMethodsToLoad[iCurMethod].pMD; iCurMethod++; LOG((LF_INTEROP, LL_INFO10, "[0x%p] <-- VTable thunk for \"%s\" (pMD = 0x%p)\n", (UINT_PTR)&(pPointers[iMethod]), pMD->m_pszDebugMethodName, pMD)); UMEntryThunk *pUMEntryThunk = (UMEntryThunk*)(void*)(GetDllThunkHeap()->AllocAlignedMem(sizeof(UMEntryThunk), CODE_SIZE_ALIGN)); // UMEntryThunk contains code FillMemory(pUMEntryThunk, sizeof(*pUMEntryThunk), 0); UMThunkMarshInfo *pUMThunkMarshInfo = (UMThunkMarshInfo*)(void*)(GetThunkHeap()->AllocAlignedMem(sizeof(UMThunkMarshInfo), CODE_SIZE_ALIGN)); FillMemory(pUMThunkMarshInfo, sizeof(*pUMThunkMarshInfo), 0); pUMThunkMarshInfo->LoadTimeInit(pMD); pUMEntryThunk->LoadTimeInit(NULL, NULL, pUMThunkMarshInfo, pMD, pAppDomain->GetId()); SetTargetForVTableEntry(hInstThis, (BYTE **)&pPointers[iMethod], (BYTE *)pUMEntryThunk->GetCode()); pData->MarkMethodFixedUp(iFixup, iMethod); } } else if ((pFixupTable[iFixup].Type & COR_VTABLE_NOT_PTRSIZED) == COR_VTABLE_NOT_PTRSIZED) { // fixup type doesn't match the platform THROW_BAD_FORMAT(BFA_FIXUP_WRONG_PLATFORM, this); } else { _ASSERTE(!"Unknown vtable fixup type"); } } // Indicate that this module has been fixed before releasing the lock pData->SetIsFixedUp(); // On the data SetIsIJWFixedUp(); // On the module } // End of Stage 3 } // Self-initializing accessor for m_pThunkHeap LoaderHeap *Module::GetDllThunkHeap() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; return PEImage::GetDllThunkHeap(GetFile()->GetIJWBase()); } LoaderHeap *Module::GetThunkHeap() { CONTRACT(LoaderHeap *) { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END if (!m_pThunkHeap) { size_t * pPrivatePCLBytes = NULL; size_t * pGlobalPCLBytes = NULL; COUNTER_ONLY(pPrivatePCLBytes = &(GetPerfCounters().m_Loading.cbLoaderHeapSize)); LoaderHeap *pNewHeap = new LoaderHeap(VIRTUAL_ALLOC_RESERVE_GRANULARITY, // DWORD dwReserveBlockSize 0, // DWORD dwCommitBlockSize pPrivatePCLBytes, ThunkHeapStubManager::g_pManager->GetRangeList(), TRUE); // BOOL fMakeExecutable if (FastInterlockCompareExchangePointer(&m_pThunkHeap, pNewHeap, 0) != 0) { delete pNewHeap; } } RETURN m_pThunkHeap; } #endif // !CROSSGEN_COMPILE #ifdef FEATURE_NATIVE_IMAGE_GENERATION // These helpers are used in Module::ExpandAll // to avoid EX_TRY/EX_CATCH in a loop (uses _alloca and guzzles stack) static TypeHandle LoadTypeDefOrRefHelper(DataImage * image, Module * pModule, mdToken tk) { STANDARD_VM_CONTRACT; TypeHandle th; EX_TRY { th = ClassLoader::LoadTypeDefOrRefThrowing(pModule, tk, ClassLoader::ThrowIfNotFound, ClassLoader::PermitUninstDefOrRef); } EX_CATCH { image->GetPreloader()->Error(tk, GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) return th; } static TypeHandle LoadTypeSpecHelper(DataImage * image, Module * pModule, mdToken tk, PCCOR_SIGNATURE pSig, ULONG cSig) { STANDARD_VM_CONTRACT; TypeHandle th; EX_TRY { SigPointer p(pSig, cSig); SigTypeContext typeContext; th = p.GetTypeHandleThrowing(pModule, &typeContext); } EX_CATCH { image->GetPreloader()->Error(tk, GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) return th; } static TypeHandle LoadGenericInstantiationHelper(DataImage * image, Module * pModule, mdToken tk, Instantiation inst) { STANDARD_VM_CONTRACT; TypeHandle th; EX_TRY { th = ClassLoader::LoadGenericInstantiationThrowing(pModule, tk, inst); } EX_CATCH { image->GetPreloader()->Error(tk, GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) return th; } static void GetDescFromMemberRefHelper(DataImage * image, Module * pModule, mdToken tk) { STANDARD_VM_CONTRACT; EX_TRY { MethodDesc * pMD = NULL; FieldDesc * pFD = NULL; TypeHandle th; // Note: using an empty type context is now OK, because even though the token is a MemberRef // neither the token nor its parent will directly refer to type variables. // @TODO GENERICS: want to allow loads of generic methods here but need strict metadata checks on parent SigTypeContext typeContext; MemberLoader::GetDescFromMemberRef(pModule, tk, &pMD, &pFD, &typeContext, FALSE /* strict metadata checks */, &th); } EX_CATCH { image->GetPreloader()->Error(tk, GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) } void Module::SetProfileData(CorProfileData * profileData) { LIMITED_METHOD_CONTRACT; m_pProfileData = profileData; } CorProfileData * Module::GetProfileData() { LIMITED_METHOD_CONTRACT; return m_pProfileData; } mdTypeDef Module::LookupIbcTypeToken(Module * pExternalModule, mdToken ibcToken, SString* optionalFullNameOut) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END _ASSERTE(TypeFromToken(ibcToken) == ibcExternalType); CorProfileData * profileData = this->GetProfileData(); CORBBTPROF_BLOB_TYPE_DEF_ENTRY * blobTypeDefEntry; blobTypeDefEntry = profileData->GetBlobExternalTypeDef(ibcToken); if (blobTypeDefEntry == NULL) return mdTypeDefNil; IbcNameHandle ibcName; ibcName.szName = &blobTypeDefEntry->name[0]; ibcName.tkIbcNameSpace = blobTypeDefEntry->nameSpaceToken; ibcName.tkIbcNestedClass = blobTypeDefEntry->nestedClassToken; ibcName.szNamespace = NULL; ibcName.tkEnclosingClass = mdTypeDefNil; if (!IsNilToken(blobTypeDefEntry->nameSpaceToken)) { _ASSERTE(IsNilToken(blobTypeDefEntry->nestedClassToken)); idExternalNamespace nameSpaceToken = blobTypeDefEntry->nameSpaceToken; _ASSERTE(TypeFromToken(nameSpaceToken) == ibcExternalNamespace); CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY * blobNamespaceDefEntry; blobNamespaceDefEntry = profileData->GetBlobExternalNamespaceDef(nameSpaceToken); if (blobNamespaceDefEntry == NULL) return mdTypeDefNil; ibcName.szNamespace = &blobNamespaceDefEntry->name[0]; if (optionalFullNameOut != NULL) { optionalFullNameOut->Append(W("[")); optionalFullNameOut->AppendUTF8(pExternalModule->GetSimpleName()); optionalFullNameOut->Append(W("]")); if ((ibcName.szNamespace != NULL) && ((*ibcName.szNamespace) != W('\0'))) { optionalFullNameOut->AppendUTF8(ibcName.szNamespace); optionalFullNameOut->Append(W(".")); } optionalFullNameOut->AppendUTF8(ibcName.szName); } } else if (!IsNilToken(blobTypeDefEntry->nestedClassToken)) { idExternalType nestedClassToken = blobTypeDefEntry->nestedClassToken; _ASSERTE(TypeFromToken(nestedClassToken) == ibcExternalType); ibcName.tkEnclosingClass = LookupIbcTypeToken(pExternalModule, nestedClassToken, optionalFullNameOut); if (optionalFullNameOut != NULL) { optionalFullNameOut->Append(W("+")); optionalFullNameOut->AppendUTF8(ibcName.szName); } if (IsNilToken(ibcName.tkEnclosingClass)) return mdTypeDefNil; } //***************************************** // look up function for TypeDef //***************************************** // STDMETHOD(FindTypeDef)( // LPCSTR szNamespace, // [IN] Namespace for the TypeDef. // LPCSTR szName, // [IN] Name of the TypeDef. // mdToken tkEnclosingClass, // [IN] TypeRef/TypeDef Token for the enclosing class. // mdTypeDef *ptypedef) PURE; // [IN] return typedef IMDInternalImport *pInternalImport = pExternalModule->GetMDImport(); mdTypeDef mdResult = mdTypeDefNil; HRESULT hr = pInternalImport->FindTypeDef(ibcName.szNamespace, ibcName.szName, ibcName.tkEnclosingClass, &mdResult); if(FAILED(hr)) mdResult = mdTypeDefNil; return mdResult; } struct IbcCompareContext { Module * pModule; TypeHandle enclosingType; DWORD cMatch; // count of methods that had a matching method name bool useBestSig; // if true we should use the BestSig when we don't find an exact match PCCOR_SIGNATURE pvBestSig; // Current Best matching signature DWORD cbBestSig; // }; //--------------------------------------------------------------------------------------- // // Compare two signatures from the same scope. // BOOL CompareIbcMethodSigs( PCCOR_SIGNATURE pvCandidateSig, // Candidate signature DWORD cbCandidateSig, // PCCOR_SIGNATURE pvIbcSignature, // The Ibc signature that we want to match DWORD cbIbcSignature, // void * pvContext) // void pointer to IbcCompareContext { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END // // Same pointer return TRUE // if (pvCandidateSig == pvIbcSignature) { _ASSERTE(cbCandidateSig == cbIbcSignature); return TRUE; } // // Check for exact match // if (cbCandidateSig == cbIbcSignature) { if (memcmp(pvCandidateSig, pvIbcSignature, cbIbcSignature) == 0) { return TRUE; } } IbcCompareContext * context = (IbcCompareContext *) pvContext; // // No exact match, we will return FALSE and keep looking at other matching method names // // However since the method name was an exact match we will remember this signature, // so that if it is the best match we can look it up again and return it's methodDef token // if (context->cMatch == 0) { context->pvBestSig = pvCandidateSig; context->cbBestSig = cbCandidateSig; context->cMatch = 1; context->useBestSig = true; } else { context->cMatch++; SigTypeContext emptyTypeContext; SigTypeContext ibcTypeContext = SigTypeContext(context->enclosingType); MetaSig ibcSignature (pvIbcSignature, cbIbcSignature, context->pModule, &ibcTypeContext); MetaSig candidateSig (pvCandidateSig, cbCandidateSig, context->pModule, &emptyTypeContext); MetaSig bestSignature(context->pvBestSig, context->cbBestSig, context->pModule, &emptyTypeContext); // // Is candidateSig a better match than bestSignature? // // First check the calling convention // if (candidateSig.GetCallingConventionInfo() != bestSignature.GetCallingConventionInfo()) { if (bestSignature.GetCallingConventionInfo() == ibcSignature.GetCallingConventionInfo()) goto LEAVE_BEST; if (candidateSig.GetCallingConventionInfo() == ibcSignature.GetCallingConventionInfo()) goto SELECT_CANDIDATE; // // Neither one is a match // goto USE_NEITHER; } // // Next check the number of arguments // if (candidateSig.NumFixedArgs() != bestSignature.NumFixedArgs()) { // // Does one of the two have the same number of args? // if (bestSignature.NumFixedArgs() == ibcSignature.NumFixedArgs()) goto LEAVE_BEST; if (candidateSig.NumFixedArgs() == ibcSignature.NumFixedArgs()) goto SELECT_CANDIDATE; // // Neither one is a match // goto USE_NEITHER; } else if (candidateSig.NumFixedArgs() != ibcSignature.NumFixedArgs()) { // // Neither one is a match // goto USE_NEITHER; } CorElementType etIbc; CorElementType etCandidate; CorElementType etBest; // // Next get the return element type // // etIbc = ibcSignature.GetReturnProps().PeekElemTypeClosed(ibcSignature.GetSigTypeContext()); IfFailThrow(ibcSignature.GetReturnProps().PeekElemType(&etIbc)); IfFailThrow(candidateSig.GetReturnProps().PeekElemType(&etCandidate)); IfFailThrow(bestSignature.GetReturnProps().PeekElemType(&etBest)); // // Do they have different return types? // if (etCandidate != etBest) { if (etBest == etIbc) goto LEAVE_BEST; if (etCandidate == etIbc) goto SELECT_CANDIDATE; } // // Now iterate over the method argument types to see which signature // is the better match // for (DWORD i = 0; (i < ibcSignature.NumFixedArgs()); i++) { ibcSignature.SkipArg(); IfFailThrow(ibcSignature.GetArgProps().PeekElemType(&etIbc)); candidateSig.SkipArg(); IfFailThrow(candidateSig.GetArgProps().PeekElemType(&etCandidate)); bestSignature.SkipArg(); IfFailThrow(bestSignature.GetArgProps().PeekElemType(&etBest)); // // Do they have different argument types? // if (etCandidate != etBest) { if (etBest == etIbc) goto LEAVE_BEST; if (etCandidate == etIbc) goto SELECT_CANDIDATE; } } // When we fall though to here we did not find any differences // that we could base a choice on // context->useBestSig = true; SELECT_CANDIDATE: context->pvBestSig = pvCandidateSig; context->cbBestSig = cbCandidateSig; context->useBestSig = true; return FALSE; USE_NEITHER: context->useBestSig = false; return FALSE; } LEAVE_BEST: return FALSE; } // CompareIbcMethodSigs mdMethodDef Module::LookupIbcMethodToken(TypeHandle enclosingType, mdToken ibcToken, SString* optionalFullNameOut) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END _ASSERTE(TypeFromToken(ibcToken) == ibcExternalMethod); CorProfileData * profileData = this->GetProfileData(); CORBBTPROF_BLOB_METHOD_DEF_ENTRY * blobMethodDefEntry; blobMethodDefEntry = profileData->GetBlobExternalMethodDef(ibcToken); if (blobMethodDefEntry == NULL) return mdMethodDefNil; idExternalType signatureToken = blobMethodDefEntry->signatureToken; _ASSERTE(!IsNilToken(signatureToken)); _ASSERTE(TypeFromToken(signatureToken) == ibcExternalSignature); CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY * blobSignatureDefEntry; blobSignatureDefEntry = profileData->GetBlobExternalSignatureDef(signatureToken); if (blobSignatureDefEntry == NULL) return mdMethodDefNil; IbcNameHandle ibcName; ibcName.szName = &blobMethodDefEntry->name[0]; ibcName.tkIbcNestedClass = blobMethodDefEntry->nestedClassToken; ibcName.tkIbcNameSpace = idExternalNamespaceNil; ibcName.szNamespace = NULL; ibcName.tkEnclosingClass = mdTypeDefNil; Module * pExternalModule = enclosingType.GetModule(); PCCOR_SIGNATURE pvSig = NULL; ULONG cbSig = 0; _ASSERTE(!IsNilToken(ibcName.tkIbcNestedClass)); _ASSERTE(TypeFromToken(ibcName.tkIbcNestedClass) == ibcExternalType); ibcName.tkEnclosingClass = LookupIbcTypeToken(pExternalModule, ibcName.tkIbcNestedClass, optionalFullNameOut); if (IsNilToken(ibcName.tkEnclosingClass)) { COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE); } if (optionalFullNameOut != NULL) { optionalFullNameOut->Append(W(".")); optionalFullNameOut->AppendUTF8(ibcName.szName); // MethodName optionalFullNameOut->Append(W("()")); } pvSig = blobSignatureDefEntry->sig; cbSig = blobSignatureDefEntry->cSig; //***************************************** // look up functions for TypeDef //***************************************** // STDMETHOD(FindMethodDefUsingCompare)( // mdTypeDef classdef, // [IN] given typedef // LPCSTR szName, // [IN] member name // PCCOR_SIGNATURE pvSigBlob, // [IN] point to a blob value of CLR signature // ULONG cbSigBlob, // [IN] count of bytes in the signature blob // PSIGCOMPARE pSignatureCompare, // [IN] Routine to compare signatures // void* pSignatureArgs, // [IN] Additional info to supply the compare function // mdMethodDef *pmd) PURE; // [OUT] matching memberdef // IMDInternalImport * pInternalImport = pExternalModule->GetMDImport(); IbcCompareContext context; memset(&context, 0, sizeof(IbcCompareContext)); context.pModule = this; context.enclosingType = enclosingType; context.cMatch = 0; context.useBestSig = false; mdMethodDef mdResult = mdMethodDefNil; HRESULT hr = pInternalImport->FindMethodDefUsingCompare(ibcName.tkEnclosingClass, ibcName.szName, pvSig, cbSig, CompareIbcMethodSigs, (void *) &context, &mdResult); if (SUCCEEDED(hr)) { _ASSERTE(mdResult != mdMethodDefNil); } else if (context.useBestSig) { hr = pInternalImport->FindMethodDefUsingCompare(ibcName.tkEnclosingClass, ibcName.szName, context.pvBestSig, context.cbBestSig, CompareIbcMethodSigs, (void *) &context, &mdResult); _ASSERTE(SUCCEEDED(hr)); _ASSERTE(mdResult != mdMethodDefNil); } else { mdResult = mdMethodDefNil; } return mdResult; } TypeHandle Module::LoadIBCTypeHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry) { CONTRACT(TypeHandle) { NOTHROW; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(CheckPointer(pBlobSigEntry)); } CONTRACT_END TypeHandle loadedType; PCCOR_SIGNATURE pSig = pBlobSigEntry->sig; ULONG cSig = pBlobSigEntry->cSig; SigPointer p(pSig, cSig); ZapSig::Context zapSigContext(this, (void *)this, ZapSig::IbcTokens); ZapSig::Context * pZapSigContext = &zapSigContext; EX_TRY { // This is what ZapSig::FindTypeHandleFromSignature does... // SigTypeContext typeContext; // empty type context loadedType = p.GetTypeHandleThrowing( this, &typeContext, ClassLoader::LoadTypes, CLASS_LOADED, FALSE, NULL, pZapSigContext); #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_1); #endif } EX_CATCH { image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION()); loadedType = TypeHandle(); } EX_END_CATCH(SwallowAllExceptions) RETURN loadedType; } //--------------------------------------------------------------------------------------- // MethodDesc* Module::LoadIBCMethodHelper(DataImage *image, CORBBTPROF_BLOB_PARAM_SIG_ENTRY * pBlobSigEntry) { CONTRACT(MethodDesc*) { NOTHROW; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); PRECONDITION(CheckPointer(pBlobSigEntry)); } CONTRACT_END MethodDesc* pMethod = NULL; PCCOR_SIGNATURE pSig = pBlobSigEntry->sig; ULONG cSig = pBlobSigEntry->cSig; SigPointer p(pSig, cSig); ZapSig::Context zapSigContext(this, (void *)this, ZapSig::IbcTokens); ZapSig::Context * pZapSigContext = &zapSigContext; TypeHandle enclosingType; // // First Decode and Load the enclosing type for this method // EX_TRY { // This is what ZapSig::FindTypeHandleFromSignature does... // SigTypeContext typeContext; // empty type context enclosingType = p.GetTypeHandleThrowing( this, &typeContext, ClassLoader::LoadTypes, CLASS_LOADED, FALSE, NULL, pZapSigContext); IfFailThrow(p.SkipExactlyOne()); #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_2); #endif } EX_CATCH { image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION()); enclosingType = TypeHandle(); } EX_END_CATCH(SwallowAllExceptions) if (enclosingType.IsNull()) return NULL; // // Now Decode and Load the method // EX_TRY { MethodTable *pOwnerMT = enclosingType.GetMethodTable(); _ASSERTE(pOwnerMT != NULL); // decode flags DWORD methodFlags; IfFailThrow(p.GetData(&methodFlags)); BOOL isInstantiatingStub = ((methodFlags & ENCODE_METHOD_SIG_InstantiatingStub) == ENCODE_METHOD_SIG_InstantiatingStub); BOOL isUnboxingStub = ((methodFlags & ENCODE_METHOD_SIG_UnboxingStub) == ENCODE_METHOD_SIG_UnboxingStub); BOOL fMethodNeedsInstantiation = ((methodFlags & ENCODE_METHOD_SIG_MethodInstantiation) == ENCODE_METHOD_SIG_MethodInstantiation); BOOL fMethodUsesSlotEncoding = ((methodFlags & ENCODE_METHOD_SIG_SlotInsteadOfToken) == ENCODE_METHOD_SIG_SlotInsteadOfToken); if ( fMethodUsesSlotEncoding ) { // get the method desc using slot number DWORD slot; IfFailThrow(p.GetData(&slot)); pMethod = pOwnerMT->GetMethodDescForSlot(slot); } else // otherwise we use the normal metadata MethodDef token encoding and we handle ibc tokens. { // // decode method token // RID methodRid; IfFailThrow(p.GetData(&methodRid)); mdMethodDef methodToken; // // Is our enclosingType from another module? // if (this == enclosingType.GetModule()) { // // The enclosing type is from our module // The method token is a normal MethodDef token // methodToken = TokenFromRid(methodRid, mdtMethodDef); } else { // // The enclosing type is from an external module // The method token is a ibcExternalMethod token // idExternalType ibcToken = RidToToken(methodRid, ibcExternalMethod); methodToken = this->LookupIbcMethodToken(enclosingType, ibcToken); if (IsNilToken(methodToken)) { COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_METHOD); } } SigTypeContext methodTypeContext( enclosingType ); pMethod = MemberLoader::GetMethodDescFromMemberDefOrRefOrSpec( pOwnerMT->GetModule(), methodToken, &methodTypeContext, FALSE, FALSE ); } Instantiation inst; // Instantiate the method if needed, or create a stub to a static method in a generic class. if (fMethodNeedsInstantiation && pMethod->HasMethodInstantiation()) { DWORD nargs = pMethod->GetNumGenericMethodArgs(); SIZE_T cbMem; if (!ClrSafeInt<SIZE_T>::multiply(nargs, sizeof(TypeHandle), cbMem/* passed by ref */)) ThrowHR(COR_E_OVERFLOW); TypeHandle * pInst = (TypeHandle*) _alloca(cbMem); SigTypeContext typeContext; // empty type context for (DWORD i = 0; i < nargs; i++) { TypeHandle curInst; curInst = p.GetTypeHandleThrowing( this, &typeContext, ClassLoader::LoadTypes, CLASS_LOADED, FALSE, NULL, pZapSigContext); // curInst will be nullptr when the type fails the versioning bubble check if (curInst.IsNull() && IsReadyToRunCompilation()) { COMPlusThrow(kTypeLoadException, IDS_IBC_MISSING_EXTERNAL_TYPE); } pInst[i] = curInst; IfFailThrow(p.SkipExactlyOne()); } inst = Instantiation(pInst, nargs); } else { inst = pMethod->LoadMethodInstantiation(); } // We should now be able to create an instantiation for this generic method // This must be called even if nargs == 0, in order to create an instantiating // stub for static methods in generic classees if needed, also for BoxedEntryPointStubs // in non-generic structs. const bool allowInstParam = !(isInstantiatingStub || isUnboxingStub); pMethod = MethodDesc::FindOrCreateAssociatedMethodDesc(pMethod, pOwnerMT, isUnboxingStub, inst, allowInstParam); #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_3); #endif } EX_CATCH { // Catch any kTypeLoadException that we may have thrown above // image->GetPreloader()->Error(pBlobSigEntry->blob.token, GET_EXCEPTION()); pMethod = NULL; } EX_END_CATCH(SwallowAllExceptions) RETURN pMethod; } // Module::LoadIBCMethodHelper #ifdef FEATURE_COMINTEROP //--------------------------------------------------------------------------------------- // // This function is a workaround for missing IBC data in WinRT assemblies and // not-yet-implemented sharing of IL_STUB(__Canon arg) IL stubs for all interfaces. // static void ExpandWindowsRuntimeType(TypeHandle t, DataImage *image) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(!t.IsNull()); } CONTRACTL_END if (t.IsTypeDesc()) return; // This array contains our poor man's IBC data - instantiations that are known to // be used by other assemblies. static const struct { LPCUTF8 m_szTypeName; BinderClassID m_GenericBinderClassID; } rgForcedInstantiations[] = { { "Windows.UI.Xaml.Data.IGroupInfo", CLASS__IENUMERABLEGENERIC }, { "Windows.UI.Xaml.UIElement", CLASS__ILISTGENERIC }, { "Windows.UI.Xaml.Visibility", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.VerticalAlignment", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.HorizontalAlignment", CLASS__CLRIREFERENCEIMPL }, // The following instantiations are used by Microsoft.PlayerFramework - http://playerframework.codeplex.com/ { "Windows.UI.Xaml.Media.AudioCategory", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.Media.AudioDeviceType", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.Media.MediaElementState", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.Media.Stereo3DVideoRenderMode", CLASS__CLRIREFERENCEIMPL }, { "Windows.UI.Xaml.Media.Stereo3DVideoPackingMode", CLASS__CLRIREFERENCEIMPL }, }; DefineFullyQualifiedNameForClass(); LPCUTF8 szTypeName = GetFullyQualifiedNameForClass(t.AsMethodTable()); for (SIZE_T i = 0; i < COUNTOF(rgForcedInstantiations); i++) { if (strcmp(szTypeName, rgForcedInstantiations[i].m_szTypeName) == 0) { EX_TRY { TypeHandle thGenericType = TypeHandle(MscorlibBinder::GetClass(rgForcedInstantiations[i].m_GenericBinderClassID)); Instantiation inst(&t, 1); thGenericType.Instantiate(inst); } EX_CATCH { image->GetPreloader()->Error(t.GetCl(), GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) } } if (strcmp(szTypeName, "Windows.Foundation.Collections.IObservableVector`1") == 0) { EX_TRY { TypeHandle thArg = TypeHandle(g_pObjectClass); Instantiation inst(&thArg, 1); t.Instantiate(inst); } EX_CATCH { image->GetPreloader()->Error(t.GetCl(), GET_EXCEPTION()); } EX_END_CATCH(SwallowAllExceptions) } } #endif // FEATURE_COMINTEROP //--------------------------------------------------------------------------------------- // void Module::ExpandAll(DataImage *image) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(!IsResource()); } CONTRACTL_END mdToken tk; DWORD assemblyFlags = GetAssembly()->GetFlags(); // // Explicitly load the global class. // MethodTable *pGlobalMT = GetGlobalMethodTable(); // // Load all classes. This also fills out the // RID maps for the typedefs, method defs, // and field defs. // IMDInternalImport *pInternalImport = GetMDImport(); { HENUMInternalHolder hEnum(pInternalImport); hEnum.EnumTypeDefInit(); while (pInternalImport->EnumTypeDefNext(&hEnum, &tk)) { #ifdef FEATURE_COMINTEROP // Skip the non-managed WinRT types since they're only used by Javascript and C++ // // With WinRT files, we want to exclude certain types that cause us problems: // * Attribute types defined in Windows.Foundation. The constructor's methodimpl flags // specify it is an internal runtime function and gets set as an FCALL when we parse // the type // if (IsAfContentType_WindowsRuntime(assemblyFlags)) { mdToken tkExtends; pInternalImport->GetTypeDefProps(tk, NULL, &tkExtends); if (TypeFromToken(tkExtends) == mdtTypeRef) { LPCSTR szNameSpace = NULL; LPCSTR szName = NULL; pInternalImport->GetNameOfTypeRef(tkExtends, &szNameSpace, &szName); if (!strcmp(szNameSpace, "System") && !_stricmp((szName), "Attribute")) { continue; } } } #endif // FEATURE_COMINTEROP TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk); if (t.IsNull()) // Skip this type continue; if (!t.HasInstantiation()) { EEClassHashEntry_t *pBucket = NULL; HashDatum data; StackSString ssFullyQualifiedName; mdToken mdEncloser; EEClassHashTable *pTable = GetAvailableClassHash(); _ASSERTE(pTable != NULL); t.GetName(ssFullyQualifiedName); // Convert to UTF8 StackScratchBuffer scratch; LPCUTF8 szFullyQualifiedName = ssFullyQualifiedName.GetUTF8(scratch); BOOL isNested = ClassLoader::IsNested(this, tk, &mdEncloser); EEClassHashTable::LookupContext sContext; pBucket = pTable->GetValue(szFullyQualifiedName, &data, isNested, &sContext); if (isNested) { while (pBucket != NULL) { _ASSERTE (TypeFromToken(tk) == mdtTypeDef); BOOL match = GetClassLoader()->CompareNestedEntryWithTypeDef( pInternalImport, mdEncloser, GetAvailableClassHash(), pBucket->GetEncloser()); if (match) break; pBucket = pTable->FindNextNestedClass(szFullyQualifiedName, &data, &sContext); } } // Save the typehandle instead of the token in the hash entry so that ngen'ed images // don't have to lookup based on token and update this entry if ((pBucket != NULL) && !t.IsNull() && t.IsRestored()) pBucket->SetData(t.AsPtr()); } DWORD nGenericClassParams = t.GetNumGenericArgs(); if (nGenericClassParams != 0) { // For generic types, load the instantiation at Object SIZE_T cbMem; if (!ClrSafeInt<SIZE_T>::multiply(sizeof(TypeHandle), nGenericClassParams, cbMem/* passed by ref */)) { ThrowHR(COR_E_OVERFLOW); } CQuickBytes qbGenericClassArgs; TypeHandle *genericClassArgs = reinterpret_cast<TypeHandle*>(qbGenericClassArgs.AllocThrows(cbMem)); for (DWORD i = 0; i < nGenericClassParams; i++) { genericClassArgs[i] = TypeHandle(g_pCanonMethodTableClass); } TypeHandle thCanonInst = LoadGenericInstantiationHelper(image, this, tk, Instantiation(genericClassArgs, nGenericClassParams)); // If successful, add the instantiation to the Module's map of generic types instantiated at Object if (!thCanonInst.IsNull() && !thCanonInst.IsTypeDesc()) { MethodTable * pCanonMT = thCanonInst.AsMethodTable(); m_GenericTypeDefToCanonMethodTableMap.AddElement(this, RidFromToken(pCanonMT->GetCl()), pCanonMT); } } #ifdef FEATURE_COMINTEROP if (IsAfContentType_WindowsRuntime(assemblyFlags)) { ExpandWindowsRuntimeType(t, image); } #endif // FEATURE_COMINTEROP } } // // Fill out TypeRef RID map // { HENUMInternalHolder hEnum(pInternalImport); hEnum.EnumAllInit(mdtTypeRef); while (pInternalImport->EnumNext(&hEnum, &tk)) { mdToken tkResolutionScope = mdTokenNil; pInternalImport->GetResolutionScopeOfTypeRef(tk, &tkResolutionScope); #ifdef FEATURE_COMINTEROP // WinRT first party files are authored with TypeRefs pointing to TypeDefs in the same module. // This causes us to load types we do not want to NGen such as custom attributes. We will not // expand any module local TypeRefs for WinMDs to prevent this. if(TypeFromToken(tkResolutionScope)==mdtModule && IsAfContentType_WindowsRuntime(assemblyFlags)) continue; #endif // FEATURE_COMINTEROP TypeHandle t = LoadTypeDefOrRefHelper(image, this, tk); if (t.IsNull()) // Skip this type continue; #ifdef FEATURE_COMINTEROP if (!g_fNGenWinMDResilient && TypeFromToken(tkResolutionScope) == mdtAssemblyRef) { DWORD dwAssemblyRefFlags; IfFailThrow(pInternalImport->GetAssemblyRefProps(tkResolutionScope, NULL, NULL, NULL, NULL, NULL, NULL, &dwAssemblyRefFlags)); if (IsAfContentType_WindowsRuntime(dwAssemblyRefFlags)) { Assembly *pAssembly = t.GetAssembly(); PEAssembly *pPEAssembly = pAssembly->GetManifestFile(); AssemblySpec refSpec; refSpec.InitializeSpec(tkResolutionScope, pInternalImport); LPCSTR psznamespace; LPCSTR pszname; pInternalImport->GetNameOfTypeRef(tk, &psznamespace, &pszname); refSpec.SetWindowsRuntimeType(psznamespace, pszname); GetAppDomain()->ToCompilationDomain()->AddDependency(&refSpec,pPEAssembly); } } #endif // FEATURE_COMINTEROP } } // // Load all type specs // { HENUMInternalHolder hEnum(pInternalImport); hEnum.EnumAllInit(mdtTypeSpec); while (pInternalImport->EnumNext(&hEnum, &tk)) { ULONG cSig; PCCOR_SIGNATURE pSig; IfFailThrow(pInternalImport->GetTypeSpecFromToken(tk, &pSig, &cSig)); // Load all types specs that do not contain variables if (SigPointer(pSig, cSig).IsPolyType(NULL) == hasNoVars) { LoadTypeSpecHelper(image, this, tk, pSig, cSig); } } } // // Load all the reported parameterized types and methods // CorProfileData * profileData = this->GetProfileData(); CORBBTPROF_BLOB_ENTRY *pBlobEntry = profileData->GetBlobStream(); if (pBlobEntry != NULL) { while (pBlobEntry->TypeIsValid()) { if (TypeFromToken(pBlobEntry->token) == ibcTypeSpec) { _ASSERTE(pBlobEntry->type == ParamTypeSpec); CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry; TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry); if (!th.IsNull()) { image->GetPreloader()->TriageTypeForZap(th, TRUE); } } else if (TypeFromToken(pBlobEntry->token) == ibcMethodSpec) { _ASSERTE(pBlobEntry->type == ParamMethodSpec); CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry; MethodDesc *pMD = LoadIBCMethodHelper(image, pBlobSigEntry); } pBlobEntry = pBlobEntry->GetNextEntry(); } _ASSERTE(pBlobEntry->type == EndOfBlobStream); } // // Record references to all of the hot methods specifiled by MethodProfilingData array // We call MethodReferencedByCompiledCode to indicate that we plan on compiling this method // CORBBTPROF_TOKEN_INFO * pMethodProfilingData = profileData->GetTokenFlagsData(MethodProfilingData); DWORD cMethodProfilingData = profileData->GetTokenFlagsCount(MethodProfilingData); for (unsigned int i = 0; (i < cMethodProfilingData); i++) { mdToken token = pMethodProfilingData[i].token; DWORD profilingFlags = pMethodProfilingData[i].flags; // We call MethodReferencedByCompiledCode only when the profile data indicates that // we executed (i.e read) the code for the method // if (profilingFlags & (1 << ReadMethodCode)) { if (TypeFromToken(token) == mdtMethodDef) { MethodDesc * pMD = LookupMethodDef(token); // // Record a reference to a hot non-generic method // image->GetPreloader()->MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD); } else if (TypeFromToken(token) == ibcMethodSpec) { CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token); if (pBlobSigEntry != NULL) { _ASSERTE(pBlobSigEntry->blob.token == token); MethodDesc * pMD = LoadIBCMethodHelper(image, pBlobSigEntry); if (pMD != NULL) { // Occasionally a non-instantiated generic method shows up in the IBC data, we should NOT compile it. if (!pMD->IsTypicalMethodDefinition()) { // // Record a reference to a hot instantiated generic method // image->GetPreloader()->MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pMD); } } } } } } { // // Fill out MemberRef RID map and va sig cookies for // varargs member refs. // HENUMInternalHolder hEnum(pInternalImport); hEnum.EnumAllInit(mdtMemberRef); while (pInternalImport->EnumNext(&hEnum, &tk)) { mdTypeRef parent; IfFailThrow(pInternalImport->GetParentOfMemberRef(tk, &parent)); #ifdef FEATURE_COMINTEROP if (IsAfContentType_WindowsRuntime(assemblyFlags) && TypeFromToken(parent) == mdtTypeRef) { mdToken tkResolutionScope = mdTokenNil; pInternalImport->GetResolutionScopeOfTypeRef(parent, &tkResolutionScope); // WinRT first party files are authored with TypeRefs pointing to TypeDefs in the same module. // This causes us to load types we do not want to NGen such as custom attributes. We will not // expand any module local TypeRefs for WinMDs to prevent this. if(TypeFromToken(tkResolutionScope)==mdtModule) continue; LPCSTR szNameSpace = NULL; LPCSTR szName = NULL; if (SUCCEEDED(pInternalImport->GetNameOfTypeRef(parent, &szNameSpace, &szName))) { if (WinMDAdapter::ConvertWellKnownTypeNameFromClrToWinRT(&szNameSpace, &szName)) { // // This is a MemberRef from a redirected WinRT type // We should skip it as managed view will never see this MemberRef anyway // Not skipping this will result MissingMethodExceptions as members in redirected // types doesn't exactly match their redirected CLR type counter part // // Typically we only need to do this for interfaces as we should never see MemberRef // from non-interfaces, but here to keep things simple I'm skipping every memberref that // belongs to redirected WinRT type // continue; } } } #endif // FEATURE_COMINTEROP // If the MethodRef has a TypeSpec as a parent (i.e. refers to a method on an array type // or on a generic class), then it could in turn refer to type variables of // an unknown class/method. So we don't preresolve any MemberRefs which have TypeSpecs as // parents. The RID maps are not filled out for such tokens anyway. if (TypeFromToken(parent) != mdtTypeSpec) { GetDescFromMemberRefHelper(image, this, tk); } } } // // Fill out binder // if (m_pBinder != NULL) { m_pBinder->BindAll(); } } // Module::ExpandAll /* static */ void Module::SaveMethodTable(DataImage * image, MethodTable * pMT, DWORD profilingFlags) { STANDARD_VM_CONTRACT; if (image->IsStored(pMT)) return; pMT->Save(image, profilingFlags); } /* static */ void Module::SaveTypeHandle(DataImage * image, TypeHandle t, DWORD profilingFlags) { STANDARD_VM_CONTRACT; t.CheckRestore(); if (t.IsTypeDesc()) { TypeDesc *pTD = t.AsTypeDesc(); if (!image->IsStored(pTD)) { pTD->Save(image); } } else { MethodTable *pMT = t.AsMethodTable(); if (pMT != NULL && !image->IsStored(pMT)) { SaveMethodTable(image, pMT, profilingFlags); _ASSERTE(image->IsStored(pMT)); } } #ifdef _DEBUG if (LoggingOn(LF_JIT, LL_INFO100)) { Module *pPrefModule = Module::GetPreferredZapModuleForTypeHandle(t); if (image->GetModule() != pPrefModule) { StackSString typeName; t.CheckRestore(); TypeString::AppendTypeDebug(typeName, t); LOG((LF_ZAP, LL_INFO100, "The type %S was saved outside its preferred module %S\n", typeName.GetUnicode(), pPrefModule->GetPath().GetUnicode())); } } #endif // _DEBUG } #ifndef DACCESS_COMPILE void ModuleCtorInfo::Save(DataImage *image, CorProfileData *profileData) { STANDARD_VM_CONTRACT; if (!numElements) return; DWORD i = 0; DWORD totalBoxedStatics = 0; // sort the tables so that // - the hot ppMT entries are at the beginning of the ppMT table // - the hot cctor entries are at the beginning of the cctorInfoHot table // - the cold cctor entries are at the end, and we make cctorInfoCold point // the first cold entry // // the invariant in this loop is: // items 0...numElementsHot-1 are hot // items numElementsHot...i-1 are cold for (i = 0; i < numElements; i++) { MethodTable *ppMTTemp = ppMT[i].GetValue(); // Count the number of boxed statics along the way totalBoxedStatics += ppMTTemp->GetNumBoxedRegularStatics(); bool hot = true; // if there's no profiling data, assume the entries are all hot. if (profileData->GetTokenFlagsData(TypeProfilingData)) { if ((profileData->GetTypeProfilingFlagsOfToken(ppMTTemp->GetCl()) & (1 << ReadCCtorInfo)) == 0) hot = false; } if (hot) { // swap ppMT[i] and ppMT[numElementsHot] to maintain the loop invariant ppMT[i].SetValue(ppMT[numElementsHot].GetValue()); ppMT[numElementsHot].SetValue(ppMTTemp); numElementsHot++; } } numHotHashes = numElementsHot ? RoundUpToPower2((numElementsHot * sizeof(PTR_MethodTable)) / CACHE_LINE_SIZE) : 0; numColdHashes = (numElements - numElementsHot) ? RoundUpToPower2(((numElements - numElementsHot) * sizeof(PTR_MethodTable)) / CACHE_LINE_SIZE) : 0; LOG((LF_ZAP, LL_INFO10, "ModuleCtorInfo::numHotHashes: 0x%4x\n", numHotHashes)); if (numColdHashes != 0) { LOG((LF_ZAP, LL_INFO10, "ModuleCtorInfo::numColdHashes: 0x%4x\n", numColdHashes)); } // The "plus one" is so we can store the offset to the end of the array at the end of // the hashoffsets arrays, enabling faster lookups. hotHashOffsets = new DWORD[numHotHashes + 1]; coldHashOffsets = new DWORD[numColdHashes + 1]; DWORD *hashArray = new DWORD[numElements]; for (i = 0; i < numElementsHot; i++) { hashArray[i] = GenerateHash(ppMT[i].GetValue(), HOT); } for (i = numElementsHot; i < numElements; i++) { hashArray[i] = GenerateHash(ppMT[i].GetValue(), COLD); } // Sort the two arrays by hash values to create regions with the same hash values. ClassCtorInfoEntryArraySort cctorInfoHotSort(hashArray, ppMT, numElementsHot); ClassCtorInfoEntryArraySort cctorInfoColdSort(hashArray + numElementsHot, ppMT + numElementsHot, numElements - numElementsHot); cctorInfoHotSort.Sort(); cctorInfoColdSort.Sort(); // Generate the indices that index into the correct "hash region" in the hot part of the ppMT array, and store // them in the hotHashOffests arrays. DWORD curHash = 0; i = 0; while (i < numElementsHot) { if (curHash < hashArray[i]) { hotHashOffsets[curHash++] = i; } else if (curHash == hashArray[i]) { hotHashOffsets[curHash++] = i++; } else { i++; } } while (curHash <= numHotHashes) { hotHashOffsets[curHash++] = numElementsHot; } // Generate the indices that index into the correct "hash region" in the hot part of the ppMT array, and store // them in the coldHashOffsets arrays. curHash = 0; i = numElementsHot; while (i < numElements) { if (curHash < hashArray[i]) { coldHashOffsets[curHash++] = i; } else if (curHash == hashArray[i]) { coldHashOffsets[curHash++] = i++; } else i++; } while (curHash <= numColdHashes) { coldHashOffsets[curHash++] = numElements; } delete[] hashArray; cctorInfoHot = new ClassCtorInfoEntry[numElements]; // make cctorInfoCold point to the first cold element cctorInfoCold = cctorInfoHot + numElementsHot; ppHotGCStaticsMTs = (totalBoxedStatics != 0) ? new RelativeFixupPointer<PTR_MethodTable>[totalBoxedStatics] : NULL; numHotGCStaticsMTs = totalBoxedStatics; DWORD iGCStaticMT = 0; for (i = 0; i < numElements; i++) { if (numElements == numElementsHot) { numHotGCStaticsMTs = iGCStaticMT; numColdGCStaticsMTs = (totalBoxedStatics - iGCStaticMT); // make ppColdGCStaticsMTs point to the first cold element ppColdGCStaticsMTs = ppHotGCStaticsMTs + numHotGCStaticsMTs; } MethodTable* pMT = ppMT[i].GetValue(); ClassCtorInfoEntry* pEntry = &cctorInfoHot[i]; WORD numBoxedStatics = pMT->GetNumBoxedRegularStatics(); pEntry->numBoxedStatics = numBoxedStatics; pEntry->hasFixedAddressVTStatics = !!pMT->HasFixedAddressVTStatics(); FieldDesc *pField = pMT->HasGenericsStaticsInfo() ? pMT->GetGenericsStaticFieldDescs() : (pMT->GetApproxFieldDescListRaw() + pMT->GetNumIntroducedInstanceFields()); FieldDesc *pFieldEnd = pField + pMT->GetNumStaticFields(); pEntry->firstBoxedStaticOffset = (DWORD)-1; pEntry->firstBoxedStaticMTIndex = (DWORD)-1; DWORD numFoundBoxedStatics = 0; while (pField < pFieldEnd) { _ASSERTE(pField->IsStatic()); if (!pField->IsSpecialStatic() && pField->IsByValue()) { if (pEntry->firstBoxedStaticOffset == (DWORD)-1) { pEntry->firstBoxedStaticOffset = pField->GetOffset(); pEntry->firstBoxedStaticMTIndex = iGCStaticMT; } _ASSERTE(pField->GetOffset() - pEntry->firstBoxedStaticOffset == (iGCStaticMT - pEntry->firstBoxedStaticMTIndex) * sizeof(MethodTable*)); TypeHandle th = pField->GetFieldTypeHandleThrowing(); ppHotGCStaticsMTs[iGCStaticMT++].SetValueMaybeNull(th.GetMethodTable()); numFoundBoxedStatics++; } pField++; } _ASSERTE(numBoxedStatics == numFoundBoxedStatics); } _ASSERTE(iGCStaticMT == totalBoxedStatics); if (numElementsHot > 0) { image->StoreStructure(cctorInfoHot, sizeof(ClassCtorInfoEntry) * numElementsHot, DataImage::ITEM_MODULE_CCTOR_INFO_HOT); image->StoreStructure(hotHashOffsets, sizeof(DWORD) * (numHotHashes + 1), DataImage::ITEM_MODULE_CCTOR_INFO_HOT); } if (numElements > 0) image->StoreStructure(ppMT, sizeof(RelativePointer<MethodTable *>) * numElements, DataImage::ITEM_MODULE_CCTOR_INFO_HOT); if (numElements > numElementsHot) { image->StoreStructure(cctorInfoCold, sizeof(ClassCtorInfoEntry) * (numElements - numElementsHot), DataImage::ITEM_MODULE_CCTOR_INFO_COLD); image->StoreStructure(coldHashOffsets, sizeof(DWORD) * (numColdHashes + 1), DataImage::ITEM_MODULE_CCTOR_INFO_COLD); } if ( numHotGCStaticsMTs ) { // Save the mt templates image->StoreStructure( ppHotGCStaticsMTs, numHotGCStaticsMTs * sizeof(RelativeFixupPointer<MethodTable*>), DataImage::ITEM_GC_STATIC_HANDLES_HOT); } else { ppHotGCStaticsMTs = NULL; } if ( numColdGCStaticsMTs ) { // Save the hot mt templates image->StoreStructure( ppColdGCStaticsMTs, numColdGCStaticsMTs * sizeof(RelativeFixupPointer<MethodTable*>), DataImage::ITEM_GC_STATIC_HANDLES_COLD); } else { ppColdGCStaticsMTs = NULL; } } #endif // !DACCESS_COMPILE bool Module::AreAllClassesFullyLoaded() { STANDARD_VM_CONTRACT; // Adjust for unused space IMDInternalImport *pImport = GetMDImport(); HENUMInternalHolder hEnum(pImport); hEnum.EnumAllInit(mdtTypeDef); mdTypeDef token; while (pImport->EnumNext(&hEnum, &token)) { _ASSERTE(TypeFromToken(token) == mdtTypeDef); // Special care has to been taken with COR_GLOBAL_PARENT_TOKEN, as the class // may not be needed, (but we have to distinguish between not needed and threw error). if (token == COR_GLOBAL_PARENT_TOKEN && !NeedsGlobalMethodTable()) { // No EEClass for this token if there was no need for a global method table continue; } TypeHandle th = LookupTypeDef(token); if (th.IsNull()) return false; if (!th.AsMethodTable()->IsFullyLoaded()) return false; } return true; } void Module::PrepareTypesForSave(DataImage *image) { STANDARD_VM_CONTRACT; // // Prepare typedefs // { LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT == NULL || !pMT->IsFullyLoaded()) continue; } } // // Prepare typespecs // { // Create a local copy in case the new elements are added to the hashtable during population InlineSArray<TypeHandle, 20> pTypes; // Make sure the iterator is destroyed before there is a chance of loading new types { EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle t = pEntry->GetTypeHandle(); if (t.IsTypeDesc()) continue; if (!image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr()))) continue; pTypes.Append(t); } } } image->GetPreloader()->TriageForZap(FALSE, FALSE); } static const char* const MethodTableRestoreReasonDescription[TotalMethodTables + 1] = { #undef RESTORE_REASON_FUNC #define RESTORE_REASON_FUNC(s) #s, METHODTABLE_RESTORE_REASON() #undef RESTORE_REASON "TotalMethodTablesEvaluated" }; // MethodDescByMethodTableTraits could be a local class in Module::Save(), but g++ doesn't like // instantiating templates with private classes. class MethodDescByMethodTableTraits : public NoRemoveSHashTraits< DefaultSHashTraits<MethodDesc *> > { public: typedef MethodTable * key_t; static MethodDesc * Null() { return NULL; } static bool IsNull(MethodDesc * pMD) { return pMD == NULL; } static MethodTable * GetKey(MethodDesc * pMD) { return pMD->GetMethodTable_NoLogging(); } static count_t Hash(MethodTable * pMT) { LIMITED_METHOD_CONTRACT; return (count_t) (UINT_PTR) pMT->GetTypeDefRid_NoLogging(); } static BOOL Equals(MethodTable * pMT1, MethodTable * pMT2) { return pMT1 == pMT2; } }; void Module::Save(DataImage *image) { STANDARD_VM_CONTRACT; // Precompute type specific auxiliary information saved into NGen image // Note that this operation can load new types. PrepareTypesForSave(image); // Cache values of all persisted flags computed from custom attributes IsNoStringInterning(); IsRuntimeWrapExceptions(); IsPreV4Assembly(); HasDefaultDllImportSearchPathsAttribute(); // Precompute property information to avoid runtime metadata lookup PopulatePropertyInfoMap(); // Any any elements and compute values of any LookupMap flags that were not available previously FinalizeLookupMapsPreSave(image); // // Save the module // ZapStoredStructure * pModuleNode = image->StoreStructure(this, sizeof(Module), DataImage::ITEM_MODULE); m_pNGenLayoutInfo = (NGenLayoutInfo *)(void *)image->GetModule()->GetLoaderAllocator()-> GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(NGenLayoutInfo))); image->StoreStructure(m_pNGenLayoutInfo, sizeof(NGenLayoutInfo), DataImage::ITEM_BINDER_ITEMS); // // If we are NGening, we don't need to keep a list of va // sig cookies, as we already have a complete set (of course we do // have to persist the cookies themselves, though. // // // Initialize maps of child data structures. Note that each tables's blocks are // concantentated to a single block in the process. // CorProfileData * profileData = GetProfileData(); // ngen the neutral resources culture if(GetNeutralResourcesLanguage(&m_pszCultureName, &m_CultureNameLength, &m_FallbackLocation, TRUE)) { image->StoreStructure((void *) m_pszCultureName, (ULONG)(m_CultureNameLength + 1), DataImage::ITEM_BINDER_ITEMS, 1); } m_TypeRefToMethodTableMap.Save(image, DataImage::ITEM_TYPEREF_MAP, profileData, mdtTypeRef); image->BindPointer(&m_TypeRefToMethodTableMap, pModuleNode, offsetof(Module, m_TypeRefToMethodTableMap)); if(m_pMemberRefToDescHashTable) m_pMemberRefToDescHashTable->Save(image, profileData); m_TypeDefToMethodTableMap.Save(image, DataImage::ITEM_TYPEDEF_MAP, profileData, mdtTypeDef); image->BindPointer(&m_TypeDefToMethodTableMap, pModuleNode, offsetof(Module, m_TypeDefToMethodTableMap)); m_MethodDefToDescMap.Save(image, DataImage::ITEM_METHODDEF_MAP, profileData, mdtMethodDef); image->BindPointer(&m_MethodDefToDescMap, pModuleNode, offsetof(Module, m_MethodDefToDescMap)); m_FieldDefToDescMap.Save(image, DataImage::ITEM_FIELDDEF_MAP, profileData, mdtFieldDef); image->BindPointer(&m_FieldDefToDescMap, pModuleNode, offsetof(Module, m_FieldDefToDescMap)); m_GenericParamToDescMap.Save(image, DataImage::ITEM_GENERICPARAM_MAP, profileData, mdtGenericParam); image->BindPointer(&m_GenericParamToDescMap, pModuleNode, offsetof(Module, m_GenericParamToDescMap)); m_GenericTypeDefToCanonMethodTableMap.Save(image, DataImage::ITEM_GENERICTYPEDEF_MAP, profileData, mdtTypeDef); image->BindPointer(&m_GenericTypeDefToCanonMethodTableMap, pModuleNode, offsetof(Module, m_GenericTypeDefToCanonMethodTableMap)); if (m_pAvailableClasses) m_pAvailableClasses->Save(image, profileData); // // Also save the parent maps; the contents will // need to be rewritten, but we can allocate the // space in the image. // // these items have no hot list and no attribution m_FileReferencesMap.Save(image, DataImage::ITEM_FILEREF_MAP, profileData, 0); image->BindPointer(&m_FileReferencesMap, pModuleNode, offsetof(Module, m_FileReferencesMap)); m_ManifestModuleReferencesMap.Save(image, DataImage::ITEM_ASSEMREF_MAP, profileData, 0); image->BindPointer(&m_ManifestModuleReferencesMap, pModuleNode, offsetof(Module, m_ManifestModuleReferencesMap)); m_MethodDefToPropertyInfoMap.Save(image, DataImage::ITEM_PROPERTYINFO_MAP, profileData, 0, TRUE /*fCopyValues*/); image->BindPointer(&m_MethodDefToPropertyInfoMap, pModuleNode, offsetof(Module, m_MethodDefToPropertyInfoMap)); if (m_pBinder != NULL) m_pBinder->Save(image); if (profileData) { // Store types. // Saving hot things first is a very good thing, because we place items // in the order they are saved and things that have hot items are also // more likely to have their other structures touched, hence these should // also be placed together, at least if we don't have any further information to go on. // Note we place particular hot items with more care in the Arrange phase. // CORBBTPROF_TOKEN_INFO * pTypeProfilingData = profileData->GetTokenFlagsData(TypeProfilingData); DWORD cTypeProfilingData = profileData->GetTokenFlagsCount(TypeProfilingData); for (unsigned int i = 0; i < cTypeProfilingData; i++) { CORBBTPROF_TOKEN_INFO *entry = &pTypeProfilingData[i]; mdToken token = entry->token; DWORD flags = entry->flags; #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_4); #endif if ((flags & (1 << ReadMethodTable)) == 0) continue; if (TypeFromToken(token) == mdtTypeDef) { MethodTable *pMT = LookupTypeDef(token).GetMethodTable(); if (pMT && pMT->IsFullyLoaded()) { SaveMethodTable(image, pMT, flags); } } else if (TypeFromToken(token) == ibcTypeSpec) { CORBBTPROF_BLOB_ENTRY *pBlobEntry = profileData->GetBlobStream(); if (pBlobEntry) { while (pBlobEntry->TypeIsValid()) { if (TypeFromToken(pBlobEntry->token) == ibcTypeSpec) { _ASSERTE(pBlobEntry->type == ParamTypeSpec); if (pBlobEntry->token == token) { CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry; TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry); if (!th.IsNull()) { // When we have stale IBC data the type could have been rejected from this image. if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(th.AsPtr()))) { SaveTypeHandle(image, th, flags); } } } } pBlobEntry = pBlobEntry->GetNextEntry(); } _ASSERTE(pBlobEntry->type == EndOfBlobStream); } } } if (m_pAvailableParamTypes != NULL) { // If we have V1 IBC data then we save the hot // out-of-module generic instantiations here CORBBTPROF_TOKEN_INFO * tokens_begin = profileData->GetTokenFlagsData(GenericTypeProfilingData); CORBBTPROF_TOKEN_INFO * tokens_end = tokens_begin + profileData->GetTokenFlagsCount(GenericTypeProfilingData); if (tokens_begin != tokens_end) { SArray<CORBBTPROF_TOKEN_INFO> tokens(tokens_begin, tokens_end); tokens_begin = &tokens[0]; tokens_end = tokens_begin + tokens.GetCount(); util::sort(tokens_begin, tokens_end); // enumerate AvailableParamTypes map and find all hot generic instantiations EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle t = pEntry->GetTypeHandle(); #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_5); #endif if (t.HasInstantiation()) { SString tokenName; t.GetName(tokenName); unsigned cur_token = tokenName.Hash() & 0xffff; CORBBTPROF_TOKEN_INFO * found = util::lower_bound(tokens_begin, tokens_end, CORBBTPROF_TOKEN_INFO(cur_token)); if (found != tokens_end && found->token == cur_token && (found->flags & (1 << ReadMethodTable))) { // When we have stale IBC data the type could have been rejected from this image. if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr()))) SaveTypeHandle(image, t, found->flags); } } } } } } // // Now save any types in the TypeDefToMethodTableMap map { LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { MethodTable * pMT = typeDefIter.GetElement(); if (pMT != NULL && !image->IsStored(pMT) && pMT->IsFullyLoaded()) { image->BeginAssociatingStoredObjectsWithMethodTable(pMT); SaveMethodTable(image, pMT, 0); image->EndAssociatingStoredObjectsWithMethodTable(); } } } // // Now save any TypeDescs in m_GenericParamToDescMap map { LookupMap<PTR_TypeVarTypeDesc>::Iterator genericParamIter(&m_GenericParamToDescMap); while (genericParamIter.Next()) { TypeVarTypeDesc *pTD = genericParamIter.GetElement(); if (pTD != NULL) { pTD->Save(image); } } } #ifdef _DEBUG SealGenericTypesAndMethods(); #endif // // Now save any types in the AvailableParamTypes map // if (m_pAvailableParamTypes != NULL) { EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle t = pEntry->GetTypeHandle(); if (image->GetPreloader()->IsTypeInTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE(t.AsPtr()))) { if (t.GetCanonicalMethodTable() != NULL) { image->BeginAssociatingStoredObjectsWithMethodTable(t.GetCanonicalMethodTable()); SaveTypeHandle(image, t, 0); image->EndAssociatingStoredObjectsWithMethodTable(); } else { SaveTypeHandle(image, t, 0); } } } } // // Now save any methods in the InstMethodHashTable // if (m_pInstMethodHashTable != NULL) { // // Find all MethodDescs that we are going to save, and hash them with MethodTable as the key // typedef SHash<MethodDescByMethodTableTraits> MethodDescByMethodTableHash; MethodDescByMethodTableHash methodDescs; InstMethodHashTable::Iterator it(m_pInstMethodHashTable); InstMethodHashEntry *pEntry; while (m_pInstMethodHashTable->FindNext(&it, &pEntry)) { MethodDesc *pMD = pEntry->GetMethod(); _ASSERTE(!pMD->IsTightlyBoundToMethodTable()); if (!image->IsStored(pMD) && image->GetPreloader()->IsMethodInTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE(pMD))) { methodDescs.Add(pMD); } } // // Save all MethodDescs on the same MethodTable using one chunk builder // for (MethodDescByMethodTableHash::Iterator i1 = methodDescs.Begin(), end1 = methodDescs.End(); i1 != end1; i1++) { MethodDesc * pMD = *(i1); if (image->IsStored(pMD)) continue; MethodTable * pMT = pMD->GetMethodTable(); MethodDesc::SaveChunk methodDescSaveChunk(image); for (MethodDescByMethodTableHash::KeyIterator i2 = methodDescs.Begin(pMT), end2 = methodDescs.End(pMT); i2 != end2; i2++) { _ASSERTE(!image->IsStored(*i2)); methodDescSaveChunk.Append(*i2); } methodDescSaveChunk.Save(); } } // Now save the tables themselves if (m_pAvailableParamTypes != NULL) { m_pAvailableParamTypes->Save(image, this, profileData); } if (m_pInstMethodHashTable != NULL) { m_pInstMethodHashTable->Save(image, profileData); } { MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable(); if (pStubMT != NULL) { SaveMethodTable(image, pStubMT, 0); } } if (m_pStubMethodHashTable != NULL) { m_pStubMethodHashTable->Save(image, profileData); } #ifdef FEATURE_COMINTEROP // the type saving operations above had the side effect of populating m_pGuidToTypeHash if (m_pGuidToTypeHash != NULL) { m_pGuidToTypeHash->Save(image, profileData); } #endif // FEATURE_COMINTEROP // Compute and save the property name set PrecomputeMatchingProperties(image); image->StoreStructure(m_propertyNameSet, m_nPropertyNameSet * sizeof(BYTE), DataImage::ITEM_PROPERTY_NAME_SET); // Sort the list of RVA statics in an ascending order wrt the RVA // and save them. image->SaveRvaStructure(); // Save static data LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: Saving module static data\n")); // We have this scenario where ngen will fail to load some classes but will generate // a valid exe, or it will choose not to save some loaded classes due to some error // conditions, where statics will be committed at runtime for the classes that ngen // wasn't able to load or save. So we can't cut down the static block size blindly if we've // failed to load or save any class. We don't think this scenario deserves complicated code // paths to get the extra working set perf (you would be pulling in the jitter if // you need any of these classes), So we are basically simplifying this down, if we failed // to load or save any class we won't compress the statics block and will persist the original // estimation. // All classes were loaded and saved, cut down the block if (AreAllClassesFullyLoaded()) { // Set a mark indicating we had all our classes loaded m_pRegularStaticOffsets = (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED; m_pThreadStaticOffsets = (PTR_DWORD) NGEN_STATICS_ALLCLASSES_WERE_LOADED; } else { // Since not all of the classes loaded we want to zero the pointers to the offset tables so they'll be // recalculated at runtime. But we can't do that here since we might try to reload some of the failed // types during the arrange phase (as the result of trying to parse profiling data). So we'll defer // zero'ing anything until the fixup phase. // Not all classes were stored, revert to uncompressed maps to support run-time changes m_TypeDefToMethodTableMap.ConvertSavedMapToUncompressed(image, DataImage::ITEM_TYPEDEF_MAP); m_MethodDefToDescMap.ConvertSavedMapToUncompressed(image, DataImage::ITEM_METHODDEF_MAP); } m_ModuleCtorInfo.Save(image, profileData); image->BindPointer(&m_ModuleCtorInfo, pModuleNode, offsetof(Module, m_ModuleCtorInfo)); if (m_pDynamicStaticsInfo) { image->StoreStructure(m_pDynamicStaticsInfo, m_maxDynamicEntries*sizeof(DynamicStaticsInfo), DataImage::ITEM_DYNAMIC_STATICS_INFO_TABLE); } InlineTrackingMap *inlineTrackingMap = image->GetInlineTrackingMap(); if (inlineTrackingMap) { m_pPersistentInlineTrackingMapNGen = new (image->GetHeap()) PersistentInlineTrackingMapNGen(this); m_pPersistentInlineTrackingMapNGen->Save(image, inlineTrackingMap); } if (m_pNgenStats && g_CorCompileVerboseLevel >= CORCOMPILE_STATS) { GetSvcLogger()->Printf ("%-35s: %s\n", "MethodTable Restore Reason", "Count"); DWORD dwTotal = 0; for (int i=0; i<TotalMethodTables; i++) { GetSvcLogger()->Printf ("%-35s: %d\n", MethodTableRestoreReasonDescription[i], m_pNgenStats->MethodTableRestoreNumReasons[i]); dwTotal += m_pNgenStats->MethodTableRestoreNumReasons[i]; } GetSvcLogger()->Printf ("%-35s: %d\n", "TotalMethodTablesNeedRestore", dwTotal); GetSvcLogger()->Printf ("%-35s: %d\n", MethodTableRestoreReasonDescription[TotalMethodTables], m_pNgenStats->MethodTableRestoreNumReasons[TotalMethodTables]); } } #ifdef _DEBUG // // We call these methods to seal the // lists: m_pAvailableClasses and m_pAvailableParamTypes // void Module::SealGenericTypesAndMethods() { LIMITED_METHOD_CONTRACT; // Enforce that after this point in ngen that no more types or methods will be loaded. // // We increment the seal count here and only decrement it after we have completed the ngen image // if (m_pAvailableParamTypes != NULL) { m_pAvailableParamTypes->Seal(); } if (m_pInstMethodHashTable != NULL) { m_pInstMethodHashTable->Seal(); } } // // We call these methods to unseal the // lists: m_pAvailableClasses and m_pAvailableParamTypes // void Module::UnsealGenericTypesAndMethods() { LIMITED_METHOD_CONTRACT; // Allow us to create generic types and methods again // // We only decrement it after we have completed the ngen image // if (m_pAvailableParamTypes != NULL) { m_pAvailableParamTypes->Unseal(); } if (m_pInstMethodHashTable != NULL) { m_pInstMethodHashTable->Unseal(); } } #endif void Module::PrepopulateDictionaries(DataImage *image, BOOL nonExpansive) { STANDARD_VM_CONTRACT; // Prepopulating the dictionaries for instantiated types // is in theory an iteraive process, i.e. filling in // a dictionary slot may result in a class load of a new type whose // dictionary may itself need to be prepopulated. The type expressions // involved can get larger, so there's no a-priori reason to expect this // process to terminate. // // Given a starting set of instantiated types, several strategies are // thus possible - no prepopulation (call this PP0), or // prepopulate only the dictionaries of the types that are in the initial // set (call this PP1), or do two iterations (call this PP2) etc. etc. // Whichever strategy we choose we can always afford to do // one round of prepopulation where we populate slots // whose corresponding resulting method/types are already loaded. // Call this PPn+PP-FINAL. // // Below we implement PP1+PP-FINAL for instantiated types and PP0+PP-FINAL // for instantiations of generic methods. We use PP1 because most collection // classes (List, Dictionary etc.) only require one pass of prepopulation in order // to fully prepopulate the dictionary. // Do PP1 for instantiated types... Do one iteration where we force type loading... // Because this phase may cause new entries to appear in the hash table we // copy the array of types to the stack before we do anything else. if (!nonExpansive && CLRConfig::GetConfigValue(CLRConfig::EXTERNAL_Prepopulate1)) { if (m_pAvailableParamTypes != NULL) { // Create a local copy in case the new elements are added to the hashtable during population InlineSArray<TypeHandle, 20> pTypes; EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle th = pEntry->GetTypeHandle(); if (th.IsTypeDesc()) continue; // Don't do prepopulation for open types - they shouldn't really have dictionaries anyway. MethodTable * pMT = th.AsMethodTable(); if (pMT->ContainsGenericVariables()) continue; // Only do PP1 on things that land in their preferred Zap module. // Forcing the load of dictionary entries in the case where we are // speculatively saving a copy of an instantiation outside its preferred // zap module is too expensive for the common collection class cases. /// // Invalid generic instantiations will not be fully loaded. // We want to ignore them as touching them will re-raise the TypeLoadException if (pMT->IsFullyLoaded() && image->GetModule() == GetPreferredZapModuleForMethodTable(pMT)) { pTypes.Append(th); } } it.Reset(); for(COUNT_T i = 0; i < pTypes.GetCount(); i ++) { TypeHandle th = pTypes[i]; _ASSERTE(image->GetModule() == GetPreferredZapModuleForTypeHandle(th) ); _ASSERTE(!th.IsTypeDesc() && !th.ContainsGenericVariables()); th.AsMethodTable()->PrepopulateDictionary(image, FALSE /* not nonExpansive, i.e. can load types */); } } } // PP-FINAL for instantiated types. // This is the final stage where we hardbind any remaining entries that map // to results that have already been loaded... // Thus we set the "nonExpansive" flag on PrepopulateDictionary // below, which may in turn greatly limit the amount of prepopulating we do // (partly because it's quite difficult to determine if some potential entries // in the dictionary are already loaded) if (m_pAvailableParamTypes != NULL) { INDEBUG(DWORD nTypes = m_pAvailableParamTypes->GetCount()); EETypeHashTable::Iterator it(m_pAvailableParamTypes); EETypeHashEntry *pEntry; while (m_pAvailableParamTypes->FindNext(&it, &pEntry)) { TypeHandle th = pEntry->GetTypeHandle(); if (th.IsTypeDesc()) continue; MethodTable * pMT = th.AsMethodTable(); if (pMT->ContainsGenericVariables()) continue; pMT->PrepopulateDictionary(image, TRUE /* nonExpansive */); } // No new instantiations should be added by nonExpansive prepopulation _ASSERTE(nTypes == m_pAvailableParamTypes->GetCount()); } // PP-FINAL for instantiations of generic methods. if (m_pInstMethodHashTable != NULL) { INDEBUG(DWORD nMethods = m_pInstMethodHashTable->GetCount()); InstMethodHashTable::Iterator it(m_pInstMethodHashTable); InstMethodHashEntry *pEntry; while (m_pInstMethodHashTable->FindNext(&it, &pEntry)) { MethodDesc *pMD = pEntry->GetMethod(); if (!pMD->ContainsGenericVariables()) { pMD->PrepopulateDictionary(image, TRUE /* nonExpansive */); } } // No new instantiations should be added by nonExpansive prepopulation _ASSERTE(nMethods == m_pInstMethodHashTable->GetCount()); } } void Module::PlaceType(DataImage *image, TypeHandle th, DWORD profilingFlags) { STANDARD_VM_CONTRACT; if (th.IsNull()) return; MethodTable *pMT = th.GetMethodTable(); if (pMT && pMT->GetLoaderModule() == this) { EEClass *pClass = pMT->GetClass(); if (profilingFlags & (1 << WriteMethodTableWriteableData)) { image->PlaceStructureForAddress(pMT->GetWriteableData(),CORCOMPILE_SECTION_WRITE); } if (profilingFlags & (1 << ReadMethodTable)) { CorCompileSection section = CORCOMPILE_SECTION_READONLY_HOT; if (pMT->IsWriteable()) section = CORCOMPILE_SECTION_HOT_WRITEABLE; image->PlaceStructureForAddress(pMT, section); if (pMT->HasInterfaceMap()) image->PlaceInternedStructureForAddress(pMT->GetInterfaceMap(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); MethodTable::VtableIndirectionSlotIterator it = pMT->IterateVtableIndirectionSlots(); while (it.Next()) { image->PlaceInternedStructureForAddress(it.GetIndirectionSlot(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); } image->PlaceStructureForAddress(pMT->GetWriteableData(), CORCOMPILE_SECTION_HOT); } if (profilingFlags & (1 << ReadNonVirtualSlots)) { if (pMT->HasNonVirtualSlotsArray()) image->PlaceStructureForAddress(pMT->GetNonVirtualSlotsArray(), CORCOMPILE_SECTION_READONLY_HOT); } if (profilingFlags & (1 << ReadDispatchMap) && pMT->HasDispatchMapSlot()) { image->PlaceInternedStructureForAddress(pMT->GetDispatchMap(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); } if (profilingFlags & (1 << WriteEEClass)) { image->PlaceStructureForAddress(pClass, CORCOMPILE_SECTION_WRITE); if (pClass->HasOptionalFields()) image->PlaceStructureForAddress(pClass->GetOptionalFields(), CORCOMPILE_SECTION_WRITE); } else if (profilingFlags & (1 << ReadEEClass)) { image->PlaceStructureForAddress(pClass, CORCOMPILE_SECTION_HOT); if (pClass->HasOptionalFields()) image->PlaceStructureForAddress(pClass->GetOptionalFields(), CORCOMPILE_SECTION_HOT); if (pClass->GetVarianceInfo() != NULL) image->PlaceInternedStructureForAddress(pClass->GetVarianceInfo(), CORCOMPILE_SECTION_READONLY_WARM, CORCOMPILE_SECTION_READONLY_WARM); #ifdef FEATURE_COMINTEROP if (pClass->GetSparseCOMInteropVTableMap() != NULL) { image->PlaceStructureForAddress(pClass->GetSparseCOMInteropVTableMap(), CORCOMPILE_SECTION_WARM); image->PlaceInternedStructureForAddress(pClass->GetSparseCOMInteropVTableMap()->GetMapList(), CORCOMPILE_SECTION_READONLY_WARM, CORCOMPILE_SECTION_READONLY_WARM); } #endif } if (profilingFlags & (1 << ReadFieldDescs)) { image->PlaceStructureForAddress(pMT->GetApproxFieldDescListRaw(), CORCOMPILE_SECTION_READONLY_HOT); } if (profilingFlags != 0) { if (pMT->HasPerInstInfo()) { DPTR(MethodTable::PerInstInfoElem_t) pPerInstInfo = pMT->GetPerInstInfo(); BOOL fIsEagerBound = pMT->CanEagerBindToParentDictionaries(image, NULL); if (fIsEagerBound) { if (MethodTable::PerInstInfoElem_t::isRelative) { image->PlaceStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_READONLY_HOT); } else { image->PlaceInternedStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); } } else { image->PlaceStructureForAddress(pPerInstInfo, CORCOMPILE_SECTION_WRITE); } } Dictionary * pDictionary = pMT->GetDictionary(); if (pDictionary != NULL) { BOOL fIsWriteable; if (!pMT->IsCanonicalMethodTable()) { // CanEagerBindToMethodTable would not work for targeted patching here. The dictionary // layout is sensitive to compilation order that can be changed by TP compatible changes. BOOL canSaveSlots = (image->GetModule() == pMT->GetCanonicalMethodTable()->GetLoaderModule()); fIsWriteable = pDictionary->IsWriteable(image, canSaveSlots, pMT->GetNumGenericArgs(), pMT->GetModule(), pClass->GetDictionaryLayout()); } else { fIsWriteable = FALSE; } if (fIsWriteable) { image->PlaceStructureForAddress(pDictionary, CORCOMPILE_SECTION_HOT_WRITEABLE); image->PlaceStructureForAddress(pClass->GetDictionaryLayout(), CORCOMPILE_SECTION_WARM); } else { image->PlaceInternedStructureForAddress(pDictionary, CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); } } } if (profilingFlags & (1 << ReadFieldMarshalers)) { if (pClass->HasLayout() && pClass->GetLayoutInfo()->GetNumCTMFields() > 0) { image->PlaceStructureForAddress((void *)pClass->GetLayoutInfo()->GetFieldMarshalers(), CORCOMPILE_SECTION_HOT); } } } if (th.IsTypeDesc()) { if (profilingFlags & (1 << WriteTypeDesc)) image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_WRITE); else if (profilingFlags & (1 << ReadTypeDesc)) image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_HOT); else image->PlaceStructureForAddress(th.AsTypeDesc(), CORCOMPILE_SECTION_WARM); } } void Module::PlaceMethod(DataImage *image, MethodDesc *pMD, DWORD profilingFlags) { STANDARD_VM_CONTRACT; if (pMD == NULL) return; if (pMD->GetLoaderModule() != this) return; if (profilingFlags & (1 << ReadMethodCode)) { if (pMD->IsNDirect()) { NDirectMethodDesc *pNMD = (NDirectMethodDesc *)pMD; image->PlaceStructureForAddress((void*) pNMD->GetWriteableData(), CORCOMPILE_SECTION_WRITE); #ifdef HAS_NDIRECT_IMPORT_PRECODE // The NDirect import thunk glue is used only if no marshaling is required if (!pNMD->MarshalingRequired()) { image->PlaceStructureForAddress((void*) pNMD->GetNDirectImportThunkGlue(), CORCOMPILE_SECTION_METHOD_PRECODE_HOT); } #endif // HAS_NDIRECT_IMPORT_PRECODE // Late bound NDirect methods require their LibName at startup. if (!pNMD->IsQCall()) { image->PlaceStructureForAddress((void*) pNMD->GetLibName(), CORCOMPILE_SECTION_READONLY_HOT); image->PlaceStructureForAddress((void*) pNMD->GetEntrypointName(), CORCOMPILE_SECTION_READONLY_HOT); } } #ifdef FEATURE_COMINTEROP if (pMD->IsComPlusCall()) { ComPlusCallMethodDesc *pCMD = (ComPlusCallMethodDesc *)pMD; // If the ComPlusCallMethodDesc was actually used for interop, its ComPlusCallInfo should be hot. image->PlaceStructureForAddress((void*) pCMD->m_pComPlusCallInfo, CORCOMPILE_SECTION_HOT); } #endif // FEATURE_COMINTEROP // Stubs-as-IL have writeable signatures sometimes, so can't place them // into read-only section. We should not get here for stubs-as-il anyway, // but we will filter them out just to be sure. if (pMD->HasStoredSig() && !pMD->IsILStub()) { StoredSigMethodDesc *pSMD = (StoredSigMethodDesc*) pMD; if (pSMD->HasStoredMethodSig()) { image->PlaceInternedStructureForAddress((void*) pSMD->GetStoredMethodSig(), CORCOMPILE_SECTION_READONLY_SHARED_HOT, CORCOMPILE_SECTION_READONLY_HOT); } } } // We store the entire hot chunk in the SECTION_WRITE section if (profilingFlags & (1 << WriteMethodDesc)) { image->PlaceStructureForAddress(pMD, CORCOMPILE_SECTION_WRITE); } if (profilingFlags & (1 << WriteMethodPrecode)) { Precode* pPrecode = pMD->GetSavedPrecodeOrNull(image); // protect against stale IBC data if (pPrecode != NULL) { CorCompileSection section = CORCOMPILE_SECTION_METHOD_PRECODE_WRITE; if (pPrecode->IsPrebound(image)) section = CORCOMPILE_SECTION_METHOD_PRECODE_HOT; // Note: This is going to place the entire PRECODE_FIXUP chunk if we have one image->PlaceStructureForAddress(pPrecode, section); } } else if (profilingFlags & (1 << ReadMethodPrecode)) { Precode* pPrecode = pMD->GetSavedPrecodeOrNull(image); // protect against stale IBC data if (pPrecode != NULL) { // Note: This is going to place the entire PRECODE_FIXUP chunk if we have one image->PlaceStructureForAddress(pPrecode, CORCOMPILE_SECTION_METHOD_PRECODE_HOT); } } } void Module::Arrange(DataImage *image) { STANDARD_VM_CONTRACT; // We collect IBC logging profiling data and use that to guide the layout of the image. image->PlaceStructureForAddress(this, CORCOMPILE_SECTION_MODULE); // The stub method table is shared by all IL stubs in the module, so place it into the hot section MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable(); if (pStubMT != NULL) PlaceType(image, pStubMT, ReadMethodTable); CorProfileData * profileData = GetProfileData(); if (profileData) { // // Place hot type structues in the order specifiled by TypeProfilingData array // CORBBTPROF_TOKEN_INFO * pTypeProfilingData = profileData->GetTokenFlagsData(TypeProfilingData); DWORD cTypeProfilingData = profileData->GetTokenFlagsCount(TypeProfilingData); for (unsigned int i = 0; (i < cTypeProfilingData); i++) { CORBBTPROF_TOKEN_INFO * entry = &pTypeProfilingData[i]; mdToken token = entry->token; DWORD flags = entry->flags; #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_6); #endif if (TypeFromToken(token) == mdtTypeDef) { TypeHandle th = LookupTypeDef(token); // // Place a hot normal type and it's data // PlaceType(image, th, flags); } else if (TypeFromToken(token) == ibcTypeSpec) { CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token); if (pBlobSigEntry == NULL) { // // Print an error message for the type load failure // StackSString msg(W("Did not find definition for type token ")); char buff[16]; sprintf_s(buff, COUNTOF(buff), "%08x", token); StackSString szToken(SString::Ascii, &buff[0]); msg += szToken; msg += W(" in profile data.\n"); GetSvcLogger()->Log(msg, LogLevel_Info); } else // (pBlobSigEntry != NULL) { _ASSERTE(pBlobSigEntry->blob.token == token); // // decode generic type signature // TypeHandle th = LoadIBCTypeHelper(image, pBlobSigEntry); // // Place a hot instantiated type and it's data // PlaceType(image, th, flags); } } else if (TypeFromToken(token) == mdtFieldDef) { FieldDesc *pFD = LookupFieldDef(token); if (pFD && pFD->IsRVA()) { if (entry->flags & (1 << RVAFieldData)) { BYTE *pRVAData = (BYTE*) pFD->GetStaticAddressHandle(NULL); // // Place a hot RVA static field // image->PlaceStructureForAddress(pRVAData, CORCOMPILE_SECTION_RVA_STATICS_HOT); } } } } // // Place hot methods and method data in the order specifiled by MethodProfilingData array // CORBBTPROF_TOKEN_INFO * pMethodProfilingData = profileData->GetTokenFlagsData(MethodProfilingData); DWORD cMethodProfilingData = profileData->GetTokenFlagsCount(MethodProfilingData); for (unsigned int i = 0; (i < cMethodProfilingData); i++) { mdToken token = pMethodProfilingData[i].token; DWORD profilingFlags = pMethodProfilingData[i].flags; #if defined(_DEBUG) && !defined(DACCESS_COMPILE) g_pConfig->DebugCheckAndForceIBCFailure(EEConfig::CallSite_7); #endif if (TypeFromToken(token) == mdtMethodDef) { MethodDesc * pMD = LookupMethodDef(token); // // Place a hot normal method and it's data // PlaceMethod(image, pMD, profilingFlags); } else if (TypeFromToken(token) == ibcMethodSpec) { CORBBTPROF_BLOB_PARAM_SIG_ENTRY *pBlobSigEntry = profileData->GetBlobSigEntry(token); if (pBlobSigEntry == NULL) { // // Print an error message for the type load failure // StackSString msg(W("Did not find definition for method token ")); char buff[16]; sprintf_s(buff, COUNTOF(buff), "%08x", token); StackSString szToken(SString::Ascii, &buff[0]); msg += szToken; msg += W(" in profile data.\n"); GetSvcLogger()->Log(msg, LogLevel_Info); } else // (pBlobSigEntry != NULL) { _ASSERTE(pBlobSigEntry->blob.token == token); MethodDesc * pMD = LoadIBCMethodHelper(image, pBlobSigEntry); if (pMD != NULL) { // // Place a hot instantiated method and it's data // PlaceMethod(image, pMD, profilingFlags); } } } } } // Now place all remaining items image->PlaceRemainingStructures(); } void ModuleCtorInfo::Fixup(DataImage *image) { STANDARD_VM_CONTRACT; if (numElementsHot > 0) { image->FixupPointerField(this, offsetof(ModuleCtorInfo, cctorInfoHot)); image->FixupPointerField(this, offsetof(ModuleCtorInfo, hotHashOffsets)); } else { image->ZeroPointerField(this, offsetof(ModuleCtorInfo, cctorInfoHot)); image->ZeroPointerField(this, offsetof(ModuleCtorInfo, hotHashOffsets)); } _ASSERTE(numElements > numElementsHot || numElements == numElementsHot); if (numElements > numElementsHot) { image->FixupPointerField(this, offsetof(ModuleCtorInfo, cctorInfoCold)); image->FixupPointerField(this, offsetof(ModuleCtorInfo, coldHashOffsets)); } else { image->ZeroPointerField(this, offsetof(ModuleCtorInfo, cctorInfoCold)); image->ZeroPointerField(this, offsetof(ModuleCtorInfo, coldHashOffsets)); } if (numElements > 0) { image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppMT)); for (DWORD i=0; i<numElements; i++) { image->FixupRelativePointerField(ppMT, i * sizeof(ppMT[0])); } } else { image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppMT)); } if (numHotGCStaticsMTs > 0) { image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppHotGCStaticsMTs)); image->BeginRegion(CORINFO_REGION_HOT); for (DWORD i=0; i < numHotGCStaticsMTs; i++) { image->FixupMethodTablePointer(ppHotGCStaticsMTs, &ppHotGCStaticsMTs[i]); } image->EndRegion(CORINFO_REGION_HOT); } else { image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppHotGCStaticsMTs)); } if (numColdGCStaticsMTs > 0) { image->FixupPointerField(this, offsetof(ModuleCtorInfo, ppColdGCStaticsMTs)); image->BeginRegion(CORINFO_REGION_COLD); for (DWORD i=0; i < numColdGCStaticsMTs; i++) { image->FixupMethodTablePointer(ppColdGCStaticsMTs, &ppColdGCStaticsMTs[i]); } image->EndRegion(CORINFO_REGION_COLD); } else { image->ZeroPointerField(this, offsetof(ModuleCtorInfo, ppColdGCStaticsMTs)); } } #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif void Module::Fixup(DataImage *image) { STANDARD_VM_CONTRACT; // Propagate all changes to the image copy memcpy(image->GetImagePointer(this), (void*)this, sizeof(Module)); // // Zero out VTable // image->ZeroPointerField(this, 0); image->FixupPointerField(this, offsetof(Module, m_pNGenLayoutInfo)); image->ZeroField(this, offsetof(Module, m_pSimpleName), sizeof(m_pSimpleName)); image->ZeroField(this, offsetof(Module, m_file), sizeof(m_file)); image->FixupPointerField(this, offsetof(Module, m_pDllMain)); image->ZeroField(this, offsetof(Module, m_dwTransientFlags), sizeof(m_dwTransientFlags)); image->ZeroField(this, offsetof(Module, m_pVASigCookieBlock), sizeof(m_pVASigCookieBlock)); image->ZeroField(this, offsetof(Module, m_pAssembly), sizeof(m_pAssembly)); image->ZeroField(this, offsetof(Module, m_moduleRef), sizeof(m_moduleRef)); image->ZeroField(this, offsetof(Module, m_Crst), sizeof(m_Crst)); image->ZeroField(this, offsetof(Module, m_FixupCrst), sizeof(m_FixupCrst)); image->ZeroField(this, offsetof(Module, m_pProfilingBlobTable), sizeof(m_pProfilingBlobTable)); image->ZeroField(this, offsetof(Module, m_pProfileData), sizeof(m_pProfileData)); image->ZeroPointerField(this, offsetof(Module, m_pNgenStats)); // fixup the pointer for NeutralResourcesLanguage, if we have it cached if(!!(m_dwPersistedFlags & NEUTRAL_RESOURCES_LANGUAGE_IS_CACHED)) { image->FixupPointerField(this, offsetof(Module, m_pszCultureName)); } // Fixup the property name set image->FixupPointerField(this, offsetof(Module, m_propertyNameSet)); // // Fixup the method table // image->ZeroField(this, offsetof(Module, m_pISymUnmanagedReader), sizeof(m_pISymUnmanagedReader)); image->ZeroField(this, offsetof(Module, m_ISymUnmanagedReaderCrst), sizeof(m_ISymUnmanagedReaderCrst)); // Clear active dependencies - they will be refilled at load time image->ZeroField(this, offsetof(Module, m_activeDependencies), sizeof(m_activeDependencies)); new (image->GetImagePointer(this, offsetof(Module, m_unconditionalDependencies))) SynchronizedBitMask(); image->ZeroField(this, offsetof(Module, m_unconditionalDependencies) + offsetof(SynchronizedBitMask, m_bitMaskLock) + offsetof(SimpleRWLock,m_spinCount), sizeof(m_unconditionalDependencies.m_bitMaskLock.m_spinCount)); image->ZeroField(this, offsetof(Module, m_dwNumberOfActivations), sizeof(m_dwNumberOfActivations)); image->ZeroField(this, offsetof(Module, m_LookupTableCrst), sizeof(m_LookupTableCrst)); m_TypeDefToMethodTableMap.Fixup(image); m_TypeRefToMethodTableMap.Fixup(image, FALSE); m_MethodDefToDescMap.Fixup(image); m_FieldDefToDescMap.Fixup(image); if(m_pMemberRefToDescHashTable != NULL) { image->FixupPointerField(this, offsetof(Module, m_pMemberRefToDescHashTable)); m_pMemberRefToDescHashTable->Fixup(image); } m_GenericParamToDescMap.Fixup(image); m_GenericTypeDefToCanonMethodTableMap.Fixup(image); m_FileReferencesMap.Fixup(image, FALSE); m_ManifestModuleReferencesMap.Fixup(image, FALSE); m_MethodDefToPropertyInfoMap.Fixup(image, FALSE); image->ZeroPointerField(this, offsetof(Module, m_pILStubCache)); if (m_pAvailableClasses != NULL) { image->FixupPointerField(this, offsetof(Module, m_pAvailableClasses)); m_pAvailableClasses->Fixup(image); } image->ZeroField(this, offsetof(Module, m_pAvailableClassesCaseIns), sizeof(m_pAvailableClassesCaseIns)); image->ZeroField(this, offsetof(Module, m_InstMethodHashTableCrst), sizeof(m_InstMethodHashTableCrst)); image->BeginRegion(CORINFO_REGION_COLD); if (m_pAvailableParamTypes) { image->FixupPointerField(this, offsetof(Module, m_pAvailableParamTypes)); m_pAvailableParamTypes->Fixup(image); } if (m_pInstMethodHashTable) { image->FixupPointerField(this, offsetof(Module, m_pInstMethodHashTable)); m_pInstMethodHashTable->Fixup(image); } { MethodTable * pStubMT = GetILStubCache()->GetStubMethodTable(); if (pStubMT != NULL) pStubMT->Fixup(image); } if (m_pStubMethodHashTable) { image->FixupPointerField(this, offsetof(Module, m_pStubMethodHashTable)); m_pStubMethodHashTable->Fixup(image); } #ifdef FEATURE_COMINTEROP if (m_pGuidToTypeHash) { image->FixupPointerField(this, offsetof(Module, m_pGuidToTypeHash)); m_pGuidToTypeHash->Fixup(image); } #endif // FEATURE_COMINTEROP image->EndRegion(CORINFO_REGION_COLD); #ifdef _DEBUG // // Unseal the generic tables: // // - We need to run managed code to serialize the Security attributes of the ngen image // and we are now using generic types in the Security/Reflection code. // - Compilation of other modules of multimodule assemblies may add more types // to the generic tables. // UnsealGenericTypesAndMethods(); #endif m_ModuleCtorInfo.Fixup(image); // // Fixup binder // if (m_pBinder != NULL) { image->FixupPointerField(this, offsetof(Module, m_pBinder)); m_pBinder->Fixup(image); } // // Fixup classes // { LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); image->BeginRegion(CORINFO_REGION_COLD); while (typeDefIter.Next()) { MethodTable * t = typeDefIter.GetElement(); if (image->IsStored(t)) t->Fixup(image); } image->EndRegion(CORINFO_REGION_COLD); } { LookupMap<PTR_TypeRef>::Iterator typeRefIter(&m_TypeRefToMethodTableMap); DWORD rid = 0; image->BeginRegion(CORINFO_REGION_HOT); while (typeRefIter.Next()) { TADDR flags; TypeHandle th = TypeHandle::FromTAddr(dac_cast<TADDR>(typeRefIter.GetElementAndFlags(&flags))); if (!th.IsNull()) { if (th.GetLoaderModule() != this || image->IsStored(th.AsPtr())) { PTR_TADDR hotItemValuePtr = m_TypeRefToMethodTableMap.FindHotItemValuePtr(rid); BOOL fSet = FALSE; if (image->CanEagerBindToTypeHandle(th)) { if (image->CanHardBindToZapModule(th.GetLoaderModule())) { PVOID pTarget = th.IsTypeDesc() ? th.AsTypeDesc() : th.AsPtr(); SSIZE_T offset = th.IsTypeDesc() ? 2 : 0; _ASSERTE((flags & offset) == 0); image->FixupField(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR), pTarget, flags | offset, IMAGE_REL_BASED_RelativePointer); // In case this item is also in the hot item subtable, fix it up there as well if (hotItemValuePtr != NULL) { image->FixupField(m_TypeRefToMethodTableMap.hotItemList, (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList, pTarget, flags | offset, IMAGE_REL_BASED_RelativePointer); } fSet = TRUE; } else // Create the indirection only if the entry is hot or we do have indirection cell already if (hotItemValuePtr != NULL || image->GetExistingTypeHandleImport(th) != NULL) { _ASSERTE((flags & FIXUP_POINTER_INDIRECTION) == 0); ZapNode * pImport = image->GetTypeHandleImport(th); image->FixupFieldToNode(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR), pImport, flags | FIXUP_POINTER_INDIRECTION, IMAGE_REL_BASED_RelativePointer); if (hotItemValuePtr != NULL) { image->FixupFieldToNode(m_TypeRefToMethodTableMap.hotItemList, (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList, pImport, flags | FIXUP_POINTER_INDIRECTION, IMAGE_REL_BASED_RelativePointer); } fSet = TRUE; } } if (!fSet) { image->ZeroPointerField(m_TypeRefToMethodTableMap.pTable, rid * sizeof(TADDR)); // In case this item is also in the hot item subtable, fix it up there as well if (hotItemValuePtr != NULL) { image->ZeroPointerField(m_TypeRefToMethodTableMap.hotItemList, (BYTE *)hotItemValuePtr - (BYTE *)m_TypeRefToMethodTableMap.hotItemList); } } } } rid++; } image->EndRegion(CORINFO_REGION_HOT); } { LookupMap<PTR_TypeVarTypeDesc>::Iterator genericParamIter(&m_GenericParamToDescMap); while (genericParamIter.Next()) { TypeVarTypeDesc * pTypeDesc = genericParamIter.GetElement(); if (pTypeDesc != NULL) { _ASSERTE(image->IsStored(pTypeDesc)); pTypeDesc->Fixup(image); } } } // // Fixup the assembly reference map table // { LookupMap<PTR_Module>::Iterator manifestModuleIter(&m_ManifestModuleReferencesMap); DWORD rid = 0; while (manifestModuleIter.Next()) { TADDR flags; Module * pModule = manifestModuleIter.GetElementAndFlags(&flags); if (pModule != NULL) { if (image->CanEagerBindToModule(pModule)) { if (image->CanHardBindToZapModule(pModule)) { image->FixupField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR), pModule, flags, IMAGE_REL_BASED_RelativePointer); } else { image->ZeroPointerField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR)); } } else { image->ZeroPointerField(m_ManifestModuleReferencesMap.pTable, rid * sizeof(TADDR)); } } rid++; } } // // Zero out file references table. // image->ZeroField(m_FileReferencesMap.pTable, 0, m_FileReferencesMap.GetSize() * sizeof(void*)); image->ZeroField(this, offsetof(Module, m_debuggerSpecificData), sizeof(m_debuggerSpecificData)); image->ZeroField(this, offsetof(Module, m_AssemblyRefByNameCount), sizeof(m_AssemblyRefByNameCount)); image->ZeroPointerField(this, offsetof(Module, m_AssemblyRefByNameTable)); image->ZeroPointerField(this,offsetof(Module, m_NativeMetadataAssemblyRefMap)); // // Fixup statics // LOG((LF_CLASSLOADER, LL_INFO10000, "STATICS: fixing up module static data\n")); image->ZeroPointerField(this, offsetof(Module, m_ModuleID)); image->ZeroField(this, offsetof(Module, m_ModuleIndex), sizeof(m_ModuleIndex)); image->FixupPointerField(this, offsetof(Module, m_pDynamicStaticsInfo)); DynamicStaticsInfo* pDSI = m_pDynamicStaticsInfo; for (DWORD i = 0; i < m_cDynamicEntries; i++, pDSI++) { if (pDSI->pEnclosingMT->GetLoaderModule() == this && // CEEPreloader::TriageTypeForZap() could have rejected this type image->IsStored(pDSI->pEnclosingMT)) { image->FixupPointerField(m_pDynamicStaticsInfo, (BYTE *)&pDSI->pEnclosingMT - (BYTE *)m_pDynamicStaticsInfo); } else { // Some other (mutually-recursive) dependency must have loaded // a generic instantiation whose static were pumped into the // assembly being ngenned. image->ZeroPointerField(m_pDynamicStaticsInfo, (BYTE *)&pDSI->pEnclosingMT - (BYTE *)m_pDynamicStaticsInfo); } } // If we failed to load some types we need to reset the pointers to the static offset tables so they'll be // rebuilt at runtime. if (m_pRegularStaticOffsets != (PTR_DWORD)NGEN_STATICS_ALLCLASSES_WERE_LOADED) { _ASSERTE(m_pThreadStaticOffsets != (PTR_DWORD)NGEN_STATICS_ALLCLASSES_WERE_LOADED); image->ZeroPointerField(this, offsetof(Module, m_pRegularStaticOffsets)); image->ZeroPointerField(this, offsetof(Module, m_pThreadStaticOffsets)); } // Fix up inlining data if(m_pPersistentInlineTrackingMapNGen) { image->FixupPointerField(this, offsetof(Module, m_pPersistentInlineTrackingMapNGen)); m_pPersistentInlineTrackingMapNGen->Fixup(image); } else { image->ZeroPointerField(this, offsetof(Module, m_pPersistentInlineTrackingMapNGen)); } SetIsModuleSaved(); } #ifdef _PREFAST_ #pragma warning(pop) #endif #endif // FEATURE_NATIVE_IMAGE_GENERATION #ifdef FEATURE_PREJIT // // Is "address" a data-structure in the native image? // BOOL Module::IsPersistedObject(void *address) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; } CONTRACTL_END; if (!HasNativeImage()) return FALSE; PEImageLayout *pLayout = GetNativeImage(); _ASSERTE(pLayout->IsMapped()); return (address >= pLayout->GetBase() && address < (BYTE*)pLayout->GetBase() + pLayout->GetVirtualSize()); } Module *Module::GetModuleFromIndex(DWORD ix) { CONTRACT(Module*) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; if (HasNativeImage()) { PRECONDITION(GetNativeImage()->CheckNativeImportFromIndex(ix)); CORCOMPILE_IMPORT_TABLE_ENTRY *p = GetNativeImage()->GetNativeImportFromIndex(ix); RETURN ZapSig::DecodeModuleFromIndexes(this, p->wAssemblyRid, p->wModuleRid); } else { mdAssemblyRef mdAssemblyRefToken = TokenFromRid(ix, mdtAssemblyRef); Assembly *pAssembly = this->LookupAssemblyRef(mdAssemblyRefToken); if (pAssembly) { RETURN pAssembly->GetManifestModule(); } else { // GetModuleFromIndex failed RETURN NULL; } } } #endif // FEATURE_PREJIT #endif // !DACCESS_COMPILE #ifdef FEATURE_PREJIT Module *Module::GetModuleFromIndexIfLoaded(DWORD ix) { CONTRACT(Module*) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(HasNativeImage()); PRECONDITION(GetNativeImage()->CheckNativeImportFromIndex(ix)); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; #ifndef DACCESS_COMPILE CORCOMPILE_IMPORT_TABLE_ENTRY *p = GetNativeImage()->GetNativeImportFromIndex(ix); RETURN ZapSig::DecodeModuleFromIndexesIfLoaded(this, p->wAssemblyRid, p->wModuleRid); #else // DACCESS_COMPILE DacNotImpl(); RETURN NULL; #endif // DACCESS_COMPILE } #ifndef DACCESS_COMPILE BYTE *Module::GetNativeFixupBlobData(RVA rva) { CONTRACT(BYTE *) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_TOLERANT; POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END; RETURN (BYTE *) GetNativeOrReadyToRunImage()->GetRvaData(rva); } IMDInternalImport *Module::GetNativeAssemblyImport(BOOL loadAllowed) { CONTRACT(IMDInternalImport *) { INSTANCE_CHECK; if (loadAllowed) GC_TRIGGERS; else GC_NOTRIGGER; if (loadAllowed) THROWS; else NOTHROW; if (loadAllowed) INJECT_FAULT(COMPlusThrowOM()); else FORBID_FAULT; MODE_ANY; PRECONDITION(HasNativeImage()); POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END; RETURN GetFile()->GetPersistentNativeImage()->GetNativeMDImport(loadAllowed); } /*static*/ void Module::RestoreMethodTablePointerRaw(MethodTable ** ppMT, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; // Ensure that the compiler won't fetch the value twice TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppMT); #ifdef _DEBUG if (pContainingModule != NULL) { Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMT)); _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule)); } #endif //_DEBUG if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); if (pContainingModule == NULL) pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMT)); PREFIX_ASSUME(pContainingModule != NULL); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_TYPE_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule); TypeHandle th = ZapSig::DecodeType(pContainingModule, pInfoModule, pBlobData, level); *EnsureWritablePages(ppMT) = th.AsMethodTable(); } else if (*ppMT) { ClassLoader::EnsureLoaded(*ppMT, level); } } /*static*/ void Module::RestoreMethodTablePointer(FixupPointer<PTR_MethodTable> * ppMT, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (ppMT->IsNull()) return; if (ppMT->IsTagged()) { RestoreMethodTablePointerRaw(ppMT->GetValuePtr(), pContainingModule, level); } else { ClassLoader::EnsureLoaded(ppMT->GetValue(), level); } } /*static*/ void Module::RestoreMethodTablePointer(RelativeFixupPointer<PTR_MethodTable> * ppMT, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (ppMT->IsNull()) return; if (ppMT->IsTagged((TADDR)ppMT)) { RestoreMethodTablePointerRaw(ppMT->GetValuePtr(), pContainingModule, level); } else { ClassLoader::EnsureLoaded(ppMT->GetValue(), level); } } #endif // !DACCESS_COMPILE BOOL Module::IsZappedCode(PCODE code) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SO_TOLERANT; SUPPORTS_DAC; } CONTRACTL_END; if (!HasNativeImage()) return FALSE; PEImageLayout *pNativeImage = GetNativeImage(); UINT32 cCode = 0; PCODE pCodeSection; pCodeSection = pNativeImage->GetNativeHotCode(&cCode); if ((pCodeSection <= code) && (code < pCodeSection + cCode)) { return TRUE; } pCodeSection = pNativeImage->GetNativeCode(&cCode); if ((pCodeSection <= code) && (code < pCodeSection + cCode)) { return TRUE; } return FALSE; } BOOL Module::IsZappedPrecode(PCODE code) { CONTRACTL { NOTHROW; GC_NOTRIGGER; SUPPORTS_DAC; SO_TOLERANT; } CONTRACTL_END; if (m_pNGenLayoutInfo == NULL) return FALSE; for (SIZE_T i = 0; i < COUNTOF(m_pNGenLayoutInfo->m_Precodes); i++) { if (m_pNGenLayoutInfo->m_Precodes[i].IsInRange(code)) return TRUE; } return FALSE; } PCCOR_SIGNATURE Module::GetEncodedSig(RVA fixupRva, Module **ppDefiningModule) { CONTRACT(PCCOR_SIGNATURE) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; SO_INTOLERANT; POSTCONDITION(CheckPointer(RETVAL)); SUPPORTS_DAC; } CONTRACT_END; #ifndef DACCESS_COMPILE PCCOR_SIGNATURE pBuffer = GetNativeFixupBlobData(fixupRva); BYTE kind = *pBuffer++; *ppDefiningModule = (kind & ENCODE_MODULE_OVERRIDE) ? GetModuleFromIndex(CorSigUncompressData(pBuffer)) : this; RETURN pBuffer; #else RETURN NULL; #endif // DACCESS_COMPILE } PCCOR_SIGNATURE Module::GetEncodedSigIfLoaded(RVA fixupRva, Module **ppDefiningModule) { CONTRACT(PCCOR_SIGNATURE) { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; SO_INTOLERANT; POSTCONDITION(CheckPointer(RETVAL)); SUPPORTS_DAC; } CONTRACT_END; #ifndef DACCESS_COMPILE PCCOR_SIGNATURE pBuffer = GetNativeFixupBlobData(fixupRva); BYTE kind = *pBuffer++; *ppDefiningModule = (kind & ENCODE_MODULE_OVERRIDE) ? GetModuleFromIndexIfLoaded(CorSigUncompressData(pBuffer)) : this; RETURN pBuffer; #else *ppDefiningModule = NULL; RETURN NULL; #endif // DACCESS_COMPILE } /*static*/ PTR_Module Module::RestoreModulePointerIfLoaded(DPTR(RelativeFixupPointer<PTR_Module>) ppModule, Module *pContainingModule) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; SUPPORTS_DAC; } CONTRACTL_END; if (!ppModule->IsTagged(dac_cast<TADDR>(ppModule))) return ppModule->GetValue(dac_cast<TADDR>(ppModule)); #ifndef DACCESS_COMPILE PTR_Module * ppValue = ppModule->GetValuePtr(); // Ensure that the compiler won't fetch the value twice TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue); if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_MODULE_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSigIfLoaded(fixupRva, &pInfoModule); if (pInfoModule) { if (EnsureWritablePagesNoThrow(ppValue, sizeof(*ppValue))) *ppValue = pInfoModule; } return pInfoModule; } else { return PTR_Module(fixup); } #else DacNotImpl(); return NULL; #endif } #ifndef DACCESS_COMPILE /*static*/ void Module::RestoreModulePointer(RelativeFixupPointer<PTR_Module> * ppModule, Module *pContainingModule) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; if (!ppModule->IsTagged((TADDR)ppModule)) return; PTR_Module * ppValue = ppModule->GetValuePtr(); // Ensure that the compiler won't fetch the value twice TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue); if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_MODULE_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule); *EnsureWritablePages(ppValue) = pInfoModule; } } /*static*/ void Module::RestoreTypeHandlePointerRaw(TypeHandle *pHandle, Module* pContainingModule, ClassLoadLevel level) { CONTRACTL { if (FORBIDGC_LOADER_USE_ENABLED()) NOTHROW; else THROWS; if (FORBIDGC_LOADER_USE_ENABLED()) GC_NOTRIGGER; else GC_TRIGGERS; if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else {INJECT_FAULT(COMPlusThrowOM(););} MODE_ANY; } CONTRACTL_END; #ifdef _DEBUG if (pContainingModule != NULL) { Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle)); _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule)); } #endif //_DEBUG TADDR fixup; if (IS_ALIGNED(pHandle, sizeof(TypeHandle))) { // Ensure that the compiler won't fetch the value twice fixup = VolatileLoadWithoutBarrier((TADDR *)pHandle); } else { // This is necessary to handle in-place fixups (see by FixupTypeHandlePointerInplace) // in stubs-as-il signatures. // // protect this unaligned read with the Module Crst for the rare case that // the TypeHandle to fixup is in a signature and unaligned. // if (NULL == pContainingModule) { pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle)); } CrstHolder ch(&pContainingModule->m_Crst); fixup = *(TADDR UNALIGNED *)pHandle; } if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); if (NULL == pContainingModule) { pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(pHandle)); } PREFIX_ASSUME(pContainingModule != NULL); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_TYPE_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule); TypeHandle thResolved = ZapSig::DecodeType(pContainingModule, pInfoModule, pBlobData, level); EnsureWritablePages(pHandle); if (IS_ALIGNED(pHandle, sizeof(TypeHandle))) { *pHandle = thResolved; } else { // // protect this unaligned write with the Module Crst for the rare case that // the TypeHandle to fixup is in a signature and unaligned. // CrstHolder ch(&pContainingModule->m_Crst); *(TypeHandle UNALIGNED *)pHandle = thResolved; } } else if (fixup != NULL) { ClassLoader::EnsureLoaded(TypeHandle::FromTAddr(fixup), level); } } /*static*/ void Module::RestoreTypeHandlePointer(FixupPointer<TypeHandle> * pHandle, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (pHandle->IsNull()) return; if (pHandle->IsTagged()) { RestoreTypeHandlePointerRaw(pHandle->GetValuePtr(), pContainingModule, level); } else { ClassLoader::EnsureLoaded(pHandle->GetValue(), level); } } /*static*/ void Module::RestoreTypeHandlePointer(RelativeFixupPointer<TypeHandle> * pHandle, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (pHandle->IsNull()) return; if (pHandle->IsTagged((TADDR)pHandle)) { RestoreTypeHandlePointerRaw(pHandle->GetValuePtr(), pContainingModule, level); } else { ClassLoader::EnsureLoaded(pHandle->GetValue((TADDR)pHandle), level); } } /*static*/ void Module::RestoreMethodDescPointerRaw(PTR_MethodDesc * ppMD, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; // Ensure that the compiler won't fetch the value twice TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppMD); #ifdef _DEBUG if (pContainingModule != NULL) { Module * dbg_pZapModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMD)); _ASSERTE((dbg_pZapModule == NULL) || (pContainingModule == dbg_pZapModule)); } #endif //_DEBUG if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { GCX_PREEMP(); #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); if (pContainingModule == NULL) pContainingModule = ExecutionManager::FindZapModule(dac_cast<TADDR>(ppMD)); PREFIX_ASSUME(pContainingModule != NULL); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_METHOD_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule); *EnsureWritablePages(ppMD) = ZapSig::DecodeMethod(pContainingModule, pInfoModule, pBlobData); } else if (*ppMD) { (*ppMD)->CheckRestore(level); } } /*static*/ void Module::RestoreMethodDescPointer(FixupPointer<PTR_MethodDesc> * ppMD, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (ppMD->IsNull()) return; if (ppMD->IsTagged()) { RestoreMethodDescPointerRaw(ppMD->GetValuePtr(), pContainingModule, level); } else { ppMD->GetValue()->CheckRestore(level); } } /*static*/ void Module::RestoreMethodDescPointer(RelativeFixupPointer<PTR_MethodDesc> * ppMD, Module *pContainingModule, ClassLoadLevel level) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (ppMD->IsNull()) return; if (ppMD->IsTagged((TADDR)ppMD)) { RestoreMethodDescPointerRaw(ppMD->GetValuePtr(), pContainingModule, level); } else { ppMD->GetValue((TADDR)ppMD)->CheckRestore(level); } } /*static*/ void Module::RestoreFieldDescPointer(RelativeFixupPointer<PTR_FieldDesc> * ppFD) { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; if (!ppFD->IsTagged()) return; PTR_FieldDesc * ppValue = ppFD->GetValuePtr(); // Ensure that the compiler won't fetch the value twice TADDR fixup = VolatileLoadWithoutBarrier((TADDR *)ppValue); if (CORCOMPILE_IS_POINTER_TAGGED(fixup)) { #ifdef _WIN64 CONSISTENCY_CHECK((CORCOMPILE_UNTAG_TOKEN(fixup)>>32) == 0); #endif Module * pContainingModule = ExecutionManager::FindZapModule((TADDR)ppValue); PREFIX_ASSUME(pContainingModule != NULL); RVA fixupRva = (RVA) CORCOMPILE_UNTAG_TOKEN(fixup); _ASSERTE((*pContainingModule->GetNativeFixupBlobData(fixupRva) & ~ENCODE_MODULE_OVERRIDE) == ENCODE_FIELD_HANDLE); Module * pInfoModule; PCCOR_SIGNATURE pBlobData = pContainingModule->GetEncodedSig(fixupRva, &pInfoModule); *EnsureWritablePages(ppValue) = ZapSig::DecodeField(pContainingModule, pInfoModule, pBlobData); } } //----------------------------------------------------------------------------- #if 0 This diagram illustrates the layout of fixups in the ngen image. This is the case where function foo2 has a class-restore fixup for class C1 in b.dll. zapBase+curTableVA+rva / FixupList (see Fixup Encoding below) m_pFixupBlobs +-------------------+ pEntry->VA +--------------------+ | non-NULL | foo1 |Handles | +-------------------+ ZapHeader.ImportTable | | | non-NULL | | | +-------------------+ +------------+ +--------------------+ | non-NULL | |a.dll | |Class cctors |<---+ +-------------------+ | | | | \ | 0 | | | p->VA/ | |<---+ \ +===================+ | | blobs +--------------------+ \ +-------non-NULL | foo2 +------------+ |Class restore | \ +-------------------+ |b.dll | | | +-------non-NULL | | | | | +-------------------+ | token_C1 |<--------------blob(=>fixedUp/0) |<--pBlob--------index | | | \ | | +-------------------+ | | \ +--------------------+ | non-NULL | | | \ | | +-------------------+ | | \ | . | | 0 | | | \ | . | +===================+ +------------+ \ | . | | 0 | foo3 \ | | +===================+ \ +--------------------+ | non-NULL | foo4 \ |Various fixups that | +-------------------+ \ |need too happen | | 0 | \| | +===================+ |(CorCompileTokenTable) | | pEntryEnd->VA +--------------------+ #endif // 0 //----------------------------------------------------------------------------- BOOL Module::FixupNativeEntry(CORCOMPILE_IMPORT_SECTION * pSection, SIZE_T fixupIndex, SIZE_T *fixupCell) { CONTRACTL { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(fixupCell)); } CONTRACTL_END; // Ensure that the compiler won't fetch the value twice SIZE_T fixup = VolatileLoadWithoutBarrier(fixupCell); if (pSection->Signatures != NULL) { if (fixup == NULL) { PTR_DWORD pSignatures = dac_cast<PTR_DWORD>(GetNativeOrReadyToRunImage()->GetRvaData(pSection->Signatures)); if (!LoadDynamicInfoEntry(this, pSignatures[fixupIndex], fixupCell)) return FALSE; _ASSERTE(*fixupCell != NULL); } } else { if (CORCOMPILE_IS_FIXUP_TAGGED(fixup, pSection)) { // Fixup has not been fixed up yet if (!LoadDynamicInfoEntry(this, (RVA)CORCOMPILE_UNTAG_TOKEN(fixup), fixupCell)) return FALSE; _ASSERTE(!CORCOMPILE_IS_FIXUP_TAGGED(*fixupCell, pSection)); } else { // // Handle tables are special. We may need to restore static handle or previous // attempts to load handle could have been partial. // if (pSection->Type == CORCOMPILE_IMPORT_TYPE_TYPE_HANDLE) { TypeHandle::FromPtr((void *)fixup).CheckRestore(); } else if (pSection->Type == CORCOMPILE_IMPORT_TYPE_METHOD_HANDLE) { ((MethodDesc *)(fixup))->CheckRestore(); } } } return TRUE; } //----------------------------------------------------------------------------- void Module::RunEagerFixups() { STANDARD_VM_CONTRACT; COUNT_T nSections; PTR_CORCOMPILE_IMPORT_SECTION pSections = GetImportSections(&nSections); if (nSections == 0) return; #ifdef _DEBUG // Loading types during eager fixup is not a tested scenario. Make bugs out of any attempts to do so in a // debug build. Use holder to recover properly in case of exception. class ForbidTypeLoadHolder { public: ForbidTypeLoadHolder() { BEGIN_FORBID_TYPELOAD(); } ~ForbidTypeLoadHolder() { END_FORBID_TYPELOAD(); } } forbidTypeLoad; #endif // TODO: Verify that eager fixup dependency graphs can contain no cycles OVERRIDE_TYPE_LOAD_LEVEL_LIMIT(CLASS_LOADED); PEImageLayout *pNativeImage = GetNativeOrReadyToRunImage(); for (COUNT_T iSection = 0; iSection < nSections; iSection++) { PTR_CORCOMPILE_IMPORT_SECTION pSection = pSections + iSection; if ((pSection->Flags & CORCOMPILE_IMPORT_FLAGS_EAGER) == 0) continue; COUNT_T tableSize; TADDR tableBase = pNativeImage->GetDirectoryData(&pSection->Section, &tableSize); if (pSection->Signatures != NULL) { PTR_DWORD pSignatures = dac_cast<PTR_DWORD>(pNativeImage->GetRvaData(pSection->Signatures)); for (SIZE_T * fixupCell = (SIZE_T *)tableBase; fixupCell < (SIZE_T *)(tableBase + tableSize); fixupCell++) { SIZE_T fixupIndex = fixupCell - (SIZE_T *)tableBase; if (!LoadDynamicInfoEntry(this, pSignatures[fixupIndex], fixupCell)) { _ASSERTE(!"LoadDynamicInfoEntry failed"); ThrowHR(COR_E_BADIMAGEFORMAT); } _ASSERTE(*fixupCell != NULL); } } else { for (SIZE_T * fixupCell = (SIZE_T *)tableBase; fixupCell < (SIZE_T *)(tableBase + tableSize); fixupCell++) { // Ensure that the compiler won't fetch the value twice SIZE_T fixup = VolatileLoadWithoutBarrier(fixupCell); // This method may execute multiple times in multi-domain scenarios. Check that the fixup has not been // fixed up yet. if (CORCOMPILE_IS_FIXUP_TAGGED(fixup, pSection)) { if (!LoadDynamicInfoEntry(this, (RVA)CORCOMPILE_UNTAG_TOKEN(fixup), fixupCell)) { _ASSERTE(!"LoadDynamicInfoEntry failed"); ThrowHR(COR_E_BADIMAGEFORMAT); } _ASSERTE(!CORCOMPILE_IS_FIXUP_TAGGED(*fixupCell, pSection)); } } } } } void Module::LoadTokenTables() { CONTRACTL { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; PRECONDITION(HasNativeImage()); } CONTRACTL_END; #ifndef CROSSGEN_COMPILE if (NingenEnabled()) return; CORCOMPILE_EE_INFO_TABLE *pEEInfo = GetNativeImage()->GetNativeEEInfoTable(); PREFIX_ASSUME(pEEInfo != NULL); pEEInfo->inlinedCallFrameVptr = InlinedCallFrame::GetMethodFrameVPtr(); pEEInfo->addrOfCaptureThreadGlobal = (LONG *)&g_TrapReturningThreads; //CoreClr doesn't always have the debugger loaded //patch up the ngen image to point to this address so that the JIT bypasses JMC if there is no debugger static DWORD g_dummyJMCFlag = 0; pEEInfo->addrOfJMCFlag = g_pDebugInterface ? g_pDebugInterface->GetJMCFlagAddr(this) : &g_dummyJMCFlag; pEEInfo->gsCookie = GetProcessGSCookie(); if (!IsSystem()) { pEEInfo->emptyString = (CORINFO_Object **)StringObject::GetEmptyStringRefPtr(); } pEEInfo->threadTlsIndex = TLS_OUT_OF_INDEXES; pEEInfo->rvaStaticTlsIndex = NULL; #endif // CROSSGEN_COMPILE } #endif // !DACCESS_COMPILE // Returns the RVA to the compressed debug information blob for the given method CORCOMPILE_DEBUG_ENTRY Module::GetMethodDebugInfoOffset(MethodDesc *pMD) { CONTRACT(CORCOMPILE_DEBUG_ENTRY) { INSTANCE_CHECK; PRECONDITION(HasNativeImage()); PRECONDITION(CheckPointer(pMD) && pMD->IsPreImplemented()); POSTCONDITION(GetNativeImage()->CheckRva(RETVAL, NULL_OK)); NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACT_END; if (!GetNativeImage()->HasNativeDebugMap() || pMD->IsRuntimeSupplied()) RETURN 0; COUNT_T size; PTR_CORCOMPILE_DEBUG_RID_ENTRY ridTable = dac_cast<PTR_CORCOMPILE_DEBUG_RID_ENTRY>(GetNativeImage()->GetNativeDebugMap(&size)); COUNT_T count = size / sizeof(CORCOMPILE_DEBUG_RID_ENTRY); // The size should be odd for better hashing _ASSERTE((count & 1) != 0); CORCOMPILE_DEBUG_RID_ENTRY ridEntry = ridTable[GetDebugRidEntryHash(pMD->GetMemberDef()) % count]; // Do we have multiple code corresponding to the same RID if (!IsMultipleLabelledEntries(ridEntry)) { RETURN(ridEntry); } PTR_CORCOMPILE_DEBUG_LABELLED_ENTRY pLabelledEntry = PTR_CORCOMPILE_DEBUG_LABELLED_ENTRY (GetNativeImage()->GetRvaData(ridEntry & ~CORCOMPILE_DEBUG_MULTIPLE_ENTRIES)); DWORD codeRVA = GetNativeImage()-> GetDataRva((const TADDR)pMD->GetNativeCode()); #if defined(_TARGET_ARM_) // Since the Thumb Bit is set on ARM, the RVA calculated above will have it set as well // and will result in the failure of checks in the loop below. Hence, mask off the // bit before proceeding ahead. codeRVA = ThumbCodeToDataPointer<DWORD, DWORD>(codeRVA); #endif // _TARGET_ARM_ for (;;) { if (pLabelledEntry->nativeCodeRVA == codeRVA) { RETURN (pLabelledEntry->debugInfoOffset & ~CORCOMPILE_DEBUG_MULTIPLE_ENTRIES); } if (!IsMultipleLabelledEntries(pLabelledEntry->debugInfoOffset)) { break; } pLabelledEntry++; } _ASSERTE(!"Debug info not found - corrupted ngen image?"); RETURN (0); } PTR_BYTE Module::GetNativeDebugInfo(MethodDesc * pMD) { CONTRACTL { INSTANCE_CHECK; PRECONDITION(HasNativeImage()); PRECONDITION(CheckPointer(pMD)); PRECONDITION(pMD->GetZapModule() == this); THROWS; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; CORCOMPILE_DEBUG_ENTRY debugInfoOffset = GetMethodDebugInfoOffset(pMD); if (debugInfoOffset == 0) return NULL; return dac_cast<PTR_BYTE>(GetNativeImage()->GetRvaData(debugInfoOffset)); } #endif //FEATURE_PREJIT #ifndef DACCESS_COMPILE #ifdef FEATURE_PREJIT // // Profile data management // ICorJitInfo::ProfileBuffer * Module::AllocateProfileBuffer(mdToken _token, DWORD _count, DWORD _ILSize) { CONTRACT (ICorJitInfo::ProfileBuffer*) { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(CONTRACT_RETURN NULL;); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; assert(_ILSize != 0); DWORD listSize = sizeof(CORCOMPILE_METHOD_PROFILE_LIST); DWORD headerSize = sizeof(CORBBTPROF_METHOD_HEADER); DWORD blockSize = _count * sizeof(CORBBTPROF_BLOCK_DATA); DWORD totalSize = listSize + headerSize + blockSize; BYTE * memory = (BYTE *) (void *) this->m_pAssembly->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(totalSize)); CORCOMPILE_METHOD_PROFILE_LIST * methodProfileList = (CORCOMPILE_METHOD_PROFILE_LIST *) (memory + 0); CORBBTPROF_METHOD_HEADER * methodProfileData = (CORBBTPROF_METHOD_HEADER *) (memory + listSize); // Note: Memory allocated on the LowFrequencyHeap is zero filled methodProfileData->size = headerSize + blockSize; methodProfileData->method.token = _token; methodProfileData->method.ILSize = _ILSize; methodProfileData->method.cBlock = _count; assert(methodProfileData->size == methodProfileData->Size()); // Link it to the per module list of profile data buffers methodProfileList->next = m_methodProfileList; m_methodProfileList = methodProfileList; RETURN ((ICorJitInfo::ProfileBuffer *) &methodProfileData->method.block[0]); } HANDLE Module::OpenMethodProfileDataLogFile(GUID mvid) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; HANDLE profileDataFile = INVALID_HANDLE_VALUE; SString path; LPCWSTR assemblyPath = m_file->GetPath(); LPCWSTR ibcDir = g_pConfig->GetZapBBInstrDir(); // should we put the ibc data into a particular directory? if (ibcDir == 0) { path.Set(assemblyPath); // no, then put it beside the IL dll } else { LPCWSTR assemblyFileName = wcsrchr(assemblyPath, DIRECTORY_SEPARATOR_CHAR_W); if (assemblyFileName) assemblyFileName++; // skip past the \ char else assemblyFileName = assemblyPath; path.Set(ibcDir); // yes, put it in the directory, named with the assembly name. path.Append(DIRECTORY_SEPARATOR_CHAR_W); path.Append(assemblyFileName); } SString::Iterator ext = path.End(); // remove the extension if (path.FindBack(ext, '.')) path.Truncate(ext); path.Append(W(".ibc")); // replace with .ibc extension profileDataFile = WszCreateFile(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (profileDataFile == INVALID_HANDLE_VALUE) COMPlusThrowWin32(); DWORD count; CORBBTPROF_FILE_HEADER fileHeader; SetFilePointer(profileDataFile, 0, NULL, FILE_BEGIN); BOOL result = ReadFile(profileDataFile, &fileHeader, sizeof(fileHeader), &count, NULL); if (result && (count == sizeof(fileHeader)) && (fileHeader.HeaderSize == sizeof(CORBBTPROF_FILE_HEADER)) && (fileHeader.Magic == CORBBTPROF_MAGIC) && (fileHeader.Version == CORBBTPROF_CURRENT_VERSION) && (fileHeader.MVID == mvid)) { // // The existing file was from the same assembly version - just append to it. // SetFilePointer(profileDataFile, 0, NULL, FILE_END); } else { // // Either this is a new file, or it's from a previous version. Replace the contents. // SetFilePointer(profileDataFile, 0, NULL, FILE_BEGIN); } return profileDataFile; } // Note that this method cleans up the profile buffers, so it's crucial that // no managed code in the module is allowed to run once this method has // been called! class ProfileMap { public: SIZE_T getCurrentOffset() {WRAPPER_NO_CONTRACT; return buffer.Size();} void * getOffsetPtr(SIZE_T offset) { LIMITED_METHOD_CONTRACT; _ASSERTE(offset <= buffer.Size()); return ((void *) (((char *) buffer.Ptr()) + offset)); } void *Allocate(SIZE_T size) { CONTRACT(void *) { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(CONTRACT_RETURN NULL;); POSTCONDITION(CheckPointer(RETVAL, NULL_OK)); } CONTRACT_END; SIZE_T oldSize = buffer.Size(); buffer.ReSizeThrows(oldSize + size); RETURN getOffsetPtr(oldSize); } private: CQuickBytes buffer; }; class ProfileEmitter { public: ProfileEmitter() { LIMITED_METHOD_CONTRACT; pSectionList = NULL; } ~ProfileEmitter() { WRAPPER_NO_CONTRACT; while (pSectionList) { SectionList *temp = pSectionList->next; delete pSectionList; pSectionList = temp; } } ProfileMap *EmitNewSection(SectionFormat format) { WRAPPER_NO_CONTRACT; SectionList *s = new SectionList(); s->format = format; s->next = pSectionList; pSectionList = s; return &s->profileMap; } // // Serialize the profile sections into pMap // void Serialize(ProfileMap *profileMap, GUID mvid) { CONTRACTL { INSTANCE_CHECK; THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; // // Allocate the file header // { CORBBTPROF_FILE_HEADER *fileHeader; fileHeader = (CORBBTPROF_FILE_HEADER *) profileMap->Allocate(sizeof(CORBBTPROF_FILE_HEADER)); fileHeader->HeaderSize = sizeof(CORBBTPROF_FILE_HEADER); fileHeader->Magic = CORBBTPROF_MAGIC; fileHeader->Version = CORBBTPROF_CURRENT_VERSION; fileHeader->MVID = mvid; } // // Count the number of sections // ULONG32 numSections = 0; for (SectionList *p = pSectionList; p; p = p->next) { numSections++; } // // Allocate the section table // SIZE_T tableEntryOffset; { CORBBTPROF_SECTION_TABLE_HEADER *tableHeader; tableHeader = (CORBBTPROF_SECTION_TABLE_HEADER *) profileMap->Allocate(sizeof(CORBBTPROF_SECTION_TABLE_HEADER)); tableHeader->NumEntries = numSections; tableEntryOffset = profileMap->getCurrentOffset(); CORBBTPROF_SECTION_TABLE_ENTRY *tableEntry; tableEntry = (CORBBTPROF_SECTION_TABLE_ENTRY *) profileMap->Allocate(sizeof(CORBBTPROF_SECTION_TABLE_ENTRY) * numSections); } // // Allocate the data sections // { ULONG secCount = 0; for (SectionList *pSec = pSectionList; pSec; pSec = pSec->next, secCount++) { SIZE_T offset = profileMap->getCurrentOffset(); assert((offset & 0x3) == 0); SIZE_T actualSize = pSec->profileMap.getCurrentOffset(); SIZE_T alignUpSize = AlignUp(actualSize, sizeof(DWORD)); profileMap->Allocate(alignUpSize); memcpy(profileMap->getOffsetPtr(offset), pSec->profileMap.getOffsetPtr(0), actualSize); if (alignUpSize > actualSize) { memset(((BYTE*)profileMap->getOffsetPtr(offset))+actualSize, 0, (alignUpSize - actualSize)); } CORBBTPROF_SECTION_TABLE_ENTRY *tableEntry; tableEntry = (CORBBTPROF_SECTION_TABLE_ENTRY *) profileMap->getOffsetPtr(tableEntryOffset); tableEntry += secCount; tableEntry->FormatID = pSec->format; tableEntry->Data.Offset = offset; tableEntry->Data.Size = alignUpSize; } } // // Allocate the end token marker // { ULONG *endToken; endToken = (ULONG *) profileMap->Allocate(sizeof(ULONG)); *endToken = CORBBTPROF_END_TOKEN; } } private: struct SectionList { SectionFormat format; ProfileMap profileMap; SectionList *next; }; SectionList * pSectionList; }; /*static*/ idTypeSpec TypeSpecBlobEntry::s_lastTypeSpecToken = idTypeSpecNil; /*static*/ idMethodSpec MethodSpecBlobEntry::s_lastMethodSpecToken = idMethodSpecNil; /*static*/ idExternalNamespace ExternalNamespaceBlobEntry::s_lastExternalNamespaceToken = idExternalNamespaceNil; /*static*/ idExternalType ExternalTypeBlobEntry::s_lastExternalTypeToken = idExternalTypeNil; /*static*/ idExternalSignature ExternalSignatureBlobEntry::s_lastExternalSignatureToken = idExternalSignatureNil; /*static*/ idExternalMethod ExternalMethodBlobEntry::s_lastExternalMethodToken = idExternalMethodNil; inline static size_t HashCombine(size_t h1, size_t h2) { LIMITED_METHOD_CONTRACT; size_t result = (h1 * 129) ^ h2; return result; } bool TypeSpecBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const TypeSpecBlobEntry * other2 = static_cast<const TypeSpecBlobEntry *>(other); if (this->cbSig() != other2->cbSig()) return false; PCCOR_SIGNATURE p1 = this->pSig(); PCCOR_SIGNATURE p2 = other2->pSig(); for (DWORD i=0; (i < this->cbSig()); i++) if (p1[i] != p2[i]) return false; return true; } size_t TypeSpecBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); PCCOR_SIGNATURE p1 = pSig(); for (DWORD i=0; (i < cbSig()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } TypeSpecBlobEntry::TypeSpecBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(_cbSig > 0); PRECONDITION(CheckPointer(_pSig)); } CONTRACTL_END; m_token = idTypeSpecNil; m_flags = 0; m_cbSig = 0; COR_SIGNATURE * pNewSig = (COR_SIGNATURE *) new (nothrow) BYTE[_cbSig]; if (pNewSig != NULL) { m_flags = 0; m_cbSig = _cbSig; memcpy(pNewSig, _pSig, _cbSig); } m_pSig = const_cast<PCCOR_SIGNATURE>(pNewSig); } /* static */ const TypeSpecBlobEntry * TypeSpecBlobEntry::FindOrAdd(PTR_Module pModule, DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if ((_cbSig == 0) || (_pSig == NULL)) return NULL; TypeSpecBlobEntry sEntry(_cbSig, _pSig); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new type spec profiling blob entry // TypeSpecBlobEntry * newEntry = new (nothrow) TypeSpecBlobEntry(_cbSig, _pSig); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc type spec token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the type spec entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ParamTypeSpec); return static_cast<const TypeSpecBlobEntry *>(pEntry); } bool MethodSpecBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const MethodSpecBlobEntry * other2 = static_cast<const MethodSpecBlobEntry *>(other); if (this->cbSig() != other2->cbSig()) return false; PCCOR_SIGNATURE p1 = this->pSig(); PCCOR_SIGNATURE p2 = other2->pSig(); for (DWORD i=0; (i < this->cbSig()); i++) if (p1[i] != p2[i]) return false; return true; } size_t MethodSpecBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); PCCOR_SIGNATURE p1 = pSig(); for (DWORD i=0; (i < cbSig()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } MethodSpecBlobEntry::MethodSpecBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(_cbSig > 0); PRECONDITION(CheckPointer(_pSig)); } CONTRACTL_END; m_token = idMethodSpecNil; m_flags = 0; m_cbSig = 0; COR_SIGNATURE * pNewSig = (COR_SIGNATURE *) new (nothrow) BYTE[_cbSig]; if (pNewSig != NULL) { m_flags = 0; m_cbSig = _cbSig; memcpy(pNewSig, _pSig, _cbSig); } m_pSig = const_cast<PCCOR_SIGNATURE>(pNewSig); } /* static */ const MethodSpecBlobEntry * MethodSpecBlobEntry::FindOrAdd(PTR_Module pModule, DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if ((_cbSig == 0) || (_pSig == NULL)) return NULL; MethodSpecBlobEntry sEntry(_cbSig, _pSig); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new method spec profiling blob entry // MethodSpecBlobEntry * newEntry = new (nothrow) MethodSpecBlobEntry(_cbSig, _pSig); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc method spec token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the method spec entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ParamMethodSpec); return static_cast<const MethodSpecBlobEntry *>(pEntry); } bool ExternalNamespaceBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const ExternalNamespaceBlobEntry * other2 = static_cast<const ExternalNamespaceBlobEntry *>(other); if (this->cbName() != other2->cbName()) return false; LPCSTR p1 = this->pName(); LPCSTR p2 = other2->pName(); for (DWORD i=0; (i < this->cbName()); i++) if (p1[i] != p2[i]) return false; return true; } size_t ExternalNamespaceBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); LPCSTR p1 = pName(); for (DWORD i=0; (i < cbName()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } ExternalNamespaceBlobEntry::ExternalNamespaceBlobEntry(LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(CheckPointer(_pName)); } CONTRACTL_END; m_token = idExternalNamespaceNil; m_cbName = 0; m_pName = NULL; DWORD _cbName = (DWORD) strlen(_pName) + 1; LPSTR * pName = (LPSTR *) new (nothrow) CHAR[_cbName]; if (pName != NULL) { m_cbName = _cbName; memcpy(pName, _pName, _cbName); m_pName = (LPCSTR) pName; } } /* static */ const ExternalNamespaceBlobEntry * ExternalNamespaceBlobEntry::FindOrAdd(PTR_Module pModule, LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if ((_pName == NULL) || (::strlen(_pName) == 0)) return NULL; ExternalNamespaceBlobEntry sEntry(_pName); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new external namespace blob entry // ExternalNamespaceBlobEntry * newEntry = new (nothrow) ExternalNamespaceBlobEntry(_pName); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc external namespace token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the external namespace entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ExternalNamespaceDef); return static_cast<const ExternalNamespaceBlobEntry *>(pEntry); } bool ExternalTypeBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const ExternalTypeBlobEntry * other2 = static_cast<const ExternalTypeBlobEntry *>(other); if (this->assemblyRef() != other2->assemblyRef()) return false; if (this->nestedClass() != other2->nestedClass()) return false; if (this->nameSpace() != other2->nameSpace()) return false; if (this->cbName() != other2->cbName()) return false; LPCSTR p1 = this->pName(); LPCSTR p2 = other2->pName(); for (DWORD i=0; (i < this->cbName()); i++) if (p1[i] != p2[i]) return false; return true; } size_t ExternalTypeBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); hashValue = HashCombine(hashValue, assemblyRef()); hashValue = HashCombine(hashValue, nestedClass()); hashValue = HashCombine(hashValue, nameSpace()); LPCSTR p1 = pName(); for (DWORD i=0; (i < cbName()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } ExternalTypeBlobEntry::ExternalTypeBlobEntry(mdToken _assemblyRef, mdToken _nestedClass, mdToken _nameSpace, LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(CheckPointer(_pName)); } CONTRACTL_END; m_token = idExternalTypeNil; m_assemblyRef = mdAssemblyRefNil; m_nestedClass = idExternalTypeNil; m_nameSpace = idExternalNamespaceNil; m_cbName = 0; m_pName = NULL; DWORD _cbName = (DWORD) strlen(_pName) + 1; LPSTR * pName = (LPSTR *) new (nothrow) CHAR[_cbName]; if (pName != NULL) { m_assemblyRef = _assemblyRef; m_nestedClass = _nestedClass; m_nameSpace = _nameSpace; m_cbName = _cbName; memcpy(pName, _pName, _cbName); m_pName = (LPCSTR) pName; } } /* static */ const ExternalTypeBlobEntry * ExternalTypeBlobEntry::FindOrAdd(PTR_Module pModule, mdToken _assemblyRef, mdToken _nestedClass, mdToken _nameSpace, LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if ((_pName == NULL) || (::strlen(_pName) == 0)) return NULL; ExternalTypeBlobEntry sEntry(_assemblyRef, _nestedClass, _nameSpace, _pName); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new external type blob entry // ExternalTypeBlobEntry * newEntry = new (nothrow) ExternalTypeBlobEntry(_assemblyRef, _nestedClass, _nameSpace, _pName); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc external type token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the external type entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ExternalTypeDef); return static_cast<const ExternalTypeBlobEntry *>(pEntry); } bool ExternalSignatureBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const ExternalSignatureBlobEntry * other2 = static_cast<const ExternalSignatureBlobEntry *>(other); if (this->cbSig() != other2->cbSig()) return false; PCCOR_SIGNATURE p1 = this->pSig(); PCCOR_SIGNATURE p2 = other2->pSig(); for (DWORD i=0; (i < this->cbSig()); i++) if (p1[i] != p2[i]) return false; return true; } size_t ExternalSignatureBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); hashValue = HashCombine(hashValue, cbSig()); PCCOR_SIGNATURE p1 = pSig(); for (DWORD i=0; (i < cbSig()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } ExternalSignatureBlobEntry::ExternalSignatureBlobEntry(DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(_cbSig > 0); PRECONDITION(CheckPointer(_pSig)); } CONTRACTL_END; m_token = idExternalSignatureNil; m_cbSig = 0; COR_SIGNATURE * pNewSig = (COR_SIGNATURE *) new (nothrow) BYTE[_cbSig]; if (pNewSig != NULL) { m_cbSig = _cbSig; memcpy(pNewSig, _pSig, _cbSig); } m_pSig = const_cast<PCCOR_SIGNATURE>(pNewSig); } /* static */ const ExternalSignatureBlobEntry * ExternalSignatureBlobEntry::FindOrAdd(PTR_Module pModule, DWORD _cbSig, PCCOR_SIGNATURE _pSig) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; if ((_cbSig == 0) || (_pSig == NULL)) return NULL; ExternalSignatureBlobEntry sEntry(_cbSig, _pSig); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new external signature blob entry // ExternalSignatureBlobEntry * newEntry = new (nothrow) ExternalSignatureBlobEntry(_cbSig, _pSig); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc external signature token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the external signature entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ExternalSignatureDef); return static_cast<const ExternalSignatureBlobEntry *>(pEntry); } bool ExternalMethodBlobEntry::IsEqual(const ProfilingBlobEntry * other) const { WRAPPER_NO_CONTRACT; if (this->kind() != other->kind()) return false; const ExternalMethodBlobEntry * other2 = static_cast<const ExternalMethodBlobEntry *>(other); if (this->nestedClass() != other2->nestedClass()) return false; if (this->signature() != other2->signature()) return false; if (this->cbName() != other2->cbName()) return false; LPCSTR p1 = this->pName(); LPCSTR p2 = other2->pName(); for (DWORD i=0; (i < this->cbName()); i++) if (p1[i] != p2[i]) return false; return true; } size_t ExternalMethodBlobEntry::Hash() const { WRAPPER_NO_CONTRACT; size_t hashValue = HashInit(); hashValue = HashCombine(hashValue, nestedClass()); hashValue = HashCombine(hashValue, signature()); LPCSTR p1 = pName(); for (DWORD i=0; (i < cbName()); i++) hashValue = HashCombine(hashValue, p1[i]); return hashValue; } ExternalMethodBlobEntry::ExternalMethodBlobEntry(mdToken _nestedClass, mdToken _signature, LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(CheckPointer(_pName)); } CONTRACTL_END; m_token = idExternalMethodNil; m_nestedClass = idExternalTypeNil; m_signature = idExternalSignatureNil; m_cbName = 0; DWORD _cbName = (DWORD) strlen(_pName) + 1; LPSTR * pName = (LPSTR *) new (nothrow) CHAR[_cbName]; if (pName != NULL) { m_nestedClass = _nestedClass; m_signature = _signature; m_cbName = _cbName; memcpy(pName, _pName, _cbName); m_pName = (LPSTR) pName; } } /* static */ const ExternalMethodBlobEntry * ExternalMethodBlobEntry::FindOrAdd( PTR_Module pModule, mdToken _nestedClass, mdToken _signature, LPCSTR _pName) { CONTRACTL { NOTHROW; GC_NOTRIGGER; PRECONDITION(CheckPointer(_pName)); } CONTRACTL_END; if ((_pName == NULL) || (::strlen(_pName) == 0)) return NULL; ExternalMethodBlobEntry sEntry(_nestedClass, _signature, _pName); const ProfilingBlobEntry * pEntry = pModule->GetProfilingBlobTable()->Lookup(&sEntry); if (pEntry == NULL) { // // Not Found, add a new external type blob entry // ExternalMethodBlobEntry * newEntry; newEntry = new (nothrow) ExternalMethodBlobEntry(_nestedClass, _signature, _pName); if (newEntry == NULL) return NULL; newEntry->newToken(); // Assign a new ibc external method token CONTRACT_VIOLATION(ThrowsViolation); pModule->GetProfilingBlobTable()->Add(newEntry); pEntry = newEntry; } // // Return the external method entry that we found or the new one that we just created // _ASSERTE(pEntry->kind() == ExternalMethodDef); return static_cast<const ExternalMethodBlobEntry *>(pEntry); } static bool GetBasename(LPCWSTR _src, __out_ecount(dstlen) __out_z LPWSTR _dst, int dstlen) { LIMITED_METHOD_CONTRACT; LPCWSTR src = _src; LPWSTR dst = _dst; if ((src == NULL) || (dstlen <= 0)) return false; bool inQuotes = false; LPWSTR dstLast = dst + (dstlen - 1); while (dst < dstLast) { WCHAR wch = *src++; if (wch == W('"')) { inQuotes = !inQuotes; continue; } if (wch == 0) break; *dst++ = wch; if (!inQuotes) { if ((wch == W('\\')) || (wch == W(':'))) { dst = _dst; } else if (wch == W(' ')) { dst--; break; } } } *dst++ = 0; return true; } static void ProfileDataAllocateScenarioInfo(ProfileEmitter * pEmitter, LPCSTR scopeName, GUID* pMvid) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; ProfileMap *profileMap = pEmitter->EmitNewSection(ScenarioInfo); // // Allocate and initialize the scenario info section // { CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *siHeader; siHeader = (CORBBTPROF_SCENARIO_INFO_SECTION_HEADER *) profileMap->Allocate(sizeof(CORBBTPROF_SCENARIO_INFO_SECTION_HEADER)); siHeader->NumScenarios = 1; siHeader->TotalNumRuns = 1; } // // Allocate and initialize the scenario header section // { LPCWSTR pCmdLine = GetCommandLineW(); S_SIZE_T cCmdLine = S_SIZE_T(wcslen(pCmdLine)); cCmdLine += 1; if (cCmdLine.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } LPCWSTR pSystemInfo = W("<machine,OS>"); S_SIZE_T cSystemInfo = S_SIZE_T(wcslen(pSystemInfo)); cSystemInfo += 1; if (cSystemInfo.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } FILETIME runTime, unused1, unused2, unused3; GetProcessTimes(GetCurrentProcess(), &runTime, &unused1, &unused2, &unused3); WCHAR scenarioName[256]; GetBasename(pCmdLine, &scenarioName[0], 256); LPCWSTR pName = &scenarioName[0]; S_SIZE_T cName = S_SIZE_T(wcslen(pName)); cName += 1; if (cName.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } S_SIZE_T sizeHeader = S_SIZE_T(sizeof(CORBBTPROF_SCENARIO_HEADER)); sizeHeader += cName * S_SIZE_T(sizeof(WCHAR)); if (sizeHeader.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } S_SIZE_T sizeRun = S_SIZE_T(sizeof(CORBBTPROF_SCENARIO_RUN)); sizeRun += cCmdLine * S_SIZE_T(sizeof(WCHAR)); sizeRun += cSystemInfo * S_SIZE_T(sizeof(WCHAR)); if (sizeRun.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } // // Allocate the Scenario Header struct // SIZE_T sHeaderOffset; { CORBBTPROF_SCENARIO_HEADER *sHeader; S_SIZE_T sHeaderSize = sizeHeader + sizeRun; if (sHeaderSize.IsOverflow()) { ThrowHR(COR_E_OVERFLOW); } sHeaderOffset = profileMap->getCurrentOffset(); sHeader = (CORBBTPROF_SCENARIO_HEADER *) profileMap->Allocate(sizeHeader.Value()); sHeader->size = sHeaderSize.Value(); sHeader->scenario.ordinal = 1; sHeader->scenario.mask = 1; sHeader->scenario.priority = 0; sHeader->scenario.numRuns = 1; sHeader->scenario.cName = cName.Value(); wcscpy_s(sHeader->scenario.name, cName.Value(), pName); } // // Allocate the Scenario Run struct // { CORBBTPROF_SCENARIO_RUN *sRun; sRun = (CORBBTPROF_SCENARIO_RUN *) profileMap->Allocate(sizeRun.Value()); sRun->runTime = runTime; sRun->mvid = *pMvid; sRun->cCmdLine = cCmdLine.Value(); sRun->cSystemInfo = cSystemInfo.Value(); wcscpy_s(sRun->cmdLine, cCmdLine.Value(), pCmdLine); wcscpy_s(sRun->cmdLine+cCmdLine.Value(), cSystemInfo.Value(), pSystemInfo); } #ifdef _DEBUG { CORBBTPROF_SCENARIO_HEADER * sHeader; sHeader = (CORBBTPROF_SCENARIO_HEADER *) profileMap->getOffsetPtr(sHeaderOffset); assert(sHeader->size == sHeader->Size()); } #endif } } static void ProfileDataAllocateMethodBlockCounts(ProfileEmitter * pEmitter, CORCOMPILE_METHOD_PROFILE_LIST * pMethodProfileListHead) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; ProfileMap *profileMap = pEmitter->EmitNewSection(MethodBlockCounts); // // Allocate and initialize the method block count section // SIZE_T mbcHeaderOffset; { CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *mbcHeader; mbcHeaderOffset = profileMap->getCurrentOffset(); mbcHeader = (CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *) profileMap->Allocate(sizeof(CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER)); mbcHeader->NumMethods = 0; // This gets filled in later } ULONG numMethods = 0; // We count the number of methods that were executed for (CORCOMPILE_METHOD_PROFILE_LIST * methodProfileList = pMethodProfileListHead; methodProfileList; methodProfileList = methodProfileList->next) { CORBBTPROF_METHOD_HEADER * pInfo = methodProfileList->GetInfo(); assert(pInfo->size == pInfo->Size()); // // We set methodWasExecuted based upon the ExecutionCount of the very first block // bool methodWasExecuted = (pInfo->method.block[0].ExecutionCount > 0); // // If the method was not executed then we don't need to output this methods block counts // SIZE_T methodHeaderOffset; if (methodWasExecuted) { DWORD profileDataSize = pInfo->size; methodHeaderOffset = profileMap->getCurrentOffset(); CORBBTPROF_METHOD_HEADER *methodHeader = (CORBBTPROF_METHOD_HEADER *) profileMap->Allocate(profileDataSize); memcpy(methodHeader, pInfo, profileDataSize); numMethods++; } // Reset all of the basic block counts to zero for (ULONG i=0; (i < pInfo->method.cBlock); i++ ) { // // If methodWasExecuted is false then every block's ExecutionCount should also be zero // _ASSERTE(methodWasExecuted || (pInfo->method.block[i].ExecutionCount == 0)); pInfo->method.block[i].ExecutionCount = 0; } } { CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *mbcHeader; // We have to refetch the mbcHeader as calls to Allocate will resize and thus move the mbcHeader mbcHeader = (CORBBTPROF_METHOD_BLOCK_COUNTS_SECTION_HEADER *) profileMap->getOffsetPtr(mbcHeaderOffset); mbcHeader->NumMethods = numMethods; } } /*static*/ void Module::ProfileDataAllocateTokenLists(ProfileEmitter * pEmitter, Module::TokenProfileData* pTokenProfileData) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; // // Allocate and initialize the token list sections // if (pTokenProfileData) { for (int format = 0; format < (int)SectionFormatCount; format++) { CQuickArray<CORBBTPROF_TOKEN_INFO> *pTokenArray = &(pTokenProfileData->m_formats[format].tokenArray); if (pTokenArray->Size() != 0) { ProfileMap * profileMap = pEmitter->EmitNewSection((SectionFormat) format); CORBBTPROF_TOKEN_LIST_SECTION_HEADER *header; header = (CORBBTPROF_TOKEN_LIST_SECTION_HEADER *) profileMap->Allocate(sizeof(CORBBTPROF_TOKEN_LIST_SECTION_HEADER) + pTokenArray->Size() * sizeof(CORBBTPROF_TOKEN_INFO)); header->NumTokens = pTokenArray->Size(); memcpy( (header + 1), &((*pTokenArray)[0]), pTokenArray->Size() * sizeof(CORBBTPROF_TOKEN_INFO)); // Reset the collected tokens for (unsigned i = 0; i < CORBBTPROF_TOKEN_MAX_NUM_FLAGS; i++) { pTokenProfileData->m_formats[format].tokenBitmaps[i].Reset(); } pTokenProfileData->m_formats[format].tokenArray.ReSizeNoThrow(0); } } } } static void ProfileDataAllocateTokenDefinitions(ProfileEmitter * pEmitter, Module * pModule) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; INJECT_FAULT(COMPlusThrowOM()); } CONTRACTL_END; // // Allocate and initialize the ibc token definition section (aka the Blob stream) // ProfileMap * profileMap = pEmitter->EmitNewSection(BlobStream); // Compute the size of the metadata section: // It is the sum of all of the Metadata Profile pool entries // plus the sum of all of the Param signature entries // size_t totalSize = 0; for (ProfilingBlobTable::Iterator cur = pModule->GetProfilingBlobTable()->Begin(), end = pModule->GetProfilingBlobTable()->End(); (cur != end); cur++) { const ProfilingBlobEntry * pEntry = *cur; size_t blobElementSize = pEntry->varSize(); switch (pEntry->kind()) { case ParamTypeSpec: case ParamMethodSpec: blobElementSize += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY); break; case ExternalNamespaceDef: blobElementSize += sizeof(CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY); break; case ExternalTypeDef: blobElementSize += sizeof(CORBBTPROF_BLOB_TYPE_DEF_ENTRY); break; case ExternalSignatureDef: blobElementSize += sizeof(CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY); break; case ExternalMethodDef: blobElementSize += sizeof(CORBBTPROF_BLOB_METHOD_DEF_ENTRY); break; default: _ASSERTE(!"Unexpected blob type"); break; } totalSize += blobElementSize; } profileMap->Allocate(totalSize); size_t currentPos = 0; // Traverse each element and record it size_t blobElementSize = 0; for (ProfilingBlobTable::Iterator cur = pModule->GetProfilingBlobTable()->Begin(), end = pModule->GetProfilingBlobTable()->End(); (cur != end); cur++, currentPos += blobElementSize) { const ProfilingBlobEntry * pEntry = *cur; blobElementSize = pEntry->varSize(); void *profileData = profileMap->getOffsetPtr(currentPos); switch (pEntry->kind()) { case ParamTypeSpec: { CORBBTPROF_BLOB_PARAM_SIG_ENTRY * bProfileData = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY*) profileData; const TypeSpecBlobEntry * typeSpecBlobEntry = static_cast<const TypeSpecBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = typeSpecBlobEntry->kind(); bProfileData->blob.token = typeSpecBlobEntry->token(); _ASSERTE(typeSpecBlobEntry->cbSig() > 0); bProfileData->cSig = typeSpecBlobEntry->cbSig(); memcpy(&bProfileData->sig[0], typeSpecBlobEntry->pSig(), typeSpecBlobEntry->cbSig()); break; } case ParamMethodSpec: { CORBBTPROF_BLOB_PARAM_SIG_ENTRY * bProfileData = (CORBBTPROF_BLOB_PARAM_SIG_ENTRY*) profileData; const MethodSpecBlobEntry * methodSpecBlobEntry = static_cast<const MethodSpecBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_PARAM_SIG_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = methodSpecBlobEntry->kind(); bProfileData->blob.token = methodSpecBlobEntry->token(); _ASSERTE(methodSpecBlobEntry->cbSig() > 0); bProfileData->cSig = methodSpecBlobEntry->cbSig(); memcpy(&bProfileData->sig[0], methodSpecBlobEntry->pSig(), methodSpecBlobEntry->cbSig()); break; } case ExternalNamespaceDef: { CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY * bProfileData = (CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY*) profileData; const ExternalNamespaceBlobEntry * namespaceBlobEntry = static_cast<const ExternalNamespaceBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = namespaceBlobEntry->kind(); bProfileData->blob.token = namespaceBlobEntry->token(); _ASSERTE(namespaceBlobEntry->cbName() > 0); bProfileData->cName = namespaceBlobEntry->cbName(); memcpy(&bProfileData->name[0], namespaceBlobEntry->pName(), namespaceBlobEntry->cbName()); break; } case ExternalTypeDef: { CORBBTPROF_BLOB_TYPE_DEF_ENTRY * bProfileData = (CORBBTPROF_BLOB_TYPE_DEF_ENTRY*) profileData; const ExternalTypeBlobEntry * typeBlobEntry = static_cast<const ExternalTypeBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_TYPE_DEF_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = typeBlobEntry->kind(); bProfileData->blob.token = typeBlobEntry->token(); bProfileData->assemblyRefToken = typeBlobEntry->assemblyRef(); bProfileData->nestedClassToken = typeBlobEntry->nestedClass(); bProfileData->nameSpaceToken = typeBlobEntry->nameSpace(); _ASSERTE(typeBlobEntry->cbName() > 0); bProfileData->cName = typeBlobEntry->cbName(); memcpy(&bProfileData->name[0], typeBlobEntry->pName(), typeBlobEntry->cbName()); break; } case ExternalSignatureDef: { CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY * bProfileData = (CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY*) profileData; const ExternalSignatureBlobEntry * signatureBlobEntry = static_cast<const ExternalSignatureBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = signatureBlobEntry->kind(); bProfileData->blob.token = signatureBlobEntry->token(); _ASSERTE(signatureBlobEntry->cbSig() > 0); bProfileData->cSig = signatureBlobEntry->cbSig(); memcpy(&bProfileData->sig[0], signatureBlobEntry->pSig(), signatureBlobEntry->cbSig()); break; } case ExternalMethodDef: { CORBBTPROF_BLOB_METHOD_DEF_ENTRY * bProfileData = (CORBBTPROF_BLOB_METHOD_DEF_ENTRY*) profileData; const ExternalMethodBlobEntry * methodBlobEntry = static_cast<const ExternalMethodBlobEntry *>(pEntry); blobElementSize += sizeof(CORBBTPROF_BLOB_METHOD_DEF_ENTRY); bProfileData->blob.size = static_cast<DWORD>(blobElementSize); bProfileData->blob.type = methodBlobEntry->kind(); bProfileData->blob.token = methodBlobEntry->token(); bProfileData->nestedClassToken = methodBlobEntry->nestedClass(); bProfileData->signatureToken = methodBlobEntry->signature(); _ASSERTE(methodBlobEntry->cbName() > 0); bProfileData->cName = methodBlobEntry->cbName(); memcpy(&bProfileData->name[0], methodBlobEntry->pName(), methodBlobEntry->cbName()); break; } default: _ASSERTE(!"Unexpected blob type"); break; } } _ASSERTE(currentPos == totalSize); // Emit a terminating entry with type EndOfBlobStream to mark the end DWORD mdElementSize = sizeof(CORBBTPROF_BLOB_ENTRY); void *profileData = profileMap->Allocate(mdElementSize); memset(profileData, 0, mdElementSize); CORBBTPROF_BLOB_ENTRY* mdProfileData = (CORBBTPROF_BLOB_ENTRY*) profileData; mdProfileData->type = EndOfBlobStream; mdProfileData->size = sizeof(CORBBTPROF_BLOB_ENTRY); } // Responsible for writing out the profile data if the COMPlus_BBInstr // environment variable is set. This is called when the module is unloaded // (usually at shutdown). HRESULT Module::WriteMethodProfileDataLogFile(bool cleanup) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_TRIGGERS; MODE_ANY; INJECT_FAULT(return E_OUTOFMEMORY;); } CONTRACTL_END; HRESULT hr = S_OK; if (IsResource()) return S_OK; EX_TRY { if (GetAssembly()->IsInstrumented() && (m_pProfilingBlobTable != NULL) && (m_tokenProfileData != NULL)) { ProfileEmitter * pEmitter = new ProfileEmitter(); // Get this ahead of time - metadata access may be logged, which will // take the m_tokenProfileData->crst, which we take a couple lines below LPCSTR pszName; GUID mvid; IfFailThrow(GetMDImport()->GetScopeProps(&pszName, &mvid)); CrstHolder ch(&m_tokenProfileData->crst); // // Create the scenario info section // ProfileDataAllocateScenarioInfo(pEmitter, pszName, &mvid); // // Create the method block count section // ProfileDataAllocateMethodBlockCounts(pEmitter, m_methodProfileList); // // Create the token list sections // ProfileDataAllocateTokenLists(pEmitter, m_tokenProfileData); // // Create the ibc token definition section (aka the Blob stream) // ProfileDataAllocateTokenDefinitions(pEmitter, this); // // Now store the profile data in the ibc file // ProfileMap profileImage; pEmitter->Serialize(&profileImage, mvid); HandleHolder profileDataFile(OpenMethodProfileDataLogFile(mvid)); ULONG count; BOOL result = WriteFile(profileDataFile, profileImage.getOffsetPtr(0), profileImage.getCurrentOffset(), &count, NULL); if (!result || (count != profileImage.getCurrentOffset())) { DWORD lasterror = GetLastError(); _ASSERTE(!"Error writing ibc profile data to file"); hr = HRESULT_FROM_WIN32(lasterror); } } if (cleanup) { DeleteProfilingData(); } } EX_CATCH { hr = E_FAIL; } EX_END_CATCH(SwallowAllExceptions) return hr; } /* static */ void Module::WriteAllModuleProfileData(bool cleanup) { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; // Iterate over all the app domains; for each one iterator over its // assemblies; for each one iterate over its modules. EX_TRY { AppDomainIterator appDomainIterator(FALSE); while(appDomainIterator.Next()) { AppDomain * appDomain = appDomainIterator.GetDomain(); AppDomain::AssemblyIterator assemblyIterator = appDomain->IterateAssembliesEx( (AssemblyIterationFlags)(kIncludeLoaded | kIncludeExecution)); CollectibleAssemblyHolder<DomainAssembly *> pDomainAssembly; while (assemblyIterator.Next(pDomainAssembly.This())) { DomainModuleIterator i = pDomainAssembly->IterateModules(kModIterIncludeLoaded); while (i.Next()) { /*hr=*/i.GetModule()->WriteMethodProfileDataLogFile(cleanup); } } } } EX_CATCH { } EX_END_CATCH(SwallowAllExceptions); } PTR_ProfilingBlobTable Module::GetProfilingBlobTable() { LIMITED_METHOD_CONTRACT; return m_pProfilingBlobTable; } void Module::CreateProfilingData() { TokenProfileData *tpd = TokenProfileData::CreateNoThrow(); PVOID pv = InterlockedCompareExchangeT(&m_tokenProfileData, tpd, NULL); if (pv != NULL) { delete tpd; } PTR_ProfilingBlobTable ppbt = new (nothrow) ProfilingBlobTable(); if (ppbt != NULL) { pv = InterlockedCompareExchangeT(&m_pProfilingBlobTable, ppbt, NULL); if (pv != NULL) { delete ppbt; } } } void Module::DeleteProfilingData() { if (m_pProfilingBlobTable != NULL) { for (ProfilingBlobTable::Iterator cur = m_pProfilingBlobTable->Begin(), end = m_pProfilingBlobTable->End(); (cur != end); cur++) { const ProfilingBlobEntry * pCurrentEntry = *cur; delete pCurrentEntry; } delete m_pProfilingBlobTable; m_pProfilingBlobTable = NULL; } if (m_tokenProfileData != NULL) { delete m_tokenProfileData; m_tokenProfileData = NULL; } // the metadataProfileData is free'ed in destructor of the corresponding MetaDataTracker } #endif //FEATURE_PREJIT void Module::SetIsIJWFixedUp() { LIMITED_METHOD_CONTRACT; FastInterlockOr(&m_dwTransientFlags, IS_IJW_FIXED_UP); } #ifdef FEATURE_PREJIT /* static */ Module::TokenProfileData *Module::TokenProfileData::CreateNoThrow(void) { STATIC_CONTRACT_NOTHROW; TokenProfileData *tpd = NULL; EX_TRY { // // This constructor calls crst.Init(), which may throw. So putting (nothrow) doesn't // do what we would want it to. Thus I wrap it here in a TRY/CATCH and revert to NULL // if it fails. // tpd = new TokenProfileData(); } EX_CATCH { tpd = NULL; } EX_END_CATCH(SwallowAllExceptions); return tpd; } #endif // FEATURE_PREJIT #endif // !DACCESS_COMPILE #ifndef DACCESS_COMPILE void Module::SetBeingUnloaded() { LIMITED_METHOD_CONTRACT; FastInterlockOr((ULONG*)&m_dwTransientFlags, IS_BEING_UNLOADED); } #endif #ifdef FEATURE_PREJIT void Module::LogTokenAccess(mdToken token, SectionFormat format, ULONG flagnum) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(g_IBCLogger.InstrEnabled()); PRECONDITION(flagnum < CORBBTPROF_TOKEN_MAX_NUM_FLAGS); } CONTRACTL_END; #ifndef DACCESS_COMPILE // // If we are in ngen instrumentation mode, then we should record this token. // if (!m_nativeImageProfiling) return; if (flagnum >= CORBBTPROF_TOKEN_MAX_NUM_FLAGS) { return; } mdToken rid = RidFromToken(token); CorTokenType tkType = (CorTokenType) TypeFromToken(token); SectionFormat tkKind = (SectionFormat) (tkType >> 24); if ((rid == 0) && (tkKind < (SectionFormat) TBL_COUNT)) return; FAULT_NOT_FATAL(); _ASSERTE(TypeProfilingData == FirstTokenFlagSection + TBL_TypeDef); _ASSERTE(MethodProfilingData == FirstTokenFlagSection + TBL_Method); _ASSERTE(SectionFormatCount >= FirstTokenFlagSection + TBL_COUNT + 4); if (!m_tokenProfileData) { CreateProfilingData(); } if (!m_tokenProfileData) { return; } if (tkKind == (SectionFormat) (ibcTypeSpec >> 24)) tkKind = IbcTypeSpecSection; else if (tkKind == (SectionFormat) (ibcMethodSpec >> 24)) tkKind = IbcMethodSpecSection; _ASSERTE(tkKind >= 0); _ASSERTE(tkKind < SectionFormatCount); if (tkKind < 0 || tkKind >= SectionFormatCount) { return; } CQuickArray<CORBBTPROF_TOKEN_INFO> * pTokenArray = &m_tokenProfileData->m_formats[format].tokenArray; RidBitmap * pTokenBitmap = &m_tokenProfileData->m_formats[tkKind].tokenBitmaps[flagnum]; // Have we seen this token with this flag already? if (pTokenBitmap->IsTokenInBitmap(token)) { return; } // Insert the token to the bitmap if (FAILED(pTokenBitmap->InsertToken(token))) { return; } ULONG flag = 1 << flagnum; // [ToDo] Fix: this is a sequential search and can be very slow for (unsigned int i = 0; i < pTokenArray->Size(); i++) { if ((*pTokenArray)[i].token == token) { _ASSERTE(! ((*pTokenArray)[i].flags & flag)); (*pTokenArray)[i].flags |= flag; return; } } if (FAILED(pTokenArray->ReSizeNoThrow(pTokenArray->Size() + 1))) { return; } (*pTokenArray)[pTokenArray->Size() - 1].token = token; (*pTokenArray)[pTokenArray->Size() - 1].flags = flag; (*pTokenArray)[pTokenArray->Size() - 1].scenarios = 0; #endif // !DACCESS_COMPILE } void Module::LogTokenAccess(mdToken token, ULONG flagNum) { WRAPPER_NO_CONTRACT; SectionFormat format = (SectionFormat)((TypeFromToken(token)>>24) + FirstTokenFlagSection); if (FirstTokenFlagSection <= format && format < SectionFormatCount) { LogTokenAccess(token, format, flagNum); } } #endif // FEATURE_PREJIT #ifndef DACCESS_COMPILE #ifdef FEATURE_PREJIT // // Encoding callbacks // /*static*/ DWORD Module::EncodeModuleHelper(void * pModuleContext, Module *pReferencedModule) { Module* pReferencingModule = (Module *) pModuleContext; _ASSERTE(pReferencingModule != pReferencedModule); Assembly *pReferencingAssembly = pReferencingModule->GetAssembly(); Assembly *pReferencedAssembly = pReferencedModule->GetAssembly(); _ASSERTE(pReferencingAssembly != pReferencedAssembly); if (pReferencedAssembly == pReferencingAssembly) { return 0; } mdAssemblyRef token = pReferencingModule->FindAssemblyRef(pReferencedAssembly); if (IsNilToken(token)) { return ENCODE_MODULE_FAILED; } return RidFromToken(token); } /*static*/ void Module::TokenDefinitionHelper(void* pModuleContext, Module *pReferencedModule, DWORD index, mdToken* pToken) { LIMITED_METHOD_CONTRACT; HRESULT hr; Module * pReferencingModule = (Module *) pModuleContext; mdAssemblyRef mdAssemblyRef = TokenFromRid(index, mdtAssemblyRef); IMDInternalImport * pImport = pReferencedModule->GetMDImport(); LPCUTF8 szName = NULL; if (TypeFromToken(*pToken) == mdtTypeDef) { // // Compute nested type (if any) // mdTypeDef mdEnclosingType = idExternalTypeNil; hr = pImport->GetNestedClassProps(*pToken, &mdEnclosingType); // If there's not enclosing type, then hr=CLDB_E_RECORD_NOTFOUND and mdEnclosingType is unchanged _ASSERTE((hr == S_OK) || (hr == CLDB_E_RECORD_NOTFOUND)); if (!IsNilToken(mdEnclosingType)) { _ASSERT(TypeFromToken(mdEnclosingType) == mdtTypeDef); TokenDefinitionHelper(pModuleContext, pReferencedModule, index, &mdEnclosingType); } _ASSERT(TypeFromToken(mdEnclosingType) == ibcExternalType); // // Compute type name and namespace. // LPCUTF8 szNamespace = NULL; hr = pImport->GetNameOfTypeDef(*pToken, &szName, &szNamespace); _ASSERTE(hr == S_OK); // // Transform namespace string into ibc external namespace token // idExternalNamespace idNamespace = idExternalNamespaceNil; if (szNamespace != NULL) { const ExternalNamespaceBlobEntry * pNamespaceEntry; pNamespaceEntry = ExternalNamespaceBlobEntry::FindOrAdd(pReferencingModule, szNamespace); if (pNamespaceEntry != NULL) { idNamespace = pNamespaceEntry->token(); } } _ASSERTE(TypeFromToken(idNamespace) == ibcExternalNamespace); // // Transform type name into ibc external type token // idExternalType idType = idExternalTypeNil; _ASSERTE(szName != NULL); const ExternalTypeBlobEntry * pTypeEntry = NULL; pTypeEntry = ExternalTypeBlobEntry::FindOrAdd(pReferencingModule, mdAssemblyRef, mdEnclosingType, idNamespace, szName); if (pTypeEntry != NULL) { idType = pTypeEntry->token(); } _ASSERTE(TypeFromToken(idType) == ibcExternalType); *pToken = idType; // Remap pToken to our idExternalType token } else if (TypeFromToken(*pToken) == mdtMethodDef) { // // Compute nested type (if any) // mdTypeDef mdEnclosingType = idExternalTypeNil; hr = pImport->GetParentToken(*pToken, &mdEnclosingType); _ASSERTE(!FAILED(hr)); if (!IsNilToken(mdEnclosingType)) { _ASSERT(TypeFromToken(mdEnclosingType) == mdtTypeDef); TokenDefinitionHelper(pModuleContext, pReferencedModule, index, &mdEnclosingType); } _ASSERT(TypeFromToken(mdEnclosingType) == ibcExternalType); // // Compute the method name and signature // PCCOR_SIGNATURE pSig = NULL; DWORD cbSig = 0; hr = pImport->GetNameAndSigOfMethodDef(*pToken, &pSig, &cbSig, &szName); _ASSERTE(hr == S_OK); // // Transform signature into ibc external signature token // idExternalSignature idSignature = idExternalSignatureNil; if (pSig != NULL) { const ExternalSignatureBlobEntry * pSignatureEntry; pSignatureEntry = ExternalSignatureBlobEntry::FindOrAdd(pReferencingModule, cbSig, pSig); if (pSignatureEntry != NULL) { idSignature = pSignatureEntry->token(); } } _ASSERTE(TypeFromToken(idSignature) == ibcExternalSignature); // // Transform method name into ibc external method token // idExternalMethod idMethod = idExternalMethodNil; _ASSERTE(szName != NULL); const ExternalMethodBlobEntry * pMethodEntry = NULL; pMethodEntry = ExternalMethodBlobEntry::FindOrAdd(pReferencingModule, mdEnclosingType, idSignature, szName); if (pMethodEntry != NULL) { idMethod = pMethodEntry->token(); } _ASSERTE(TypeFromToken(idMethod) == ibcExternalMethod); *pToken = idMethod; // Remap pToken to our idMethodSpec token } else { _ASSERTE(!"Unexpected token type"); } } idTypeSpec Module::LogInstantiatedType(TypeHandle typeHnd, ULONG flagNum) { CONTRACT(idTypeSpec) { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION(g_IBCLogger.InstrEnabled()); PRECONDITION(!typeHnd.HasUnrestoredTypeKey()); // We want to report the type only in its own loader module as a type's // MethodTable can only live in its own loader module. // We can relax this if we allow a (duplicate) MethodTable to live // in any module (which might be needed for ngen of generics) #ifdef FEATURE_PREJIT // All callsites already do this... // PRECONDITION(this == GetPreferredZapModuleForTypeHandle(typeHnd)); #endif } CONTRACT_END; idTypeSpec result = idTypeSpecNil; if (m_nativeImageProfiling) { CONTRACT_VIOLATION(ThrowsViolation|FaultViolation|GCViolation); SigBuilder sigBuilder; ZapSig zapSig(this, this, ZapSig::IbcTokens, Module::EncodeModuleHelper, Module::TokenDefinitionHelper); BOOL fSuccess = zapSig.GetSignatureForTypeHandle(typeHnd, &sigBuilder); // a return value of 0 indicates a failure to create the signature if (fSuccess) { DWORD cbSig; PCCOR_SIGNATURE pSig = (PCCOR_SIGNATURE)sigBuilder.GetSignature(&cbSig); ULONG flag = (1 << flagNum); TypeSpecBlobEntry * pEntry = const_cast<TypeSpecBlobEntry *>(TypeSpecBlobEntry::FindOrAdd(this, cbSig, pSig)); if (pEntry != NULL) { // Update the flags with any new bits pEntry->orFlag(flag); result = pEntry->token(); } } } _ASSERTE(TypeFromToken(result) == ibcTypeSpec); RETURN result; } idMethodSpec Module::LogInstantiatedMethod(const MethodDesc * md, ULONG flagNum) { CONTRACT(idMethodSpec) { NOTHROW; GC_NOTRIGGER; MODE_ANY; PRECONDITION( md != NULL ); } CONTRACT_END; idMethodSpec result = idMethodSpecNil; if (m_nativeImageProfiling) { CONTRACT_VIOLATION(ThrowsViolation|FaultViolation|GCViolation); // get data SigBuilder sigBuilder; BOOL fSuccess; fSuccess = ZapSig::EncodeMethod(const_cast<MethodDesc *>(md), this, &sigBuilder, (LPVOID) this, (ENCODEMODULE_CALLBACK) Module::EncodeModuleHelper, (DEFINETOKEN_CALLBACK) Module::TokenDefinitionHelper); if (fSuccess) { DWORD dataSize; BYTE * pBlob = (BYTE *)sigBuilder.GetSignature(&dataSize); ULONG flag = (1 << flagNum); MethodSpecBlobEntry * pEntry = const_cast<MethodSpecBlobEntry *>(MethodSpecBlobEntry::FindOrAdd(this, dataSize, pBlob)); if (pEntry != NULL) { // Update the flags with any new bits pEntry->orFlag(flag); result = pEntry->token(); } } } _ASSERTE(TypeFromToken(result) == ibcMethodSpec); RETURN result; } #endif // DACCESS_COMPILE #endif //FEATURE_PREJIT #ifndef DACCESS_COMPILE #ifndef CROSSGEN_COMPILE // =========================================================================== // ReflectionModule // =========================================================================== /* static */ ReflectionModule *ReflectionModule::Create(Assembly *pAssembly, PEFile *pFile, AllocMemTracker *pamTracker, LPCWSTR szName, BOOL fIsTransient) { CONTRACT(ReflectionModule *) { STANDARD_VM_CHECK; PRECONDITION(CheckPointer(pAssembly)); PRECONDITION(CheckPointer(pFile)); PRECONDITION(pFile->IsDynamic()); POSTCONDITION(CheckPointer(RETVAL)); } CONTRACT_END; // Hoist CONTRACT into separate routine because of EX incompatibility mdFile token; _ASSERTE(pFile->IsAssembly()); token = mdFileNil; // Initial memory block for Modules must be zero-initialized (to make it harder // to introduce Destruct crashes arising from OOM's during initialization.) void* pMemory = pamTracker->Track(pAssembly->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(ReflectionModule)))); ReflectionModuleHolder pModule(new (pMemory) ReflectionModule(pAssembly, token, pFile)); pModule->DoInit(pamTracker, szName); // Set this at module creation time. The m_fIsTransient field should never change during the lifetime of this ReflectionModule. pModule->SetIsTransient(fIsTransient ? true : false); RETURN pModule.Extract(); } // Module initialization occurs in two phases: the constructor phase and the Initialize phase. // // The constructor phase initializes just enough so that Destruct() can be safely called. // It cannot throw or fail. // ReflectionModule::ReflectionModule(Assembly *pAssembly, mdFile token, PEFile *pFile) : Module(pAssembly, token, pFile) { CONTRACTL { NOTHROW; GC_TRIGGERS; FORBID_FAULT; } CONTRACTL_END m_pInMemoryWriter = NULL; m_sdataSection = NULL; m_pISymUnmanagedWriter = NULL; m_pCreatingAssembly = NULL; m_pCeeFileGen = NULL; m_pDynamicMetadata = NULL; m_fSuppressMetadataCapture = false; m_fIsTransient = false; } HRESULT STDMETHODCALLTYPE CreateICeeGen(REFIID riid, void **pCeeGen); // Module initialization occurs in two phases: the constructor phase and the Initialize phase. // // The Initialize() phase completes the initialization after the constructor has run. // It can throw exceptions but whether it throws or succeeds, it must leave the Module // in a state where Destruct() can be safely called. // void ReflectionModule::Initialize(AllocMemTracker *pamTracker, LPCWSTR szName) { CONTRACTL { INSTANCE_CHECK; STANDARD_VM_CHECK; PRECONDITION(szName != NULL); } CONTRACTL_END; Module::Initialize(pamTracker); IfFailThrow(CreateICeeGen(IID_ICeeGen, (void **)&m_pCeeFileGen)); // Collectible modules should try to limit the growth of their associate IL section, as common scenarios for collectible // modules include single type modules if (IsCollectible()) { ReleaseHolder<ICeeGenInternal> pCeeGenInternal(NULL); IfFailThrow(m_pCeeFileGen->QueryInterface(IID_ICeeGenInternal, (void **)&pCeeGenInternal)); IfFailThrow(pCeeGenInternal->SetInitialGrowth(CEE_FILE_GEN_GROWTH_COLLECTIBLE)); } m_pInMemoryWriter = new RefClassWriter(); IfFailThrow(m_pInMemoryWriter->Init(GetCeeGen(), GetEmitter(), szName)); m_CrstLeafLock.Init(CrstLeafLock); } void ReflectionModule::Destruct() { CONTRACTL { NOTHROW; GC_TRIGGERS; MODE_PREEMPTIVE; } CONTRACTL_END; delete m_pInMemoryWriter; if (m_pISymUnmanagedWriter) { m_pISymUnmanagedWriter->Close(); m_pISymUnmanagedWriter->Release(); m_pISymUnmanagedWriter = NULL; } if (m_pCeeFileGen) m_pCeeFileGen->Release(); Module::Destruct(); delete m_pDynamicMetadata; m_pDynamicMetadata = NULL; m_CrstLeafLock.Destroy(); } // Returns true iff metadata capturing is suppressed. // // Notes: // This is during the window after code:ReflectionModule.SuppressMetadataCapture and before // code:ReflectionModule.ResumeMetadataCapture. // // If metadata updates are suppressed, then class-load notifications should be suppressed too. bool ReflectionModule::IsMetadataCaptureSuppressed() { return m_fSuppressMetadataCapture; } // // Holder of changed value of MDUpdateMode via IMDInternalEmit::SetMDUpdateMode. // Returns back the original value on release. // class MDUpdateModeHolder { public: MDUpdateModeHolder() { m_pInternalEmitter = NULL; m_OriginalMDUpdateMode = ULONG_MAX; } ~MDUpdateModeHolder() { WRAPPER_NO_CONTRACT; (void)Release(); } HRESULT SetMDUpdateMode(IMetaDataEmit *pEmitter, ULONG updateMode) { LIMITED_METHOD_CONTRACT; HRESULT hr = S_OK; _ASSERTE(updateMode != ULONG_MAX); IfFailRet(pEmitter->QueryInterface(IID_IMDInternalEmit, (void **)&m_pInternalEmitter)); _ASSERTE(m_pInternalEmitter != NULL); IfFailRet(m_pInternalEmitter->SetMDUpdateMode(updateMode, &m_OriginalMDUpdateMode)); _ASSERTE(m_OriginalMDUpdateMode != ULONG_MAX); return hr; } HRESULT Release(ULONG expectedPreviousUpdateMode = ULONG_MAX) { HRESULT hr = S_OK; if (m_OriginalMDUpdateMode != ULONG_MAX) { _ASSERTE(m_pInternalEmitter != NULL); ULONG previousUpdateMode; // Ignore the error when releasing hr = m_pInternalEmitter->SetMDUpdateMode(m_OriginalMDUpdateMode, &previousUpdateMode); m_OriginalMDUpdateMode = ULONG_MAX; if (expectedPreviousUpdateMode != ULONG_MAX) { if ((hr == S_OK) && (expectedPreviousUpdateMode != previousUpdateMode)) { hr = S_FALSE; } } } if (m_pInternalEmitter != NULL) { (void)m_pInternalEmitter->Release(); m_pInternalEmitter = NULL; } return hr; } ULONG GetOriginalMDUpdateMode() { WRAPPER_NO_CONTRACT; _ASSERTE(m_OriginalMDUpdateMode != LONG_MAX); return m_OriginalMDUpdateMode; } private: IMDInternalEmit *m_pInternalEmitter; ULONG m_OriginalMDUpdateMode; }; // Called in live paths to fetch metadata for dynamic modules. This makes the metadata available to the // debugger from out-of-process. // // Notes: // This buffer can be retrieved by the debugger via code:ReflectionModule.GetDynamicMetadataBuffer // // Threading: // - Callers must ensure nobody else is adding to the metadata. // - This function still takes its own locks to cooperate with the Debugger's out-of-process access. // The debugger can slip this thread outside the locks to ensure the data is consistent. // // This does not raise a debug notification to invalidate the metadata. Reasoning is that this only // happens in two cases: // 1) manifest module is updated with the name of a new dynamic module. // 2) on each class load, in which case we already send a debug event. In this case, we already send a // class-load notification, so sending a separate "metadata-refresh" would make the eventing twice as // chatty. Class-load events are high-volume and events are slow. // Thus we can avoid the chatiness by ensuring the debugger knows that Class-load also means "refresh // metadata". // void ReflectionModule::CaptureModuleMetaDataToMemory() { CONTRACTL { THROWS; GC_TRIGGERS; } CONTRACTL_END; // If we've suppresed metadata capture, then skip this. We'll recapture when we enable it. This allows // for batching up capture. // If a debugger is attached, then the CLR will still send ClassLoad notifications for dynamic modules, // which mean we still need to keep the metadata available. This is the same as Whidbey. // An alternative (and better) design would be to suppress ClassLoad notifications too, but then we'd // need some way of sending a "catchup" notification to the debugger after we re-enable notifications. if (IsMetadataCaptureSuppressed() && !CORDebuggerAttached()) { return; } // Do not release the emitter. This is a weak reference. IMetaDataEmit *pEmitter = this->GetEmitter(); _ASSERTE(pEmitter != NULL); HRESULT hr; MDUpdateModeHolder hMDUpdateMode; IfFailThrow(hMDUpdateMode.SetMDUpdateMode(pEmitter, MDUpdateExtension)); _ASSERTE(hMDUpdateMode.GetOriginalMDUpdateMode() == MDUpdateFull); DWORD numBytes; hr = pEmitter->GetSaveSize(cssQuick, &numBytes); IfFailThrow(hr); // Operate on local data, and then persist it into the module once we know it's valid. NewHolder<SBuffer> pBuffer(new SBuffer()); _ASSERTE(pBuffer != NULL); // allocation would throw first // ReflectionModule is still in a consistent state, and now we're just operating on local data to // assemble the new metadata buffer. If this fails, then worst case is that metadata does not include // recently generated classes. // Caller ensures serialization that guarantees that the metadata doesn't grow underneath us. BYTE * pRawData = pBuffer->OpenRawBuffer(numBytes); hr = pEmitter->SaveToMemory(pRawData, numBytes); pBuffer->CloseRawBuffer(); IfFailThrow(hr); // Now that we're successful, transfer ownership back into the module. { CrstHolder ch(&m_CrstLeafLock); delete m_pDynamicMetadata; m_pDynamicMetadata = pBuffer.Extract(); } // hr = hMDUpdateMode.Release(MDUpdateExtension); // Will be S_FALSE if someone changed the MDUpdateMode (from MDUpdateExtension) meanwhile _ASSERTE(hr == S_OK); } // Suppress the eager metadata serialization. // // Notes: // This casues code:ReflectionModule.CaptureModuleMetaDataToMemory to be a nop. // This is not nestable. // This exists purely for performance reasons. // // Don't call this directly. Use a SuppressMetadataCaptureHolder holder to ensure it's // balanced with code:ReflectionModule.ResumeMetadataCapture // // Types generating while eager metadata-capture is suppressed should not actually be executed until // after metadata capture is restored. void ReflectionModule::SuppressMetadataCapture() { LIMITED_METHOD_CONTRACT; // If this fires, then you probably missed a call to ResumeMetadataCapture. CONSISTENCY_CHECK_MSG(!m_fSuppressMetadataCapture, "SuppressMetadataCapture is not nestable"); m_fSuppressMetadataCapture = true; } // Resumes eager metadata serialization. // // Notes: // This casues code:ReflectionModule.CaptureModuleMetaDataToMemory to resume eagerly serializing metadata. // This must be called after code:ReflectionModule.SuppressMetadataCapture. // void ReflectionModule::ResumeMetadataCapture() { WRAPPER_NO_CONTRACT; _ASSERTE(m_fSuppressMetadataCapture); m_fSuppressMetadataCapture = false; CaptureModuleMetaDataToMemory(); } void ReflectionModule::ReleaseILData() { WRAPPER_NO_CONTRACT; if (m_pISymUnmanagedWriter) { m_pISymUnmanagedWriter->Release(); m_pISymUnmanagedWriter = NULL; } Module::ReleaseILData(); } #endif // !CROSSGEN_COMPILE #endif // !DACCESS_COMPILE #ifdef DACCESS_COMPILE // Accessor to expose m_pDynamicMetadata to debugger. // // Returns: // Pointer to SBuffer containing metadata buffer. May be null. // // Notes: // Only used by the debugger, so only accessible via DAC. // The buffer is updated via code:ReflectionModule.CaptureModuleMetaDataToMemory PTR_SBuffer ReflectionModule::GetDynamicMetadataBuffer() const { SUPPORTS_DAC; // If we ask for metadata, but have been suppressing capture, then we're out of date. // However, the debugger may be debugging already baked types in the module and so may need the metadata // for that. So we return what we do have. // // Debugger will get the next metadata update: // 1) with the next load class // 2) or if this is right after the last class, see code:ReflectionModule.CaptureModuleMetaDataToMemory return m_pDynamicMetadata; } #endif TADDR ReflectionModule::GetIL(RVA il) // virtual { #ifndef DACCESS_COMPILE WRAPPER_NO_CONTRACT; BYTE* pByte = NULL; m_pCeeFileGen->GetMethodBuffer(il, &pByte); return TADDR(pByte); #else // DACCESS_COMPILE SUPPORTS_DAC; DacNotImpl(); return NULL; #endif // DACCESS_COMPILE } PTR_VOID ReflectionModule::GetRvaField(RVA field, BOOL fZapped) // virtual { _ASSERTE(!fZapped); #ifndef DACCESS_COMPILE WRAPPER_NO_CONTRACT; // This function should be call only if the target is a field or a field with RVA. PTR_BYTE pByte = NULL; m_pCeeFileGen->ComputePointer(m_sdataSection, field, &pByte); return dac_cast<PTR_VOID>(pByte); #else // DACCESS_COMPILE SUPPORTS_DAC; DacNotImpl(); return NULL; #endif // DACCESS_COMPILE } #ifndef DACCESS_COMPILE // =========================================================================== // VASigCookies // =========================================================================== //========================================================================== // Enregisters a VASig. //========================================================================== VASigCookie *Module::GetVASigCookie(Signature vaSignature) { CONTRACT(VASigCookie*) { INSTANCE_CHECK; THROWS; GC_TRIGGERS; MODE_ANY; POSTCONDITION(CheckPointer(RETVAL)); INJECT_FAULT(COMPlusThrowOM()); } CONTRACT_END; VASigCookieBlock *pBlock; VASigCookie *pCookie; pCookie = NULL; // First, see if we already enregistered this sig. // Note that we're outside the lock here, so be a bit careful with our logic for (pBlock = m_pVASigCookieBlock; pBlock != NULL; pBlock = pBlock->m_Next) { for (UINT i = 0; i < pBlock->m_numcookies; i++) { if (pBlock->m_cookies[i].signature.GetRawSig() == vaSignature.GetRawSig()) { pCookie = &(pBlock->m_cookies[i]); break; } } } if (!pCookie) { // If not, time to make a new one. // Compute the size of args first, outside of the lock. // @TODO GENERICS: We may be calling a varargs method from a // generic type/method. Using an empty context will make such a // case cause an unexpected exception. To make this work, // we need to create a specialized signature for every instantiation SigTypeContext typeContext; MetaSig metasig(vaSignature, this, &typeContext); ArgIterator argit(&metasig); // Upper estimate of the vararg size DWORD sizeOfArgs = argit.SizeOfArgStack(); // enable gc before taking lock { CrstHolder ch(&m_Crst); // Note that we were possibly racing to create the cookie, and another thread // may have already created it. We could put another check // here, but it's probably not worth the effort, so we'll just take an // occasional duplicate cookie instead. // Is the first block in the list full? if (m_pVASigCookieBlock && m_pVASigCookieBlock->m_numcookies < VASigCookieBlock::kVASigCookieBlockSize) { // Nope, reserve a new slot in the existing block. pCookie = &(m_pVASigCookieBlock->m_cookies[m_pVASigCookieBlock->m_numcookies]); } else { // Yes, create a new block. VASigCookieBlock *pNewBlock = new VASigCookieBlock(); pNewBlock->m_Next = m_pVASigCookieBlock; pNewBlock->m_numcookies = 0; m_pVASigCookieBlock = pNewBlock; pCookie = &(pNewBlock->m_cookies[0]); } // Now, fill in the new cookie (assuming we had enough memory to create one.) pCookie->pModule = this; pCookie->pNDirectILStub = NULL; pCookie->sizeOfArgs = sizeOfArgs; pCookie->signature = vaSignature; // Finally, now that it's safe for asynchronous readers to see it, // update the count. m_pVASigCookieBlock->m_numcookies++; } } RETURN pCookie; } // =========================================================================== // LookupMap // =========================================================================== #ifdef FEATURE_NATIVE_IMAGE_GENERATION int __cdecl LookupMapBase::HotItem::Cmp(const void* a_, const void* b_) { LIMITED_METHOD_CONTRACT; const HotItem *a = (const HotItem *)a_; const HotItem *b = (const HotItem *)b_; if (a->rid < b->rid) return -1; else if (a->rid > b->rid) return 1; else return 0; } void LookupMapBase::CreateHotItemList(DataImage *image, CorProfileData *profileData, int table, BOOL fSkipNullEntries /*= FALSE*/) { STANDARD_VM_CONTRACT; _ASSERTE(!MapIsCompressed()); if (profileData) { DWORD numInTokenList = profileData->GetHotTokens(table, 1<<RidMap, 1<<RidMap, NULL, 0); if (numInTokenList > 0) { HotItem *itemList = (HotItem*)(void*)image->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(HotItem)) * S_SIZE_T(numInTokenList)); mdToken *tokenList = (mdToken*)(void*)image->GetModule()->GetLoaderAllocator()->GetHighFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(mdToken)) * S_SIZE_T(numInTokenList)); profileData->GetHotTokens(table, 1<<RidMap, 1<<RidMap, tokenList, numInTokenList); DWORD numItems = 0; for (DWORD i = 0; i < numInTokenList; i++) { DWORD rid = RidFromToken(tokenList[i]); TADDR value = RelativePointer<TADDR>::GetValueMaybeNullAtPtr(dac_cast<TADDR>(GetElementPtr(RidFromToken(tokenList[i])))); if (!fSkipNullEntries || value != NULL) { itemList[numItems].rid = rid; itemList[numItems].value = value; ++numItems; } } if (numItems > 0) { qsort(itemList, // start of array numItems, // array size in elements sizeof(HotItem), // element size in bytes HotItem::Cmp); // comparer function // Eliminate any duplicates in the list. Due to the qsort, they must be adjacent now. // We do this by walking the array and copying entries that are not duplicates of the previous one. // We can start the loop at +1, because 0 is not a duplicate of the previous entry, and does not // need to be copied either. DWORD j = 1; for (DWORD i = 1; i < numItems; i++) { if (itemList[i].rid != itemList[i-1].rid) { itemList[j].rid = itemList[i].rid; itemList[j].value = itemList[i].value; j++; } } _ASSERTE(j <= numItems); numItems = j; // We have treated the values as normal TADDRs to let qsort move them around freely. // Fix them up to be the relative pointers now. for (DWORD ii = 0; ii < numItems; ii++) { if (itemList[ii].value != NULL) { RelativePointer<TADDR> *pRelPtr = (RelativePointer<TADDR> *)&itemList[ii].value; pRelPtr->SetValueMaybeNull(itemList[ii].value); } } if (itemList != NULL) image->StoreStructure(itemList, sizeof(HotItem)*numItems, DataImage::ITEM_RID_MAP_HOT); hotItemList = itemList; dwNumHotItems = numItems; } } } } void LookupMapBase::Save(DataImage *image, DataImage::ItemKind kind, CorProfileData *profileData, int table, BOOL fCopyValues /*= FALSE*/) { STANDARD_VM_CONTRACT; // the table index that comes in is a token mask, the upper 8 bits are the table type for the tokens, that's all we want table >>= 24; dwNumHotItems = 0; hotItemList = NULL; if (table != 0) { // Because we use the same IBC encoding to record a touch to the m_GenericTypeDefToCanonMethodTableMap as // to the m_TypeDefToMethodTableMap, the hot items we get in both will be the union of the touches. This limitation // in the IBC infrastructure does not hurt us much because touching an entry for a generic type in one map often if // not always implies touching the corresponding entry in the other. But when saving the GENERICTYPEDEF_MAP it // does mean that we need to be prepared to see "hot" items whose data is NULL in this map (specifically, the non- // generic types). We don't want the hot list to be unnecessarily big with these entries, so tell CreateHotItemList to // skip them. BOOL fSkipNullEntries = (kind == DataImage::ITEM_GENERICTYPEDEF_MAP); CreateHotItemList(image, profileData, table, fSkipNullEntries); } // Determine whether we want to compress this lookup map (to improve density of cold pages in the map on // hot item cache misses). We only enable this optimization for the TypeDefToMethodTable, the // GenericTypeDefToCanonMethodTable, and the MethodDefToDesc maps since (a) they're the largest and // as a result reap the most space savings and (b) these maps are fully populated in an ngen image and immutable // at runtime, something that's important when dealing with a compressed version of the table. if (kind == DataImage::ITEM_TYPEDEF_MAP || kind == DataImage::ITEM_GENERICTYPEDEF_MAP || kind == DataImage::ITEM_METHODDEF_MAP) { // The bulk of the compression work is done in the later stages of ngen image generation (since it // relies on knowing the final RVAs of each value stored in the table). So we create a specialzed // ZapNode that knows how to perform the compression for us. image->StoreCompressedLayoutMap(this, DataImage::ITEM_COMPRESSED_MAP); // We need to know we decided to compress during the Fixup stage but the table kind is not available // there. So we use the cIndexEntryBits field as a flag (this will be initialized to zero and is only // set to a meaningful value near the end of ngen image generation, during the compression of the // table itself). cIndexEntryBits = 1; // The ZapNode we allocated above takes care of all the rest of the processing for this map, so we're // done here. return; } SaveUncompressedMap(image, kind, fCopyValues); } void LookupMapBase::SaveUncompressedMap(DataImage *image, DataImage::ItemKind kind, BOOL fCopyValues /*= FALSE*/) { STANDARD_VM_CONTRACT; // We should only be calling this once per map _ASSERTE(!image->IsStored(pTable)); // // We will only store one (big) node instead of the full list, // and make the one node large enough to fit all the RIDs // ZapStoredStructure * pTableNode = image->StoreStructure(NULL, GetSize() * sizeof(TADDR), kind); LookupMapBase *map = this; DWORD offsetIntoCombo = 0; while (map != NULL) { DWORD len = map->dwCount * sizeof(void*); if (fCopyValues) image->CopyDataToOffset(pTableNode, offsetIntoCombo, map->pTable, len); image->BindPointer(map->pTable,pTableNode,offsetIntoCombo); offsetIntoCombo += len; map = map->pNext; } } void LookupMapBase::ConvertSavedMapToUncompressed(DataImage *image, DataImage::ItemKind kind) { STANDARD_VM_CONTRACT; // Check whether we decided to compress this map (see Save() above). if (cIndexEntryBits == 0) return; cIndexEntryBits = 0; SaveUncompressedMap(image, kind); } void LookupMapBase::Fixup(DataImage *image, BOOL fFixupEntries /*=TRUE*/) { STANDARD_VM_CONTRACT; if (hotItemList != NULL) image->FixupPointerField(this, offsetof(LookupMapBase, hotItemList)); // Find the biggest RID supported by the entire list of LookupMaps. // We will only store one LookupMap node instead of the full list, // and make it big enough to fit all RIDs. *(DWORD *)image->GetImagePointer(this, offsetof(LookupMapBase, dwCount)) = GetSize(); // Persist the supportedFlags that this particular instance was created with. *(TADDR *)image->GetImagePointer(this, offsetof(LookupMapBase, supportedFlags)) = supportedFlags; image->ZeroPointerField(this, offsetof(LookupMapBase, pNext)); // Check whether we've decided to compress this map (see Save() above). if (cIndexEntryBits == 1) { // In the compressed case most of the Fixup logic is performed by the specialized ZapNode we allocated // during Save(). But we still have to record fixups for any hot items we've cached (these aren't // compressed). for (DWORD i = 0; i < dwNumHotItems; i++) { TADDR *pHotValueLoc = &hotItemList[i].value; TADDR pHotValue = RelativePointer<TADDR>::GetValueMaybeNullAtPtr((TADDR)pHotValueLoc); TADDR flags = pHotValue & supportedFlags; pHotValue -= flags; if (image->IsStored((PVOID)pHotValue)) { image->FixupField(hotItemList, (BYTE *)pHotValueLoc - (BYTE *)hotItemList, (PVOID)pHotValue, flags, IMAGE_REL_BASED_RelativePointer); } else { image->ZeroPointerField(hotItemList, (BYTE *)pHotValueLoc - (BYTE *)hotItemList); } } // The ZapNode will handle everything else so we're done. return; } // Note that the caller is responsible for calling FixupPointerField() // or zeroing out the contents of pTable as appropriate image->FixupPointerField(this, offsetof(LookupMapBase, pTable)); if (fFixupEntries) { LookupMap<PVOID>::Iterator iter((LookupMap<PVOID> *)this); DWORD rid = 0; while (iter.Next()) { TADDR flags; PVOID p = iter.GetElementAndFlags(&flags); PTR_TADDR hotItemValuePtr = FindHotItemValuePtr(rid); if (image->IsStored(p)) { image->FixupField(pTable, rid * sizeof(TADDR), p, flags, IMAGE_REL_BASED_RelativePointer); // In case this item is also in the hot item subtable, fix it up there as well if (hotItemValuePtr != NULL) image->FixupField(hotItemList, (BYTE *)hotItemValuePtr - (BYTE *)hotItemList, p, flags, IMAGE_REL_BASED_RelativePointer); } else { image->ZeroPointerField(pTable, rid * sizeof(TADDR)); // In case this item is also in the hot item subtable, zero it there as well if (hotItemValuePtr != NULL) image->ZeroPointerField(hotItemList, (BYTE *)hotItemValuePtr - (BYTE *)hotItemList); } rid++; } } } #endif // FEATURE_NATIVE_IMAGE_GENERATION #endif // !DACCESS_COMPILE #ifdef DACCESS_COMPILE void LookupMapBase::EnumMemoryRegions(CLRDataEnumMemoryFlags flags, bool enumThis) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; SUPPORTS_DAC; } CONTRACTL_END; if (enumThis) { DacEnumHostDPtrMem(this); } if (pTable.IsValid()) { #ifdef FEATURE_PREJIT if (MapIsCompressed()) { // Compressed maps have tables whose size cannot be calculated cheaply. Plus they have an // additional index blob. DacEnumMemoryRegion(dac_cast<TADDR>(pTable), cbTable); DacEnumMemoryRegion(dac_cast<TADDR>(pIndex), cbIndex); } else #endif // FEATURE_PREJIT DacEnumMemoryRegion(dac_cast<TADDR>(pTable), dwCount * sizeof(TADDR)); } #ifdef FEATURE_PREJIT if (dwNumHotItems && hotItemList.IsValid()) { DacEnumMemoryRegion(dac_cast<TADDR>(hotItemList), dwNumHotItems * sizeof(HotItem)); } #endif // FEATURE_PREJIT } /* static */ void LookupMapBase::ListEnumMemoryRegions(CLRDataEnumMemoryFlags flags) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; SUPPORTS_DAC; } CONTRACTL_END; LookupMapBase * headMap = this; bool enumHead = false; while (headMap) { headMap->EnumMemoryRegions(flags, enumHead); if (!headMap->pNext.IsValid()) { break; } headMap = headMap->pNext; enumHead = true; } } #endif // DACCESS_COMPILE // Optimization intended for Module::EnsureActive only #include <optsmallperfcritical.h> #ifndef DACCESS_COMPILE VOID Module::EnsureActive() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; GetDomainFile()->EnsureActive(); } #endif // DACCESS_COMPILE #include <optdefault.h> #ifndef DACCESS_COMPILE VOID Module::EnsureAllocated() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; GetDomainFile()->EnsureAllocated(); } VOID Module::EnsureLibraryLoaded() { STANDARD_VM_CONTRACT; GetDomainFile()->EnsureLibraryLoaded(); } #endif // !DACCESS_COMPILE CHECK Module::CheckActivated() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; #ifndef DACCESS_COMPILE DomainFile *pDomainFile = FindDomainFile(GetAppDomain()); CHECK(pDomainFile != NULL); PREFIX_ASSUME(pDomainFile != NULL); CHECK(pDomainFile->CheckActivated()); #endif CHECK_OK; } #ifdef DACCESS_COMPILE void ModuleCtorInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags) { SUPPORTS_DAC; // This class is contained so do not enumerate 'this'. DacEnumMemoryRegion(dac_cast<TADDR>(ppMT), numElements * sizeof(RelativePointer<MethodTable *>)); DacEnumMemoryRegion(dac_cast<TADDR>(cctorInfoHot), numElementsHot * sizeof(ClassCtorInfoEntry)); DacEnumMemoryRegion(dac_cast<TADDR>(cctorInfoCold), (numElements - numElementsHot) * sizeof(ClassCtorInfoEntry)); DacEnumMemoryRegion(dac_cast<TADDR>(hotHashOffsets), numHotHashes * sizeof(DWORD)); DacEnumMemoryRegion(dac_cast<TADDR>(coldHashOffsets), numColdHashes * sizeof(DWORD)); } void Module::EnumMemoryRegions(CLRDataEnumMemoryFlags flags, bool enumThis) { CONTRACTL { INSTANCE_CHECK; NOTHROW; GC_NOTRIGGER; MODE_ANY; FORBID_FAULT; SUPPORTS_DAC; } CONTRACTL_END; if (enumThis) { DAC_ENUM_VTHIS(); EMEM_OUT(("MEM: %p Module\n", dac_cast<TADDR>(this))); } //Save module id data only if it a real pointer, not a tagged sugestion to use ModuleIndex. if (!Module::IsEncodedModuleIndex(GetModuleID())) { if (m_ModuleID.IsValid()) { m_ModuleID->EnumMemoryRegions(flags); } } // TODO: Enumerate DomainLocalModules? It's not clear if we need all AppDomains // in the multi-domain case (where m_ModuleID has it's low-bit set). if (m_file.IsValid()) { m_file->EnumMemoryRegions(flags); } if (m_pAssembly.IsValid()) { m_pAssembly->EnumMemoryRegions(flags); } m_TypeRefToMethodTableMap.ListEnumMemoryRegions(flags); m_TypeDefToMethodTableMap.ListEnumMemoryRegions(flags); if (flags != CLRDATA_ENUM_MEM_MINI && flags != CLRDATA_ENUM_MEM_TRIAGE) { if (m_pAvailableClasses.IsValid()) { m_pAvailableClasses->EnumMemoryRegions(flags); } if (m_pAvailableParamTypes.IsValid()) { m_pAvailableParamTypes->EnumMemoryRegions(flags); } if (m_pInstMethodHashTable.IsValid()) { m_pInstMethodHashTable->EnumMemoryRegions(flags); } if (m_pAvailableClassesCaseIns.IsValid()) { m_pAvailableClassesCaseIns->EnumMemoryRegions(flags); } #ifdef FEATURE_PREJIT if (m_pStubMethodHashTable.IsValid()) { m_pStubMethodHashTable->EnumMemoryRegions(flags); } #endif // FEATURE_PREJIT if (m_pBinder.IsValid()) { m_pBinder->EnumMemoryRegions(flags); } m_ModuleCtorInfo.EnumMemoryRegions(flags); // Save the LookupMap structures. m_MethodDefToDescMap.ListEnumMemoryRegions(flags); m_FieldDefToDescMap.ListEnumMemoryRegions(flags); m_pMemberRefToDescHashTable->EnumMemoryRegions(flags); m_GenericParamToDescMap.ListEnumMemoryRegions(flags); m_GenericTypeDefToCanonMethodTableMap.ListEnumMemoryRegions(flags); m_FileReferencesMap.ListEnumMemoryRegions(flags); m_ManifestModuleReferencesMap.ListEnumMemoryRegions(flags); m_MethodDefToPropertyInfoMap.ListEnumMemoryRegions(flags); LookupMap<PTR_MethodTable>::Iterator typeDefIter(&m_TypeDefToMethodTableMap); while (typeDefIter.Next()) { if (typeDefIter.GetElement()) { typeDefIter.GetElement()->EnumMemoryRegions(flags); } } LookupMap<PTR_TypeRef>::Iterator typeRefIter(&m_TypeRefToMethodTableMap); while (typeRefIter.Next()) { if (typeRefIter.GetElement()) { TypeHandle th = TypeHandle::FromTAddr(dac_cast<TADDR>(typeRefIter.GetElement())); th.EnumMemoryRegions(flags); } } LookupMap<PTR_MethodDesc>::Iterator methodDefIter(&m_MethodDefToDescMap); while (methodDefIter.Next()) { if (methodDefIter.GetElement()) { methodDefIter.GetElement()->EnumMemoryRegions(flags); } } LookupMap<PTR_FieldDesc>::Iterator fieldDefIter(&m_FieldDefToDescMap); while (fieldDefIter.Next()) { if (fieldDefIter.GetElement()) { fieldDefIter.GetElement()->EnumMemoryRegions(flags); } } LookupMap<PTR_TypeVarTypeDesc>::Iterator genericParamIter(&m_GenericParamToDescMap); while (genericParamIter.Next()) { if (genericParamIter.GetElement()) { genericParamIter.GetElement()->EnumMemoryRegions(flags); } } LookupMap<PTR_MethodTable>::Iterator genericTypeDefIter(&m_GenericTypeDefToCanonMethodTableMap); while (genericTypeDefIter.Next()) { if (genericTypeDefIter.GetElement()) { genericTypeDefIter.GetElement()->EnumMemoryRegions(flags); } } } // !CLRDATA_ENUM_MEM_MINI && !CLRDATA_ENUM_MEM_TRIAGE LookupMap<PTR_Module>::Iterator fileRefIter(&m_FileReferencesMap); while (fileRefIter.Next()) { if (fileRefIter.GetElement()) { fileRefIter.GetElement()->EnumMemoryRegions(flags, true); } } LookupMap<PTR_Module>::Iterator asmRefIter(&m_ManifestModuleReferencesMap); while (asmRefIter.Next()) { if (asmRefIter.GetElement()) { asmRefIter.GetElement()->GetAssembly()->EnumMemoryRegions(flags); } } ECall::EnumFCallMethods(); } FieldDesc *Module::LookupFieldDef(mdFieldDef token) { WRAPPER_NO_CONTRACT; _ASSERTE(TypeFromToken(token) == mdtFieldDef); g_IBCLogger.LogRidMapAccess( MakePair( this, token ) ); return m_FieldDefToDescMap.GetElement(RidFromToken(token)); } #endif // DACCESS_COMPILE //------------------------------------------------------------------------------- // Make best-case effort to obtain an image name for use in an error message. // // This routine must expect to be called before the this object is fully loaded. // It can return an empty if the name isn't available or the object isn't initialized // enough to get a name, but it mustn't crash. //------------------------------------------------------------------------------- LPCWSTR Module::GetPathForErrorMessages() { CONTRACTL { THROWS; GC_TRIGGERS; if (FORBIDGC_LOADER_USE_ENABLED()) FORBID_FAULT; else { INJECT_FAULT(COMPlusThrowOM()); } } CONTRACTL_END PEFile *pFile = GetFile(); if (pFile) { return pFile->GetPathForErrorMessages(); } else { return W(""); } } #if defined(_DEBUG) && !defined(DACCESS_COMPILE) && !defined(CROSS_COMPILE) void Module::ExpandAll() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_ANY; } CONTRACTL_END; //This is called from inside EEStartupHelper, so it breaks the SO rules. However, this is debug only //(and only supported for limited jit testing), so it's ok here. CONTRACT_VIOLATION(SOToleranceViolation); //If the EE isn't started yet, it's not safe to jit. We fail in COM jitting a p/invoke. if (!g_fEEStarted) return; struct Local { static void CompileMethodDesc(MethodDesc * pMD) { //Must have a method body if (pMD->HasILHeader() //Can't jit open instantiations && !pMD->IsGenericMethodDefinition() //These are the only methods we can jit && (pMD->IsStatic() || pMD->GetNumGenericMethodArgs() == 0 || pMD->HasClassInstantiation()) && (pMD->MayHaveNativeCode() && !pMD->IsFCallOrIntrinsic())) { pMD->PrepareInitialCode(); } } static void CompileMethodsForMethodTable(MethodTable * pMT) { MethodTable::MethodIterator it(pMT); for (; it.IsValid(); it.Next()) { MethodDesc * pMD = it.GetMethodDesc(); CompileMethodDesc(pMD); } } #if 0 static void CompileMethodsForTypeDef(Module * pModule, mdTypeDef td) { TypeHandle th = ClassLoader::LoadTypeDefThrowing(pModule, td, ClassLoader::ThrowIfNotFound, ClassLoader::PermitUninstDefOrRef); MethodTable * pMT = th.GetMethodTable(); CompileMethodsForMethodTable(pMT); } #endif static void CompileMethodsForTypeDefRefSpec(Module * pModule, mdToken tok) { TypeHandle th; HRESULT hr = S_OK; EX_TRY { th = ClassLoader::LoadTypeDefOrRefOrSpecThrowing( pModule, tok, NULL /*SigTypeContext*/); } EX_CATCH { hr = GET_EXCEPTION()->GetHR(); } EX_END_CATCH(SwallowAllExceptions); //Only do this for non-generic types and unshared generic types //(canonical generics and value type generic instantiations). if (SUCCEEDED(hr) && !th.IsTypeDesc() && th.AsMethodTable()->IsCanonicalMethodTable()) { CompileMethodsForMethodTable(th.AsMethodTable()); } } static void CompileMethodsForMethodDefRefSpec(Module * pModule, mdToken tok) { HRESULT hr = S_OK; EX_TRY { MethodDesc * pMD = MemberLoader::GetMethodDescFromMemberDefOrRefOrSpec(pModule, tok, /*SigTypeContext*/NULL, TRUE, TRUE); CompileMethodDesc(pMD); } EX_CATCH { hr = GET_EXCEPTION()->GetHR(); //@telesto what should we do with this HR? the Silverlight code doesn't seem //to do anything...but that doesn't seem safe... } EX_END_CATCH(SwallowAllExceptions); } }; //Jit all methods eagerly IMDInternalImport * pMDI = GetMDImport(); HENUMTypeDefInternalHolder hEnum(pMDI); mdTypeDef td; hEnum.EnumTypeDefInit(); //verify global methods if (GetGlobalMethodTable()) { //jit everything in the MT. Local::CompileMethodsForTypeDefRefSpec(this, COR_GLOBAL_PARENT_TOKEN); } while (pMDI->EnumTypeDefNext(&hEnum, &td)) { //jit everything Local::CompileMethodsForTypeDefRefSpec(this, td); } //Get the type refs. They're always awesome. HENUMInternalHolder hEnumTypeRefs(pMDI); mdToken tr; hEnumTypeRefs.EnumAllInit(mdtTypeRef); while (hEnumTypeRefs.EnumNext(&tr)) { Local::CompileMethodsForTypeDefRefSpec(this, tr); } //make sure to get the type specs HENUMInternalHolder hEnumTypeSpecs(pMDI); mdToken ts; hEnumTypeSpecs.EnumAllInit(mdtTypeSpec); while (hEnumTypeSpecs.EnumNext(&ts)) { Local::CompileMethodsForTypeDefRefSpec(this, ts); } //And now for the interesting generic methods HENUMInternalHolder hEnumMethodSpecs(pMDI); mdToken ms; hEnumMethodSpecs.EnumAllInit(mdtMethodSpec); while (hEnumMethodSpecs.EnumNext(&ms)) { Local::CompileMethodsForMethodDefRefSpec(this, ms); } } #endif //_DEBUG && !DACCESS_COMPILE && !CROSS_COMPILE //------------------------------------------------------------------------------- // Verify consistency of asmconstants.h // Wrap all C_ASSERT's in asmconstants.h with a class definition. Many of the // fields referenced below are private, and this class is a friend of the // enclosing type. (A C_ASSERT isn't a compiler intrinsic, just a magic // typedef that produces a compiler error when the condition is false.) #include "clrvarargs.h" /* for VARARG C_ASSERTs in asmconstants.h */ class CheckAsmOffsets { #ifndef CROSSBITNESS_COMPILE #define ASMCONSTANTS_C_ASSERT(cond) static_assert(cond, #cond); #include "asmconstants.h" #endif // CROSSBITNESS_COMPILE }; //------------------------------------------------------------------------------- #ifndef DACCESS_COMPILE void Module::CreateAssemblyRefByNameTable(AllocMemTracker *pamTracker) { CONTRACTL { THROWS; GC_NOTRIGGER; INJECT_FAULT(COMPlusThrowOM();); } CONTRACTL_END LoaderHeap * pHeap = GetLoaderAllocator()->GetLowFrequencyHeap(); IMDInternalImport * pImport = GetMDImport(); DWORD dwMaxRid = pImport->GetCountWithTokenKind(mdtAssemblyRef); if (dwMaxRid == 0) return; S_SIZE_T dwAllocSize = S_SIZE_T(sizeof(LPWSTR)) * S_SIZE_T(dwMaxRid); m_AssemblyRefByNameTable = (LPCSTR *) pamTracker->Track( pHeap->AllocMem(dwAllocSize) ); DWORD dwCount = 0; for (DWORD rid=1; rid <= dwMaxRid; rid++) { mdAssemblyRef mdToken = TokenFromRid(rid,mdtAssemblyRef); LPCSTR szName; HRESULT hr; hr = pImport->GetAssemblyRefProps(mdToken, NULL, NULL, &szName, NULL, NULL, NULL, NULL); if (SUCCEEDED(hr)) { m_AssemblyRefByNameTable[dwCount++] = szName; } } m_AssemblyRefByNameCount = dwCount; } bool Module::HasReferenceByName(LPCUTF8 pModuleName) { LIMITED_METHOD_CONTRACT; for (DWORD i=0; i < m_AssemblyRefByNameCount; i++) { if (0 == strcmp(pModuleName, m_AssemblyRefByNameTable[i])) return true; } return false; } #endif #ifdef _MSC_VER #pragma warning(pop) #endif // _MSC_VER: warning C4244 #if defined(_DEBUG) && !defined(DACCESS_COMPILE) NOINLINE void NgenForceFailure_AV() { LIMITED_METHOD_CONTRACT; static int* alwaysNull = 0; *alwaysNull = 0; } NOINLINE void NgenForceFailure_TypeLoadException() { WRAPPER_NO_CONTRACT; ::ThrowTypeLoadException("ForceIBC", "Failure", W("Assembly"), NULL, IDS_CLASSLOAD_BADFORMAT); } void EEConfig::DebugCheckAndForceIBCFailure(BitForMask bitForMask) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; static DWORD s_ibcCheckCount = 0; // Both of these must be set to non-zero values for us to force a failure // if ((NgenForceFailureCount() == 0) || (NgenForceFailureKind() == 0)) return; // The bitForMask value must also beset in the FailureMask // if ((((DWORD) bitForMask) & NgenForceFailureMask()) == 0) return; s_ibcCheckCount++; if (s_ibcCheckCount < NgenForceFailureCount()) return; // We force one failure every NgenForceFailureCount() // s_ibcCheckCount = 0; switch (NgenForceFailureKind()) { case 1: NgenForceFailure_TypeLoadException(); break; case 2: NgenForceFailure_AV(); break; } } #endif // defined(_DEBUG) && !defined(DACCESS_COMPILE)
; A065383: a(n) = smallest prime >= n*(n + 1)/2. ; 2,2,3,7,11,17,23,29,37,47,59,67,79,97,107,127,137,157,173,191,211,233,257,277,307,331,353,379,409,439,467,499,541,563,599,631,673,709,743,787,821,863,907,947,991,1039,1087,1129,1181,1229,1277,1327,1381,1433,1487,1543,1597,1657,1721,1777,1831,1901,1973,2017,2081,2153,2213,2281,2347,2417,2503,2557,2633,2707,2777,2851,2927,3011,3083,3163,3251,3323,3407,3491,3571,3659,3761,3833,3917,4007,4099,4201,4283,4373,4481,4561,4657,4759,4861,4951 mov $2,$0 mul $2,$0 add $2,$0 div $2,2 lpb $2 lpb $0 add $1,1 gcd $0,$1 lpe sub $2,1 mul $0,$2 lpe add $1,2 mov $0,$1
push 1 push 1 sethi 0x0400 st_em 0x0,2,0 push 0 push 0 pull_cp 0 push 100 cmp_ult bz 5 drop 0 push 3 sethi 0x0400 st_em 0x0,2,0 halt tuck_cp 1 add pull 1 push 1 add j -15
; A053796: a(n) = (n^2+n) modulo 5. ; 0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0,0,2,1,2,0 mov $1,$0 pow $0,2 add $0,$1 mod $0,5
; A209359: a(n) = 2^n * (n^4 - 4*n^3 + 18*n^2 - 52*n + 75) - 75. ; 0,1,33,357,2405,12405,53877,207541,731829,2411445,7531445,22523829,64991157,181977013,496680885,1326120885,3473604533,8947236789,22706651061,56869519285,140755599285,344683708341,835954147253,2009692372917,4792831180725,11346431180725,26680001298357,62344403091381,144842134912949,334701432668085,769566871388085,1761189994430389,4012989808115637,9106481718755253,20585520551690165,46366061745930165,104077228064636853,232868591303655349,519447500990447541,1155361320908881845,2562736204462161845,5669693281278099381,12512385149486235573,27548430959695101877,60517032031860817845,132655989930244177845,290192467845617549237,633569491803225194421,1380662626788462034869,3003309854005028454325,6521747062888228454325,14138686238559855181749,30602981785097933422517,66138549076471912071093,142727268742692832542645,307570274103521412382645,661895334271334479822773,1422535368993295810166709,3053414318392966482231221,6546005837389048452218805,14016937187241416856698805,29980105025508587597725621,64052016092901225233645493,136699726085433148217229237,291442230996105682579619765,620728141926867247394979765,1320772339643273812578926517,2807662627184690186457972661,5962996795310735289602801589,12653150074907652494972682165,26826152481620175192577802165,56826970138564022380982697909,120281068558496678502960463797,254387970029351234865995972533,537603172906197863453058662325,1135277680894387335811458662325,2395665054798372045226527162293,5051753736227851018866675154869,10645310850338025683989536178101,22417250499583324468931712778165,47176051285290929966914197258165,99216343751938199568951212507061,208532677606659932412051967705013,438027036056496603088735092866997,919538669617016685574048249282485,1929245603417351118580393506242485,4045380925541799803183093904310197,8477961486978677724625914273202101,17757797705949431058282530088157109,37175580778047630304374305775943605,77786203766804530222440075944263605,162677893681137950443816798539218869,340048199490371922415936259387031477,710465613349134993716993228588187573 add $0,1 lpb $0 sub $0,1 mul $2,2 mov $3,$0 pow $3,4 add $2,$3 mov $1,$2 lpe div $1,2 mov $0,$1
db 0 ; species ID placeholder db 78, 70, 61, 100, 50, 61 ; hp atk def spd sat sdf db NORMAL, NORMAL ; type db 90 ; catch rate db 128 ; base exp db BERRY, GOLD_BERRY ; items db GENDER_F50 ; gender ratio db 15 ; step cycles to hatch INCBIN "gfx/pokemon/linoone/front.dimensions" db GROWTH_MEDIUM_FAST ; growth rate dn EGG_GROUND, EGG_GROUND ; egg groups db 70 ; happiness ; tm/hm learnset tmhm WATER_PULSE, ROAR, TOXIC, HIDDEN_POWER, SUNNY_DAY, ICE_BEAM, BLIZZARD, HYPER_BEAM, PROTECT, RAIN_DANCE, FRUSTRATION, IRON_TAIL, THUNDERBOLT, THUNDER, RETURN, DIG, SHADOW_BALL, DOUBLE_TEAM, SHOCK_WAVE, FACADE, SECRET_POWER, REST, ATTRACT, THIEF, FLING, CHARGE_BEAM, ENDURE, SHADOW_CLAW, GIGA_IMPACT, THUNDER_WAVE, CAPTIVATE, SLEEP_TALK, NATURAL_GIFT, GRASS_KNOT, SWAGGER, SUBSTITUTE, CUT, SURF, STRENGTH, ROCK_SMASH, FURY_CUTTER, GUNK_SHOT, HELPING_HAND, ICY_WIND, LAST_RESORT, MUD_SLAP, ROLLOUT, SEED_BOMB, SNORE, SWIFT, TRICK ; end
; infinite loop (e9 fd ff) loop: jmp loop ; Fill with 510 zeros - size of the prev code times 510 - ($ - $$) db 0 ; Magic number dw 0xaa55
; ; ZX81 libraries - Stefano ; ;---------------------------------------------------------------- ; ; $Id: zx_cls.asm,v 1.9 2016-06-26 20:32:08 dom Exp $ ; ;---------------------------------------------------------------- ; ; ROM mode CLS.. useful to expand collapsed display file ; ;---------------------------------------------------------------- SECTION code_clib PUBLIC zx_cls PUBLIC _zx_cls IF FORzx80 EXTERN filltxt ELSE EXTERN restore81 EXTERN zx_topleft ENDIF zx_cls: _zx_cls: IF FORzx80 ld l,0 jp filltxt ENDIF IF FORzx81 call restore81 call $A2A jp zx_topleft ENDIF IF FORlambda call restore81 call $1C7D jp zx_topleft ENDIF
; ; Grundy Newbrain Specific libraries ; ; Stefano Bodrato - 30/03/2007 ; ; ; Check if user pressed BREAK ; 1 if BREAK, otherwise 0 ; ; ; ; $Id: break_status.asm,v 1.2 2007/06/03 15:13:06 stefano Exp $ ; XLIB break_status .break_status rst 20h defb 36h ld hl,1 ret c dec hl ret
; A333296: Largest number of non-congruent integer-sided bricks that can be assembled into an n X n X n cube. ; Submitted by Jon Maiga ; 1,1,6,10,15,21,28,35,43,52 add $0,1 mov $2,$0 lpb $0 mov $3,$2 dif $3,$0 add $4,2 mul $3,$4 cmp $3,$2 cmp $3,0 add $6,1 mod $2,$6 mov $5,$4 cmp $5,0 add $4,$5 div $2,$4 sub $2,1 mul $3,$0 sub $0,1 add $1,$3 mul $4,$2 lpe mov $0,$1
#include <Font.h> #include <Utils.h> #include <Surface.h> #include <map> #if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX) // Include neko glue.... #define NEKO_COMPATIBLE #endif #include <ExternalInterface.h> namespace nme { // --- CFFI font delegates to haxe to get the glyphs ----- static int _id_bold; static int _id_name; static int _id_italic; static int _id_height; static int _id_ascent; static int _id_descent; static int _id_isRGB; static int _id_getGlyphInfo; static int _id_renderGlyphInternal; static int _id_width; static int _id_advance; static int _id_offsetX; static int _id_offsetY; class CFFIFont : public FontFace { public: CFFIFont(value inHandle) : mHandle(inHandle) { mAscent = val_number( val_field(inHandle, _id_ascent) ); mDescent = val_number( val_field(inHandle, _id_descent) ); mHeight = val_number( val_field(inHandle, _id_height) ); mIsRGB = val_bool( val_field(inHandle, _id_isRGB) ); } bool WantRGB() { return true; } bool GetGlyphInfo(int inChar, int &outW, int &outH, int &outAdvance, int &outOx, int &outOy) { value result = val_ocall1( mHandle.get(), _id_getGlyphInfo, alloc_int(inChar) ); if (!val_is_null(result)) { outW = val_number( val_field(result, _id_width) ); outH = val_number( val_field(result, _id_height) ); outAdvance = (int)(val_number( val_field(result, _id_advance) )) << 6; outOx = val_number( val_field(result, _id_offsetX) ); outOy = val_number( val_field(result, _id_offsetY) ); return true; } return false; } void RenderGlyph(int inChar,const RenderTarget &outTarget) { value glyphBmp = val_ocall1(mHandle.get(), _id_renderGlyphInternal, alloc_int(inChar) ); Surface *surface = 0; if (AbstractToObject(glyphBmp,surface) ) { surface->BlitTo(outTarget, Rect(0,0,surface->Width(), surface->Height()), outTarget.mRect.x, outTarget.mRect.y, bmNormal, 0 ); } } void UpdateMetrics(TextLineMetrics &ioMetrics) { ioMetrics.ascent = std::max( ioMetrics.ascent, (float)mAscent); ioMetrics.descent = std::max( ioMetrics.descent, (float)mDescent); ioMetrics.height = std::max( ioMetrics.height, (float)mHeight); } int Height() { return mHeight; } AutoGCRoot mHandle; float mAscent; float mDescent; int mHeight; bool mIsRGB; }; AutoGCRoot *sCFFIFontFactory = 0; value nme_font_set_factory(value inFactory) { if (!sCFFIFontFactory) { sCFFIFontFactory = new AutoGCRoot(inFactory); _id_bold = val_id("bold"); _id_name = val_id("name"); _id_italic = val_id("italic"); _id_height = val_id("height"); _id_ascent = val_id("ascent"); _id_descent = val_id("descent"); _id_isRGB = val_id("isRGB"); _id_getGlyphInfo = val_id("getGlyphInfo"); _id_renderGlyphInternal = val_id("renderGlyphInternal"); _id_width = val_id("width"); _id_advance = val_id("advance"); _id_offsetX = val_id("offset_x"); _id_offsetY = val_id("offsetY"); } return alloc_null(); } DEFINE_PRIM(nme_font_set_factory,1) FontFace *FontFace::CreateCFFIFont(const TextFormat &inFormat,double inScale) { if (!sCFFIFontFactory) return 0; value format = alloc_empty_object(); alloc_field(format, _id_bold, alloc_bool( inFormat.bold ) ); alloc_field(format, _id_name, alloc_wstring( inFormat.font.Get().c_str() ) ); alloc_field(format, _id_italic, alloc_bool( inFormat.italic ) ); alloc_field(format, _id_height, alloc_float( (int )(inFormat.size*inScale + 0.5) ) ); value result = val_call1( sCFFIFontFactory->get(), format ); if (val_is_null(result)) return 0; return new CFFIFont(result); } // --- Font ---------------------------------------------------------------- Font::Font(FontFace *inFace, int inPixelHeight, GlyphRotation inRotation,bool inInitRef) : Object(inInitRef), mFace(inFace), mPixelHeight(inPixelHeight) { mRotation = inRotation; mCurrentSheet = -1; } Font::~Font() { for(int i=0;i<mSheets.size();i++) mSheets[i]->DecRef(); } Tile Font::GetGlyph(int inCharacter,int &outAdvance) { bool use_default = false; Glyph &glyph = inCharacter < 128 ? mGlyph[inCharacter] : mExtendedGlyph[inCharacter]; if (glyph.sheet<0) { int gw,gh,adv,ox,oy; bool ok = mFace->GetGlyphInfo(inCharacter,gw,gh,adv,ox,oy); if (!ok) { if (inCharacter=='?') { gw = mPixelHeight; gh = mPixelHeight; ox = oy = 0; adv = mPixelHeight<<6; use_default = true; } else { Tile result = GetGlyph('?',outAdvance); glyph = mGlyph['?']; return result; } } int orig_w = gw; int orig_h = gh; switch(mRotation) { case gr0: break; case gr270: std::swap(gw,gh); std::swap(ox,oy); oy = -gh-oy; break; case gr180: ox = -gw-ox; oy = -gh-oy; break; case gr90: std::swap(gw,gh); std::swap(ox,oy); ox = -gw-ox; break; } while(1) { // Allocate new sheet? if (mCurrentSheet<0) { int rows = mPixelHeight > 128 ? 1 : mPixelHeight > 64 ? 2 : mPixelHeight>32 ? 4 : 5; int h = 4; while(h<mPixelHeight*rows) h*=2; int w = h; while(w<orig_w) w*=2; if (mRotation!=gr0 && mRotation!=gr180) std::swap(w,h); PixelFormat pf = mFace->WantRGB() ? pfARGB : pfAlpha; Tilesheet *sheet = new Tilesheet(w,h,pf,true); sheet->GetSurface().Clear(0); mCurrentSheet = mSheets.size(); mSheets.push_back(sheet); } int tid = mSheets[mCurrentSheet]->AllocRect(gw,gh,ox,oy); if (tid>=0) { glyph.sheet = mCurrentSheet; glyph.tile = tid; glyph.advance = adv; break; } // Need new sheet... mCurrentSheet = -1; } // Now fill rect... Tile tile = mSheets[glyph.sheet]->GetTile(glyph.tile); // SharpenText(bitmap); RenderTarget target = tile.mSurface->BeginRender(tile.mRect); if (use_default) { for(int y=0; y<target.mRect.h; y++) { uint8 *dest = (uint8 *)target.Row(y + target.mRect.y) + target.mRect.x; for(int x=0; x<target.mRect.w; x++) *dest++ = 0xff; } } else if (mRotation==gr0) mFace->RenderGlyph(inCharacter,target); else { SimpleSurface *buf = new SimpleSurface(orig_w,orig_h,pfAlpha,true); buf->IncRef(); { AutoSurfaceRender renderer(buf); mFace->RenderGlyph(inCharacter,renderer.Target()); } const uint8 *src; for(int y=0; y<target.mRect.h; y++) { uint8 *dest = (uint8 *)target.Row(y + target.mRect.y) + target.mRect.x; switch(mRotation) { case gr0: break; case gr270: src = buf->Row(0) + buf->Width() -1 - y; for(int x=0; x<target.mRect.w; x++) { *dest++ = *src; src += buf->GetStride(); } break; case gr180: src = buf->Row(buf->Height()-1-y) + buf->Width() -1; for(int x=0; x<target.mRect.w; x++) *dest++ = *src--; break; case gr90: src = buf->Row(buf->Height()-1) + y; for(int x=0; x<target.mRect.w; x++) { *dest++ = *src; src -= buf->GetStride(); } break; } } buf->DecRef(); } tile.mSurface->EndRender(); outAdvance = glyph.advance; return tile; } outAdvance = glyph.advance; return mSheets[glyph.sheet]->GetTile(glyph.tile); } void Font::UpdateMetrics(TextLineMetrics &ioMetrics) { if (mFace) mFace->UpdateMetrics(ioMetrics); } int Font::Height() { if (!mFace) return 12; return mFace->Height(); } // --- CharGroup --------------------------------------------- void CharGroup::UpdateMetrics(TextLineMetrics &ioMetrics) { if (mFont) mFont->UpdateMetrics(ioMetrics); } int CharGroup::Height() { return mFont ? mFont->Height() : 12; } // --- Create font from TextFormat ---------------------------------------------------- struct FontInfo { FontInfo(const TextFormat &inFormat,double inScale,GlyphRotation inRotation,bool inNative) { name = inFormat.font; height = (int )(inFormat.size*inScale + 0.5); flags = 0; native = inNative; if (inFormat.bold) flags |= ffBold; if (inFormat.italic) flags |= ffItalic; rotation = inRotation; } bool operator<(const FontInfo &inRHS) const { if (name < inRHS.name) return true; if (name > inRHS.name) return false; if (height < inRHS.height) return true; if (height > inRHS.height) return false; if (!native && inRHS.native) return true; if (native && !inRHS.native) return false; if (rotation < inRHS.rotation) return true; if (rotation > inRHS.rotation) return false; return flags < inRHS.flags; } WString name; bool native; int height; unsigned int flags; GlyphRotation rotation; }; typedef std::map<FontInfo, Font *> FontMap; FontMap sgFontMap; typedef std::map<std::string, AutoGCRoot *> FontBytesMap; FontBytesMap sgRegisteredFonts; Font *Font::Create(TextFormat &inFormat,double inScale,GlyphRotation inRotation,bool inNative,bool inInitRef) { FontInfo info(inFormat,inScale,inRotation,inNative); Font *font = 0; FontMap::iterator fit = sgFontMap.find(info); if (fit!=sgFontMap.end()) { font = fit->second; if (inInitRef) font->IncRef(); return font; } FontFace *face = 0; AutoGCRoot *bytes = 0; FontBytesMap::iterator fbit = sgRegisteredFonts.find(WideToUTF8(inFormat.font).c_str()); if (fbit!=sgRegisteredFonts.end()) { bytes = fbit->second; } if (bytes != NULL) face = FontFace::CreateFreeType(inFormat,inScale,bytes); if (!face) face = FontFace::CreateCFFIFont(inFormat,inScale); if (!face && inNative) face = FontFace::CreateNative(inFormat,inScale); if (!face) face = FontFace::CreateFreeType(inFormat,inScale,NULL); if (!face && !inNative) face = FontFace::CreateNative(inFormat,inScale); if (!face) return 0; font = new Font(face,info.height,inRotation,inInitRef); // Store for Ron ... font->IncRef(); sgFontMap[info] = font; // Clear out any old fonts for (FontMap::iterator fit = sgFontMap.begin(); fit!=sgFontMap.end();) { if (fit->second->GetRefCount()==1) { fit->second->DecRef(); FontMap::iterator next = fit; next++; sgFontMap.erase(fit); fit = next; } else ++fit; } return font; } value nme_font_register_font(value inFontName, value inBytes) { AutoGCRoot *bytes = new AutoGCRoot(inBytes); sgRegisteredFonts[std::string(val_string(inFontName))] = bytes; return alloc_null(); } DEFINE_PRIM(nme_font_register_font,2) } // end namespace nme
#define BOOST_TEST_MODULE example #include <boost/test/included/unit_test.hpp> //____________________________________________________________________________// BOOST_AUTO_TEST_CASE( test ) { int i = 7; int j = 7; BOOST_CHECK_LT( i, j ); } //____________________________________________________________________________//
copyright zengfr site:http://github.com/zengfr/romhack 00042A move.l D1, (A0)+ 00042C dbra D0, $42a 004D3C move.l D0, (A4)+ 004D3E move.l D0, (A4)+ 07ECC2 move.l A0, ($88,A6) [etc+80, etc+82] 07ECC6 move.b #$2, ($5,A6) [etc+88, etc+8A] 07ED0E move.l A0, ($88,A6) [etc+80, etc+82] 07ED12 movea.l ($80,A6), A1 [etc+88, etc+8A] 07ED22 move.l A0, ($88,A6) 07ED26 cmpi.w #$4040, D0 [etc+88, etc+8A] 089F0A move.b #$0, ($88,A6) [etc+84] 089F10 moveq #$0, D0 089F94 move.b #$1, ($88,A6) 089F9A bra $89fbc [etc+88] 089FB6 move.b #$0, ($88,A6) [base+7E4] 089FBC rts 0AAACA move.l (A0), D2 0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAACE move.w D0, ($2,A0) 0AAAD2 cmp.l (A0), D0 0AAAD4 bne $aaafc 0AAAD8 move.l D2, (A0)+ 0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAE6 move.l (A0), D2 0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] 0AAAF4 move.l D2, (A0)+ 0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1] copyright zengfr site:http://github.com/zengfr/romhack
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/utilities/wait_util.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/test_macros/test.h" #include "gtest/gtest.h" using namespace NEO; namespace CpuIntrinsicsTests { extern std::atomic<uint32_t> pauseCounter; } // namespace CpuIntrinsicsTests TEST(WaitTest, givenDefaultSettingsWhenNoPollAddressProvidedThenPauseDefaultTimeAndReturnFalse) { EXPECT_EQ(1u, WaitUtils::defaultWaitCount); WaitUtils::init(); EXPECT_EQ(WaitUtils::defaultWaitCount, WaitUtils::waitCount); uint32_t oldCount = CpuIntrinsicsTests::pauseCounter.load(); bool ret = WaitUtils::waitFunction(nullptr, 0u); EXPECT_FALSE(ret); EXPECT_EQ(oldCount + WaitUtils::waitCount, CpuIntrinsicsTests::pauseCounter); } TEST(WaitTest, givenDebugFlagOverridesWhenNoPollAddressProvidedThenPauseDefaultTimeAndReturnFalse) { DebugManagerStateRestore restore; VariableBackup<uint32_t> backupWaitCount(&WaitUtils::waitCount); uint32_t count = 10u; DebugManager.flags.WaitLoopCount.set(count); WaitUtils::init(); EXPECT_EQ(count, WaitUtils::waitCount); uint32_t oldCount = CpuIntrinsicsTests::pauseCounter.load(); bool ret = WaitUtils::waitFunction(nullptr, 0u); EXPECT_FALSE(ret); EXPECT_EQ(oldCount + count, CpuIntrinsicsTests::pauseCounter); } TEST(WaitTest, givenDefaultSettingsWhenPollAddressProvidedDoesNotMeetCriteriaThenPauseDefaultTimeAndReturnFalse) { WaitUtils::init(); EXPECT_EQ(WaitUtils::defaultWaitCount, WaitUtils::waitCount); volatile uint32_t pollValue = 1u; uint32_t expectedValue = 3; uint32_t oldCount = CpuIntrinsicsTests::pauseCounter.load(); bool ret = WaitUtils::waitFunction(&pollValue, expectedValue); EXPECT_FALSE(ret); EXPECT_EQ(oldCount + WaitUtils::waitCount, CpuIntrinsicsTests::pauseCounter); } TEST(WaitTest, givenDefaultSettingsWhenPollAddressProvidedMeetsCriteriaThenPauseDefaultTimeAndReturnTrue) { WaitUtils::init(); EXPECT_EQ(WaitUtils::defaultWaitCount, WaitUtils::waitCount); volatile uint32_t pollValue = 3u; uint32_t expectedValue = 1; uint32_t oldCount = CpuIntrinsicsTests::pauseCounter.load(); bool ret = WaitUtils::waitFunction(&pollValue, expectedValue); EXPECT_TRUE(ret); EXPECT_EQ(oldCount + WaitUtils::waitCount, CpuIntrinsicsTests::pauseCounter); } TEST(WaitTest, givenDebugFlagSetZeroWhenPollAddressProvidedMeetsCriteriaThenPauseZeroTimesAndReturnTrue) { DebugManagerStateRestore restore; VariableBackup<uint32_t> backupWaitCount(&WaitUtils::waitCount); uint32_t count = 0u; DebugManager.flags.WaitLoopCount.set(count); WaitUtils::init(); EXPECT_EQ(count, WaitUtils::waitCount); volatile uint32_t pollValue = 3u; uint32_t expectedValue = 1; uint32_t oldCount = CpuIntrinsicsTests::pauseCounter.load(); bool ret = WaitUtils::waitFunction(&pollValue, expectedValue); EXPECT_TRUE(ret); EXPECT_EQ(oldCount + WaitUtils::waitCount, CpuIntrinsicsTests::pauseCounter); }
#include "extensions/tracers/common/ot/opentracing_driver_impl.h" #include <sstream> #include "envoy/stats/scope.h" #include "common/common/assert.h" #include "common/common/base64.h" #include "common/common/utility.h" #include "common/tracing/http_tracer_impl.h" namespace Envoy { namespace Extensions { namespace Tracers { namespace Common { namespace Ot { Http::RegisterCustomInlineHeader<Http::CustomInlineHeaderRegistry::Type::RequestHeaders> ot_span_context_handle(Http::CustomHeaders::get().OtSpanContext); namespace { class OpenTracingHTTPHeadersWriter : public opentracing::HTTPHeadersWriter { public: explicit OpenTracingHTTPHeadersWriter(Http::HeaderMap& request_headers) : request_headers_(request_headers) {} // opentracing::HTTPHeadersWriter opentracing::expected<void> Set(opentracing::string_view key, opentracing::string_view value) const override { Http::LowerCaseString lowercase_key{key}; request_headers_.remove(lowercase_key); request_headers_.addCopy(std::move(lowercase_key), {value.data(), value.size()}); return {}; } private: Http::HeaderMap& request_headers_; }; class OpenTracingHTTPHeadersReader : public opentracing::HTTPHeadersReader { public: explicit OpenTracingHTTPHeadersReader(const Http::RequestHeaderMap& request_headers) : request_headers_(request_headers) {} using OpenTracingCb = std::function<opentracing::expected<void>(opentracing::string_view, opentracing::string_view)>; // opentracing::HTTPHeadersReader opentracing::expected<opentracing::string_view> LookupKey(opentracing::string_view key) const override { const Http::HeaderEntry* entry = request_headers_.get(Http::LowerCaseString{key}); if (entry != nullptr) { return opentracing::string_view{entry->value().getStringView().data(), entry->value().getStringView().length()}; } else { return opentracing::make_unexpected(opentracing::key_not_found_error); } } opentracing::expected<void> ForeachKey(OpenTracingCb f) const override { request_headers_.iterate(headerMapCallback(f)); return {}; } private: const Http::RequestHeaderMap& request_headers_; static Http::HeaderMap::ConstIterateCb headerMapCallback(OpenTracingCb callback) { return [callback = std::move(callback)](const Http::HeaderEntry& header) -> Http::HeaderMap::Iterate { opentracing::string_view key{header.key().getStringView().data(), header.key().getStringView().length()}; opentracing::string_view value{header.value().getStringView().data(), header.value().getStringView().length()}; if (callback(key, value)) { return Http::HeaderMap::Iterate::Continue; } else { return Http::HeaderMap::Iterate::Break; } }; } }; } // namespace OpenTracingSpan::OpenTracingSpan(OpenTracingDriver& driver, std::unique_ptr<opentracing::Span>&& span) : driver_{driver}, span_(std::move(span)) {} void OpenTracingSpan::finishSpan() { span_->FinishWithOptions(finish_options_); } void OpenTracingSpan::setOperation(absl::string_view operation) { span_->SetOperationName({operation.data(), operation.length()}); } void OpenTracingSpan::setTag(absl::string_view name, absl::string_view value) { span_->SetTag({name.data(), name.length()}, opentracing::v2::string_view{value.data(), value.length()}); } void OpenTracingSpan::log(SystemTime timestamp, const std::string& event) { opentracing::LogRecord record{timestamp, {{Tracing::Logs::get().EventKey, event}}}; finish_options_.log_records.emplace_back(std::move(record)); } void OpenTracingSpan::injectContext(Http::RequestHeaderMap& request_headers) { if (driver_.propagationMode() == OpenTracingDriver::PropagationMode::SingleHeader) { // Inject the span context using Envoy's single-header format. std::ostringstream oss; const opentracing::expected<void> was_successful = span_->tracer().Inject(span_->context(), oss); if (!was_successful) { ENVOY_LOG(debug, "Failed to inject span context: {}", was_successful.error().message()); driver_.tracerStats().span_context_injection_error_.inc(); return; } const std::string current_span_context = oss.str(); request_headers.setInline( ot_span_context_handle.handle(), Base64::encode(current_span_context.c_str(), current_span_context.length())); } else { // Inject the context using the tracer's standard HTTP header format. const OpenTracingHTTPHeadersWriter writer{request_headers}; const opentracing::expected<void> was_successful = span_->tracer().Inject(span_->context(), writer); if (!was_successful) { ENVOY_LOG(debug, "Failed to inject span context: {}", was_successful.error().message()); driver_.tracerStats().span_context_injection_error_.inc(); return; } } } void OpenTracingSpan::setSampled(bool sampled) { span_->SetTag(opentracing::ext::sampling_priority, sampled ? 1 : 0); } Tracing::SpanPtr OpenTracingSpan::spawnChild(const Tracing::Config&, const std::string& name, SystemTime start_time) { std::unique_ptr<opentracing::Span> ot_span = span_->tracer().StartSpan( name, {opentracing::ChildOf(&span_->context()), opentracing::StartTimestamp(start_time)}); RELEASE_ASSERT(ot_span != nullptr, ""); return Tracing::SpanPtr{new OpenTracingSpan{driver_, std::move(ot_span)}}; } OpenTracingDriver::OpenTracingDriver(Stats::Scope& scope) : tracer_stats_{OPENTRACING_TRACER_STATS(POOL_COUNTER_PREFIX(scope, "tracing.opentracing."))} {} Tracing::SpanPtr OpenTracingDriver::startSpan(const Tracing::Config& config, Http::RequestHeaderMap& request_headers, const std::string& operation_name, SystemTime start_time, const Tracing::Decision tracing_decision) { const PropagationMode propagation_mode = this->propagationMode(); const opentracing::Tracer& tracer = this->tracer(); std::unique_ptr<opentracing::Span> active_span; std::unique_ptr<opentracing::SpanContext> parent_span_ctx; if (propagation_mode == PropagationMode::SingleHeader && request_headers.getInline(ot_span_context_handle.handle())) { opentracing::expected<std::unique_ptr<opentracing::SpanContext>> parent_span_ctx_maybe; std::string parent_context = Base64::decode( std::string(request_headers.getInlineValue(ot_span_context_handle.handle()))); if (!parent_context.empty()) { InputConstMemoryStream istream{parent_context.data(), parent_context.size()}; parent_span_ctx_maybe = tracer.Extract(istream); } else { parent_span_ctx_maybe = opentracing::make_unexpected(opentracing::span_context_corrupted_error); } if (parent_span_ctx_maybe) { parent_span_ctx = std::move(*parent_span_ctx_maybe); } else { ENVOY_LOG(debug, "Failed to extract span context: {}", parent_span_ctx_maybe.error().message()); tracerStats().span_context_extraction_error_.inc(); } } else if (propagation_mode == PropagationMode::TracerNative) { const OpenTracingHTTPHeadersReader reader{request_headers}; opentracing::expected<std::unique_ptr<opentracing::SpanContext>> parent_span_ctx_maybe = tracer.Extract(reader); if (parent_span_ctx_maybe) { parent_span_ctx = std::move(*parent_span_ctx_maybe); } else { ENVOY_LOG(debug, "Failed to extract span context: {}", parent_span_ctx_maybe.error().message()); tracerStats().span_context_extraction_error_.inc(); } } opentracing::StartSpanOptions options; options.references.emplace_back(opentracing::SpanReferenceType::ChildOfRef, parent_span_ctx.get()); options.start_system_timestamp = start_time; if (!tracing_decision.traced) { options.tags.emplace_back(opentracing::ext::sampling_priority, 0); } active_span = tracer.StartSpanWithOptions(operation_name, options); RELEASE_ASSERT(active_span != nullptr, ""); active_span->SetTag(opentracing::ext::span_kind, config.operationName() == Tracing::OperationName::Egress ? opentracing::ext::span_kind_rpc_client : opentracing::ext::span_kind_rpc_server); return Tracing::SpanPtr{new OpenTracingSpan{*this, std::move(active_span)}}; } } // namespace Ot } // namespace Common } // namespace Tracers } // namespace Extensions } // namespace Envoy
; A180004: Nearest integer to n*(27/26) ; 1,2,3,4,5,6,7,8,9,10,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,68,69,70,71,72,73,74,75 mov $1,222222222 add $1,$0 div $1,26 add $1,$0 sub $1,8547007 mov $0,$1
; super rod data ; format: map, pointer to fishing group SuperRodData: dbw PALLET_TOWN, FishingGroup1 dbw VIRIDIAN_CITY, FishingGroup1 dbw CERULEAN_CITY, FishingGroup3 dbw VERMILION_CITY, FishingGroup4 dbw CELADON_CITY, FishingGroup5 dbw FUCHSIA_CITY, FishingGroup10 dbw CINNABAR_ISLAND, FishingGroup8 dbw ROUTE_4, FishingGroup3 dbw ROUTE_6, FishingGroup4 dbw ROUTE_10, FishingGroup5 dbw ROUTE_11, FishingGroup4 dbw ROUTE_12, FishingGroup7 dbw ROUTE_13, FishingGroup7 dbw ROUTE_17, FishingGroup7 dbw ROUTE_18, FishingGroup7 dbw ROUTE_19, FishingGroup8 dbw ROUTE_20, FishingGroup8 dbw ROUTE_21, FishingGroup8 dbw ROUTE_22, FishingGroup2 dbw ROUTE_23, FishingGroup9 dbw ROUTE_24, FishingGroup3 dbw ROUTE_25, FishingGroup3 dbw CERULEAN_GYM, FishingGroup3 dbw VERMILION_DOCK, FishingGroup4 dbw SEAFOAM_ISLANDS_B3F, FishingGroup8 dbw SEAFOAM_ISLANDS_B4F, FishingGroup8 dbw SAFARI_ZONE_EAST, FishingGroup6 dbw SAFARI_ZONE_NORTH, FishingGroup6 dbw SAFARI_ZONE_WEST, FishingGroup6 dbw SAFARI_ZONE_CENTER, FishingGroup6 dbw CERULEAN_CAVE_2F, FishingGroup9 dbw CERULEAN_CAVE_B1F, FishingGroup9 dbw CERULEAN_CAVE_1F, FishingGroup9 db $FF ; fishing groups ; number of monsters, followed by level/monster pairs FishingGroup1: db 2 db 15,TENTACOOL db 15,POLIWAG FishingGroup2: db 2 db 15,GOLDEEN db 15,POLIWAG FishingGroup3: db 3 db 15,PSYDUCK db 15,GOLDEEN db 15,KRABBY FishingGroup4: db 2 db 15,KRABBY db 15,SHELLDER FishingGroup5: db 2 db 23,POLIWHIRL db 15,SLOWPOKE FishingGroup6: db 4 db 15,DRATINI db 15,KRABBY db 15,PSYDUCK db 15,SLOWPOKE FishingGroup7: db 4 db 5,TENTACOOL db 15,KRABBY db 15,GOLDEEN db 15,MAGIKARP FishingGroup8: db 4 db 15,STARYU db 15,HORSEA db 15,SHELLDER db 15,GOLDEEN FishingGroup9: db 4 db 23,SLOWBRO db 23,SEAKING db 23,KINGLER db 23,SEADRA FishingGroup10: db 4 db 23,SEAKING db 15,KRABBY db 15,GOLDEEN db 15,MAGIKARP
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84_goodG2B.cpp Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml Template File: sources-sinks-84_goodG2B.tmpl.cpp */ /* * @description * CWE: 789 Uncontrolled Memory Allocation * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Small number greater than zero * Sinks: * GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated * BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define LISTEN_BACKLOG 5 #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) #define HELLO_STRING "hello" namespace CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84 { CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84_goodG2B::CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84_goodG2B(size_t dataCopy) { data = dataCopy; /* FIX: Use a relatively small number for memory allocation */ data = 20; } CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84_goodG2B::~CWE789_Uncontrolled_Mem_Alloc__malloc_char_listen_socket_84_goodG2B() { { char * myString; /* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough * for the strcpy() function to not cause a buffer overflow */ /* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */ if (data > strlen(HELLO_STRING)) { myString = (char *)malloc(data*sizeof(char)); if (myString == NULL) {exit(-1);} /* Copy a small string into myString */ strcpy(myString, HELLO_STRING); printLine(myString); free(myString); } else { printLine("Input is less than the length of the source string"); } } } } #endif /* OMITGOOD */
.MODEL SMALL .DATA INPUT DB 10,13 , 'ENTER 8-BIT BINARY DATA : $' OUTPUT DB 10,13, 'THE ASCII CHARACTER IS : $' .CODE .STARTUP MOV AH,09H MOV DX,OFFSET INPUT INT 21H MOV BL,00H MOV CL,08H INPUT1:MOV AH,01H INT 21H SUB AL,30H SHL BL,1 ADD BL,AL LOOP INPUT1 MOV AH,09H MOV DX,OFFSET OUTPUT INT 21H MOV AH,02H MOV DL,BL INT 21H .EXIT END
RESULTS_START EQU $c000 RESULTS_N_ROWS EQU 16 include "base.inc" ; The duty patterns are: ; 00: 00000010 ; 01: 00000011 ; 10: 00001111 ; 11: 11111100 ; The starting positions can be assumed from the other tests CorrectResults: db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $08, $08, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $08, $08, $08, $08, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $00, $00, $00, $00 db $00, $00, $00, $00, $08, $08, $08, $08 db $08, $08, $08, $08, $00, $00, $00, $00 db $00, $00, $00, $00, $08, $08, $08, $08 db $00, $00, $00, $00, $08, $08, $08, $08 db $08, $08, $08, $08, $08, $08, $08, $08 db $00, $00, $00, $00, $08, $08, $08, $08 db $08, $08, $08, $08, $08, $08, $08, $08 SubTest: MACRO xor a ldh [rNR52], a cpl ldh [rNR52], a ld a, $ff ldh [rNR13], a ld a, c ld hl, rPCM12 ldh [rNR11], a ld a, $80 ldh [rNR12], a ld a, $87 ldh [rNR14], a nops \1 ld a, [hl] call StoreResult ENDM RunTest: ld a, 1 ldh [rKEY1], a stop ld de, $c000 ld c, $00 call TestGroup ld c, $40 call TestGroup ld c, $80 call TestGroup ld c, $C0 call TestGroup ret TestGroup: SubTest $0 SubTest $1 SubTest $2 SubTest $3 SubTest $4 SubTest $5 SubTest $6 SubTest $7 SubTest $8 SubTest $9 SubTest $a SubTest $b SubTest $c SubTest $d SubTest $e SubTest $f SubTest $10 SubTest $11 SubTest $12 SubTest $13 SubTest $14 SubTest $15 SubTest $16 SubTest $17 SubTest $18 SubTest $19 SubTest $1a SubTest $1b SubTest $1c SubTest $1d SubTest $1e SubTest $1f ret StoreResult:: ld [de], a inc de ret CGB_MODE
; A036220: Expansion of 1/(1-3*x)^7; 7-fold convolution of A000244 (powers of 3). ; 1,21,252,2268,17010,112266,673596,3752892,19702683,98513415,472864392,2192371272,9865670724,43257171636,185387878440,778629089448,3211844993973,13036312034361,52145248137444,205836505805700,802762372642230,3096369151620030 mov $2,$0 mov $3,3 mov $4,$0 mov $6,6 add $6,$0 bin $6,$0 mov $0,$6 lpb $2 add $4,$3 lpb $4 mul $0,$3 trn $4,$5 add $4,$5 sub $4,1 mov $5,4 lpe sub $2,1 mov $3,1 lpe mov $1,$0
/*========================================================================= Library: CTK Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // ctkDICOMCore includes #include "ctkDICOMThumbnailGenerator.h" #include "ctkLogger.h" // Qt includes #include <QImage> // DCMTK includes #include "dcmimage.h" static ctkLogger logger ( "org.commontk.dicom.DICOMThumbnailGenerator" ); struct Node; //------------------------------------------------------------------------------ class ctkDICOMThumbnailGeneratorPrivate { Q_DECLARE_PUBLIC(ctkDICOMThumbnailGenerator); public: ctkDICOMThumbnailGeneratorPrivate(ctkDICOMThumbnailGenerator&); virtual ~ctkDICOMThumbnailGeneratorPrivate(); protected: ctkDICOMThumbnailGenerator* const q_ptr; private: Q_DISABLE_COPY( ctkDICOMThumbnailGeneratorPrivate ); }; //------------------------------------------------------------------------------ ctkDICOMThumbnailGeneratorPrivate::ctkDICOMThumbnailGeneratorPrivate(ctkDICOMThumbnailGenerator& o):q_ptr(&o) { } //------------------------------------------------------------------------------ ctkDICOMThumbnailGeneratorPrivate::~ctkDICOMThumbnailGeneratorPrivate() { } //------------------------------------------------------------------------------ ctkDICOMThumbnailGenerator::ctkDICOMThumbnailGenerator(QObject* parentValue) : d_ptr(new ctkDICOMThumbnailGeneratorPrivate(*this)) { Q_UNUSED(parentValue); } //------------------------------------------------------------------------------ ctkDICOMThumbnailGenerator::~ctkDICOMThumbnailGenerator() { } //------------------------------------------------------------------------------ bool ctkDICOMThumbnailGenerator::generateThumbnail(DicomImage *dcmImage, const QString &path){ QImage image; // Check whether we have a valid image EI_Status result = dcmImage->getStatus(); if (result != EIS_Normal) { logger.error(QString("Rendering of DICOM image failed for thumbnail failed: ") + DicomImage::getString(result)); return false; } // Select first window defined in image. If none, compute min/max window as best guess. // Only relevant for monochrome. if (dcmImage->isMonochrome()) { if (dcmImage->getWindowCount() > 0) { dcmImage->setWindow(0); } else { dcmImage->setMinMaxWindow(OFTrue /* ignore extreme values */); } } /* get image extension and prepare image header */ const unsigned long width = dcmImage->getWidth(); const unsigned long height = dcmImage->getHeight(); unsigned long offset = 0; unsigned long length = 0; QString header; if (dcmImage->isMonochrome()) { // write PGM header (binary monochrome image format) header = QString("P5 %1 %2 255\n").arg(width).arg(height); offset = header.length(); length = width * height + offset; } else { // write PPM header (binary color image format) header = QString("P6 %1 %2 255\n").arg(width).arg(height); offset = header.length(); length = width * height * 3 /* RGB */ + offset; } /* create output buffer for DicomImage class */ QByteArray buffer; /* copy header to output buffer and resize it for pixel data */ buffer.append(header); buffer.resize(length); /* render pixel data to buffer */ if (dcmImage->getOutputData(static_cast<void *>(buffer.data() + offset), length - offset, 8, 0)) { if (!image.loadFromData( buffer )) { logger.error("QImage couldn't created"); return false; } } image.scaled(128,128,Qt::KeepAspectRatio).save(path,"PNG"); return true; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: DG.Tweening.ShortcutExtensions #include "DG/Tweening/ShortcutExtensions.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Camera class Camera; // Forward declaring type: Vector3 struct Vector3; } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0); DEFINE_IL2CPP_ARG_TYPE(::DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0*, "DG.Tweening", "ShortcutExtensions/<>c__DisplayClass10_0"); // Type namespace: DG.Tweening namespace DG::Tweening { // Size: 0x18 #pragma pack(push, 1) // Autogenerated type: DG.Tweening.ShortcutExtensions/DG.Tweening.<>c__DisplayClass10_0 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class ShortcutExtensions::$$c__DisplayClass10_0 : public ::Il2CppObject { public: public: // public UnityEngine.Camera target // Size: 0x8 // Offset: 0x10 ::UnityEngine::Camera* target; // Field size check static_assert(sizeof(::UnityEngine::Camera*) == 0x8); public: // Creating conversion operator: operator ::UnityEngine::Camera* constexpr operator ::UnityEngine::Camera*() const noexcept { return target; } // Get instance field reference: public UnityEngine.Camera target [[deprecated("Use field access instead!")]] ::UnityEngine::Camera*& dyn_target(); // public System.Void .ctor() // Offset: 0x18643A8 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ShortcutExtensions::$$c__DisplayClass10_0* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ShortcutExtensions::$$c__DisplayClass10_0*, creationType>())); } // UnityEngine.Vector3 <DOShakeRotation>b__0() // Offset: 0x18643B0 ::UnityEngine::Vector3 $DOShakeRotation$b__0(); // System.Void <DOShakeRotation>b__1(UnityEngine.Vector3 x) // Offset: 0x18643DC void $DOShakeRotation$b__1(::UnityEngine::Vector3 x); }; // DG.Tweening.ShortcutExtensions/DG.Tweening.<>c__DisplayClass10_0 #pragma pack(pop) static check_size<sizeof(ShortcutExtensions::$$c__DisplayClass10_0), 16 + sizeof(::UnityEngine::Camera*)> __DG_Tweening_ShortcutExtensions_$$c__DisplayClass10_0SizeCheck; static_assert(sizeof(ShortcutExtensions::$$c__DisplayClass10_0) == 0x18); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::$DOShakeRotation$b__0 // Il2CppName: <DOShakeRotation>b__0 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::*)()>(&DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::$DOShakeRotation$b__0)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0*), "<DOShakeRotation>b__0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::$DOShakeRotation$b__1 // Il2CppName: <DOShakeRotation>b__1 template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::*)(::UnityEngine::Vector3)>(&DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0::$DOShakeRotation$b__1)> { static const MethodInfo* get() { static auto* x = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(DG::Tweening::ShortcutExtensions::$$c__DisplayClass10_0*), "<DOShakeRotation>b__1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{x}); } };
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.28.29336.0 include listing.inc INCLUDELIB MSVCRTD INCLUDELIB OLDNAMES msvcjmc SEGMENT __F01778D6_pch@h DB 01H __6CB86619_windows@pch DB 01H __893247DF_dllmain@cpp DB 01H msvcjmc ENDS PUBLIC DllMain PUBLIC __JustMyCode_Default EXTRN _RTC_InitBase:PROC EXTRN _RTC_Shutdown:PROC EXTRN __CheckForDebuggerJustMyCode:PROC ; COMDAT pdata pdata SEGMENT $pdata$DllMain DD imagerel $LN6 DD imagerel $LN6+90 DD imagerel $unwind$DllMain pdata ENDS ; COMDAT rtc$TMZ rtc$TMZ SEGMENT _RTC_Shutdown.rtc$TMZ DQ FLAT:_RTC_Shutdown rtc$TMZ ENDS ; COMDAT rtc$IMZ rtc$IMZ SEGMENT _RTC_InitBase.rtc$IMZ DQ FLAT:_RTC_InitBase rtc$IMZ ENDS ; COMDAT xdata xdata SEGMENT $unwind$DllMain DD 025053301H DD 0117231cH DD 07010001fH DD 0500fH xdata ENDS ; Function compile flags: /Odt ; COMDAT __JustMyCode_Default _TEXT SEGMENT __JustMyCode_Default PROC ; COMDAT ret 0 __JustMyCode_Default ENDP _TEXT ENDS ; Function compile flags: /Odtp /RTCsu /ZI ; COMDAT DllMain _TEXT SEGMENT tv64 = 192 hModule$ = 240 ul_reason_for_call$ = 248 lpReserved$ = 256 DllMain PROC ; COMDAT ; File G:\Users\jackd\eclipse-workspace\system\src\main\c\dllmain.cpp ; Line 8 $LN6: mov QWORD PTR [rsp+24], r8 mov DWORD PTR [rsp+16], edx mov QWORD PTR [rsp+8], rcx push rbp push rdi sub rsp, 248 ; 000000f8H lea rbp, QWORD PTR [rsp+32] mov rdi, rsp mov ecx, 62 ; 0000003eH mov eax, -858993460 ; ccccccccH rep stosd mov rcx, QWORD PTR [rsp+280] lea rcx, OFFSET FLAT:__893247DF_dllmain@cpp call __CheckForDebuggerJustMyCode ; Line 9 mov eax, DWORD PTR ul_reason_for_call$[rbp] mov DWORD PTR tv64[rbp], eax ; Line 17 mov eax, 1 ; Line 18 lea rsp, QWORD PTR [rbp+216] pop rdi pop rbp ret 0 DllMain ENDP _TEXT ENDS END
// Copyright (c) 2020 The PIVX developers // Copyright (c) 2021 The INFAQCOIN developers // Distributed under the MIT software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "destination_io.h" #include "base58.h" #include "sapling/key_io_sapling.h" namespace Standard { std::string EncodeDestination(const CWDestination &address, const CChainParams::Base58Type addrType) { const CTxDestination *dest = boost::get<CTxDestination>(&address); if (!dest) { return KeyIO::EncodePaymentAddress(*boost::get<libzcash::SaplingPaymentAddress>(&address)); } return EncodeDestination(*dest, addrType); }; CWDestination DecodeDestination(const std::string& strAddress) { bool isStaking = false; return DecodeDestination(strAddress, isStaking); } CWDestination DecodeDestination(const std::string& strAddress, bool& isStaking) { bool isShielded = false; return DecodeDestination(strAddress, isStaking, isShielded); } // agregar isShielded CWDestination DecodeDestination(const std::string& strAddress, bool& isStaking, bool& isShielded) { CWDestination dest; CTxDestination regDest = ::DecodeDestination(strAddress, isStaking); if (!IsValidDestination(regDest)) { const auto sapDest = KeyIO::DecodeSaplingPaymentAddress(strAddress); if (sapDest) { isShielded = true; return *sapDest; } } return regDest; } bool IsValidDestination(const CWDestination& address) { // Only regular base58 addresses and shielded addresses accepted here for now const libzcash::SaplingPaymentAddress *dest1 = boost::get<libzcash::SaplingPaymentAddress>(&address); if (dest1) return true; const CTxDestination *dest = boost::get<CTxDestination>(&address); return dest && ::IsValidDestination(*dest); } const libzcash::SaplingPaymentAddress* GetShieldedDestination(const CWDestination& dest) { return boost::get<libzcash::SaplingPaymentAddress>(&dest); } const CTxDestination* GetTransparentDestination(const CWDestination& dest) { return boost::get<CTxDestination>(&dest); } } // End Standard namespace
#include "AddressBook.h" #include <QDebug> AddressBook::AddressBook(Cred::AddressBook *abImpl,QObject *parent) : QObject(parent), m_addressBookImpl(abImpl) { qDebug(__FUNCTION__); getAll(); } QString AddressBook::errorString() const { return QString::fromStdString(m_addressBookImpl->errorString()); } int AddressBook::errorCode() const { return m_addressBookImpl->errorCode(); } QList<Cred::AddressBookRow*> AddressBook::getAll(bool update) const { qDebug(__FUNCTION__); emit refreshStarted(); if(update) m_rows.clear(); if (m_rows.empty()){ for (auto &abr: m_addressBookImpl->getAll()) { m_rows.append(abr); } } emit refreshFinished(); return m_rows; } Cred::AddressBookRow * AddressBook::getRow(int index) const { return m_rows.at(index); } bool AddressBook::addRow(const QString &address, const QString &payment_id, const QString &description) const { // virtual bool addRow(const std::string &dst_addr , const std::string &payment_id, const std::string &description) = 0; bool r = m_addressBookImpl->addRow(address.toStdString(), payment_id.toStdString(), description.toStdString()); if(r) getAll(true); return r; } bool AddressBook::deleteRow(int rowId) const { bool r = m_addressBookImpl->deleteRow(rowId); // Fetch new data from wallet2. getAll(true); return r; } quint64 AddressBook::count() const { return m_rows.size(); } int AddressBook::lookupPaymentID(const QString &payment_id) const { return m_addressBookImpl->lookupPaymentID(payment_id.toStdString()); }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iotanalytics/model/CreateDatastoreRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoTAnalytics::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateDatastoreRequest::CreateDatastoreRequest() : m_datastoreNameHasBeenSet(false), m_datastoreStorageHasBeenSet(false), m_retentionPeriodHasBeenSet(false), m_tagsHasBeenSet(false), m_fileFormatConfigurationHasBeenSet(false), m_datastorePartitionsHasBeenSet(false) { } Aws::String CreateDatastoreRequest::SerializePayload() const { JsonValue payload; if(m_datastoreNameHasBeenSet) { payload.WithString("datastoreName", m_datastoreName); } if(m_datastoreStorageHasBeenSet) { payload.WithObject("datastoreStorage", m_datastoreStorage.Jsonize()); } if(m_retentionPeriodHasBeenSet) { payload.WithObject("retentionPeriod", m_retentionPeriod.Jsonize()); } if(m_tagsHasBeenSet) { Array<JsonValue> tagsJsonList(m_tags.size()); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); } payload.WithArray("tags", std::move(tagsJsonList)); } if(m_fileFormatConfigurationHasBeenSet) { payload.WithObject("fileFormatConfiguration", m_fileFormatConfiguration.Jsonize()); } if(m_datastorePartitionsHasBeenSet) { payload.WithObject("datastorePartitions", m_datastorePartitions.Jsonize()); } return payload.View().WriteReadable(); }
#TODO: fix clumsy use of $t2 register: you have to reset it every time u use it .data fileName: .asciiz "test.asm" # filename for input buffer: .space 1024 tempString: .space 20 #For Sound instrument: .byte 11 duration: .byte 500 volume: .byte 127 pitch: .byte 65 R_FORMAT: .asciiz "R" I_FORMAT: .asciiz "I" J_FORMAT: .asciiz "J" # binary values are NOT ACCURATE, need to go to mips sheet and correct them. ADD_OP: .asciiz "add" ADD_BIN: .asciiz "000000" ADDI_OP: .asciiz "addi" ADDI_BIN: .asciiz "001000" ADDIU_OP: .asciiz "addiu" ADDIU_BIN:.asciiz "001001" ADDU_OP: .asciiz "addu" ADDU_BIN: .asciiz "000000" AND_OP: .asciiz "and" AND_BIN: .asciiz "000000" ANDI_OP: .asciiz "andi" ANDI_BIN: .asciiz "001100" BEQ_OP: .asciiz "beq" BEQ_BIN:.asciiz "000100" BNE_OP: .asciiz "bne" BNE_BIN: .asciiz "000101" J_OP: .asciiz "j" J_BIN:.asciiz "000010" JAL_OP: .asciiz "jal" JAL_BIN: .asciiz "000011" JR_OP: .asciiz "jr" JR_BIN:.asciiz "000000" LW_OP: .asciiz "lw" LW_BIN:.asciiz "100011" ORI_OP: .asciiz "ori" ORI_BIN:.asciiz "001101" SLL_OP: .asciiz "sll" SLL_BIN:.asciiz "000000" SRL_OP: .asciiz "srl" SRL_BIN:.asciiz "000000" SUB_OP: .asciiz "sub" SUB_BIN:.asciiz "000000" SW_OP: .asciiz "sw" SW_BIN:.asciiz "101011" SYSCALL_OP: .asciiz "syscall" SYCALL_BIN: .asciiz "000000" ZERO_OP: .asciiz "$zero" ZERO_BIN: .asciiz "000000" AT_OP: .asciiz "$at" AT_BIN: .asciiz "000001" V0_OP: .asciiz "$v0" V0_BIN: .asciiz "000010" V1_OP: .asciiz "$v1" V1_BIN: .asciiz "000011" A0_OP: .asciiz "$a0" A0_BIN: .asciiz "000100" A1_OP: .asciiz "$a1" A1_BIN: .asciiz "000101" A2_OP: .asciiz "$a2" A2_BIN: .asciiz "000110" A3_OP: .asciiz "$a3" A3_BIN: .asciiz "000111" T0_OP: .asciiz "$t0" T0_BIN: .asciiz "001000" T1_OP: .asciiz "$t1" T1_BIN: .asciiz "001001" T2_OP: .asciiz "$t2" T2_BIN: .asciiz "001010" T3_OP: .asciiz "$t3" T3_BIN: .asciiz "001011" T4_OP: .asciiz "$t4" T4_BIN: .asciiz "001100" T5_OP: .asciiz "$t5" T5_BIN: .asciiz "001101" T6_OP: .asciiz "$t6" T6_BIN: .asciiz "001110" T7_OP: .asciiz "$t7" T7_BIN: .asciiz "001111" S0_OP: .asciiz "$s0" S0_BIN: .asciiz "010000" S1_OP: .asciiz "$s1" S1_BIN: .asciiz "010001" S2_OP: .asciiz "$s2" S2_BIN: .asciiz "010010" S3_OP: .asciiz "$s3" S3_BIN: .asciiz "010011" S4_OP: .asciiz "$s4" S4_BIN: .asciiz "010100" S5_OP: .asciiz "$s5" S5_BIN: .asciiz "010101" S6_OP: .asciiz "$s6" S6_BIN: .asciiz "010110" S7_OP: .asciiz "$s7" S7_BIN: .asciiz "010111" T8_OP: .asciiz "$t8" T8_BIN: .asciiz "011000" T9_OP: .asciiz "$t9" T9_BIN: .asciiz "011001" GP_OP: .asciiz "$gp" GP_BIN: .asciiz "011100" SP_OP: .asciiz "$sp" SP_BIN: .asciiz "011101" FP_OP: .asciiz "$fp" FP_BIN: .asciiz "011110" RA_OP: .asciiz "$ra" RA_BIN: .asciiz "011111" .macro printStringLn(%arg) li $v0, 4 # service 4 is print string add $a0, %arg, $zero # load desired value into argument register $a0, using pseudo-op syscall printNewLine() .end_macro .macro printString(%arg) li $v0, 4 # service 4 is print string add $a0, %arg, $zero # load desired value into argument register $a0, using pseudo-op syscall .end_macro .macro printNewLine addi $a0, $0, 0xA #ascii code for LF, if you have any trouble try 0xD for CR. addi $v0, $0, 0xB #syscall 11 prints the lower 8 bits of $a0 as an ascii character. syscall .end_macro .macro printChar(%arg) li $v0, 11 # service 11 is print char add $a0, %arg, $zero # load desired value into argument register $a0, using pseudo-op syscall printNewLine() .end_macro .macro handleComparison(%string, %binary) la $t2, tempString la $t3, %string la $t4, %binary add $t6, $0, $0 jal comparePhraseLoop .end_macro .macro handleOpComparison(%string, %binary, %format) la $t2, tempString la $t3, %string la $t4, %binary la $t6, %format jal comparePhraseLoop .end_macro .text openFile: #open a file for writing li $v0, 13 # system call for open file la $a0, fileName # load file name li $a1, 0 # Open for reading (0 is read, 1 is write) li $a2, 0 # ignore mode ??? syscall # open a file (file descriptor returned in $v0) move $s6, $v0 # save the file descriptor to $s6 readFile: #read from file li $v0, 14 # system call for read from file move $a0, $s6 # use file descriptor la $a1, buffer # address of buffer to which to write to li $a2, 1024 # hardcoded buffer length syscall # read from file loadByteLoop: la $t0, buffer # load buffer address in $t0 li $t1, 0 # reserved for temp chars la $t2, tempString # tempString to store phrase every time a delimiter is met li $t3, 0 # reserved for holding address of temp phrases li $t4, 0 # reserved for holding address of temp binary output li $t5, 0 # reserved for second temp char li $t6, 0 # reserved for holding address to format li $t7, 0 # reserved for holding address to resulting opcode li $t8, 0 # reserved for holding address to resulting format li $t9, 0 # reserved for holding format type li $s0, ' ' # load space char li $s1, ',' # load space char li $s2, '\n' # load newline char li $s3, '\0' # null char (end of file) add $s4, $0, $0 #reserved for holding address to final opcode add $s5, $0, $0 #reserved for holding address to first arg add $s6, $0, $0 #reserved for holding address to second arg add $s7, $0, $0 #reserved for holding address to third arg #print the buffer printStringLn($t0) byteLoop: lb $t1, ($t0) # load current incremented byte from buffer beq $t1, $s3, end # exit if char == end of file beq $t1, $s2, handleNewLine # if char == newline go to handler beq $t1, $s1, handleComma # if char == comma go to handler beq $t1, $s0, handleSpace # if char == space go to handler sb $t1, ($t2) # store current byte into tempstring addi $t0, $t0, 1 # increment byte from buffer addi $t2, $t2, 1 # increment tempstring byte j byteLoop # jump back to the top comparePhraseLoop: #handle each character lb $t1, ($t2) # get character from temp phrase lb $t5, ($t3) # get character from comparing phrase bne $t1, $t5, comparePhraseElse # exit if char != compared char beq $t1, $s3, comparePhraseDone # exit if char == null, phrase is complete # printChar($t5) # printChar($t1) addi $t2, $t2, 1 # increment through the phrase addi $t3, $t3, 1 # increment hardcoded phrase j comparePhraseLoop comparePhraseElse: la $t2, tempString # reset the counter again jr $ra comparePhraseDone: #perform ouput operation here add $t7, $t4, $0 # save the resulting argument bne $t6, $0, addFormat j addFormatDone addFormat: add $t8, $t6, $0 addFormatDone: la $t2, tempString # reset the counter again jr $ra emptyPhraseLoop: lb $t1, ($t2) # get character from temp phrase sb $s3, ($t2) # set char to null for next iteration, this way the phase will be empty beq $t1, $s3, emptyPhraseDone # exit if char == null, phrase is complete addi $t2, $t2, 1 # increment through the phrase j emptyPhraseLoop emptyPhraseDone: la $t2, tempString # reset the counter jr $ra handleSpace: # op codes go here addi $t0, $t0, 1 # increment byte from buffer to skip the space add $t7, $0, $0 # reset the result storage #brute force & hardcoded my nigga #TODO: not use macro for something so bullshit handleOpComparison(ADD_OP,ADD_BIN,R_FORMAT) handleOpComparison(ADDI_OP,ADDI_BIN,I_FORMAT) handleOpComparison(ADDIU_OP,ADDIU_BIN,R_FORMAT) handleOpComparison(ADDU_OP,ADDU_BIN,R_FORMAT) handleOpComparison(AND_OP,AND_BIN,R_FORMAT) handleOpComparison(ANDI_OP,ANDI_BIN,I_FORMAT) handleOpComparison(BEQ_OP,BEQ_BIN,I_FORMAT) handleOpComparison(BNE_OP,BNE_BIN,I_FORMAT) handleOpComparison(J_OP,J_BIN,J_FORMAT) handleOpComparison(JAL_OP,JAL_BIN,J_FORMAT) handleOpComparison(JR_OP,JR_BIN,R_FORMAT) handleOpComparison(LW_OP,LW_BIN,I_FORMAT) handleOpComparison(ORI_OP,ORI_BIN,I_FORMAT) handleOpComparison(SLL_OP,SLL_BIN,R_FORMAT) handleOpComparison(SRL_OP,SRL_BIN,R_FORMAT) handleOpComparison(SUB_OP,SUB_BIN,R_FORMAT) handleOpComparison(SW_OP,SW_BIN,I_FORMAT) handleOpComparison(SYSCALL_OP,SYCALL_BIN,R_FORMAT) add $s4, $t4, $0 # load the resulting opcode into temp register jal emptyPhraseLoop j byteLoop handleComma: # arguments go here addi $t0, $t0, 1 # increment byte from buffer to skip the comma add $t7, $0, $0 # reset the result storage handleComparison(ZERO_OP,ZERO_BIN) handleComparison(S0_OP,S0_BIN) handleComparison(S1_OP,S1_BIN) handleComparison(S2_OP,S2_BIN) handleComparison(S3_OP,S3_BIN) handleComparison(S4_OP,S4_BIN) handleComparison(S5_OP,S5_BIN) handleComparison(S6_OP,S6_BIN) handleComparison(S7_OP,S7_BIN) handleComparison(AT_OP,AT_BIN) handleComparison(V0_OP,V0_BIN) handleComparison(V1_OP,V1_BIN) handleComparison(A0_OP,A0_BIN) handleComparison(A1_OP,A1_BIN) handleComparison(A2_OP,A2_BIN) handleComparison(T1_OP,T1_BIN) handleComparison(T2_OP,T2_BIN) handleComparison(T3_OP,T3_BIN) handleComparison(T4_OP,T4_BIN) handleComparison(T5_OP,T5_BIN) handleComparison(T6_OP,T6_BIN) handleComparison(T7_OP,T7_BIN) handleComparison(T8_OP,T8_BIN) handleComparison(T9_OP,T9_BIN) handleComparison(GP_OP,GP_BIN) handleComparison(SP_OP,SP_BIN) handleComparison(FP_OP,FP_BIN) handleComparison(RA_OP,RA_BIN) beq $t7, $0, newlineLoadArgDone #if no results made, go to end beq $s5, $0, commaLoadFirstArg beq $s6, $0, commaLoadSecondArg j commaLoadArgDone commaLoadFirstArg: add $s5, $t7, $0 # put the resulting argument into arg storage j commaLoadArgDone commaLoadSecondArg: add $s6, $t7, $0 # put the resulting argument into arg storage j commaLoadArgDone commaLoadArgDone: jal emptyPhraseLoop j byteLoop handleNewLine: # new instructions addi $t0, $t0, 1 # increment byte from buffer to skip the newline add $t7, $0, $0 # reset the result storage handleComparison(ZERO_OP,ZERO_BIN) handleComparison(S0_OP,S0_BIN) handleComparison(S1_OP,S1_BIN) handleComparison(S2_OP,S2_BIN) handleComparison(S3_OP,S3_BIN) handleComparison(S4_OP,S4_BIN) handleComparison(S5_OP,S5_BIN) handleComparison(S6_OP,S6_BIN) handleComparison(S7_OP,S7_BIN) handleComparison(AT_OP,AT_BIN) handleComparison(V0_OP,V0_BIN) handleComparison(V1_OP,V1_BIN) handleComparison(A0_OP,A0_BIN) handleComparison(A1_OP,A1_BIN) handleComparison(A2_OP,A2_BIN) handleComparison(T1_OP,T1_BIN) handleComparison(T2_OP,T2_BIN) handleComparison(T3_OP,T3_BIN) handleComparison(T4_OP,T4_BIN) handleComparison(T5_OP,T5_BIN) handleComparison(T6_OP,T6_BIN) handleComparison(T7_OP,T7_BIN) handleComparison(T8_OP,T8_BIN) handleComparison(T9_OP,T9_BIN) handleComparison(GP_OP,GP_BIN) handleComparison(SP_OP,SP_BIN) handleComparison(FP_OP,FP_BIN) handleComparison(RA_OP,RA_BIN) beq $t7, $0, newlineLoadArgDone #if no results made, go to end beq $s6, $0, newlineLoadSecondArg beq $s7, $0, newlineLoadThirdArg j newlineLoadArgDone newlineLoadSecondArg: add $s6, $t7, $0 # put the resulting argument into arg storage j newlineLoadArgDone newlineLoadThirdArg: add $s7, $t7, $0 # put the resulting argument into arg storage j newlineLoadArgDone newlineLoadArgDone: #here we write the processing for the final binary instruction la $t9, R_FORMAT beq $t9, $t8, printR j printDone printR: printStringLn($s4) printStringLn($s6) printStringLn($s7) printStringLn($s5) printNewLine() printDone: #reset all of the instruction stores add $s4, $0, $0 add $s5, $0, $0 add $s6, $0, $0 add $s7, $0, $0 add $t6, $0, $0 jal emptyPhraseLoop j byteLoop end: #Close the file and play a sound when done #sound functionality li $v0,33 addi $t2,$a0,12 la $a0,pitch lbu $a0 0($a0) la $a1,duration lbu $a1, 0($a1) la $a2,instrument lbu $a2 0($a2) la $a3,volume lbu $a3, 0($a3) syscall li $v0, 16 # system call for close file move $a0, $s6 # file descriptor to close syscall # close file
; A132607: X-values of solutions to the equation X*(X + 1) - 11*Y^2 = 0. ; Submitted by Christian Krause ; 0,99,39600,15760899,6272798400,2496558002499,993623812196400,395459780696164899,157391999093261433600,62641620179337354408099,24931207439377173792990000,9922557919251935832255612099 mov $2,1 lpb $0 sub $0,1 mov $1,$3 mul $1,18 add $2,$1 add $3,$2 lpe pow $3,2 mov $0,$3 mul $0,99
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2018-2019 The DeVault developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/devault-config.h" #endif #include "init.h" #include "addrman.h" #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "compat/sanity.h" #include "consensus/validation.h" #include "httpserver.h" #include "httprpc.h" #include "kernel.h" #include "key.h" #include "main.h" #include "miner.h" #include "net.h" #include "ntpclient.h" #include "policy/policy.h" #include "rpc/server.h" #include "rpc/register.h" #include "script/standard.h" #include "script/sigcache.h" #include "scheduler.h" #include "timedata.h" #include "txdb.h" #include "txmempool.h" #include "torcontrol.h" #include "ui_interface.h" #include "untar.h" #include "util.h" #include "utiltime.h" #include "utilmoneystr.h" #include "validationinterface.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #include "zerowallet.h" #include "zerowitnesser.h" #endif #include <stdint.h> #include <stdio.h> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/function.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <curl/curl.h> #include <openssl/crypto.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/aes.h> #if ENABLE_ZMQ #include "zmq/zmqnotificationinterface.h" #endif using namespace std; bool fFeeEstimatesInitialized = false; static const bool DEFAULT_PROXYRANDOMIZE = true; static const bool DEFAULT_REST_ENABLE = false; static const bool DEFAULT_DISABLE_SAFEMODE = false; static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false; unsigned int nMinerSleep; #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = NULL; #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files don't count towards the fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1), BF_WHITELIST = (1U << 2), }; static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat"; static float fBootstrapProgress = 0.0; static int xferinfo(void *p, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { float fProgress = (float)dlnow/(float)dltotal*100.0f; if (fProgress == fBootstrapProgress) return 0; uiInterface.InitMessage(strprintf("[BOOTSTRAP] Downloaded %" CURL_FORMAT_CURL_OFF_T "MB of %" CURL_FORMAT_CURL_OFF_T "MB (%.2f%%)", dlnow/(1024*1024), dltotal/(1024*1024), (float)dlnow/(float)dltotal*100.0f)); fprintf(stdout, "[BOOTSTRAP] Downloaded %" CURL_FORMAT_CURL_OFF_T "MB of %" CURL_FORMAT_CURL_OFF_T "MB (%.2f%%) \r", dlnow/(1024*1024), dltotal/(1024*1024), fProgress); fBootstrapProgress = fProgress; return 0; } size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written; written = fwrite(ptr, size, nmemb, stream); return written; } ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // std::atomic<bool> fRequestShutdown(false); void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } /** * This is a minimally invasive approach to shutdown on LevelDB read errors from the * chainstate, while keeping user interface out of the common library, which is shared * between devaultd, and devault-qt and non-server tools. */ class CCoinsViewErrorCatcher : public CCoinsViewBacked { public: CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} bool GetCoins(const uint256 &txid, CCoins &coins) const { try { return CCoinsViewBacked::GetCoins(txid, coins); } catch(const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpretation. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static CCoinsViewDB *pcoinsdbview = NULL; static CCoinsViewErrorCatcher *pcoinscatcher = NULL; static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle; void Interrupt(boost::thread_group& threadGroup) { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); threadGroup.interrupt_all(); } void Shutdown() { LogPrintf("%s: In progress...\n", __func__); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; /// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. RenameThread("devault-shutoff"); mempool.AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->Flush(false); #endif StopNode(); StopTorControl(); UnregisterNodeSignals(GetNodeSignals()); if (fFeeEstimatesInitialized) { boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); if (!est_fileout.IsNull()) mempool.WriteFeeEstimates(est_fileout); else LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); fFeeEstimatesInitialized = false; } { LOCK(cs_main); if (pcoinsTip != NULL) { FlushStateToDisk(); } delete pcoinsTip; pcoinsTip = NULL; delete pcoinscatcher; pcoinscatcher = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->Flush(true); #endif #if ENABLE_ZMQ if (pzmqNotificationInterface) { UnregisterValidationInterface(pzmqNotificationInterface); delete pzmqNotificationInterface; pzmqNotificationInterface = NULL; } #endif #ifndef WIN32 try { boost::filesystem::remove(GetPidFile()); } catch (const boost::filesystem::filesystem_error& e) { LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what()); } #endif UnregisterAllValidationInterfaces(); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do, so: */ void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static Bind(const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } void OnRPCStopped() { cvBlockChange.notify_all(); LogPrint("rpc", "RPC stopped.\n"); } void OnRPCPreCommand(const CRPCCommand& cmd) { // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) && !cmd.okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); } std::string HelpMessage(HelpMessageMode mode) { const bool showDebug = GetBoolArg("-help-debug", false); // When adding new options to the categories, please keep and ensure alphabetical ordering. // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators. string strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("Print this help message and exit")); strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)")); if (showDebug) strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY)); strUsage += HelpMessageOpt("-bootstrap=<url>", _("Specifies an URL from where a bootstrapped copy of the blockchain would be downloaded")); strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS)); strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL)); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), DEVAULT_CONF_FILENAME)); if (mode == HMM_DEVAULTD) { #ifndef WIN32 strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); #endif } strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); if (showDebug) strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER)); strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup")); strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE)); strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY)); strUsage += HelpMessageOpt("-minersleep=<n>", strprintf(_("Sets the default sleep for the staking thread (default: %u)"), 500)); strUsage += HelpMessageOpt("-mininputvalue=<n>", strprintf(_("Sets the minimum value for an output to be considered as a coinstake kernel candidate"))); strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); #ifndef WIN32 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), DEVAULT_PID_FILENAME)); #endif strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. " "Warning: Reverting this setting requires re-downloading the entire blockchain. " "(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks")); strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk")); #ifdef ENABLE_WALLET strUsage += HelpMessageOpt("-staking=<bool>", _("Enables or disables the staking thread.")); strUsage += HelpMessageOpt("-enablewitnesser=<bool>", _("Enables or disables the witnesser thread.")); strUsage += HelpMessageOpt("-defaultsecuritylevel=<level>", strprintf(_("Sets the required minimum count of additional mints for a zerocoin to be spent. (default: %d)"), DEFAULT_SPEND_MIN_MINT_COUNT)); #endif #ifndef WIN32 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)")); #endif strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX)); strUsage += HelpMessageOpt("-addressindex", strprintf(_("Maintain a full address index, used to query for the balance, txids and unspent outputs for addresses (default: %u)"), DEFAULT_ADDRESSINDEX)); strUsage += HelpMessageOpt("-timestampindex", strprintf(_("Maintain a timestamp index for block hashes, used to query blocks hashes by a range of timestamps (default: %u)"), DEFAULT_TIMESTAMPINDEX)); strUsage += HelpMessageOpt("-spentindex", strprintf(_("Maintain a full spent index, used to query the spending txid and input index for an outpoint (default: %u)"), DEFAULT_SPENTINDEX)); strUsage += HelpMessageGroup(_("Clock options:")); strUsage += HelpMessageOpt("-ntpserver=<ip/host>", _("Adds a ntp server to use for clock syncronization")); strUsage += HelpMessageOpt("-ntpminmeasures=<n>", strprintf(_("Min. number of valid requests to NTP servers (default: %u)"), MINIMUM_NTP_MEASURE)); strUsage += HelpMessageOpt("-ntptimeout=<n>", strprintf(_("Number of seconds to wait for a response from a NTP server (default: %u)"), DEFAULT_NTP_TIMEOUT)); strUsage += HelpMessageOpt("-maxtimeoffset=<n>", strprintf(_("Max number of seconds allowed as clock offset for a peer (default: %u)"), MAXIMUM_TIME_OFFSET)); strUsage += HelpMessageGroup(_("Connection options:")); strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open")); strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD)); strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME)); strUsage += HelpMessageOpt("-banversion=<string>", strprintf(_("Version of wallet to be banned"))); strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)")); strUsage += HelpMessageOpt("-devnet", _("Uses the devnet network")); strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)")); strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP)); strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)")); strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address")); strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED)); strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)")); strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION)); strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS)); strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER)); strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER)); strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT)); strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy")); strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)")); strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG)); strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS)); strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u or devnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort(), Params(CBaseChainParams::DEVNET).GetDefaultPort())); strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE)); strUsage += HelpMessageOpt("-rejectversionbit=<n>", _("Reject a suggested version bit")); strUsage += HelpMessageOpt("-acceptversionbit=<n>", _("Accept a suggested version bit")); strUsage += HelpMessageOpt("-requirednssec", _("Requires DNS Sec for OpenAlias requests (default: true)")); strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect")); #ifdef ENABLE_WALLET strUsage += HelpMessageOpt("-stakervote=<string>", _("Defines the staker vote to be attached to found blocks.")); #endif strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT)); strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL)); strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)")); #ifdef USE_UPNP #if USE_UPNP strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)")); #else strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0)); #endif #endif strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") + " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway")); strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY)); strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY)); strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET)); #ifdef ENABLE_WALLET strUsage += CWallet::GetWalletHelpString(showDebug); strUsage += HelpMessageGroup(_("Witnesser thread options:")); strUsage += HelpMessageOpt("-witnesser_block_snapshot=<count>", strprintf(_("Snapshot for recovery purposes in case of block reorg every <count> blocks. (default: %d)"), DEFAULT_BLOCK_SNAPSHOT)); strUsage += HelpMessageOpt("-witnesser_blocks_per_round=<count>", strprintf(_("Precompute witness for <count> blocks in each round to prevent main thread locking. (default: %d)"), DEFAULT_BLOCKS_PER_ROUND)); #endif #if ENABLE_ZMQ strUsage += HelpMessageGroup(_("ZeroMQ notification options:")); strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>")); strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>")); strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>")); strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>")); #endif strUsage += HelpMessageGroup(_("Debugging/Testing options:")); strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string")); if (showDebug) { strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED)); strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE)); strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE)); strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages"); strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages"); strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT)); strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT)); strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT)); strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT)); strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT)); } string debugCategories = "addrman, alert, bench, coindb, db, http, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below if (mode == HMM_DEVAULT_QT) debugCategories += ", qt"; strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " + _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + "."); if (showDebug) strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0"); strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)")); strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS)); strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS)); if (showDebug) { strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS)); strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)"); strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY)); strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY)); strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE)); strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE)); } strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation"), CURRENCY_UNIT)); strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions"), CURRENCY_UNIT)); strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file")); if (showDebug) { strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY)); } strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)")); AppendParamsHelpMessages(strUsage, showDebug); strUsage += HelpMessageGroup(_("Node relay options:")); if (showDebug) strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard())); strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP)); strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER)); strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY)); strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT)); strUsage += HelpMessageGroup(_("Block creation options:")); strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT)); strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE)); strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE)); if (showDebug) strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios"); strUsage += HelpMessageGroup(_("RPC server options:")); strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands")); strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE)); strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)")); strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u or devnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort(), BaseParams(CBaseChainParams::DEVNET).RPCPort())); strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS)); strUsage += HelpMessageGroup(_("GUI options:")); strUsage += HelpMessageOpt("-updatefiatperiod=<miliseconds>", _("Sets the interval in miliseconds to update the fiat price from CoinMarketcap. Min. 120000")); if (showDebug) { strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE)); strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT)); } strUsage += HelpMessageOpt("-headerspamfilter=<n>", strprintf(_("Use header spam filter (default: %u)"), DEFAULT_HEADER_SPAM_FILTER)); strUsage += HelpMessageOpt("-headerspamfiltermaxsize=<n>", strprintf(_("Maximum size of the list of indexes in the header spam filter (default: %u)"), DEFAULT_HEADER_SPAM_FILTER_MAX_SIZE)); strUsage += HelpMessageOpt("-headerspamfiltermaxavg=<n>", strprintf(_("Maximum average size of an index occurrence in the header spam filter (default: %u)"), DEFAULT_HEADER_SPAM_FILTER_MAX_AVG)); return strUsage; } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://github.com/devaultcrypto/DeVault-Core>"; const std::string URL_WEBSITE = "<https://devault.cc>"; // todo: remove urls from translations on next change return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software."), PACKAGE_NAME, URL_WEBSITE) + "\n" + strprintf(_("The source code is available from %s."), URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.") + "\n" + _("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.") + "\n" + "\n" + _("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.") + "\n" + _("Copyright (c) 2014-2017, The Monero Project") + "\n" + "\n" + _("All rights reserved.") + "\n" + "\n" + _("Redistribution and use in source and binary forms, with or without modification, are") + "\n" + _("permitted provided that the following conditions are met:") + "\n" + "\n" + _("1. Redistributions of source code must retain the above copyright notice, this list of") + "\n" + _(" conditions and the following disclaimer.") + "\n" + "\n" + _("2. Redistributions in binary form must reproduce the above copyright notice, this list") + "\n" + _(" of conditions and the following disclaimer in the documentation and/or other") + "\n" + _(" materials provided with the distribution.") + "\n" + "\n" + _("3. Neither the name of the copyright holder nor the names of its contributors may be") + "\n" + _(" used to endorse or promote products derived from this software without specific") + "\n" + _(" prior written permission.") + "\n" + "\n" + _("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY") + "\n" + _(" EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF") + "\n" + _(" MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL") + "\n" + _(" THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,") + "\n" + _(" SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,") + "\n" + _(" PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS") + "\n" + _(" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,") + "\n" + _(" STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF") + "\n" + _(" THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.") + "\n" + "\n"; } static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex) { if (initialSync || !pBlockIndex) return; std::string strCmd = GetArg("-blocknotify", ""); boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; // If we're using -prune with -reindex, then delete block files that will be ignored by the // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile // is missing, do the same here to delete any later block files after a gap. Also delete all // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile // is in sync with what's actually on disk by the time we start downloading, so that pruning // works correctly. void CleanupBlockRevFiles() { using namespace boost::filesystem; map<string, path> mapBlockFiles; // Glob all blk?????.dat and rev?????.dat files from the blocks directory. // Remove the rev files immediately and insert the blk file paths into an // ordered map keyed by block file index. LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); path blocksdir = GetDataDir() / "blocks"; for (directory_iterator it(blocksdir); it != directory_iterator(); it++) { if (is_regular_file(*it) && it->path().filename().string().length() == 12 && it->path().filename().string().substr(8,4) == ".dat") { if (it->path().filename().string().substr(0,3) == "blk") mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path(); else if (it->path().filename().string().substr(0,3) == "rev") remove(it->path()); } } // Remove all block files that aren't part of a contiguous set starting at // zero by walking the ordered map (keys are block file indices) by // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) // start removing block files. int nContigCounter = 0; BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) { if (atoi(item.first) == nContigCounter) { nContigCounter++; continue; } remove(item.second); } } void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) { const CChainParams& chainparams = Params(); RenameThread("devault-loadblk"); CImportingNow imp; // -reindex if (fReindex) { int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk"))) break; // No block files left to reindex FILE *file = OpenBlockFile(pos, true); if (!file) break; // This error is logged in OpenBlockFile LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(chainparams, file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(chainparams); } // hardcoded $DATADIR/bootstrap.dat boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (boost::filesystem::exists(pathBootstrap)) { FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(chainparams, file); RenameOver(pathBootstrap, pathBootstrapOld); } else { LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); } } // -loadblock= BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) { FILE *file = fopen(path.string().c_str(), "rb"); if (file) { LogPrintf("Importing blocks file %s...\n", path.string()); LoadExternalBlockFile(chainparams, file); } else { LogPrintf("Warning: Could not open blocks file %s\n", path.string()); } } // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ActivateBestChain(state, chainparams)) { LogPrintf("Failed to connect best block"); StartShutdown(); } if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { LogPrintf("Stopping after block import\n"); StartShutdown(); } } /** Sanity checks * Ensure that DeVault is running in a usable environment with all * necessary library support. */ bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("Elliptic curve cryptography sanity check failure. Aborting."); return false; } if (!glibc_sanity_test() || !glibcxx_sanity_test()) return false; return true; } bool AppInitServers(boost::thread_group& threadGroup) { RPCServer::OnStopped(&OnRPCStopped); RPCServer::OnPreCommand(&OnRPCPreCommand); if (!InitHTTPServer()) return false; if (!StartRPC()) return false; if (!StartHTTPRPC()) return false; if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST()) return false; if (!StartHTTPServer()) return false; return true; } // Parameter interaction based on rules void InitParameterInteraction() { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (mapArgs.count("-bind")) { if (SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); } if (mapArgs.count("-whitebind")) { if (SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (SoftSetBoolArg("-dnsseed", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); if (SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); // to protect privacy, do not discover addresses by default if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); } if (!GetBoolArg("-listen", DEFAULT_LISTEN)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); if (SoftSetBoolArg("-listenonion", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions if (SoftSetBoolArg("-rescan", true)) LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } // -zapwallettx implies a rescan if (GetBoolArg("-zapwallettxes", false)) { if (SoftSetBoolArg("-rescan", true)) LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__); } // disable walletbroadcast and whitelistrelay in blocksonly mode if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) { if (SoftSetBoolArg("-whitelistrelay", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__); #ifdef ENABLE_WALLET if (SoftSetBoolArg("-walletbroadcast", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); #endif } // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place. if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { if (SoftSetBoolArg("-whitelistrelay", true)) LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__); } } static std::string ResolveErrMsg(const char * const optname, const std::string& strBind) { return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind); } void InitLogging() { fPrintToConsole = GetBoolArg("-printtoconsole", false); fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS); fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS); fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("DeVault version %s\n", FormatFullVersion()); } void DownloadBlockchain(std::string url) { CURL *curl; FILE *fp, *a; CURLcode res; curl = curl_easy_init(); if (curl) { std::string sDownload = (GetDataDir(true).string() + "/bootstrap_temp.tar"); fp = fopen(sDownload.c_str(),"wb"); curl_easy_setopt(curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferinfo); curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); res = curl_easy_perform(curl); if (res != CURLE_OK) { curl_easy_cleanup(curl); curl_global_cleanup(); throw std::runtime_error("Failed!"); } else { curl_easy_cleanup(curl); curl_global_cleanup(); int i=fclose(fp); if(i==0) { a = fopen(sDownload.c_str(), "rb"); if (a == NULL) { boost::filesystem::remove_all(sDownload); throw std::runtime_error("Unable to open downloaded file."); } else { boost::filesystem::remove_all(GetDataDir(true) / "blocks"); boost::filesystem::remove_all(GetDataDir(true) / "chainstate"); boost::filesystem::remove_all(GetDataDir(true) / "cfund"); bool fOk = untar(a, sDownload.c_str()); fclose(a); boost::filesystem::remove_all(sDownload); if(!fOk) throw std::runtime_error("Could not extract data."); } } else { throw std::runtime_error("Failed!"); } } } else { throw std::runtime_error("Failed!"); } } /** Initialize devault. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler) { // ********************************************************* Step 0: download bootstrap std::string sBootstrap = GetArg("-bootstrap",""); if(sBootstrap != "") { RemoveConfigFile("bootstrap"); uiInterface.InitMessage(strprintf("Trying to download from %s", sBootstrap.c_str())); try { DownloadBlockchain(sBootstrap); } catch(const std::exception& e) { return InitError(strprintf("[BOOTSTRAP] %s", e.what())); } uiInterface.InitMessage("Downloaded"); } // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif if (!SetupNetworking()) return InitError("Initializing networking failed"); #ifndef WIN32 if (GetBoolArg("-sysperms", false)) { #ifdef ENABLE_WALLET if (!GetBoolArg("-disablewallet", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); #endif } else { umask(077); } // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #endif // ********************************************************* Step 2: parameter interactions const CChainParams& chainparams = Params(); // also see: InitParameterInteraction() // if using block pruning, then disable txindex if (GetArg("-prune", 0)) { if (GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); #ifdef ENABLE_WALLET if (GetBoolArg("-rescan", false)) { return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); } #endif } nMinerSleep = GetArg("-minersleep", 500); // Make sure enough file descriptors are available int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1); int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); // Trim requested connection counts, to fit into system limitations nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections); if (nMaxConnections < nUserMaxConnections) InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); // ********************************************************* Step 3: parameter-to-internal-flags fDebug = !mapMultiArgs["-debug"].empty(); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages const vector<string>& categories = mapMultiArgs["-debug"]; if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) fDebug = false; // Check for -debugnet if (GetBoolArg("-debugnet", false)) InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net.")); // Check for -socks - as this is a privacy risk to continue, exit here if (mapArgs.count("-socks")) return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); // Check for -tor - as this is a privacy risk to continue, exit here if (GetBoolArg("-tor", false)) return InitError(_("Unsupported argument -tor found, use -onion.")); if (GetBoolArg("-benchmark", false)) InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench.")); if (GetBoolArg("-whitelistalwaysrelay", false)) InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.")); if (mapArgs.count("-blockminsize")) InitWarning("Unsupported argument -blockminsize ignored."); // Checkmempool and checkblockindex default to true in regtest mode int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); if (ratio != 0) { mempool.setSanityCheck(1.0 / ratio); } fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED); // mempool limits int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0))); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (nScriptCheckThreads <= 0) nScriptCheckThreads += GetNumCores(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; fServer = GetBoolArg("-server", false); // block pruning; get the amount of disk space (in MiB) to allot for block & undo files int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024; if (nSignedPruneTarget < 0) { return InitError(_("Prune cannot be configured with a negative value.")); } nPruneTarget = (uint64_t) nSignedPruneTarget; if (nPruneTarget) { if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) { return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); } LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024); fPruneMode = true; } RegisterAllCoreRPCCommands(tableRPC); #ifdef ENABLE_WALLET bool fDisableWallet = GetBoolArg("-disablewallet", false); if (!fDisableWallet) RegisterWalletRPCCommands(tableRPC); #endif nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; // Fee-per-kilobyte amount considered the same as "free" // If you are mining, be careful setting this: // if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-minrelaytxfee")) { CAmount n = 0; if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) ::minRelayTxFee = CFeeRate(n); else return InitError(AmountErrMsg("minrelaytxfee", mapArgs["-minrelaytxfee"])); } fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard()); if (Params().RequireStandard() && !fRequireStandard) return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString())); nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp); #ifdef ENABLE_WALLET if (!CWallet::ParameterInteraction()) return false; #endif // ENABLE_WALLET fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG); fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER); nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes); // Option to startup with mocktime set (used for regression testing): SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT); if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) { // Minimal effort at forwards compatibility std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible std::vector<std::string> vstrReplacementModes; boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(",")); fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end()); } // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log // Initialize elliptic curve code ECC_Start(); globalVerifyHandle.reset(new ECCVerifyHandle()); // Sanity check if (!InitSanityCheck()) return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME))); std::string strDataDir = GetDataDir().string(); // Make sure only a single DeVault process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); try { static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME))); } catch(const boost::interprocess::interprocess_exception& e) { return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what())); } #ifndef WIN32 CreatePidFile(GetPidFile(), getpid()); #endif if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); if (fPrintToDebugLog) OpenDebugLog(); if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", strDataDir); LogPrintf("Using config file %s\n", GetConfigFile().string()); LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); std::ostringstream strErrors; LogPrintf("Using %u threads for script and zerocoin verification\n", nScriptCheckThreads); if (nScriptCheckThreads) { for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); threadGroup.create_thread(&ThreadCoinSpendCheck); threadGroup.create_thread(&ThreadPublicCoinCheck); } // Start the lightweight task scheduler thread CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler); threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop)); /* Start the RPC server already. It will be started in "warmup" mode * and not really process calls already (but it will signify connections * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ if (fServer) { uiInterface.InitMessage.connect(SetRPCWarmupStatus); if (!AppInitServers(threadGroup)) return InitError(_("Unable to start HTTP server. See debug log for details.")); } int64_t nStart; // ********************************************************* Step 5: verify wallet database integrity #ifdef ENABLE_WALLET if (!fDisableWallet) { if (!CWallet::Verify()) return false; } // (!fDisableWallet) #endif // ENABLE_WALLET // ********************************************************* Step 6: network initialization uiInterface.InitMessage(_("Synchronizing clock...")); string sMsg = ""; int nWarningCounter = 0; if(GetArg("-ntpminmeasures", MINIMUM_NTP_MEASURE) == 0) { sMsg = "You have set to ignore NTP Sync with the wallet " "setting ntpminmeasures=0. Please be aware that " "your system clock needs to be correct in order " "to synchronize with the network. "; } else { while(1) { if(ShutdownRequested()) break; if(!NtpClockSync()) { sMsg = "A connection could not be made to any ntp server. " "Please ensure you system clock is correct otherwise " "your stakes will be rejected by the network"; if (nWarningCounter == 0) { uiInterface.ThreadSafeMessageBox(sMsg, "", CClientUIInterface::MSG_ERROR); } strMiscWarning = sMsg; AlertNotify(strMiscWarning); LogPrintf(strMiscWarning.c_str()); uiInterface.InitMessage(_(strprintf("Synchronizing clock attempt %i...", nWarningCounter+1).c_str())); nWarningCounter++; MilliSleep(30000); } else { strMiscWarning = ""; sMsg = ""; break; } } } if (sMsg != "") { uiInterface.ThreadSafeMessageBox(sMsg, "", CClientUIInterface::MSG_ERROR); strMiscWarning = sMsg; AlertNotify(strMiscWarning); LogPrintf(strMiscWarning.c_str()); } RegisterNodeSignals(GetNodeSignals()); // sanitize comments per BIP-0014, format user agent and check total size std::vector<string> uacomments; BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"]) { if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)); } strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."), strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } if (mapArgs.count("-whitelist")) { BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) { CSubNet subnet(net); if (!subnet.IsValid()) return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); CNode::AddWhitelistedRange(subnet); } } bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE); // -proxy sets a proxy for all outgoing network traffic // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default std::string proxyArg = GetArg("-proxy", ""); SetLimited(NET_TOR); if (proxyArg != "" && proxyArg != "0") { proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg)); SetProxy(NET_IPV4, addrProxy); SetProxy(NET_IPV6, addrProxy); SetProxy(NET_TOR, addrProxy); SetNameProxy(addrProxy); SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later } // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses // -noonion (or -onion=0) disables connecting to .onion entirely // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none) std::string onionArg = GetArg("-onion", ""); if (onionArg != "") { if (onionArg == "0") { // Handle -noonion/-onion=0 SetLimited(NET_TOR); // set onions as unreachable } else { proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg)); SetProxy(NET_TOR, addrOnion); SetLimited(NET_TOR, false); } } // see Step 2: parameter interactions for more information about these fListen = GetBoolArg("-listen", DEFAULT_LISTEN); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP); fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY); bool fBound = false; if (fListen) { if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) { BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(ResolveErrMsg("bind", strBind)); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, 0, false)) return InitError(ResolveErrMsg("whitebind", strBind)); if (addrBind.GetPort() == 0) return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind)); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) { CService addrLocal; if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) AddLocal(addrLocal, LOCAL_MANUAL); else return InitError(ResolveErrMsg("externalip", strAddr)); } } BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); #if ENABLE_ZMQ pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs); if (pzmqNotificationInterface) { RegisterValidationInterface(pzmqNotificationInterface); } #endif if (mapArgs.count("-maxuploadtarget")) { CNode::SetMaxOutboundTarget(GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024); } // ********************************************************* Step 7: load block chain fReindex = GetBoolArg("-reindex", false); bool fReindexChainState = GetBoolArg("-reindex-chainstate", false); // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ boost::filesystem::path blocksDir = GetDataDir() / "blocks"; if (!boost::filesystem::exists(blocksDir)) { boost::filesystem::create_directories(blocksDir); bool linked = false; for (unsigned int i = 1; i < 10000; i++) { boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); if (!boost::filesystem::exists(source)) break; boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); try { boost::filesystem::create_hard_link(source, dest); LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string()); linked = true; } catch (const boost::filesystem::filesystem_error& e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what()); break; } } if (linked) { fReindex = true; } } // block tree db settings int dbMaxOpenFiles = GetArg("-dbmaxopenfiles", DEFAULT_DB_MAX_OPEN_FILES); bool dbCompression = GetBoolArg("-dbcompression", DEFAULT_DB_COMPRESSION); LogPrintf("Block index database configuration:\n"); LogPrintf("* Using %d max open files\n", dbMaxOpenFiles); LogPrintf("* Compression is %s\n", dbCompression ? "enabled" : "disabled"); // cache size calculations int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20); nTotalCache -= nBlockTreeDBCache; int64_t nTxIndexCache = std::min(nTotalCache / 8, GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0); nTotalCache -= nTxIndexCache; int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache nTotalCache -= nCoinDBCache; nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024)); if (GetBoolArg("-txindex", DEFAULT_TXINDEX)) { LogPrintf("* Using %.1fMiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024)); } LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024)); LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024)); bool fLoaded = false; while (!fLoaded) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); do { try { UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pcoinscatcher; delete pblocktree; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex, dbCompression, dbMaxOpenFiles); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState); pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview); pcoinsTip = new CCoinsViewCache(pcoinscatcher); if (fReindex) { pblocktree->WriteReindexing(true); //If we're reindexing in prune mode, wipe away unusable block files and all undo data files if (fPruneMode) CleanupBlockRevFiles(); } if (!LoadBlockIndex()) { strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex(chainparams)) { strLoadError = _("Error initializing block database"); break; } // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) { strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex"); break; } // Check for changed -addressindex state if (fAddressIndex != GetBoolArg("-addressindex", DEFAULT_ADDRESSINDEX)) { strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -addressindex"); break; } // Check for changed -spentindex state if (fSpentIndex != GetBoolArg("-spentindex", DEFAULT_SPENTINDEX)) { strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -spentindex"); break; } // Check for changed -timestampindex state if (fTimestampIndex != GetBoolArg("-timestampindex", DEFAULT_TIMESTAMPINDEX)) { strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -timestampindex"); break; } // Check for changed -prune state. What we are concerned about is a user who has pruned blocks // in the past, but is now trying to run unpruned. if (fHavePruned && !fPruneMode) { strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain"); break; } if (!fReindex) { uiInterface.InitMessage(_("Rewinding blocks...")); if (!RewindBlockIndex(chainparams)) { strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain"); break; } } uiInterface.InitMessage(_("Verifying blocks...")); if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks", MIN_BLOCKS_TO_KEEP); } bool fReindexSupply = false; { LOCK(cs_main); CBlockIndex* tip = chainActive.Tip(); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = _("The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. " "Only rebuild the block database if you are sure that your computer's date and time are correct"); break; } CBlockIndex* firstBlock = chainActive[1]; if(firstBlock != NULL && firstBlock->nMoneySupply == 0) { LogPrintf("Reindexing money supply...\n"); fReindexSupply = true; } std::pair<int, uint256> firstZero = make_pair(0, uint256()); pblocktree->ReadFirstZerocoinBlock(firstZero); CBlockIndex* firstZeroBlock = chainActive[firstZero.first]; CBlockIndex* prevZeroBlock = chainActive[firstZero.first-1]; if(firstZero.first != 0 && ((firstZeroBlock && (firstZeroBlock->nVersion & VERSIONBITS_TOP_BITS_ZEROCOIN) != VERSIONBITS_TOP_BITS_ZEROCOIN) || (prevZeroBlock && (prevZeroBlock->nVersion & VERSIONBITS_TOP_BITS_ZEROCOIN) == VERSIONBITS_TOP_BITS_ZEROCOIN) || (!firstZeroBlock) || (firstZeroBlock->GetBlockHash() != firstZero.second))) { CBlockIndex* pindex = chainActive.Genesis(); while (pindex) { if ((pindex->nVersion & VERSIONBITS_TOP_BITS_ZEROCOIN) == VERSIONBITS_TOP_BITS_ZEROCOIN) break; pindex = chainActive.Next(pindex); } pblocktree->WriteFirstZerocoinBlock(make_pair(pindex ? pindex->nHeight : 0, pindex ? pindex->GetBlockHash() : uint256())); LogPrintf("First zerocoin block ammended to %d\n", pindex ? pindex->nHeight : 0); } } if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, 4, fReindexSupply ? 0 : GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) { strLoadError = _("Corrupted block database detected"); break; } } catch (const std::exception& e) { if (fDebug) LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } fLoaded = true; } while(false); if (!fLoaded) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeQuestion( strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.", "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION); // Allowed to fail as this file IS missing on first startup. if (!est_filein.IsNull()) mempool.ReadFeeEstimates(est_filein); fFeeEstimatesInitialized = true; // ********************************************************* Step 8: load wallet #ifdef ENABLE_WALLET if (fDisableWallet) { pwalletMain = NULL; LogPrintf("Wallet disabled!\n"); } else { CWallet::InitLoadWallet(); if (!pwalletMain) return false; } #else // ENABLE_WALLET LogPrintf("No wallet support compiled in!\n"); #endif // !ENABLE_WALLET // ********************************************************* Step 9: data directory maintenance // if pruning, unset the service bit and perform the initial blockstore prune // after any wallet rescanning has taken place. if (fPruneMode) { LogPrintf("Unsetting NODE_NETWORK on prune mode\n"); nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK); if (!fReindex) { uiInterface.InitMessage(_("Pruning blockstore...")); PruneAndFlush(); } } // ********************************************************* Step 10: import blocks if (mapArgs.count("-blocknotify")) uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); std::vector<boost::filesystem::path> vImportFiles; if (mapArgs.count("-loadblock")) { BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // Wait for genesis block to be processed bool fHaveGenesis = false; while (!fHaveGenesis && !fRequestShutdown) { { LOCK(cs_main); fHaveGenesis = (chainActive.Tip() != NULL); } if (!fHaveGenesis) { MilliSleep(10); } } // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; if (!strErrors.str().empty()) return InitError(strErrors.str()); //// debug print LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); LogPrintf("nBestHeight = %d\n", chainActive.Height()); #ifdef ENABLE_WALLET LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0); LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0); LogPrintf("mapSerial.size() = %u\n", pwalletMain ? pwalletMain->mapSerial.size() : 0); LogPrintf("mapWitness.size() = %u\n", pwalletMain ? pwalletMain->mapWitness.size() : 0); LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0); #endif if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) StartTorControl(threadGroup, scheduler); StartNode(threadGroup, scheduler); // ********************************************************* Step 12: finished SetRPCWarmupFinished(); #ifdef ENABLE_WALLET // Generate coins in the background SetStaking(GetBoolArg("-staking", true)); uiInterface.InitMessage(_("Starting staker thread...")); threadGroup.create_thread(boost::bind(&DeVaultStaker, boost::cref(chainparams))); if(GetBoolArg("-enablewitnesser", true)) { uiInterface.InitMessage(_("Starting witnesser thread...")); threadGroup.create_thread(boost::bind(&DeVaultWitnesser, boost::cref(chainparams))); } #endif uiInterface.InitMessage(_("Done loading")); #ifdef ENABLE_WALLET if (pwalletMain) { // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); // Run a thread to flush wallet periodically threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); } #endif return !fRequestShutdown; } void AlertNotify(const std::string& strMessage) { uiInterface.NotifyAlertChanged(); std::string strCmd = GetArg("-alertnotify", ""); if (strCmd.empty()) return; // Alert text should be plain ascii coming from a trusted source, but to // be safe we first strip anything not in safeChars, then add single quotes around // the whole string before passing it to the shell: std::string singleQuote("'"); std::string safeStatus = SanitizeString(strMessage); safeStatus = singleQuote+safeStatus+singleQuote; boost::replace_all(strCmd, "%s", safeStatus); boost::thread t(runCommand, strCmd); // thread runs free }
; Assembly for testpow2-native.bas ; compiled with mcbasic -native ; Equates for MC-10 MICROCOLOR BASIC 1.0 ; ; Direct page equates DP_LNUM .equ $E2 ; current line in BASIC DP_TABW .equ $E4 ; current tab width on console DP_LPOS .equ $E6 ; current line position on console DP_LWID .equ $E7 ; current line width of console ; ; Memory equates M_KBUF .equ $4231 ; keystrobe buffer (8 bytes) M_PMSK .equ $423C ; pixel mask for SET, RESET and POINT M_IKEY .equ $427F ; key code for INKEY$ M_CRSR .equ $4280 ; cursor location M_LBUF .equ $42B2 ; line input buffer (130 chars) M_MSTR .equ $4334 ; buffer for small string moves M_CODE .equ $4346 ; start of program space ; ; ROM equates R_BKMSG .equ $E1C1 ; 'BREAK' string location R_ERROR .equ $E238 ; generate error and restore direct mode R_BREAK .equ $E266 ; generate break and restore direct mode R_RESET .equ $E3EE ; setup stack and disable CONT R_SPACE .equ $E7B9 ; emit " " to console R_QUEST .equ $E7BC ; emit "?" to console R_REDO .equ $E7C1 ; emit "?REDO" to console R_EXTRA .equ $E8AB ; emit "?EXTRA IGNORED" to console R_DMODE .equ $F7AA ; display OK prompt and restore direct mode R_KPOLL .equ $F879 ; if key is down, do KEYIN, else set Z CCR flag R_KEYIN .equ $F883 ; poll key for key-down transition set Z otherwise R_PUTC .equ $F9C9 ; write ACCA to console R_MKTAB .equ $FA7B ; setup tabs for console R_GETLN .equ $FAA4 ; get line, returning with X pointing to M_BUF-1 R_SETPX .equ $FB44 ; write pixel character to X R_CLRPX .equ $FB59 ; clear pixel character in X R_MSKPX .equ $FB7C ; get pixel screen location X and mask in R_PMSK R_CLSN .equ $FBC4 ; clear screen with color code in ACCB R_CLS .equ $FBD4 ; clear screen with space character R_SOUND .equ $FFAB ; play sound with pitch in ACCA and duration in ACCB R_MCXID .equ $FFDA ; ID location for MCX BASIC ; direct page registers .org $80 strtcnt .block 1 strbuf .block 2 strend .block 2 strfree .block 2 strstop .block 2 dataptr .block 2 inptptr .block 2 redoptr .block 2 letptr .block 2 .org $a3 r1 .block 5 r2 .block 5 r3 .block 5 r4 .block 5 rend rvseed .block 2 tmp1 .block 2 tmp2 .block 2 tmp3 .block 2 tmp4 .block 2 tmp5 .block 2 argv .block 10 ; main program .org M_CODE jsr progbegin jsr clear LINE_10 ; FOR I=-3 TO 3 ldx #INTVAR_I ldab #-3 jsr for_ix_nb ldab #3 jsr to_ip_pb LINE_15 ; X=SHIFT(1,I) ldab #1 jsr ld_ir1_pb ldx #INTVAR_I jsr shift_fr1_ir1_ix ldx #FLTVAR_X jsr ld_fx_fr1 LINE_20 ; Y=2^(I+0.001) ldab #2 jsr ld_ir1_pb ldx #INTVAR_I jsr ld_ir2_ix ldx #FLT_0p00100 jsr add_fr2_ir2_fx jsr pow_fr1_ir1_fr2 ldx #FLTVAR_Y jsr ld_fx_fr1 LINE_25 ; PRINT STR$(SHIFT(1,I));" ";STR$(X);" ";STR$(Y);" " ldab #1 jsr ld_ir1_pb ldx #INTVAR_I jsr shift_fr1_ir1_ix jsr str_sr1_fr1 jsr pr_sr1 jsr pr_ss .text 1, " " ldx #FLTVAR_X jsr str_sr1_fx jsr pr_sr1 jsr pr_ss .text 1, " " ldx #FLTVAR_Y jsr str_sr1_fx jsr pr_sr1 jsr pr_ss .text 2, " \r" LINE_30 ; NEXT jsr next LLAST ; END jsr progend .module mdarg2x ; copy argv to [X] ; ENTRY Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; EXIT Y copied to 0,x 1,x 2,x 3,x 4,x arg2x ldab 0+argv stab 0,x ldd 1+argv std 1,x ldd 3+argv std 3,x rts .module mddivflt ; divide X by Y ; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x) ; scratch in (5,x 6,x 7,x 8,x 9,x) ; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; EXIT X/Y in (0,x 1,x 2,x 3,x 4,x) ; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4 divflt ldaa #8*5 bsr divmod tst tmp4 bmi _add1 _com ldd 8,x coma comb std 3,x ldd 6,x coma comb std 1,x ldab 5,x comb stab 0,x rts _add1 ldd 8,x addd #1 std 3,x ldd 6,x adcb #0 adca #0 std 1,x ldab 5,x adcb #0 stab 0,x rts divuflt clr tmp4 ldab #8*5 stab tmp1 bsr divumod bra _com .module mddivmod ; divide/modulo X by Y with remainder ; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x) ; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; #shifts in ACCA (24 for modulus, 40 for division ; EXIT for division: ; NOT ABS(X)/ABS(Y) in (5,x 6,x 7,x 8,x 9,x) ; EXIT for modulus: ; NOT INT(ABS(X)/ABS(Y)) in (7,x 8,x 9,x) ; FMOD(X,Y) in (0,x 1,x 2,x 3,x 4,x) ; result sign in tmp4.(0 = pos, -1 = neg). ; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4 divmod staa tmp1 clr tmp4 tst 0,x bpl _posX com tmp4 jsr negx _posX tst 0+argv bpl divumod com tmp4 jsr negargv divumod ldd 3,x std 6,x ldd 1,x std 4,x ldab 0,x stab 3,x clra clrb std 8,x std 1,x stab 0,x _nxtdiv rol 7,x rol 6,x rol 5,x rol 4,x rol 3,x rol 2,x rol 1,x rol 0,x bcc _trialsub ; force subtraction ldd 3,x subd 3+argv std 3,x ldd 1,x sbcb 2+argv sbca 1+argv std 1,x ldab 0,x sbcb 0+argv stab 0,x clc bra _shift _trialsub ldd 3,x subd 3+argv std tmp3 ldd 1,x sbcb 2+argv sbca 1+argv std tmp2 ldab 0,x sbcb 0+argv stab tmp1+1 blo _shift ldd tmp3 std 3,x ldd tmp2 std 1,x ldab tmp1+1 stab 0,x _shift rol 9,x rol 8,x dec tmp1 bne _nxtdiv rol 7,x rol 6,x rol 5,x rts .module mdexp exp ; X = EXP(X) ; ENTRY X in 0,X 1,X 2,X 3,X 4,X ; EXIT EXP(X) in (0,x 1,x 2,x 3,x 4,x) ; uses (5,x 6,x 7,x 8,x 9,x) ; uses argv and tmp1-tmp4 (tmp4+1 unused) ldd #exp_max bsr dd2argv bsr cmpxa bmi _ok ble _ok ldab #OV_ERROR jmp error _ok ldd #exp_min bsr dd2argv bsr cmpxa bge _go ldd #0 std 3,x std 1,x stab 0,x rts cmpxa ldd 3,x subd 3+argv ldd 1,x sbcb 2+argv sbca 1+argv ldab 0,x sbcb 0+argv rts dd2argv pshx pshb psha pulx ldab 0,x stab 0+argv ldd 1,x std 1+argv ldd 3,x std 3+argv pulx rts _go ldd #exp_ln2 bsr dd2argv jsr modflt ldab 9,x pshb ldab 0,x stab 0+argv ldd 1,x std 1+argv ldd 3,x std 3+argv ldd #8 bsr _addd ldd #56 bsr _mac ldd #336 bsr _mac ldd #1680 bsr _mac ldd #6720 bsr _mac ldd #20160 bsr _mac ldd #40320 bsr _mac ldd #40320 bsr _mac ldd #$A11A jsr rmul315 pulb jmp shift _mac pshb psha jsr mulfltx pula pulb _addd addd 1,x std 1,x ldab 0,x adcb #0 stab 0,x _rts rts exp_max .byte $00,$00,$0F,$F1,$3E exp_min .byte $FF,$FF,$F4,$E8,$DE exp_ln2 .byte $00,$00,$00,$B1,$72 .module mdidivb ; fast integer division by three or five ; ENTRY+EXIT: int in tmp1+1,tmp2,tmp2+1 ; ACCB contains: ; $CC for div-5 ; $AA for div-3 ; tmp3,tmp3+1,tmp4 used for storage idivb stab tmp4 ldab tmp1+1 pshb ldd tmp2 psha ldaa tmp4 mul std tmp3 addd tmp2 std tmp2 ldab tmp1+1 adcb tmp3+1 stab tmp1+1 ldd tmp1+1 addd tmp3 std tmp1+1 pulb ldaa tmp4 mul stab tmp3+1 addd tmp1+1 std tmp1+1 pulb ldaa tmp4 mul addb tmp1+1 addb tmp3+1 stab tmp1+1 rts .module mdimodb ; fast integer modulo operation by three or five ; ENTRY: int in tmp1+1,tmp2,tmp2+1 ; ACCB contains modulus (3 or 5) ; EXIT: result in ACCA imodb pshb ldaa tmp1+1 bpl _ok deca _ok adda tmp2 adca tmp2+1 adca #0 adca #0 tab lsra lsra lsra lsra andb #$0F aba pulb _dec sba bhs _dec aba tst tmp1+1 rts .module mdlog ; ENTRY X in 0,X 1,X 2,X 3,X 4,X ; EXIT Y=LOG(X) in (0,x 1,x 2,x 3,x 4,x) ; uses (5,x 6,x 7,x 8,x 9,x) as tmp storage for X ; uses argv and tmp1-tmp4 (tmp4+1 unused) log ldd 0,x subd #$7fff bne _normal ldab #1 jsr shrflt bsr _normal ldd 3,x addd #$B172 std 3,x ldab 2,x adcb #0 stab 2,x rts _normal jsr msbit tsta beq _fcerror cmpa #40 bne _ok _fcerror ldab #FC_ERROR jmp error _ok nega adda #40 staa tmp1 ldab #$DE mul std 8,x ldaa tmp1 ldab #$B1 mul addb 8,x adca #0 std 7,x ldd 8,x subd #$1720 std 8,x ldab 7,x sbcb #$0B stab 7,x ldaa #0 sbca #0 tab std 5,x _newton pshx ldab #5 abx ldd exp_max jsr dd2argv jsr cmpxa bmi _go ble _go jsr arg2x _go ldab 0,x stab 5,x ldd 1,x std 6,x ldd 3,x std 8,x ldab #5 abx jsr exp jsr x2arg pulx ldab 0,x stab 10,x ldd 1,x std 11,x ldd 3,x std 13,x pshx ldab #10 abx jsr divflt pulx ldd 11,x subd #1 std 11,x ldab 10,x sbcb #0 stab 10,x bne _again ldd 11,x bne _again ldd 13,x beq _done _again ldd 13,x addd 8,x std 8,x ldd 11,x adcb 7,x adca 6,x std 6,x ldab 10,x adcb 5,x stab 5,x bra _newton _done ldab 5,x stab 0,x ldd 6,x std 1,x ldd 8,x std 3,x rts .module mdmodflt ; modulo X by Y ; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x) ; scratch in (5,x 6,x 7,x 8,x 9,x) ; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; EXIT X%Y in (0,x 1,x 2,x 3,x 4,x) ; FIX(X/Y) in (7,x 8,x 9,x) ; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4 modflt ldaa #8*3 jsr divmod tst tmp4 bpl _rts jsr negx ldd 8,x addd #1 std 8,x ldab 7,x adcb #0 stab 7,x rts _rts com 9,x com 8,x com 7,x rts .module mdmsbit ; ACCA = MSBit(X) ; ENTRY X in 0,X 1,X 2,X 3,X 4,X ; EXIT most siginficant bit in ACCA ; 0 = sign bit, 39 = LSB. 40 if zero msbit pshx clra _nxtbyte ldab ,x bne _dobit adda #8 inx cmpa #40 blo _nxtbyte _rts pulx rts _dobit lslb bcs _rts inca bra _dobit .module mdmulflt mulfltx bsr mulfltt ldab tmp1+1 stab 0,x ldd tmp2 std 1,x ldd tmp3 std 3,x rts mulfltt jsr mulhlf clr tmp4 _4_3 ldaa 4+argv beq _3_4 ldab 3,x bsr _m43 _4_1 ldaa 4+argv ldab 1,x bsr _m41 _4_2 ldaa 4+argv ldab 2,x bsr _m42 _4_0 ldaa 4+argv ldab 0,x bsr _m40 ldab 0,x bpl _4_4 ldd tmp1+1 subb 4+argv sbca #0 std tmp1+1 _4_4 ldaa 4+argv ldab 4,x beq _rndup mul lslb adca tmp4 staa tmp4 bsr mulflt3 _3_4 ldab 4,x beq _rndup ldaa 3+argv bsr _m43 _1_4 ldab 4,x ldaa 1+argv bsr _m41 _2_4 ldab 4,x ldaa 2+argv bsr _m42 _0_4 ldab 4,x ldaa 0+argv bsr _m40 ldaa 0+argv bpl _rndup ldd tmp1+1 subb 4,x sbca #0 std tmp1+1 _rndup ldaa tmp4 lsla mulflt3 ldd tmp3 adcb #0 adca #0 std tmp3 ldd tmp2 adcb #0 adca #0 jmp mulhlf2 _m43 mul addd tmp3+1 std tmp3+1 rol tmp4+1 rts _m41 mul lsr tmp4+1 adcb tmp3 adca tmp2+1 std tmp2+1 ldd tmp1+1 adcb #0 adca #0 std tmp1+1 rts _m42 mul addd tmp3 std tmp3 rol tmp4+1 rts _m40 mul lsr tmp4+1 adcb tmp2+1 adca tmp2 bra mulhlf2 .module mdmulhlf mulhlf bsr mulint ldd #0 std tmp3 stab tmp4+1 _3_2 ldaa 3+argv beq _2_3 ldab 2,x bsr _m32 _3_0 ldaa 3+argv ldab 0,x bsr _m30 ldab 0,x bpl _3_3 ldab tmp1+1 subb 3+argv stab tmp1+1 _3_3 ldaa 3+argv ldab 3,x mul adda tmp3 std tmp3 rol tmp4+1 _3_1 ldaa 3+argv ldab 1,x bsr _m31 _2_3 ldab 3,x beq _rts ldaa 2+argv bsr _m32 _0_3 ldab 3,x ldaa 0+argv bsr _m30 ldaa 0+argv bpl _1_3 ldab tmp1+1 subb 3,x stab tmp1+1 _1_3 ldab 3,x ldaa 1+argv clr tmp4+1 _m31 mul lsr tmp4+1 adcb tmp2+1 adca tmp2 mulhlf2 std tmp2 ldab tmp1+1 adcb #0 stab tmp1+1 rts _m32 mul addd tmp2+1 std tmp2+1 rol tmp4+1 rts _m30 mul lsr tmp4+1 adcb tmp2 adca tmp1+1 std tmp1+1 _rts rts .module mdmulint mulint ldaa 2+argv ldab 2,x mul std tmp2 ldaa 1+argv ldab 1,x mul stab tmp1+1 ldaa 2+argv ldab 1,x mul addb tmp2 adca tmp1+1 std tmp1+1 ldaa 1+argv ldab 2,x mul addb tmp2 adca tmp1+1 std tmp1+1 ldaa 2+argv ldab 0,x mul addb tmp1+1 stab tmp1+1 ldaa 0+argv ldab 2,x mul addb tmp1+1 stab tmp1+1 rts mulintx bsr mulint ldab tmp1+1 stab 0,x ldd tmp2 std 1,x rts .module mdnegargv negargv neg 4+argv bcs _com3 neg 3+argv bcs _com2 neg 2+argv bcs _com1 neg 1+argv bcs _com0 neg 0+argv rts _com3 com 3+argv _com2 com 2+argv _com1 com 1+argv _com0 com 0+argv rts .module mdnegtmp negtmp neg tmp3+1 bcs _com3 neg tmp3 bcs _com2 neg tmp2+1 bcs _com1 neg tmp2 bcs _com0 neg tmp1+1 rts _com3 com tmp3 _com2 com tmp2+1 _com1 com tmp2 _com0 com tmp1+1 rts .module mdnegx negx neg 4,x bcs _com3 neg 3,x bcs _com2 negxi neg 2,x bcs _com1 neg 1,x bcs _com0 neg 0,x rts _com3 com 3,x _com2 com 2,x _com1 com 1,x _com0 com 0,x rts .module mdpowflt powfltx ldd 3+argv pshb psha ldd 1+argv pshb psha ldab 0+argv pshb jsr log pulb stab 0+argv pula pulb std 1+argv pula pulb std 3+argv jsr mulfltx jmp exp .module mdprint print _loop ldaa ,x jsr R_PUTC inx decb bne _loop rts .module mdrmul315 ; special routine to divide by 5040 or 40320 ; (reciprocal-multiply by 315 and shifting) ; 1/5040 = 256/315 >> 16 ; 1/40320 = 128/315 >> 16 ; ENTRY X in 0,X 1,X 2,X 3,X 4,X ; 0DD0 or A11A in ACCD ; EXIT result in (0,x 1,x 2,x 3,x 4,x) ; result ~= X/5040 when D is $0DD0 ; result ~= X/40320 when D is $A11A ; uses argv and tmp1-tmp4 (tmp4+1 unused) rmul315 stab 4+argv tab anda #$0f andb #$f0 std 2+argv ldd #0 std 0+argv jsr mulfltx ldd 1,x std 3,x ldab 0,x stab 2,x ldd #0 std 0,x rts .module mdshift ; multiply X by 2^ACCB for ACCB ; ENTRY X contains multiplicand in (0,x 1,x 2,x 3,x 4,x) ; EXIT X*2^ACCB in (0,x 1,x 2,x 3,x 4,x) ; uses tmp1 shifti clr 3,x clr 4,x shift tstb beq _rts bpl shlflt negb bra shrflt _rts rts .module mdshlflt ; multiply X by 2^ACCB for positive ACCB ; ENTRY X contains multiplicand in (0,x 1,x 2,x 3,x 4,x) ; EXIT X*2^ACCB in (0,x 1,x 2,x 3,x 4,x) ; uses tmp1 shlflt cmpb #8 blo _shlbit stab tmp1 ldd 1,x std 0,x ldd 3,x std 2,x clr 4,x ldab tmp1 subb #8 bne shlflt rts _shlbit lsl 4,x rol 3,x rol 2,x rol 1,x rol 0,x decb bne _shlbit rts .module mdshrflt ; divide X by 2^ACCB for positive ACCB ; ENTRY X contains multiplicand in (0,x 1,x 2,x 3,x 4,x) ; EXIT X*2^ACCB in (0,x 1,x 2,x 3,x 4,x) ; uses tmp1 shrint clr 3,x clr 4,x shrflt cmpb #8 blo _shrbit stab tmp1 ldd 2,x std 3,x ldd 0,x std 1,x clrb lsla sbcb #0 stab 0,x ldab tmp1 subb #8 bne shrflt rts _shrbit asr 0,x ror 1,x ror 2,x ror 3,x ror 4,x decb bne _shrbit rts .module mdstrflt strflt inc strtcnt pshx tst tmp1+1 bmi _neg ldab #' ' bra _wdigs _neg jsr negtmp ldab #'-' _wdigs ldx tmp3 pshx ldx strfree stab ,x clr tmp1 _nxtwdig inc tmp1 lsr tmp1+1 ror tmp2 ror tmp2+1 ror tmp3 ldab #5 jsr imodb staa tmp3+1 lsl tmp3 rola adda #'0' psha ldd tmp2 subb tmp3+1 sbca #0 std tmp2 ldab tmp1+1 sbcb #0 stab tmp1+1 ldab #$CC jsr idivb bne _nxtwdig ldd tmp2 bne _nxtwdig ldab tmp1 _nxtc pula inx staa ,x decb bne _nxtc inx inc tmp1 pula pulb subd #0 bne _fdo jmp _fdone _fdo std tmp2 ldab #'.' stab ,x inc tmp1 inx ldd #6 staa tmp1+1 stab tmp3 _nxtf ldd tmp2 lsl tmp2+1 rol tmp2 rol tmp1+1 lsl tmp2+1 rol tmp2 rol tmp1+1 addd tmp2 std tmp2 ldab tmp1+1 adcb #0 stab tmp1+1 lsl tmp2+1 rol tmp2 rol tmp1+1 ldd tmp1 addb #'0' stab ,x inx inc tmp1 clrb stab tmp1+1 dec tmp3 bne _nxtf tst tmp2 bmi _nxtrnd _nxtzero dex dec tmp1 ldaa ,x cmpa #'0' beq _nxtzero bra _zdone _nxtrnd dex dec tmp1 ldaa ,x cmpa #'.' beq _dot inca cmpa #'9' bhi _nxtrnd bra _rdone _dot ldaa #'0' staa ,x ldab tmp1 _ndot decb beq _dzero dex ldaa ,x inca cmpa #'9' bls _ddone bra _ndot _ddone staa ,x ldx strfree ldab tmp1 abx bra _fdone _dzero ldaa #'1' staa ,x ldx strfree ldab tmp1 abx ldaa #'0' _rdone staa ,x _zdone inx inc tmp1 _fdone ldd strfree stx strfree pulx rts .module mdstrrel ; release a temporary string ; ENTRY: X holds string start ; EXIT: <all reg's preserved> ; sttrel should be called from: ; - ASC, VAL, LEN, PRINT ; - right hand side of strcat ; - relational operators ; - when LEFT$, MID$, RIGHT$ return null strrel cpx strend bls _rts cpx strstop bhs _rts tst strtcnt beq _panic dec strtcnt beq _restore stx strfree _rts rts _restore pshx ldx strend inx inx stx strfree pulx rts _panic ldab #1 jmp error .module mdtonat ; push for-loop record on stack ; ENTRY: ACCB contains size of record ; r1 contains stopping variable ; and is always fixedpoint. ; r1+3 must contain zero if an integer. to clra std tmp3 pulx stx tmp1 tsx clrb _nxtfor abx ldd 1,x subd letptr beq _oldfor ldab ,x cmpb #3 bhi _nxtfor sts tmp2 ldd tmp2 subd tmp3 std tmp2 lds tmp2 tsx ldab tmp3+1 stab 0,x ldd letptr std 1,x _oldfor ldd tmp1 std 3,x ldab r1 stab 5,x ldd r1+1 std 6,x ldd r1+3 std 8,x ldab tmp3+1 cmpb #15 beq _flt inca staa 10,x bra _done _flt ldd #0 std 10,x std 13,x inca staa 12,x _done ldx tmp1 jmp ,x .module mdx2arg ; copy [X] to argv ; ENTRY Y in 0,x 1,x 2,x 3,x 4,x ; EXIT Y copied to 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; copy x to argv x2arg ldab 0,x stab 0+argv ldd 1,x std 1+argv ldd 3,x std 3+argv rts add_fr2_ir2_fx ; numCalls = 1 .module modadd_fr2_ir2_fx ldd 3,x std r2+3 ldd r2+1 addd 1,x std r2+1 ldab r2 adcb 0,x stab r2 rts clear ; numCalls = 1 .module modclear clra ldx #bss bra _start _again staa ,x inx _start cpx #bes bne _again stx strbuf stx strend inx inx stx strfree ldx #$8FFF stx strstop ldx #startdata stx dataptr rts for_ix_nb ; numCalls = 1 .module modfor_ix_nb stx letptr ldaa #-1 staa 0,x std 1,x rts ld_fx_fr1 ; numCalls = 2 .module modld_fx_fr1 ldd r1+3 std 3,x ldd r1+1 std 1,x ldab r1 stab 0,x rts ld_ir1_pb ; numCalls = 3 .module modld_ir1_pb stab r1+2 ldd #0 std r1 rts ld_ir2_ix ; numCalls = 1 .module modld_ir2_ix ldd 1,x std r2+1 ldab 0,x stab r2 rts next ; numCalls = 1 .module modnext pulx stx tmp1 tsx ldab ,x cmpb #3 bhi _ok ldab #NF_ERROR jmp error _ok cmpb #11 bne _flt ldd 9,x std r1+1 ldab 8,x stab r1 ldx 1,x ldd r1+1 addd 1,x std r1+1 std 1,x ldab r1 adcb ,x stab r1 stab ,x tsx tst 8,x bpl _iopp ldd r1+1 subd 6,x ldab r1 sbcb 5,x blt _idone ldx 3,x jmp ,x _iopp ldd 6,x subd r1+1 ldab 5,x sbcb r1 blt _idone ldx 3,x jmp ,x _idone ldab #11 bra _done _flt ldd 13,x std r1+3 ldd 11,x std r1+1 ldab 10,x stab r1 ldx 1,x ldd r1+3 addd 3,x std r1+3 std 3,x ldd 1,x adcb r1+2 adca r1+1 std r1+1 std 1,x ldab r1 adcb ,x stab r1 stab ,x tsx tst 10,x bpl _fopp ldd r1+3 subd 8,x ldd r1+1 sbcb 7,x sbca 6,x ldab r1 sbcb 5,x blt _fdone ldx 3,x jmp ,x _fopp ldd 8,x subd r1+3 ldd 6,x sbcb r1+2 sbca r1+1 ldab 5,x sbcb r1 blt _fdone ldx 3,x jmp ,x _fdone ldab #15 _done abx txs ldx tmp1 jmp ,x pow_fr1_ir1_fr2 ; numCalls = 1 .module modpow_fr1_ir1_fr2 ldab r2 stab 0+argv ldd r2+1 std 1+argv ldd r2+3 std 3+argv ldd #0 std r1+3 ldx #r1 jmp powfltx pr_sr1 ; numCalls = 3 .module modpr_sr1 ldab r1 beq _rts ldx r1+1 jsr print ldx r1+1 jmp strrel _rts rts pr_ss ; numCalls = 3 .module modpr_ss pulx ldab ,x beq _null inx jsr print jmp ,x _null jmp 1,x progbegin ; numCalls = 1 .module modprogbegin ldx R_MCXID cpx #'h'*256+'C' bne _mcbasic pulx clrb pshb pshb pshb stab strtcnt jmp ,x _reqmsg .text "?MICROCOLOR BASIC ROM REQUIRED" _mcbasic ldx #_reqmsg ldab #30 jsr print pulx rts progend ; numCalls = 1 .module modprogend pulx pula pula pula jsr R_RESET jmp R_DMODE NF_ERROR .equ 0 RG_ERROR .equ 4 OD_ERROR .equ 6 FC_ERROR .equ 8 OV_ERROR .equ 10 OM_ERROR .equ 12 BS_ERROR .equ 16 DD_ERROR .equ 18 LS_ERROR .equ 28 error jmp R_ERROR shift_fr1_ir1_ix ; numCalls = 2 .module modshift_fr1_ir1_ix ldab 2,x ldx #r1 jmp shifti str_sr1_fr1 ; numCalls = 1 .module modstr_sr1_fr1 ldd r1+1 std tmp2 ldab r1 stab tmp1+1 ldd r1+3 std tmp3 jsr strflt std r1+1 ldab tmp1 stab r1 rts str_sr1_fx ; numCalls = 2 .module modstr_sr1_fx ldd 1,x std tmp2 ldab 0,x stab tmp1+1 ldd 3,x std tmp3 jsr strflt std r1+1 ldab tmp1 stab r1 rts to_ip_pb ; numCalls = 1 .module modto_ip_pb stab r1+2 ldd #0 std r1 std r1+3 ldab #11 jmp to ; data table startdata enddata ; fixed-point constants FLT_0p00100 .byte $00, $00, $00, $00, $42 ; block started by symbol bss ; Numeric Variables INTVAR_I .block 3 FLTVAR_X .block 5 FLTVAR_Y .block 5 ; String Variables ; Numeric Arrays ; String Arrays ; block ended by symbol bes .end
/* * Copyright 2017 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 "pc/rtptransceiver.h" #include <algorithm> #include <string> #include "pc/rtpmediautils.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" namespace webrtc { RtpTransceiver::RtpTransceiver(cricket::MediaType media_type) : unified_plan_(false), media_type_(media_type) { RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO || media_type == cricket::MEDIA_TYPE_VIDEO); } RtpTransceiver::RtpTransceiver( rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender, rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>> receiver) : unified_plan_(true), media_type_(sender->media_type()) { RTC_DCHECK(media_type_ == cricket::MEDIA_TYPE_AUDIO || media_type_ == cricket::MEDIA_TYPE_VIDEO); RTC_DCHECK_EQ(sender->media_type(), receiver->media_type()); senders_.push_back(sender); receivers_.push_back(receiver); } RtpTransceiver::~RtpTransceiver() { Stop(); } void RtpTransceiver::SetChannel(cricket::ChannelInterface* channel) { // Cannot set a non-null channel on a stopped transceiver. if (stopped_ && channel) { return; } if (channel) { RTC_DCHECK_EQ(media_type(), channel->media_type()); } if (channel_) { channel_->SignalFirstPacketReceived().disconnect(this); } channel_ = channel; if (channel_) { channel_->SignalFirstPacketReceived().connect( this, &RtpTransceiver::OnFirstPacketReceived); } for (auto sender : senders_) { sender->internal()->SetMediaChannel(channel_ ? channel_->media_channel() : nullptr); } for (auto receiver : receivers_) { if (!channel_) { receiver->internal()->Stop(); } receiver->internal()->SetMediaChannel(channel_ ? channel_->media_channel() : nullptr); } } void RtpTransceiver::AddSender( rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender) { RTC_DCHECK(!stopped_); RTC_DCHECK(!unified_plan_); RTC_DCHECK(sender); RTC_DCHECK_EQ(media_type(), sender->media_type()); RTC_DCHECK(std::find(senders_.begin(), senders_.end(), sender) == senders_.end()); senders_.push_back(sender); } bool RtpTransceiver::RemoveSender(RtpSenderInterface* sender) { RTC_DCHECK(!unified_plan_); if (sender) { RTC_DCHECK_EQ(media_type(), sender->media_type()); } auto it = std::find(senders_.begin(), senders_.end(), sender); if (it == senders_.end()) { return false; } (*it)->internal()->Stop(); senders_.erase(it); return true; } void RtpTransceiver::AddReceiver( rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>> receiver) { RTC_DCHECK(!stopped_); RTC_DCHECK(!unified_plan_); RTC_DCHECK(receiver); RTC_DCHECK_EQ(media_type(), receiver->media_type()); RTC_DCHECK(std::find(receivers_.begin(), receivers_.end(), receiver) == receivers_.end()); receivers_.push_back(receiver); } bool RtpTransceiver::RemoveReceiver(RtpReceiverInterface* receiver) { RTC_DCHECK(!unified_plan_); if (receiver) { RTC_DCHECK_EQ(media_type(), receiver->media_type()); } auto it = std::find(receivers_.begin(), receivers_.end(), receiver); if (it == receivers_.end()) { return false; } (*it)->internal()->Stop(); receivers_.erase(it); return true; } rtc::scoped_refptr<RtpSenderInternal> RtpTransceiver::sender_internal() const { RTC_DCHECK(unified_plan_); RTC_CHECK_EQ(1u, senders_.size()); return senders_[0]->internal(); } rtc::scoped_refptr<RtpReceiverInternal> RtpTransceiver::receiver_internal() const { RTC_DCHECK(unified_plan_); RTC_CHECK_EQ(1u, receivers_.size()); return receivers_[0]->internal(); } cricket::MediaType RtpTransceiver::media_type() const { return media_type_; } absl::optional<std::string> RtpTransceiver::mid() const { return mid_; } void RtpTransceiver::OnFirstPacketReceived(cricket::ChannelInterface*) { for (auto receiver : receivers_) { receiver->internal()->NotifyFirstPacketReceived(); } } rtc::scoped_refptr<RtpSenderInterface> RtpTransceiver::sender() const { RTC_DCHECK(unified_plan_); RTC_CHECK_EQ(1u, senders_.size()); return senders_[0]; } rtc::scoped_refptr<RtpReceiverInterface> RtpTransceiver::receiver() const { RTC_DCHECK(unified_plan_); RTC_CHECK_EQ(1u, receivers_.size()); return receivers_[0]; } void RtpTransceiver::set_current_direction(RtpTransceiverDirection direction) { RTC_LOG(LS_INFO) << "Changing transceiver (MID=" << mid_.value_or("<not set>") << ") current direction from " << (current_direction_ ? RtpTransceiverDirectionToString( *current_direction_) : "<not set>") << " to " << RtpTransceiverDirectionToString(direction) << "."; current_direction_ = direction; if (RtpTransceiverDirectionHasSend(*current_direction_)) { has_ever_been_used_to_send_ = true; } } void RtpTransceiver::set_fired_direction(RtpTransceiverDirection direction) { fired_direction_ = direction; } bool RtpTransceiver::stopped() const { return stopped_; } RtpTransceiverDirection RtpTransceiver::direction() const { return direction_; } void RtpTransceiver::SetDirection(RtpTransceiverDirection new_direction) { if (stopped()) { return; } if (new_direction == direction_) { return; } direction_ = new_direction; SignalNegotiationNeeded(); } absl::optional<RtpTransceiverDirection> RtpTransceiver::current_direction() const { return current_direction_; } absl::optional<RtpTransceiverDirection> RtpTransceiver::fired_direction() const { return fired_direction_; } void RtpTransceiver::Stop() { for (auto sender : senders_) { sender->internal()->Stop(); } for (auto receiver : receivers_) { receiver->internal()->Stop(); } stopped_ = true; current_direction_ = absl::nullopt; } void RtpTransceiver::SetCodecPreferences( rtc::ArrayView<RtpCodecCapability> codecs) { // TODO(steveanton): Implement this. RTC_NOTREACHED() << "Not implemented"; } } // namespace webrtc
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r15 push %r9 push %rcx push %rdx // Store lea addresses_UC+0x1c52f, %r9 clflush (%r9) add %rdx, %rdx mov $0x5152535455565758, %r10 movq %r10, %xmm5 vmovups %ymm5, (%r9) inc %r10 // Store lea addresses_PSE+0x26a7, %rcx nop nop add %r9, %r9 mov $0x5152535455565758, %r10 movq %r10, (%rcx) // Exception!!! nop nop mov (0), %r15 nop nop nop nop xor %r11, %r11 // Store lea addresses_US+0x7bef, %r10 nop inc %rdx movw $0x5152, (%r10) // Exception!!! nop nop nop nop mov (0), %r9 add %rcx, %rcx // Faulty Load lea addresses_US+0x7bef, %r9 nop nop add $36775, %r15 mov (%r9), %r10d lea oracles, %r9 and $0xff, %r10 shlq $12, %r10 mov (%r9,%r10,1), %r10 pop %rdx pop %rcx pop %r9 pop %r15 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 5, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 2, 'size': 8, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': True, 'congruent': 0, 'size': 4, 'same': True, 'NT': True}} <gen_prepare_buffer> {'52': 2} 52 52 */
MOV 0x20,#0x01 MOV 0x21,#0x02 MOV 0x22,#0x04 MOV 0x23,#0x08 MOV 0x24,#0x10 MOV 0x25,#0x20 MOV 0x26,#0x40 MOV 0x27,#0x80 ORL A,0x20 ORL A,0x21 ORL A,0x22 ORL A,0x23 ORL A,0x24 ORL A,0x25 ORL A,0x26 ORL A,0x27
; A013958: sigma_10(n), the sum of the 10th powers of the divisors of n. ; 1,1025,59050,1049601,9765626,60526250,282475250,1074791425,3486843451,10009766650,25937424602,61978939050,137858491850,289537131250,576660215300,1100586419201,2015993900450,3574014537275,6131066257802,10250010815226,16680163512500,26585860217050,41426511213650,63466433646250,95367441406251,141304954146250,205894618938100,296486304875250,420707233300202,591076720682500,819628286980802,1127000493261825,1531604922748100,2066393747961250,2758547645756500,3659794373013051,4808584372417850,6284342914247050,8140543943742500,10496011084557050,13422659310152402,17097167600312500,21611482313284250,27223946799683802,34051209063015326,42462173993991250,52599132235830050,64989628053819050,79792266580087251,97751627441407275,119044439821572500,144696410904251850,174887470365513050,211041984411552500,253295188066330852,303601976474731250,362039462523208100,431224914132707050,511116753300641402,605263138639095300,713342911662882602,840118994155322050,984946975532087750,1154048505100108801,1346274472331148100,1569895045816802500,1822837804551761450,2115989213906220450,2446235487166032500,2827511336900412500,3255243551009881202,3747629441452207675,4297625829703557650,4928798981728296250,5631447415039121550,6435173275255237002,7326680498806100500,8344057542336062500,9468276082626847202,10747915350596184826,12157871353675866901,13758225792906212050,15516041187205853450,17507516302883512500,19687442450075931700,22151769371116356250,24842762126376928100,27877321548813637850,31181719929966183602,34902489289590709150,38941611949951712500,43481307596358253650,48399050346216358100,53914110541725801250,59873700054913914052,66549379127110766250,73742412689492826050,81787073244589432275,90439739109289981502,100097761867442455851 add $0,1 mov $2,$0 lpb $0 mov $3,$2 mov $4,$0 cmp $4,0 add $0,$4 dif $3,$0 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 pow $3,10 add $1,$3 lpe add $1,1 mov $0,$1
#include "MFB/Sage/variable-declaration.hpp" #include "MFB/Sage/namespace-declaration.hpp" #include "sage3basic.h" #ifndef VERBOSE # define VERBOSE 0 #endif namespace MFB { bool ignore(const std::string & name); bool ignore(SgScopeStatement * scope); template <> bool Driver<Sage>::resolveValidParent<SgVariableSymbol>(SgVariableSymbol * symbol) { SgSymbol * parent = NULL; if (p_valid_symbols.find(symbol) != p_valid_symbols.end()) return true; SgNamespaceDefinitionStatement * namespace_scope = isSgNamespaceDefinitionStatement(symbol->get_scope()); SgClassDefinition * class_scope = isSgClassDefinition (symbol->get_scope()); if (namespace_scope != NULL) { SgNamespaceDeclarationStatement * parent_decl = namespace_scope->get_namespaceDeclaration(); assert(parent_decl != NULL); parent = SageInterface::lookupNamespaceSymbolInParentScopes(parent_decl->get_name(), parent_decl->get_scope()); assert(parent != NULL); if (!resolveValidParent<SgNamespaceSymbol>((SgNamespaceSymbol *)parent)) return false; assert(p_valid_symbols.find(parent) != p_valid_symbols.end()); } else if (class_scope != NULL) { SgClassDeclaration * parent_decl = class_scope->get_declaration(); assert(parent_decl != NULL); parent = SageInterface::lookupClassSymbolInParentScopes(parent_decl->get_name(), parent_decl->get_scope()); assert(parent != NULL); if (!resolveValidParent<SgClassSymbol>((SgClassSymbol *)parent)) return false; assert(p_valid_symbols.find(parent) != p_valid_symbols.end()); } p_valid_symbols.insert(symbol); p_parent_map.insert(std::pair<SgSymbol *, SgSymbol *>(symbol, parent)); p_variable_symbols.insert(symbol); return true; } template <> void Driver<Sage>::loadSymbols<SgVariableDeclaration>(size_t file_id, SgSourceFile * file) { std::vector<SgVariableDeclaration *> variable_decl = SageInterface::querySubTree<SgVariableDeclaration>(file); std::set<SgVariableSymbol *> variable_symbols; std::vector<SgVariableDeclaration *>::const_iterator it_variable_decl; for (it_variable_decl = variable_decl.begin(); it_variable_decl != variable_decl.end(); it_variable_decl++) { SgVariableDeclaration * variable_decl = *it_variable_decl; #if VERBOSE std::cout << "[Debug] (MFB::Driver<Sage>::loadSymbols<SgVariableDeclaration>) variable_decl = " << variable_decl << " (" << variable_decl->get_name().str() << ")" << std::endl; #endif ROSE_ASSERT(variable_decl->get_variables().size() == 1); SgTemplateVariableDeclaration * tplvar_decl = isSgTemplateVariableDeclaration(variable_decl); SgInitializedName * init_name = variable_decl->get_variables()[0]; ROSE_ASSERT(init_name != NULL); ROSE_ASSERT(init_name->get_scope() != NULL); SgInitializedName * prev_init_name = init_name->get_prev_decl_item(); ROSE_ASSERT( !( prev_init_name != NULL ) || ( prev_init_name->get_scope() != NULL ) ); #if 1 if (prev_init_name != NULL) { ROSE_ASSERT(init_name->get_scope() == prev_init_name->get_scope()); } #endif if (prev_init_name != NULL) continue; SgScopeStatement * scope = variable_decl->get_scope(); ROSE_ASSERT(scope != NULL); if (ignore(scope)) continue; if (init_name->get_name().getString() == "") { #if VERBOSE std::cout << "[Debug] (MFB::Driver<Sage>::loadSymbols<SgVariableDeclaration>) SgInitializedName with empty name!" << std::endl; std::cout << "[Debug] Parents: " << std::endl; SgNode * p = init_name->get_parent(); while (p != NULL && !isSgFile(p)) { std::cout << "[Debug] - " << std::hex << p << " (" << p->class_name() << ")" << std::endl; p = p->get_parent(); } #endif continue; // FIXME ROSE‌-1465 } if (ignore(init_name->get_name().getString())) continue; SgVariableSymbol * variable_sym = NULL; if (tplvar_decl == NULL) { variable_sym = SageInterface::lookupVariableSymbolInParentScopes(init_name->get_name(), scope); if (variable_sym == NULL) { std::cerr << "[Error] (MFB::Driver<Sage>::loadSymbols<SgVariableDeclaration>) Not found: " << init_name->get_name().getString() << std::endl; } ROSE_ASSERT(variable_sym != NULL); } else { variable_sym = SageInterface::lookupTemplateVariableSymbolInParentScopes(init_name->get_name(), &(tplvar_decl->get_templateParameters()), &(tplvar_decl->get_templateSpecializationArguments()), scope); if (variable_sym == NULL) { std::cerr << "[Error] (MFB::Driver<Sage>::loadSymbols<SgVariableDeclaration>) Not found: " << init_name->get_name().getString() << " (templated variable)" << std::endl; continue; // FIXME ROSE‌-1465 } ROSE_ASSERT(variable_sym != NULL); ROSE_ASSERT(isSgTemplateVariableSymbol(variable_sym)); } variable_symbols.insert(variable_sym); } std::set<SgVariableSymbol *>::iterator it; for (it = variable_symbols.begin(); it != variable_symbols.end(); it++) if (resolveValidParent<SgVariableSymbol>(*it)) { p_symbol_to_file_id_map[*it] = file_id; #if VERBOSE std::cerr << "[Info] (MFB::Driver<Sage>::loadSymbols<SgVariableDeclaration>) Add: " << (*it)->get_name().getString() << " from File #" << file_id << std::endl; #endif } } Sage<SgVariableDeclaration>::object_desc_t::object_desc_t( std::string name_, SgType * type_, SgInitializer * initializer_, SgSymbol * parent_, size_t file_id_, bool is_static_, bool create_definition_ ) : name(name_), type(type_), initializer(initializer_), parent(parent_), file_id(file_id_), is_static(is_static_), create_definition(create_definition_) {} template <> Sage<SgVariableDeclaration>::build_result_t Driver<Sage>::build<SgVariableDeclaration>(const Sage<SgVariableDeclaration>::object_desc_t & desc) { Sage<SgVariableDeclaration>::build_result_t result; SgScopeStatement * decl_scope = getBuildScopes<SgVariableDeclaration>(desc); SgVariableDeclaration * var_decl = SageBuilder::buildVariableDeclaration(desc.name, desc.type, desc.initializer, decl_scope); SageInterface::appendStatement(var_decl, decl_scope); result.symbol = decl_scope->lookup_variable_symbol(desc.name); assert(result.symbol != NULL); result.definition = var_decl->get_variables()[0]; assert(result.definition != NULL); if (isSgClassSymbol(desc.parent) != NULL) { std::map<SgSymbol *, size_t>::iterator it_sym_to_file = p_symbol_to_file_id_map.find(desc.parent); assert(it_sym_to_file != p_symbol_to_file_id_map.end()); p_symbol_to_file_id_map.insert(std::pair<SgSymbol *, size_t>(result.symbol, it_sym_to_file->second)); } else p_symbol_to_file_id_map.insert(std::pair<SgSymbol *, size_t>(result.symbol, desc.file_id)); p_valid_symbols.insert(result.symbol); p_parent_map.insert(std::pair<SgSymbol *, SgSymbol *>(result.symbol, desc.parent)); p_variable_symbols.insert(result.symbol); return result; } template <> Sage<SgVariableDeclaration>::build_scopes_t Driver<Sage>::getBuildScopes<SgVariableDeclaration>(const Sage<SgVariableDeclaration>::object_desc_t & desc) { Sage<SgVariableDeclaration>::build_scopes_t result = NULL; SgClassSymbol * class_symbol = isSgClassSymbol(desc.parent); SgNamespaceSymbol * namespace_symbol = isSgNamespaceSymbol(desc.parent); std::map<size_t, SgSourceFile *>::iterator it_file = id_to_file_map.find(desc.file_id); assert(it_file != id_to_file_map.end()); SgSourceFile * file = it_file->second; assert(file != NULL); if (desc.parent == NULL) result = file->get_globalScope(); else if (namespace_symbol != NULL) result = Sage<SgNamespaceDeclarationStatement>::getDefinition(namespace_symbol, file); else if (class_symbol != NULL) result = ((SgClassDeclaration *)class_symbol->get_declaration()->get_definingDeclaration())->get_definition(); else ROSE_ABORT(); assert(result != NULL); return result; } template <> void Driver<Sage>::createForwardDeclaration<SgVariableDeclaration>(Sage<SgVariableDeclaration>::symbol_t symbol, size_t target_file_id) { std::map<size_t, SgSourceFile *>::iterator it_target_file = id_to_file_map.find(target_file_id); assert(it_target_file != id_to_file_map.end()); SgSourceFile * target_file = it_target_file->second; assert(target_file != NULL); ROSE_ABORT(); } }
; A198689: 8*7^n-1. ; 7,55,391,2743,19207,134455,941191,6588343,46118407,322828855,2259801991,15818613943,110730297607,775112083255,5425784582791,37980492079543,265863444556807,1861044111897655,13027308783283591,91191161482985143,638338130380896007,4468366912666272055,31278568388663904391,218949978720647330743,1532649851044531315207,10728548957311719206455,75099842701182034445191,525698898908274241116343,3679892292357919687814407,25759246046505437814700855,180314722325538064702905991,1262203056278766452920341943 mov $1,7 pow $1,$0 mul $1,8 sub $1,1 mov $0,$1
SFX_Healing_Machine_1_Ch1: duty 2 unknownsfx0x10 44 unknownsfx0x20 4, 242, 0, 5 unknownsfx0x10 34 unknownsfx0x20 2, 241, 0, 5 unknownsfx0x10 8 unknownsfx0x20 1, 0, 0, 0 endchannel
;Ejemplo Desarrollado Simulador EMU8086 .model small .stack 64 .data ;------------------------------------------------------------ num1 db 'Introduce el primer numero==>',10,13,'$' num2 db 'Introduce el segundo numero==>',10,13,'$' guarda1 db '?',10,13,'$' guarda2 db '?',10,13,'$' resultado db 'El mayor es:','$' hecho db 'Ciencias-3','$' salto db '',10,13,'$' ;----------------------------------------------------------- .code mov ax,@data mov ds,ax ;----------------------------------------------------------- mov ah,06 mov al,01 mov bh,09 ;color de letra mov cx,0000h mov dx,184fh int 10H mov ah,9 lea dx,num1 ;pide 1er numero int 21h mov ah,1 ;teclado int 21h mov bl,al ;guardamos valor mov ah,9 lea dx,salto ;salto int 21h mov ah,9 lea dx,num2 ;pide 2do numero int 21h mov ah,1 ;teclado int 21h mov guarda1,al ;respaldamos para que no lo pierda en el salto mov ah,9 lea dx,salto ;salto int 21h mov al,guarda1 ;recuperamos valor ;----------------------------------------------------------- cmp bl,al ;COMPARACIONES jae imprime1 jmp imprime2 ;------------------------------------------------------------ imprime1: mov guarda1,bl mov ah,9 lea dx,resultado ;MENSAJE DE RESULTADO int 21h mov ah,2 mov dl,guarda1 ;IMPRIMIMOS MAYOR int 21h jmp termina ;----------------------------------------------------------- imprime2: mov guarda2,al mov ah,9 lea dx,resultado ;MENSAJE DE RESULTADO int 21h mov ah,2 mov dl,guarda2 ;IMPRIMIMOS MAYOR int 21h jmp termina ;---------------------------------------------------------- termina: mov ah,9 lea dx,salto ;salto int 21h mov ah,9 lea dx,hecho ;MENSAJE DE RESULTADO int 21h mov ax,4c00h ;TERMINA PROGRAMA int 21h end ends
; Z88 Small C+ Run Time Library ; Long functions ; SECTION code_clib SECTION code_l_sccz80 PUBLIC l_long_uge EXTERN l_long_ucmp l_long_uge: ; PRIMARY >= SECONDARY, carry set if true ; HL set to 0 (false) or 1 (true) ; dehl = secondary ; stack = primary, ret call l_long_ucmp ccf ret c dec l ret
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string> #include "modules/mymodule.h" #include "modules/mymultiplier.h" #include "modules/mycalculator.h" int main (int argc, char *argv[]) { printf("invoked as %s\n", argv[0]); MyModule* myObject = new MyModule(); std::string myStr = myObject->foo(); myStr += "\n"; printf(myStr.c_str()); MyMultiplier* myMultiplier = new MyMultiplier(); MyCalculator* myCalculator = new MyCalculator(myMultiplier); printf("%f\n", myCalculator->multiply(3.14, 42)); return 0; }
; A156675: a(n) = 17*((100^(n+1) - 1)/99). ; 17,1717,171717,17171717,1717171717,171717171717,17171717171717,1717171717171717,171717171717171717,17171717171717171717,1717171717171717171717,171717171717171717171717,17171717171717171717171717,1717171717171717171717171717,171717171717171717171717171717,17171717171717171717171717171717,1717171717171717171717171717171717,171717171717171717171717171717171717,17171717171717171717171717171717171717,1717171717171717171717171717171717171717,171717171717171717171717171717171717171717 mov $1,100 pow $1,$0 div $1,99 mul $1,1700 add $1,17 mov $0,$1
; A219086: a(n) = floor((n + 1/2)^4). ; 0,5,39,150,410,915,1785,3164,5220,8145,12155,17490,24414,33215,44205,57720,74120,93789,117135,144590,176610,213675,256289,304980,360300,422825,493155,571914,659750,757335,865365,984560,1115664,1259445,1416695,1588230,1774890,1977539,2197065,2434380,2690420,2966145,3262539,3580610,3921390,4285935,4675325,5090664,5533080,6003725,6503775,7034430,7596914,8192475,8822385,9487940,10190460,10931289,11711795,12533370,13397430,14305415,15258789,16259040,17307680,18406245,19556295,20759414,22017210 mul $0,2 add $0,1 pow $0,4 div $0,16
.686p .mmx .model flat,stdcall option casemap:none option prologue:none option epilogue:none .code zero proc ptrA:DWORD push eax push esi xor eax, eax mov esi, dword ptr [esp+4+8] and dword ptr [esi ], eax and dword ptr [esi+ 4], eax and dword ptr [esi+ 8], eax and dword ptr [esi+12], eax pop esi pop eax ret 4 zero endp end
.ktext 0x4180 li $t1,0 eret .text 0x3000 li $t1,0x7fffffff li $t2,0x7fffffff add $t3,$t1,$t2
<% from pwnlib.shellcraft.thumb.linux import syscall %> <%page args="file, file_times"/> <%docstring> Invokes the syscall utime. See 'man 2 utime' for more information. Arguments: file(char): file file_times(utimbuf): file_times </%docstring> ${syscall('SYS_utime', file, file_times)}
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r15 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_UC_ht+0x10ea3, %r15 cmp $60758, %r14 mov (%r15), %rax nop nop nop nop cmp $22566, %r15 lea addresses_normal_ht+0x1c183, %r11 clflush (%r11) nop nop nop cmp $21743, %rdi movl $0x61626364, (%r11) nop add %r11, %r11 lea addresses_WT_ht+0x1c673, %r9 nop nop dec %r14 movw $0x6162, (%r9) nop cmp %rax, %rax lea addresses_normal_ht+0x24c7, %rsi lea addresses_A_ht+0x698b, %rdi nop nop xor $14736, %r9 mov $16, %rcx rep movsb nop nop nop nop dec %rax lea addresses_UC_ht+0x104a3, %rsi lea addresses_D_ht+0x78a3, %rdi nop nop nop xor %r9, %r9 mov $88, %rcx rep movsb nop nop nop nop sub $16443, %r15 lea addresses_normal_ht+0x109e3, %rdi nop nop inc %r9 mov (%rdi), %cx nop nop add %rcx, %rcx lea addresses_A_ht+0x60b3, %rsi lea addresses_normal_ht+0x3123, %rdi nop nop nop nop nop dec %rax mov $107, %rcx rep movsb nop nop cmp $4723, %rsi lea addresses_UC_ht+0x50a3, %r15 nop nop sub %rsi, %rsi and $0xffffffffffffffc0, %r15 movntdqa (%r15), %xmm4 vpextrq $1, %xmm4, %rdi and $59584, %r15 lea addresses_D_ht+0x5ea3, %r11 nop nop nop inc %rcx mov $0x6162636465666768, %r9 movq %r9, %xmm3 vmovups %ymm3, (%r11) and $4384, %rsi lea addresses_D_ht+0x88a3, %rdi nop nop add %rcx, %rcx mov $0x6162636465666768, %rsi movq %rsi, (%rdi) nop nop nop nop nop sub %r11, %r11 lea addresses_WC_ht+0x14a3, %rsi lea addresses_WC_ht+0xfea3, %rdi clflush (%rdi) nop nop nop nop nop sub $32132, %r11 mov $118, %rcx rep movsq nop nop nop sub %rax, %rax lea addresses_WC_ht+0xb123, %r14 nop add %r9, %r9 and $0xffffffffffffffc0, %r14 vmovntdqa (%r14), %ymm4 vextracti128 $0, %ymm4, %xmm4 vpextrq $0, %xmm4, %rdi nop inc %r9 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r15 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r9 push %rax push %rbx push %rcx push %rdi push %rsi // Store lea addresses_WC+0x6723, %r12 nop nop nop cmp %r9, %r9 movw $0x5152, (%r12) nop nop nop nop add $10822, %rbx // Store lea addresses_A+0x11ea3, %r12 nop nop nop and %rbx, %rbx mov $0x5152535455565758, %r9 movq %r9, %xmm4 movups %xmm4, (%r12) nop nop nop nop nop add $33263, %rdi // REPMOV lea addresses_WT+0xbaa3, %rsi lea addresses_A+0x167d0, %rdi clflush (%rsi) nop nop nop nop nop inc %r9 mov $124, %rcx rep movsb nop nop dec %rdi // Store lea addresses_D+0x18a2b, %r9 nop nop add %rbx, %rbx mov $0x5152535455565758, %rsi movq %rsi, %xmm4 movups %xmm4, (%r9) nop nop nop nop dec %r9 // Store lea addresses_UC+0x14c93, %rsi inc %r10 movl $0x51525354, (%rsi) nop nop nop nop cmp %rdi, %rdi // Load lea addresses_WC+0x1a8f6, %r10 nop nop nop and %rbx, %rbx mov (%r10), %ax nop nop nop xor %rdi, %rdi // Faulty Load lea addresses_RW+0x76a3, %r12 nop nop nop and $18413, %rsi movb (%r12), %r9b lea oracles, %rdi and $0xff, %r9 shlq $12, %r9 mov (%rdi,%r9,1), %r9 pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_RW', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 2, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WT', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_A', 'congruent': 0, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_D', 'same': False, 'size': 16, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_RW', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 32, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'same': True, 'size': 32, 'congruent': 6, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'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 */
; char *gets(char *s) INCLUDE "clib_cfg.asm" SECTION code_stdio ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $02 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC gets EXTERN asm_gets defc gets = asm_gets ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; PUBLIC gets EXTERN gets_unlocked defc gets = gets_unlocked ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkCenteredAffineTransform_hxx #define itkCenteredAffineTransform_hxx #include "itkNumericTraits.h" #include "vnl/algo/vnl_matrix_inverse.h" namespace itk { // Constructor with default arguments template <typename TParametersValueType, unsigned int VDimension> CenteredAffineTransform<TParametersValueType, VDimension>::CenteredAffineTransform() : Superclass(ParametersDimension) {} // Get parameters template <typename TParametersValueType, unsigned int VDimension> auto CenteredAffineTransform<TParametersValueType, VDimension>::GetParameters() const -> const ParametersType & { // Transfer the linear part unsigned int par = 0; const MatrixType & matrix = this->GetMatrix(); for (unsigned int row = 0; row < VDimension; ++row) { for (unsigned int col = 0; col < VDimension; ++col) { this->m_Parameters[par] = matrix[row][col]; ++par; } } // Transfer the rotation center InputPointType center = this->GetCenter(); for (unsigned int j = 0; j < VDimension; ++j) { this->m_Parameters[par] = center[j]; ++par; } // Transfer the translation OutputVectorType translation = this->GetTranslation(); for (unsigned int k = 0; k < VDimension; ++k) { this->m_Parameters[par] = translation[k]; ++par; } return this->m_Parameters; } /** Set the parameters */ template <typename TParametersValueType, unsigned int VDimension> void CenteredAffineTransform<TParametersValueType, VDimension>::SetParameters(const ParametersType & parameters) { // Transfer the linear part unsigned int par = 0; // Save parameters. Needed for proper operation of TransformUpdateParameters. if (&parameters != &(this->m_Parameters)) { this->m_Parameters = parameters; } MatrixType matrix; for (unsigned int row = 0; row < VDimension; ++row) { for (unsigned int col = 0; col < VDimension; ++col) { matrix[row][col] = this->m_Parameters[par]; ++par; } } this->SetMatrix(matrix); // Transfer the rotation center InputPointType center; for (unsigned int i = 0; i < VDimension; ++i) { center[i] = this->m_Parameters[par]; ++par; } this->SetCenter(center); // Transfer the translation OutputVectorType translation; for (unsigned int k = 0; k < VDimension; ++k) { translation[k] = this->m_Parameters[par]; ++par; } this->SetTranslation(translation); // Modified is always called since we just have a pointer to the // parameters and cannot know if the parameters have changed. this->Modified(); } template <typename TParametersValueType, unsigned int VDimension> void CenteredAffineTransform<TParametersValueType, VDimension>::ComputeJacobianWithRespectToParameters( const InputPointType & p, JacobianType & jacobian) const { // The Jacobian of the affine transform is composed of // subblocks of diagonal matrices, each one of them having // a constant value in the diagonal. // The block corresponding to the center parameters is // composed by ( Identity matrix - Rotation Matrix). jacobian.SetSize(VDimension, this->GetNumberOfLocalParameters()); jacobian.Fill(0.0); unsigned int blockOffset = 0; for (unsigned int block = 0; block < SpaceDimension; ++block) { for (unsigned int dim = 0; dim < SpaceDimension; ++dim) { jacobian(block, blockOffset + dim) = p[dim]; } blockOffset += SpaceDimension; } // Block associated with the center parameters const MatrixType & matrix = this->GetMatrix(); for (unsigned int k = 0; k < SpaceDimension; ++k) { jacobian(k, blockOffset + k) = 1.0; for (unsigned int dim = 0; dim < SpaceDimension; ++dim) { jacobian(k, blockOffset + dim) -= matrix[k][dim]; } } blockOffset += SpaceDimension; // Block associated with the translations for (unsigned int dim = 0; dim < SpaceDimension; ++dim) { jacobian(dim, blockOffset + dim) = 1.0; } } // Get an inverse of this transform template <typename TParametersValueType, unsigned int VDimension> bool CenteredAffineTransform<TParametersValueType, VDimension>::GetInverse(Self * inverse) const { return this->Superclass::GetInverse(inverse); } // Return an inverse of this transform template <typename TParametersValueType, unsigned int VDimension> auto CenteredAffineTransform<TParametersValueType, VDimension>::GetInverseTransform() const -> InverseTransformBasePointer { Pointer inv = New(); return this->GetInverse(inv) ? inv.GetPointer() : nullptr; } } // namespace itk #endif
Name: window.asm Type: file Size: 7803 Last-Modified: '1992-04-28T12:18:21Z' SHA-1: 5C60618CE23E0EE6656CE1143704D0489FCD39E5 Description: null
[bits 32] [section .text] INT_VECTOR_SYS_CALL equ 0x80 _NR_REWINDIR EQU 20 global rewinddir rewinddir: mov eax, _NR_REWINDIR mov ebx, [esp + 4] int INT_VECTOR_SYS_CALL ret
/* * FreeRTOS Kernel V10.0.1 * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include "FreeRTOSConfig.h" #include "portasm.h" .CODE /* * The RTOS tick ISR. * * If the cooperative scheduler is in use this simply increments the tick * count. * * If the preemptive scheduler is in use a context switch can also occur. */ _vTickISR: portSAVE_CONTEXT call #_xTaskIncrementTick cmp.w #0x00, r15 jeq _SkipContextSwitch call #_vTaskSwitchContext _SkipContextSwitch: portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* * Manual context switch called by the portYIELD() macro. */ _vPortYield:: /* Mimic an interrupt by pushing the SR. */ push SR /* Now the SR is stacked we can disable interrupts. */ dint /* Save the context of the current task. */ portSAVE_CONTEXT /* Switch to the highest priority task that is ready to run. */ call #_vTaskSwitchContext /* Restore the context of the new task. */ portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* * Start off the scheduler by initialising the RTOS tick timer, then restoring * the context of the first task. */ _xPortStartScheduler:: /* Setup the hardware to generate the tick. Interrupts are disabled when this function is called. */ call #_prvSetupTimerInterrupt /* Restore the context of the first task that is going to run. */ portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* Place the tick ISR in the correct vector. */ .VECTORS .KEEP ORG TIMERA0_VECTOR DW _vTickISR END
; ; MSX specific routines ; by Stefano Bodrato, 12/12/2007 ; ; void msx_screen(int mode); ; ; Change the MSX screen mode; mode in HL (FASTCALL) ; ; $Id: msx_screen.asm,v 1.4 2007/12/18 09:00:45 stefano Exp $ ; XLIB msx_screen LIB msxbios LIB msxextrom INCLUDE "#msxbios.def" msx_screen: ld a,(0FAF8h) ; use EXBRSA to check if running on MSX1 and a ld a,l ; screen mode (FASTCALL parameter passing mode) jr z,screen_msx1 ; yes ld ix,01B5h ; CHGMDP: change screen mode and initialize palette jp msxextrom ; screen_msx1: ld ix,CHGMOD jp msxbios
/* !@ MIT License Copyright (c) 2019 Skylicht Technology CO., LTD 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. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #include "stdafx.h" #include "CNullMutex.h" namespace SkylichtSystem { CNullMutex::CNullMutex() { } CNullMutex::~CNullMutex() { } void CNullMutex::lock() { // do nothing for nonthread system (Emscripten) } void CNullMutex::unlock() { // do nothing for nonthread system (Emscripten) } }
extended_object_lookup_GI: BGE T8, 0x192, @@extended_item nop @@normal_item: LUI T0, 0x8010 JR RA ADDIU T0, T0, 0x8FF8 @@extended_item: LA T0, EXTENDED_OBJECT_TABLE JR RA ADDIU T8, T8, -0x193 extended_object_lookup_load: ADDU V1, A0, T6 ; displaced BGE A2, 0x192, @@extended_item nop @@normal_item: LUI T9, 0x8010 JR RA ADDIU T9, T9, 0x8FF8 @@extended_item: LA T9, EXTENDED_OBJECT_TABLE JR RA ADDIU A2, A2, -0x193 extended_object_lookup_shop: LH T9, 0x00(S0) ; displaced LW A1, 0x04(S0) ; displaced ADDIU A0, S0, 0x08 ; displaced SUBU T0, R0, T9 ; displaced ; T0 is item ID, S3 is table start BGE T0, 0x192, @@extended_item nop @@normal_item: LUI S3, 0x8010 JR RA ADDIU S3, S3, 0x8FF8 @@extended_item: LA S3, EXTENDED_OBJECT_TABLE JR RA ADDIU T0, T0, -0x193 extended_object_lookup_shop_unpause: LW A0, 0x10(S0) ; displaced ; V1 is item ID, S3 is table start BGE V1, 0x192, @@extended_item nop @@normal_item: LUI S3, 0x8010 J @@return ADDIU S3, S3, 0x8FF8 @@extended_item: LA S3, EXTENDED_OBJECT_TABLE ADDIU V1, V1, -0x193 @@return: SLL T7, V1, 0x3 ADDU V0, S3, T7 JR RA LW A1, 0x0(V0)
; A003751: Number of spanning trees in K_5 x P_n. ; 125,300125,663552000,1464514260125,3232184906328125,7133430745792512000,15743478429512478120125,34745849760772636969860125,76684074678559433693601792000,169241718069731503830237768828125,373516395095822778319979141039280125,824350514734762803332621362645696512000,1819341212503226411193949869046491708240125,4015285231644105954745139459991345230255580125,8861732686897329338896247617904661941867520000000,19557840024697174206838070137792417994319413174820125 seq $0,290903 ; p-INVERT of the positive integers, where p(S) = 1 - 5*S. pow $0,4 div $0,625 mul $0,125
#include "id_ordered_paths.hpp" namespace odgi { namespace algorithms { std::vector<path_handle_t> id_ordered_paths(const PathHandleGraph& g, bool avg, bool rev) { return prefix_and_id_ordered_paths(g, "", avg, rev); } std::vector<path_handle_t> prefix_and_id_ordered_paths(const PathHandleGraph& g, const std::string& prefix_delimiter, bool avg, bool rev) { // find the prefix order based on existing set std::unordered_set<std::string> seen_prefixes; std::unordered_map<std::string, uint64_t> initial_path_prefix_rank; auto get_path_prefix = [&](const path_handle_t& p) -> std::string { if (prefix_delimiter.empty()) { return ""; } else { std::string path_name = g.get_path_name(p); return path_name.substr(0, path_name.find(prefix_delimiter)); } }; g.for_each_path_handle([&](const path_handle_t& p) { std::string path_prefix = get_path_prefix(p); if (!seen_prefixes.count(path_prefix)) { initial_path_prefix_rank[path_prefix] = seen_prefixes.size(); seen_prefixes.insert(path_prefix); } }); std::vector<std::string> path_prefix_order(seen_prefixes.size()); for (auto& p : initial_path_prefix_rank) { path_prefix_order[p.second] = p.first; } // accumulate the paths by their minimum id per prefix std::unordered_map<std::string, std::vector<std::pair<double, path_handle_t> > > paths; g.for_each_path_handle([&](const path_handle_t& p) { // get the min id if (avg) { double sum_id = 0; uint64_t step_count = 0; g.for_each_step_in_path(p, [&](const step_handle_t& occ) { sum_id += (double)g.get_id(g.get_handle_of_step(occ)); ++step_count; }); std::string path_prefix = get_path_prefix(p); paths[path_prefix].push_back(make_pair(sum_id/(double)step_count, p)); } else { double min_id = std::numeric_limits<double>::max(); g.for_each_step_in_path(p, [&](const step_handle_t& occ) { min_id = std::min((double)g.get_id(g.get_handle_of_step(occ)), min_id); }); std::string path_prefix = get_path_prefix(p); paths[path_prefix].push_back(make_pair(min_id, p)); } }); for (auto& b : paths) { auto& paths_by = b.second; std::sort(paths_by.begin(), paths_by.end(), [&](const std::pair<double, path_handle_t>& a, const std::pair<double, path_handle_t>& b) { return a.first < b.first || a.first == b.first && as_integer(a.second) < as_integer(b.second); }); if (rev) { std::reverse(paths_by.begin(), paths_by.end()); } } std::vector<path_handle_t> order; order.reserve(g.get_path_count()); for (auto& path_prefix : path_prefix_order) { for (auto& p : paths[path_prefix]) { order.push_back(p.second); } } return order; } } }
; ; Copyright (c) 2010 The WebM 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 "vpx_ports/x86_abi_support.asm" ; tabulate_ssim - sums sum_s,sum_r,sum_sq_s,sum_sq_r, sum_sxr %macro TABULATE_SSIM 0 paddusw xmm15, xmm3 ; sum_s paddusw xmm14, xmm4 ; sum_r movdqa xmm1, xmm3 pmaddwd xmm1, xmm1 paddd xmm13, xmm1 ; sum_sq_s movdqa xmm2, xmm4 pmaddwd xmm2, xmm2 paddd xmm12, xmm2 ; sum_sq_r pmaddwd xmm3, xmm4 paddd xmm11, xmm3 ; sum_sxr %endmacro ; Sum across the register %1 starting with q words %macro SUM_ACROSS_Q 1 movdqa xmm2,%1 punpckldq %1,xmm0 punpckhdq xmm2,xmm0 paddq %1,xmm2 movdqa xmm2,%1 punpcklqdq %1,xmm0 punpckhqdq xmm2,xmm0 paddq %1,xmm2 %endmacro ; Sum across the register %1 starting with q words %macro SUM_ACROSS_W 1 movdqa xmm1, %1 punpcklwd %1,xmm0 punpckhwd xmm1,xmm0 paddd %1, xmm1 SUM_ACROSS_Q %1 %endmacro ;void ssim_parms_sse2( ; unsigned char *s, ; int sp, ; unsigned char *r, ; int rp ; unsigned long *sum_s, ; unsigned long *sum_r, ; unsigned long *sum_sq_s, ; unsigned long *sum_sq_r, ; unsigned long *sum_sxr); ; ; TODO: Use parm passing through structure, probably don't need the pxors ; ( calling app will initialize to 0 ) could easily fit everything in sse2 ; without too much hastle, and can probably do better estimates with psadw ; or pavgb At this point this is just meant to be first pass for calculating ; all the parms needed for 16x16 ssim so we can play with dssim as distortion ; in mode selection code. global sym(vp8_ssim_parms_16x16_sse2) PRIVATE sym(vp8_ssim_parms_16x16_sse2): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 9 SAVE_XMM 15 push rsi push rdi ; end prolog mov rsi, arg(0) ;s mov rcx, arg(1) ;sp mov rdi, arg(2) ;r mov rax, arg(3) ;rp pxor xmm0, xmm0 pxor xmm15,xmm15 ;sum_s pxor xmm14,xmm14 ;sum_r pxor xmm13,xmm13 ;sum_sq_s pxor xmm12,xmm12 ;sum_sq_r pxor xmm11,xmm11 ;sum_sxr mov rdx, 16 ;row counter .NextRow: ;grab source and reference pixels movdqu xmm5, [rsi] movdqu xmm6, [rdi] movdqa xmm3, xmm5 movdqa xmm4, xmm6 punpckhbw xmm3, xmm0 ; high_s punpckhbw xmm4, xmm0 ; high_r TABULATE_SSIM movdqa xmm3, xmm5 movdqa xmm4, xmm6 punpcklbw xmm3, xmm0 ; low_s punpcklbw xmm4, xmm0 ; low_r TABULATE_SSIM add rsi, rcx ; next s row add rdi, rax ; next r row dec rdx ; counter jnz .NextRow SUM_ACROSS_W xmm15 SUM_ACROSS_W xmm14 SUM_ACROSS_Q xmm13 SUM_ACROSS_Q xmm12 SUM_ACROSS_Q xmm11 mov rdi,arg(4) movd [rdi], xmm15; mov rdi,arg(5) movd [rdi], xmm14; mov rdi,arg(6) movd [rdi], xmm13; mov rdi,arg(7) movd [rdi], xmm12; mov rdi,arg(8) movd [rdi], xmm11; ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret ;void ssim_parms_sse2( ; unsigned char *s, ; int sp, ; unsigned char *r, ; int rp ; unsigned long *sum_s, ; unsigned long *sum_r, ; unsigned long *sum_sq_s, ; unsigned long *sum_sq_r, ; unsigned long *sum_sxr); ; ; TODO: Use parm passing through structure, probably don't need the pxors ; ( calling app will initialize to 0 ) could easily fit everything in sse2 ; without too much hastle, and can probably do better estimates with psadw ; or pavgb At this point this is just meant to be first pass for calculating ; all the parms needed for 16x16 ssim so we can play with dssim as distortion ; in mode selection code. global sym(vp8_ssim_parms_8x8_sse2) PRIVATE sym(vp8_ssim_parms_8x8_sse2): push rbp mov rbp, rsp SHADOW_ARGS_TO_STACK 9 SAVE_XMM 15 push rsi push rdi ; end prolog mov rsi, arg(0) ;s mov rcx, arg(1) ;sp mov rdi, arg(2) ;r mov rax, arg(3) ;rp pxor xmm0, xmm0 pxor xmm15,xmm15 ;sum_s pxor xmm14,xmm14 ;sum_r pxor xmm13,xmm13 ;sum_sq_s pxor xmm12,xmm12 ;sum_sq_r pxor xmm11,xmm11 ;sum_sxr mov rdx, 8 ;row counter .NextRow: ;grab source and reference pixels movq xmm3, [rsi] movq xmm4, [rdi] punpcklbw xmm3, xmm0 ; low_s punpcklbw xmm4, xmm0 ; low_r TABULATE_SSIM add rsi, rcx ; next s row add rdi, rax ; next r row dec rdx ; counter jnz .NextRow SUM_ACROSS_W xmm15 SUM_ACROSS_W xmm14 SUM_ACROSS_Q xmm13 SUM_ACROSS_Q xmm12 SUM_ACROSS_Q xmm11 mov rdi,arg(4) movd [rdi], xmm15; mov rdi,arg(5) movd [rdi], xmm14; mov rdi,arg(6) movd [rdi], xmm13; mov rdi,arg(7) movd [rdi], xmm12; mov rdi,arg(8) movd [rdi], xmm11; ; begin epilog pop rdi pop rsi RESTORE_XMM UNSHADOW_ARGS pop rbp ret