text
stringlengths
1
1.05M
%ifdef CONFIG { "RegData": { "RAX": "0x1600", "RDI": "0xE000000C", "RSI": "0xE0000004" }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x61626364 mov [rdx + 8 * 0], rax mov rax, 0x55565758 mov [rdx + 8 * 1], rax lea rdi, [rdx + 8 * 1] lea rsi, [rdx + 8 * 0] cld cmpsd ; rdi cmp rsi ; cmp = 0x55565758 - 0x61626364 = 0xF3F3F3F4 ; 0: CF - 00000001 ; 1: - 00000010 ; 2: PF - 00000000 ; 3: 0 - 00000000 ; 4: AF - 00000000 ; 5: 0 - 00000000 ; 6: ZF - 00000000 ; 7: SF - 10000000 ; ================ ; 10000011 ; OF: LAHF doesn't load - 0 mov rax, 0 lahf hlt
; A097195: Expansion of s(12)^3*s(18)^2/(s(6)^2*s(36)), where s(k) := subs(q=q^k, eta(q)) and eta(q) is Dedekind's function, cf. A010815. Then replace q^6 with q. ; Submitted by Jon Maiga ; 1,2,2,2,1,2,2,2,3,0,2,2,2,2,0,4,2,2,2,0,1,2,4,2,0,2,2,2,3,2,2,0,2,2,0,2,4,2,2,0,2,4,0,4,0,2,2,2,1,0,4,2,2,0,2,2,2,4,2,0,3,2,2,2,0,0,2,4,2,0,2,4,2,2,0,0,2,2,4,2,4,2,0,2,0,4,0,2,1,0,2,2,4,4,0,2,2,0,4,0 mul $0,6 seq $0,123331 ; Expansion of (c(q)^2/(3c(q^2))-1)/2 in powers of q where c(q) is a cubic AGM function.
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: et sw=2 ts=2 fdm=marker */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsEUCTWProber.h" void nsEUCTWProber::Reset(void) { mCodingSM->Reset(); mState = eDetecting; mDistributionAnalyser.Reset(mIsPreferredLanguage); //mContextAnalyser.Reset(); } nsProbingState nsEUCTWProber::HandleData(const char* aBuf, PRUint32 aLen) { nsSMState codingState; for (PRUint32 i = 0; i < aLen; i++) { codingState = mCodingSM->NextState(aBuf[i]); if (codingState == eItsMe) { mState = eFoundIt; break; } if (codingState == eStart) { PRUint32 charLen = mCodingSM->GetCurrentCharLen(); if (i == 0) { mLastChar[1] = aBuf[0]; mDistributionAnalyser.HandleOneChar(mLastChar, charLen); } else mDistributionAnalyser.HandleOneChar(aBuf+i-1, charLen); } } mLastChar[0] = aBuf[aLen-1]; if (mState == eDetecting) if (mDistributionAnalyser.GotEnoughData() && GetConfidence() > SHORTCUT_THRESHOLD) mState = eFoundIt; // else // mDistributionAnalyser.HandleData(aBuf, aLen); return mState; } float nsEUCTWProber::GetConfidence(void) { float distribCf = mDistributionAnalyser.GetConfidence(); return (float)distribCf; }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // 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 "platform/platform.h" #include "T3D/gameBase/gameConnection.h" #include "platform/profiler.h" #include "core/dnet.h" #include "core/util/safeDelete.h" #include "core/stream/bitStream.h" #include "console/consoleTypes.h" #include "console/simBase.h" #include "sfx/sfxProfile.h" #include "sfx/sfxDescription.h" #include "app/game.h" #include "app/auth.h" #include "T3D/camera.h" #include "T3D/gameBase/gameProcess.h" #include "T3D/gameBase/gameConnectionEvents.h" #include "console/engineAPI.h" #include "math/mTransform.h" #ifdef TORQUE_EXPERIMENTAL_EC #include "T3D/entity.h" #include "T3D/components/coreInterfaces.h" #endif #ifdef TORQUE_HIFI_NET #include "T3D/gameBase/hifi/hifiMoveList.h" #elif defined TORQUE_EXTENDED_MOVE #include "T3D/gameBase/extended/extendedMoveList.h" #else #include "T3D/gameBase/std/stdMoveList.h" #endif //---------------------------------------------------------------------------- #define MAX_MOVE_PACKET_SENDS 4 #define ControlRequestTime 5000 const U32 GameConnection::CurrentProtocolVersion = 12; const U32 GameConnection::MinRequiredProtocolVersion = 12; //---------------------------------------------------------------------------- IMPLEMENT_CONOBJECT(GameConnection); S32 GameConnection::mLagThresholdMS = 0; Signal<void(F32)> GameConnection::smFovUpdate; Signal<void()> GameConnection::smPlayingDemo; ConsoleDocClass( GameConnection, "@brief The game-specific subclass of NetConnection.\n\n" "The GameConnection introduces the concept of the control object. The control object " "is simply the object that the client is associated with that network connection controls. By " "default the control object is an instance of the Player class, but can also be an instance " "of Camera (when editing the mission, for example), or any other ShapeBase derived class as " "appropriate for the game.\n\n" "Torque uses a model in which the server is the authoritative master of the simulation. To " "prevent clients from cheating, the server simulates all player moves and then tells the " "client where his player is in the world. This model, while secure, can have problems. If " "the network latency is high, this round-trip time can give the player a very noticeable sense " "of movement lag. To correct this problem, the game uses a form of prediction - it simulates " "the movement of the control object on the client and on the server both. This way the client " "doesn't need to wait for round-trip verification of his moves. Only in the case of a force " "acting on the control object on the server that doesn't exist on the client does the client's " "position need to be forcefully changed.\n\n" "To support this, all control objects (derivative of ShapeBase) must supply a writePacketData() " "and readPacketData() function that send enough data to accurately simulate the object on the " "client. These functions are only called for the current control object, and only when the " "server can determine that the client's simulation is somehow out of sync with the server. This " "occurs usually if the client is affected by a force not present on the server (like an " "interpolating object) or if the server object is affected by a server only force (such as the " "impulse from an explosion).\n\n" "The Move structure is a 32 millisecond snapshot of player input, containing x, y, and z " "positional and rotational changes as well as trigger state changes. When time passes in the " "simulation moves are collected (depending on how much time passes), and applied to the current " "control object on the client. The same moves are then packed over to the server in " "GameConnection::writePacket(), for processing on the server's version of the control object.\n\n" "@see @ref Networking, NetConnection, ShapeBase\n\n" "@ingroup Networking\n"); //---------------------------------------------------------------------------- IMPLEMENT_CALLBACK( GameConnection, onConnectionTimedOut, void, (), (), "@brief Called on the client when the connection to the server times out.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onConnectionAccepted, void, (), (), "@brief Called on the client when the connection to the server has been established.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onConnectRequestTimedOut, void, (), (), "@brief Called when connection attempts have timed out.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onConnectionDropped, void, (const char* reason), (reason), "@brief Called on the client when the connection to the server has been dropped.\n\n" "@param reason The reason why the connection was dropped.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onConnectRequestRejected, void, (const char* reason), (reason), "@brief Called on the client when the connection to the server has been rejected.\n\n" "@param reason The reason why the connection request was rejected.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onConnectionError, void, (const char* errorString), (errorString), "@brief Called on the client when there is an error with the connection to the server.\n\n" "@param errorString The connection error text.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onDrop, void, (const char* disconnectReason), (disconnectReason), "@brief Called on the server when the client's connection has been dropped.\n\n" "@param disconnectReason The reason why the connection was dropped.\n\n"); IMPLEMENT_CALLBACK( GameConnection, initialControlSet, void, (), (), "@brief Called on the client when the first control object has been set by the " "server and we are now ready to go.\n\n" "A common action to perform when this callback is called is to switch the GUI " "canvas from the loading screen and over to the 3D game GUI."); IMPLEMENT_CALLBACK( GameConnection, onControlObjectChange, void, (), (), "@brief Called on the client when the control object has been changed by the " "server.\n\n"); IMPLEMENT_CALLBACK( GameConnection, setLagIcon, void, (bool state), (state), "@brief Called on the client to display the lag icon.\n\n" "When the connection with the server is lagging, this callback is called to " "allow the game GUI to display some indicator to the player.\n\n" "@param state Set to true if the lag icon should be displayed.\n\n"); IMPLEMENT_CALLBACK( GameConnection, onDataBlocksDone, void, (U32 sequence), (sequence), "@brief Called on the server when all datablocks has been sent to the client.\n\n" "During phase 1 of the mission download, all datablocks are sent from the server " "to the client. Once all datablocks have been sent, this callback is called and " "the mission download procedure may move on to the next phase.\n\n" "@param sequence The sequence is common between the server and client and ensures " "that the client is acting on the most recent mission start process. If an errant " "network packet (one that was lost but has now been found) is received by the client " "with an incorrect sequence, it is just ignored. This sequence number is updated on " "the server every time a mission is loaded.\n\n" "@see GameConnection::transmitDataBlocks()\n\n"); IMPLEMENT_GLOBAL_CALLBACK( onDataBlockObjectReceived, void, (U32 index, U32 total), (index, total), "@brief Called on the client each time a datablock has been received.\n\n" "This callback is typically used to notify the player of how far along " "in the datablock download process they are.\n\n" "@param index The index of the datablock just received.\n" "@param total The total number of datablocks to be received.\n\n" "@see GameConnection, GameConnection::transmitDataBlocks(), GameConnection::onDataBlocksDone()\n\n" "@ingroup Networking\n"); IMPLEMENT_CALLBACK( GameConnection, onFlash, void, (bool state), (state), "@brief Called on the client when the damage flash or white out states change.\n\n" "When the server changes the damage flash or white out values, this callback is called " "either is on or both are off. Typically this is used to enable the flash postFx.\n\n" "@param state Set to true if either the damage flash or white out conditions are active.\n\n"); //---------------------------------------------------------------------------- GameConnection::GameConnection() { mLagging = false; mControlObject = NULL; mCameraObject = NULL; #ifdef TORQUE_HIFI_NET mMoveList = new HifiMoveList(); #elif defined TORQUE_EXTENDED_MOVE mMoveList = new ExtendedMoveList(); #else mMoveList = new StdMoveList(); #endif mMoveList->setConnection( this ); mDataBlockModifiedKey = 0; mMaxDataBlockModifiedKey = 0; mAuthInfo = NULL; mControlForceMismatch = false; mConnectArgc = 0; for(U32 i = 0; i < MaxConnectArgs; i++) mConnectArgv[i] = 0; mJoinPassword = NULL; mMissionCRC = 0xffffffff; mDamageFlash = mWhiteOut = 0; mCameraPos = 0; mCameraSpeed = 10; mCameraFov = 90.f; mUpdateCameraFov = false; mAIControlled = false; mLastPacketTime = 0; mDisconnectReason[0] = 0; //blackout vars mBlackOut = 0.0f; mBlackOutTimeMS = 0; mBlackOutStartTimeMS = 0; mFadeToBlack = false; // first person mFirstPerson = true; mUpdateFirstPerson = false; // Control scheme mUpdateControlScheme = false; mAbsoluteRotation = false; mAddYawToAbsRot = false; mAddPitchToAbsRot = false; mVisibleGhostDistance = 0.0f; clearDisplayDevice(); } GameConnection::~GameConnection() { setDisplayDevice(NULL); delete mAuthInfo; for(U32 i = 0; i < mConnectArgc; i++) dFree(mConnectArgv[i]); dFree(mJoinPassword); delete mMoveList; } //---------------------------------------------------------------------------- void GameConnection::setVisibleGhostDistance(F32 dist) { mVisibleGhostDistance = dist; } F32 GameConnection::getVisibleGhostDistance() { return mVisibleGhostDistance; } bool GameConnection::canRemoteCreate() { return true; } void GameConnection::setConnectArgs(U32 argc, const char **argv) { if(argc > MaxConnectArgs) argc = MaxConnectArgs; mConnectArgc = argc; for(U32 i = 0; i < mConnectArgc; i++) mConnectArgv[i] = dStrdup(argv[i]); } void GameConnection::setJoinPassword(const char *password) { mJoinPassword = dStrdup(password); } DefineEngineMethod( GameConnection, setJoinPassword, void, (const char* password),, "@brief On the client, set the password that will be passed to the server.\n\n" "On the server, this password is compared with what is stored in $pref::Server::Password. " "If $pref::Server::Password is empty then the client's sent password is ignored. Otherwise, " "if the passed in client password and the server password do not match, the CHR_PASSWORD " "error string is sent back to the client and the connection is immediately terminated.\n\n" "This password checking is performed quite early on in the connection request process so as " "to minimize the impact of multiple failed attempts -- also known as hacking.") { object->setJoinPassword(password); } ConsoleMethod(GameConnection, setConnectArgs, void, 3, 17, "(const char* args) @brief On the client, pass along a variable set of parameters to the server.\n\n" "Once the connection is established with the server, the server calls its onConnect() method " "with the client's passed in parameters as aruments.\n\n" "@see GameConnection::onConnect()\n\n") { StringStackWrapper args(argc - 2, argv + 2); object->setConnectArgs(args.count(), args); } void GameConnection::onTimedOut() { if(isConnectionToServer()) { Con::printf("Connection to server timed out"); onConnectionTimedOut_callback(); } else { Con::printf("Client %d timed out.", getId()); setDisconnectReason("TimedOut"); } } void GameConnection::onConnectionEstablished(bool isInitiator) { if(isInitiator) { setGhostFrom(false); setGhostTo(true); setSendingEvents(true); setTranslatesStrings(true); setIsConnectionToServer(); mServerConnection = this; Con::printf("Connection established %d", getId()); onConnectionAccepted_callback(); } else { setGhostFrom(true); setGhostTo(false); setSendingEvents(true); setTranslatesStrings(true); Sim::getClientGroup()->addObject(this); mMoveList->init(); const char *argv[MaxConnectArgs + 2]; argv[0] = "onConnect"; argv[1] = NULL; // Filled in later for(U32 i = 0; i < mConnectArgc; i++) argv[i + 2] = mConnectArgv[i]; // NOTE: Need to fallback to Con::execute() as IMPLEMENT_CALLBACK does not // support variadic functions. Con::execute(this, mConnectArgc + 2, argv); } } void GameConnection::onConnectTimedOut() { onConnectRequestTimedOut_callback(); } void GameConnection::onDisconnect(const char *reason) { if(isConnectionToServer()) { Con::printf("Connection with server lost."); onConnectionDropped_callback(reason); mMoveList->init(); } else { Con::printf("Client %d disconnected.", getId()); setDisconnectReason(reason); } } void GameConnection::onConnectionRejected(const char *reason) { onConnectRequestRejected_callback(reason); } void GameConnection::handleStartupError(const char *errorString) { onConnectRequestRejected_callback(errorString); } void GameConnection::writeConnectAccept(BitStream *stream) { Parent::writeConnectAccept(stream); stream->write(getProtocolVersion()); } bool GameConnection::readConnectAccept(BitStream *stream, const char **errorString) { if(!Parent::readConnectAccept(stream, errorString)) return false; U32 protocolVersion; stream->read(&protocolVersion); if(protocolVersion < MinRequiredProtocolVersion || protocolVersion > CurrentProtocolVersion) { *errorString = "CHR_PROTOCOL"; // this should never happen unless someone is faking us out. return false; } return true; } void GameConnection::writeConnectRequest(BitStream *stream) { Parent::writeConnectRequest(stream); stream->writeString(TORQUE_APP_NAME); stream->write(CurrentProtocolVersion); stream->write(MinRequiredProtocolVersion); stream->writeString(mJoinPassword); stream->write(mConnectArgc); for(U32 i = 0; i < mConnectArgc; i++) stream->writeString(mConnectArgv[i]); } bool GameConnection::readConnectRequest(BitStream *stream, const char **errorString) { if(!Parent::readConnectRequest(stream, errorString)) return false; U32 currentProtocol, minProtocol; char gameString[256]; stream->readString(gameString); if(dStrcmp(gameString, TORQUE_APP_NAME)) { *errorString = "CHR_GAME"; return false; } stream->read(&currentProtocol); stream->read(&minProtocol); char joinPassword[256]; stream->readString(joinPassword); if(currentProtocol < MinRequiredProtocolVersion) { *errorString = "CHR_PROTOCOL_LESS"; return false; } if(minProtocol > CurrentProtocolVersion) { *errorString = "CHR_PROTOCOL_GREATER"; return false; } setProtocolVersion(currentProtocol < CurrentProtocolVersion ? currentProtocol : CurrentProtocolVersion); const char *serverPassword = Con::getVariable("pref::Server::Password"); if(serverPassword[0]) { if(dStrcmp(joinPassword, serverPassword)) { *errorString = "CHR_PASSWORD"; return false; } } stream->read(&mConnectArgc); if(mConnectArgc > MaxConnectArgs) { *errorString = "CR_INVALID_ARGS"; return false; } ConsoleValueRef connectArgv[MaxConnectArgs + 3]; ConsoleValue connectArgvValue[MaxConnectArgs + 3]; for(U32 i = 0; i < mConnectArgc+3; i++) { connectArgv[i].value = &connectArgvValue[i]; connectArgvValue[i].init(); } for(U32 i = 0; i < mConnectArgc; i++) { char argString[256]; stream->readString(argString); mConnectArgv[i] = dStrdup(argString); connectArgv[i + 3] = mConnectArgv[i]; } connectArgvValue[0].setStackStringValue("onConnectRequest"); connectArgvValue[1].setIntValue(0); char buffer[256]; Net::addressToString(getNetAddress(), buffer); connectArgvValue[2].setStackStringValue(buffer); // NOTE: Cannot convert over to IMPLEMENT_CALLBACK as it has variable args. const char *ret = Con::execute(this, mConnectArgc + 3, connectArgv); if(ret[0]) { *errorString = ret; return false; } return true; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- void GameConnection::connectionError(const char *errorString) { if(isConnectionToServer()) { Con::printf("Connection error: %s.", errorString); onConnectionError_callback(errorString); } else { Con::printf("Client %d packet error: %s.", getId(), errorString); setDisconnectReason("Packet Error."); } deleteObject(); } void GameConnection::setAuthInfo(const AuthInfo *info) { mAuthInfo = new AuthInfo; *mAuthInfo = *info; } const AuthInfo *GameConnection::getAuthInfo() { return mAuthInfo; } //---------------------------------------------------------------------------- void GameConnection::setControlObject(GameBase *obj) { if(mControlObject == obj) return; if(mControlObject && mControlObject != mCameraObject) mControlObject->setControllingClient(0); if(obj) { // Nothing else is permitted to control this object. if (GameBase* coo = obj->getControllingObject()) coo->setControlObject(0); if (GameConnection *con = obj->getControllingClient()) { if(this != con) { // was it controlled via camera or control if(con->getControlObject() == obj) con->setControlObject(0); else con->setCameraObject(0); } } // We are now the controlling client of this object. obj->setControllingClient(this); // Update the camera's FOV to match the new control object //but only if we don't have a specific camera object if (!mCameraObject) setControlCameraFov(obj->getCameraFov()); } // Okay, set our control object. mControlObject = obj; mControlForceMismatch = true; if(mCameraObject.isNull()) setScopeObject(mControlObject); } void GameConnection::setCameraObject(GameBase *obj) { if(mCameraObject == obj) return; if(mCameraObject && mCameraObject != mControlObject) mCameraObject->setControllingClient(0); if(obj) { // nothing else is permitted to control this object if(GameBase *coo = obj->getControllingObject()) coo->setControlObject(0); if(GameConnection *con = obj->getControllingClient()) { if(this != con) { // was it controlled via camera or control if(con->getControlObject() == obj) con->setControlObject(0); else con->setCameraObject(0); } } // we are now the controlling client of this object obj->setControllingClient(this); } // Okay, set our camera object. mCameraObject = obj; if(mCameraObject.isNull()) setScopeObject(mControlObject); else { setScopeObject(mCameraObject); // if this is a client then set the fov and active image if(isConnectionToServer()) { F32 fov = mCameraObject->getDefaultCameraFov(); //GameSetCameraFov(fov); smFovUpdate.trigger(fov); } } } GameBase* GameConnection::getCameraObject() { // If there is no camera object, or if we're first person, return // the control object. if( !mControlObject.isNull() && (mCameraObject.isNull() || mFirstPerson)) return mControlObject; return mCameraObject; } static S32 sChaseQueueSize = 0; static MatrixF* sChaseQueue = 0; static S32 sChaseQueueHead = 0; static S32 sChaseQueueTail = 0; bool GameConnection::getControlCameraTransform(F32 dt, MatrixF* mat) { GameBase* obj = getCameraObject(); if(!obj) return false; GameBase* cObj = obj; while((cObj = cObj->getControlObject()) != 0) { if(cObj->useObjsEyePoint()) obj = cObj; } if (dt) { if (mFirstPerson || obj->onlyFirstPerson()) { if (mCameraPos > 0) if ((mCameraPos -= mCameraSpeed * dt) <= 0) mCameraPos = 0; } else { if (mCameraPos < 1) if ((mCameraPos += mCameraSpeed * dt) > 1) mCameraPos = 1; } } if (!sChaseQueueSize || mFirstPerson || obj->onlyFirstPerson()) obj->getCameraTransform(&mCameraPos,mat); else { MatrixF& hm = sChaseQueue[sChaseQueueHead]; MatrixF& tm = sChaseQueue[sChaseQueueTail]; obj->getCameraTransform(&mCameraPos,&hm); *mat = tm; if (dt) { if ((sChaseQueueHead += 1) >= sChaseQueueSize) sChaseQueueHead = 0; if (sChaseQueueHead == sChaseQueueTail) if ((sChaseQueueTail += 1) >= sChaseQueueSize) sChaseQueueTail = 0; } } return true; } bool GameConnection::getControlCameraHeadTransform(IDisplayDevice *display, MatrixF *transform) { GameBase* obj = getCameraObject(); if (!obj) return false; GameBase* cObj = obj; while ((cObj = cObj->getControlObject()) != 0) { if (cObj->useObjsEyePoint()) obj = cObj; } obj->getEyeCameraTransform(display, -1, transform); return true; } bool GameConnection::getControlCameraEyeTransforms(IDisplayDevice *display, MatrixF *transforms) { GameBase* obj = getCameraObject(); if(!obj) return false; GameBase* cObj = obj; while((cObj = cObj->getControlObject()) != 0) { if(cObj->useObjsEyePoint()) obj = cObj; } // Perform operation on left & right eyes. For each we need to calculate the world space // of the rotated eye offset and add that onto the camera world space. for (U32 i=0; i<2; i++) { obj->getEyeCameraTransform(display, i, &transforms[i]); } return true; } bool GameConnection::getControlCameraDefaultFov(F32 * fov) { //find the last control object in the chain (client->player->turret->whatever...) GameBase *obj = getCameraObject(); GameBase *cObj = NULL; while (obj) { cObj = obj; obj = obj->getControlObject(); } if (cObj) { *fov = cObj->getDefaultCameraFov(); return(true); } return(false); } bool GameConnection::getControlCameraFov(F32 * fov) { //find the last control object in the chain (client->player->turret->whatever...) GameBase *obj = getCameraObject(); GameBase *cObj = NULL; while (obj) { cObj = obj; obj = obj->getControlObject(); } if (cObj) { #ifdef TORQUE_EXPERIMENTAL_EC if (Entity* ent = dynamic_cast<Entity*>(cObj)) { if (CameraInterface* camInterface = ent->getComponent<CameraInterface>()) { *fov = camInterface->getCameraFov(); } } else { *fov = cObj->getCameraFov(); } #else *fov = cObj->getCameraFov(); #endif return(true); } return(false); } bool GameConnection::isValidControlCameraFov(F32 fov) { //find the last control object in the chain (client->player->turret->whatever...) GameBase *obj = getCameraObject(); GameBase *cObj = NULL; while (obj) { cObj = obj; obj = obj->getControlObject(); } if (cObj) { #ifdef TORQUE_EXPERIMENTAL_EC if (Entity* ent = dynamic_cast<Entity*>(cObj)) { if (CameraInterface* camInterface = ent->getComponent<CameraInterface>()) { return camInterface->isValidCameraFov(fov); } } else { return cObj->isValidCameraFov(fov); } #else return cObj->isValidCameraFov(fov); #endif } return NULL; } bool GameConnection::setControlCameraFov(F32 fov) { //find the last control object in the chain (client->player->turret->whatever...) GameBase *obj = getCameraObject(); GameBase *cObj = NULL; while (obj) { cObj = obj; obj = obj->getControlObject(); } if (cObj) { #ifdef TORQUE_EXPERIMENTAL_EC F32 newFov = 90.f; if (Entity* ent = dynamic_cast<Entity*>(cObj)) { if (CameraInterface* camInterface = ent->getComponent<CameraInterface>()) { camInterface->setCameraFov(mClampF(fov, MinCameraFov, MaxCameraFov)); newFov = camInterface->getCameraFov(); } else { Con::errorf("Attempted to setControlCameraFov, but we don't have a camera!"); } } else { // allow shapebase to clamp fov to its datablock values cObj->setCameraFov(mClampF(fov, MinCameraFov, MaxCameraFov)); newFov = cObj->getCameraFov(); } #else // allow shapebase to clamp fov to its datablock values cObj->setCameraFov(mClampF(fov, MinCameraFov, MaxCameraFov)); F32 newFov = cObj->getCameraFov(); #endif // server fov of client has 1degree resolution if( S32(newFov) != S32(mCameraFov) || newFov != fov ) mUpdateCameraFov = true; mCameraFov = newFov; return(true); } return(false); } bool GameConnection::getControlCameraVelocity(Point3F *vel) { if (GameBase* obj = getCameraObject()) { *vel = obj->getVelocity(); return true; } return false; } bool GameConnection::isControlObjectRotDampedCamera() { if (Camera* cam = dynamic_cast<Camera*>(getCameraObject())) { if(cam->isRotationDamped()) return true; } return false; } void GameConnection::setFirstPerson(bool firstPerson) { mFirstPerson = firstPerson; mUpdateFirstPerson = true; } //---------------------------------------------------------------------------- void GameConnection::setControlSchemeParameters(bool absoluteRotation, bool addYawToAbsRot, bool addPitchToAbsRot) { mAbsoluteRotation = absoluteRotation; mAddYawToAbsRot = addYawToAbsRot; mAddPitchToAbsRot = addPitchToAbsRot; mUpdateControlScheme = true; } //---------------------------------------------------------------------------- bool GameConnection::onAdd() { if (!Parent::onAdd()) return false; return true; } void GameConnection::onRemove() { if(isNetworkConnection()) { sendDisconnectPacket(mDisconnectReason); } else if (isLocalConnection() && isConnectionToServer()) { // We're a client-side but local connection // delete the server side of the connection on our local server so that it updates // clientgroup and what not (this is so that we can disconnect from a local server // without needing to destroy and recreate the server before we can connect to it // again). // Safe-delete as we don't know whether the server connection is currently being // worked on. getRemoteConnection()->safeDeleteObject(); setRemoteConnectionObject(NULL); } if(!isConnectionToServer()) { onDrop_callback(mDisconnectReason); } if (mControlObject) mControlObject->setControllingClient(0); Parent::onRemove(); } void GameConnection::setDisconnectReason(const char *str) { dStrncpy(mDisconnectReason, str, sizeof(mDisconnectReason) - 1); mDisconnectReason[sizeof(mDisconnectReason) - 1] = 0; } //---------------------------------------------------------------------------- void GameConnection::handleRecordedBlock(U32 type, U32 size, void *data) { switch(type) { case BlockTypeMove: mMoveList->pushMove(*((Move *) data)); if(isRecording()) // put it back into the stream recordBlock(type, size, data); break; default: Parent::handleRecordedBlock(type, size, data); break; } } void GameConnection::writeDemoStartBlock(ResizeBitStream *stream) { // write all the data blocks to the stream: for(SimObjectId i = DataBlockObjectIdFirst; i <= DataBlockObjectIdLast; i++) { SimDataBlock *data; if(Sim::findObject(i, data)) { stream->writeFlag(true); SimDataBlockEvent evt(data); evt.pack(this, stream); stream->validate(); } } stream->writeFlag(false); stream->write(mFirstPerson); stream->write(mCameraPos); stream->write(mCameraSpeed); // Control scheme stream->write(mAbsoluteRotation); stream->write(mAddYawToAbsRot); stream->write(mAddPitchToAbsRot); stream->writeString(Con::getVariable("$Client::MissionFile")); mMoveList->writeDemoStartBlock(stream); // dump all the "demo" vars associated with this connection: SimFieldDictionaryIterator itr(getFieldDictionary()); SimFieldDictionary::Entry *entry; while((entry = *itr) != NULL) { if(!dStrnicmp(entry->slotName, "demo", 4)) { stream->writeFlag(true); stream->writeString(entry->slotName + 4); stream->writeString(entry->value); stream->validate(); } ++itr; } stream->writeFlag(false); Parent::writeDemoStartBlock(stream); stream->validate(); // dump out the control object ghost id S32 idx = mControlObject ? getGhostIndex(mControlObject) : -1; stream->write(idx); if(mControlObject) { #ifdef TORQUE_NET_STATS U32 beginPos = stream->getBitPosition(); #endif mControlObject->writePacketData(this, stream); #ifdef TORQUE_NET_STATS // TYPEOF( mControlObject )->getNetInfo().updateNetStatWriteData( stream->getBitPosition() - beginPos ); mControlObject->getClassRep()->updateNetStatWriteData( stream->getBitPosition() - beginPos); #endif } idx = mCameraObject ? getGhostIndex(mCameraObject) : -1; stream->write(idx); if(mCameraObject && mCameraObject != mControlObject) { #ifdef TORQUE_NET_STATS U32 beginPos = stream->getBitPosition(); #endif mCameraObject->writePacketData(this, stream); #ifdef TORQUE_NET_STATS mCameraObject->getClassRep()->updateNetStatWriteData( stream->getBitPosition() - beginPos); #endif } mLastControlRequestTime = Platform::getVirtualMilliseconds(); } bool GameConnection::readDemoStartBlock(BitStream *stream) { while(stream->readFlag()) { SimDataBlockEvent evt; evt.unpack(this, stream); evt.process(this); } while(mDataBlockLoadList.size()) { preloadNextDataBlock(false); if(mErrorBuffer.isNotEmpty()) return false; } stream->read(&mFirstPerson); stream->read(&mCameraPos); stream->read(&mCameraSpeed); // Control scheme stream->read(&mAbsoluteRotation); stream->read(&mAddYawToAbsRot); stream->read(&mAddPitchToAbsRot); char buf[256]; stream->readString(buf); Con::setVariable("$Client::MissionFile",buf); mMoveList->readDemoStartBlock(stream); // read in all the demo vars associated with this recording // they are all tagged on to the object and start with the // string "demo" while(stream->readFlag()) { StringTableEntry slotName = StringTable->insert("demo"); char array[256]; char value[256]; stream->readString(array); stream->readString(value); setDataField(slotName, array, value); } bool ret = Parent::readDemoStartBlock(stream); // grab the control object S32 idx; stream->read(&idx); GameBase * obj = 0; if(idx != -1) { obj = dynamic_cast<GameBase*>(resolveGhost(idx)); setControlObject(obj); obj->readPacketData(this, stream); } // Get the camera object, and read it in if it's different S32 idx2; stream->read(&idx2); obj = 0; if(idx2 != -1 && idx2 != idx) { obj = dynamic_cast<GameBase*>(resolveGhost(idx2)); setCameraObject(obj); obj->readPacketData(this, stream); } return ret; } void GameConnection::demoPlaybackComplete() { static const char* demoPlaybackArgv[1] = { "demoPlaybackComplete" }; static StringStackConsoleWrapper demoPlaybackCmd(1, demoPlaybackArgv); Sim::postCurrentEvent(Sim::getRootGroup(), new SimConsoleEvent(demoPlaybackCmd.argc, demoPlaybackCmd.argv, false)); Parent::demoPlaybackComplete(); } void GameConnection::ghostPreRead(NetObject * nobj, bool newGhost) { Parent::ghostPreRead( nobj, newGhost ); mMoveList->ghostPreRead(nobj,newGhost); } void GameConnection::ghostReadExtra(NetObject * nobj, BitStream * bstream, bool newGhost) { Parent::ghostReadExtra( nobj, bstream, newGhost ); mMoveList->ghostReadExtra(nobj, bstream, newGhost); } void GameConnection::ghostWriteExtra(NetObject * nobj, BitStream * bstream) { Parent::ghostWriteExtra( nobj, bstream); mMoveList->ghostWriteExtra(nobj, bstream); } //---------------------------------------------------------------------------- void GameConnection::readPacket(BitStream *bstream) { bstream->clearStringBuffer(); bstream->clearCompressionPoint(); if (isConnectionToServer()) { mMoveList->clientReadMovePacket(bstream); bool hadFlash = mDamageFlash > 0 || mWhiteOut > 0; mDamageFlash = 0; mWhiteOut = 0; if(bstream->readFlag()) { if(bstream->readFlag()) mDamageFlash = bstream->readFloat(7); if(bstream->readFlag()) mWhiteOut = bstream->readFloat(7) * 1.5; if(!hadFlash) { // Started a damage flash or white out onFlash_callback(true); } else { if(!(mDamageFlash > 0 || mWhiteOut > 0)) { // Received a zero damage flash and white out. onFlash_callback(false); } } } else if(hadFlash) { // Catch those cases where both the damage flash and white out are at zero // on the server but we did not receive an exact zero packet due to // precision over the network issues. No problem as the flag we just // read (which is false if we're here) has also told us about the change. onFlash_callback(false); } if ( bstream->readFlag() ) // gIndex != -1 { if ( bstream->readFlag() ) // mMoveList->isMismatch() || mControlForceMismatch { // the control object is dirty...so we get an update: bool callScript = false; bool controlObjChange = false; if(mControlObject.isNull()) callScript = true; S32 gIndex = bstream->readInt(NetConnection::GhostIdBitSize); GameBase* obj = dynamic_cast<GameBase*>(resolveGhost(gIndex)); if (mControlObject != obj) { setControlObject(obj); controlObjChange = true; } #ifdef TORQUE_NET_STATS U32 beginSize = bstream->getBitPosition(); #endif obj->readPacketData(this, bstream); #ifdef TORQUE_NET_STATS obj->getClassRep()->updateNetStatReadData(bstream->getBitPosition() - beginSize); #endif // let move list know that control object is dirty mMoveList->markControlDirty(); if(callScript) { initialControlSet_callback(); } if(controlObjChange) { onControlObjectChange_callback(); } } else { // read out the compression point Point3F pos; bstream->read(&pos.x); bstream->read(&pos.y); bstream->read(&pos.z); bstream->setCompressionPoint(pos); } } if (bstream->readFlag()) { bool callScript = false; if (mCameraObject.isNull()) callScript = true; S32 gIndex = bstream->readInt(NetConnection::GhostIdBitSize); GameBase* obj = dynamic_cast<GameBase*>(resolveGhost(gIndex)); setCameraObject(obj); obj->readPacketData(this, bstream); if (callScript) initialControlSet_callback(); } else setCameraObject(0); // server changed control scheme if(bstream->readFlag()) { bool absoluteRotation = bstream->readFlag(); bool addYawToAbsRot = bstream->readFlag(); bool addPitchToAbsRot = bstream->readFlag(); setControlSchemeParameters(absoluteRotation, addYawToAbsRot, addPitchToAbsRot); mUpdateControlScheme = false; } // server changed first person if(bstream->readFlag()) { setFirstPerson(bstream->readFlag()); mUpdateFirstPerson = false; } // server forcing a fov change? if(bstream->readFlag()) { S32 fov = bstream->readInt(8); setControlCameraFov((F32)fov); // don't bother telling the server if we were able to set the fov F32 setFov; if(getControlCameraFov(&setFov) && (S32(setFov) == fov)) mUpdateCameraFov = false; // update the games fov info smFovUpdate.trigger((F32)fov); } } else { mMoveList->serverReadMovePacket(bstream); mCameraPos = bstream->readFlag() ? 1.0f : 0.0f; if (bstream->readFlag()) mControlForceMismatch = true; // client changed control scheme if(bstream->readFlag()) { bool absoluteRotation = bstream->readFlag(); bool addYawToAbsRot = bstream->readFlag(); bool addPitchToAbsRot = bstream->readFlag(); setControlSchemeParameters(absoluteRotation, addYawToAbsRot, addPitchToAbsRot); mUpdateControlScheme = false; } // client changed first person if(bstream->readFlag()) { setFirstPerson(bstream->readFlag()); mUpdateFirstPerson = false; } // check fov change.. 1degree granularity on server if(bstream->readFlag()) { S32 fov = mClamp(bstream->readInt(8), S32(MinCameraFov), S32(MaxCameraFov)); setControlCameraFov((F32)fov); // may need to force client back to a valid fov F32 setFov; if(getControlCameraFov(&setFov) && (S32(setFov) == fov)) mUpdateCameraFov = false; } } Parent::readPacket(bstream); bstream->clearCompressionPoint(); bstream->clearStringBuffer(); if (isConnectionToServer()) { PROFILE_START(ClientCatchup); ClientProcessList::get()->clientCatchup(this); PROFILE_END(); } } void GameConnection::writePacket(BitStream *bstream, PacketNotify *note) { bstream->clearCompressionPoint(); bstream->clearStringBuffer(); GamePacketNotify *gnote = (GamePacketNotify *) note; U32 startPos = bstream->getBitPosition(); if (isConnectionToServer()) { mMoveList->clientWriteMovePacket(bstream); bstream->writeFlag(mCameraPos == 1); // if we're recording, we want to make sure that we get periodic updates of the // control object "just in case" - ie if the math copro is different between the // recording machine (SIMD vs FPU), we get periodic corrections bool forceUpdate = false; if(isRecording()) { U32 currentTime = Platform::getVirtualMilliseconds(); if(currentTime - mLastControlRequestTime > ControlRequestTime) { mLastControlRequestTime = currentTime; forceUpdate=true;; } } bstream->writeFlag(forceUpdate); // Control scheme changed? if(bstream->writeFlag(mUpdateControlScheme)) { bstream->writeFlag(mAbsoluteRotation); bstream->writeFlag(mAddYawToAbsRot); bstream->writeFlag(mAddPitchToAbsRot); mUpdateControlScheme = false; } // first person changed? if(bstream->writeFlag(mUpdateFirstPerson)) { bstream->writeFlag(mFirstPerson); mUpdateFirstPerson = false; } // camera fov changed? (server fov resolution is 1 degree) if(bstream->writeFlag(mUpdateCameraFov)) { bstream->writeInt(mClamp(S32(mCameraFov), S32(MinCameraFov), S32(MaxCameraFov)), 8); mUpdateCameraFov = false; } DEBUG_LOG(("PKLOG %d CLIENTMOVES: %d", getId(), bstream->getCurPos() - startPos)); } else { mMoveList->serverWriteMovePacket(bstream); // get the ghost index of the control object, and write out // all the damage flash & white out S32 gIndex = -1; if (!mControlObject.isNull()) { gIndex = getGhostIndex(mControlObject); F32 flash = mControlObject->getDamageFlash(); F32 whiteOut = mControlObject->getWhiteOut(); if(bstream->writeFlag(flash != 0 || whiteOut != 0)) { if(bstream->writeFlag(flash != 0)) bstream->writeFloat(flash, 7); if(bstream->writeFlag(whiteOut != 0)) bstream->writeFloat(whiteOut/1.5, 7); } } else bstream->writeFlag(false); if (bstream->writeFlag(gIndex != -1)) { // assume that the control object will write in a compression point if(bstream->writeFlag(mMoveList->isMismatch() || mControlForceMismatch)) { #ifdef TORQUE_DEBUG_NET if (mMoveList->isMismatch()) Con::printf("packetDataChecksum disagree!"); else Con::printf("packetDataChecksum disagree! (force)"); #endif bstream->writeInt(gIndex, NetConnection::GhostIdBitSize); #ifdef TORQUE_NET_STATS U32 beginSize = bstream->getBitPosition(); #endif mControlObject->writePacketData(this, bstream); #ifdef TORQUE_NET_STATS mControlObject->getClassRep()->updateNetStatWriteData(bstream->getBitPosition() - beginSize); #endif mControlForceMismatch = false; } else { // we'll have to use the control object's position as the compression point // should make this lower res for better space usage: Point3F coPos = mControlObject->getPosition(); bstream->write(coPos.x); bstream->write(coPos.y); bstream->write(coPos.z); bstream->setCompressionPoint(coPos); } } DEBUG_LOG(("PKLOG %d CONTROLOBJECTSTATE: %d", getId(), bstream->getCurPos() - startPos)); startPos = bstream->getBitPosition(); if (!mCameraObject.isNull() && mCameraObject != mControlObject) { gIndex = getGhostIndex(mCameraObject); if (bstream->writeFlag(gIndex != -1)) { bstream->writeInt(gIndex, NetConnection::GhostIdBitSize); mCameraObject->writePacketData(this, bstream); } } else bstream->writeFlag( false ); // Control scheme changed? if(bstream->writeFlag(mUpdateControlScheme)) { bstream->writeFlag(mAbsoluteRotation); bstream->writeFlag(mAddYawToAbsRot); bstream->writeFlag(mAddPitchToAbsRot); mUpdateControlScheme = false; } // first person changed? if(bstream->writeFlag(mUpdateFirstPerson)) { bstream->writeFlag(mFirstPerson); mUpdateFirstPerson = false; } // server forcing client fov? gnote->cameraFov = -1; if(bstream->writeFlag(mUpdateCameraFov)) { gnote->cameraFov = mClamp(S32(mCameraFov), S32(MinCameraFov), S32(MaxCameraFov)); bstream->writeInt(gnote->cameraFov, 8); mUpdateCameraFov = false; } DEBUG_LOG(("PKLOG %d PINGCAMSTATE: %d", getId(), bstream->getCurPos() - startPos)); } Parent::writePacket(bstream, note); bstream->clearCompressionPoint(); bstream->clearStringBuffer(); } void GameConnection::detectLag() { //see if we're lagging... S32 curTime = Sim::getCurrentTime(); if (curTime - mLastPacketTime > mLagThresholdMS) { if (!mLagging) { mLagging = true; setLagIcon_callback(true); } } else if (mLagging) { mLagging = false; setLagIcon_callback(false); } } GameConnection::GamePacketNotify::GamePacketNotify() { // need to fill in empty notifes for demo start block cameraFov = 0; } NetConnection::PacketNotify *GameConnection::allocNotify() { return new GamePacketNotify; } void GameConnection::packetReceived(PacketNotify *note) { //record the time so we can tell if we're lagging... mLastPacketTime = Sim::getCurrentTime(); // If we wanted to do something special, we grab our note like this: //GamePacketNotify *gnote = (GamePacketNotify *) note; Parent::packetReceived(note); } void GameConnection::packetDropped(PacketNotify *note) { Parent::packetDropped(note); GamePacketNotify *gnote = (GamePacketNotify *) note; if(gnote->cameraFov != -1) mUpdateCameraFov = true; } //---------------------------------------------------------------------------- void GameConnection::play2D(SFXProfile* profile) { postNetEvent(new Sim2DAudioEvent(profile)); } void GameConnection::play3D(SFXProfile* profile, const MatrixF *transform) { if ( !transform ) play2D(profile); else if ( !mControlObject ) postNetEvent(new Sim3DAudioEvent(profile,transform)); else { // TODO: Maybe improve this to account for the duration // of the sound effect and if the control object can get // into hearing range within time? // Only post the event if it's within audible range // of the control object. Point3F ear,pos; transform->getColumn(3,&pos); mControlObject->getTransform().getColumn(3,&ear); if ((ear - pos).len() < profile->getDescription()->mMaxDistance) postNetEvent(new Sim3DAudioEvent(profile,transform)); } } void GameConnection::doneScopingScene() { // Could add special post-scene scoping here, such as scoping // objects not visible to the camera, but visible to sensors. } void GameConnection::preloadDataBlock(SimDataBlock *db) { mDataBlockLoadList.push_back(db); if(mDataBlockLoadList.size() == 1) preloadNextDataBlock(false); } void GameConnection::fileDownloadSegmentComplete() { // this is called when a the file list has finished processing... // at this point we can try again to add the object // subclasses can override this to do, for example, datablock redos. if(mDataBlockLoadList.size()) preloadNextDataBlock(mNumDownloadedFiles != 0); Parent::fileDownloadSegmentComplete(); } void GameConnection::preloadNextDataBlock(bool hadNewFiles) { if(!mDataBlockLoadList.size()) return; while(mDataBlockLoadList.size()) { // only check for new files if this is the first load, or if new // files were downloaded from the server. // if(hadNewFiles) // gResourceManager->setMissingFileLogging(true); // gResourceManager->clearMissingFileList(); SimDataBlock *object = mDataBlockLoadList[0]; if(!object) { // a null object is used to signify that the last ghost in the list is down mDataBlockLoadList.pop_front(); AssertFatal(mDataBlockLoadList.size() == 0, "Error! Datablock save list should be empty!"); sendConnectionMessage(DataBlocksDownloadDone, mDataBlockSequence); // gResourceManager->setMissingFileLogging(false); return; } mFilesWereDownloaded = hadNewFiles; if(!object->preload(false, mErrorBuffer)) { mFilesWereDownloaded = false; // make sure there's an error message if necessary if(mErrorBuffer.isEmpty()) setLastError("Invalid packet. (object preload)"); // if there were new files, make sure the error message // is the one from the last time we tried to add this object if(hadNewFiles) { mErrorBuffer = mLastFileErrorBuffer; // gResourceManager->setMissingFileLogging(false); return; } // object failed to load, let's see if it had any missing files if(isLocalConnection() /*|| !gResourceManager->getMissingFileList(mMissingFileList)*/) { // no missing files, must be an error // connection will automagically delete the ghost always list // when this error is reported. // gResourceManager->setMissingFileLogging(false); return; } // ok, copy the error buffer out to a scratch pad for now mLastFileErrorBuffer = mErrorBuffer; //mErrorBuffer = String(); // request the missing files... mNumDownloadedFiles = 0; sendNextFileDownloadRequest(); break; } mFilesWereDownloaded = false; // gResourceManager->setMissingFileLogging(false); mDataBlockLoadList.pop_front(); hadNewFiles = true; } } void GameConnection::onEndGhosting() { Parent::onEndGhosting(); // Reset move list. All the moves are obsolete now and furthermore, // if we don't clear out the list now we might run in danger of // getting backlogged later on what is a list full of obsolete moves. mMoveList->reset(); } //---------------------------------------------------------------------------- //localconnection only blackout functions void GameConnection::setBlackOut(bool fadeToBlack, S32 timeMS) { mFadeToBlack = fadeToBlack; mBlackOutStartTimeMS = Sim::getCurrentTime(); mBlackOutTimeMS = timeMS; //if timeMS <= 0 set the value instantly if (mBlackOutTimeMS <= 0) mBlackOut = (mFadeToBlack ? 1.0f : 0.0f); } F32 GameConnection::getBlackOut() { S32 curTime = Sim::getCurrentTime(); //see if we're in the middle of a black out if (curTime < mBlackOutStartTimeMS + mBlackOutTimeMS) { S32 elapsedTime = curTime - mBlackOutStartTimeMS; F32 timePercent = F32(elapsedTime) / F32(mBlackOutTimeMS); mBlackOut = (mFadeToBlack ? timePercent : 1.0f - timePercent); } else mBlackOut = (mFadeToBlack ? 1.0f : 0.0f); //return the blackout time return mBlackOut; } void GameConnection::handleConnectionMessage(U32 message, U32 sequence, U32 ghostCount) { if(isConnectionToServer()) { if(message == DataBlocksDone) { mDataBlockLoadList.push_back(NULL); mDataBlockSequence = sequence; if(mDataBlockLoadList.size() == 1) preloadNextDataBlock(true); } } else { if(message == DataBlocksDownloadDone) { if(getDataBlockSequence() == sequence) { onDataBlocksDone_callback( getDataBlockSequence() ); } } } Parent::handleConnectionMessage(message, sequence, ghostCount); } //---------------------------------------------------------------------------- DefineEngineMethod( GameConnection, transmitDataBlocks, void, (S32 sequence),, "@brief Sent by the server during phase 1 of the mission download to send the datablocks to the client.\n\n" "SimDataBlocks, also known as just datablocks, need to be transmitted to the client " "prior to the client entering the game world. These represent the static data that " "most objects in the world reference. This is typically done during the standard " "mission start phase 1 when following Torque's example mission startup sequence.\n\n" "When the datablocks have all been transmitted, onDataBlocksDone() is called to move " "the mission start process to the next phase." "@param sequence The sequence is common between the server and client and ensures " "that the client is acting on the most recent mission start process. If an errant " "network packet (one that was lost but has now been found) is received by the client " "with an incorrect sequence, it is just ignored. This sequence number is updated on " "the server every time a mission is loaded.\n\n" "@tsexample\n" "function serverCmdMissionStartPhase1Ack(%client, %seq)\n" "{\n" " // Make sure to ignore calls from a previous mission load\n" " if (%seq != $missionSequence || !$MissionRunning)\n" " return;\n" " if (%client.currentPhase != 0)\n" " return;\n" " %client.currentPhase = 1;\n" "\n" " // Start with the CRC\n" " %client.setMissionCRC( $missionCRC );\n" "\n" " // Send over the datablocks...\n" " // OnDataBlocksDone will get called when have confirmation\n" " // that they've all been received.\n" " %client.transmitDataBlocks($missionSequence);\n" "}\n" "@endtsexample\n\n" "@see GameConnection::onDataBlocksDone()\n\n") { // Set the datablock sequence. object->setDataBlockSequence(sequence); // Store a pointer to the datablock group. SimDataBlockGroup* pGroup = Sim::getDataBlockGroup(); // Determine the size of the datablock group. const U32 iCount = pGroup->size(); // If this is the local client... if (GameConnection::getLocalClientConnection() == object) { // Set up a pointer to the datablock. SimDataBlock* pDataBlock = 0; // Set up a buffer for the datablock send. U8 iBuffer[16384]; BitStream mStream(iBuffer, 16384); // Iterate through all the datablocks... for (U32 i = 0; i < iCount; i++) { // Get a pointer to the datablock in question... pDataBlock = (SimDataBlock*)(*pGroup)[i]; // Set the client's new modified key. object->setMaxDataBlockModifiedKey(pDataBlock->getModifiedKey()); // Pack the datablock stream. mStream.setPosition(0); mStream.clearCompressionPoint(); pDataBlock->packData(&mStream); // Unpack the datablock stream. mStream.setPosition(0); mStream.clearCompressionPoint(); pDataBlock->unpackData(&mStream); // Call the console function to set the number of blocks to be sent. onDataBlockObjectReceived_callback(i, iCount); // Preload the datablock on the dummy client. pDataBlock->preload(false, NetConnection::getErrorBuffer()); } // Get the last datablock (if any)... if (pDataBlock) { // Ensure the datablock modified key is set. object->setDataBlockModifiedKey(object->getMaxDataBlockModifiedKey()); // Ensure that the client knows that the datablock send is done... object->sendConnectionMessage(GameConnection::DataBlocksDone, object->getDataBlockSequence()); } if (iCount == 0) { //if we have no datablocks to send, we still need to be able to complete the level load process //so fire off our callback anyways object->sendConnectionMessage(GameConnection::DataBlocksDone, object->getDataBlockSequence()); } } else { // Otherwise, store the current datablock modified key. const S32 iKey = object->getDataBlockModifiedKey(); // Iterate through the datablock group... U32 i = 0; for (; i < iCount; i++) { // If the datablock's modified key has already been set, break out of the loop... if (((SimDataBlock*)(*pGroup)[i])->getModifiedKey() > iKey) { break; } } // If this is the last datablock in the group... if (i == iCount) { // Ensure that the client knows that the datablock send is done... object->sendConnectionMessage(GameConnection::DataBlocksDone, object->getDataBlockSequence()); // Then exit out since nothing else needs to be done. return; } // Set the maximum datablock modified key value. object->setMaxDataBlockModifiedKey(iKey); // Get the minimum number of datablocks... const U32 iMax = getMin(i + DataBlockQueueCount, iCount); // Iterate through the remaining datablocks... for (;i < iMax; i++) { // Get a pointer to the datablock in question... SimDataBlock* pDataBlock = (SimDataBlock*)(*pGroup)[i]; // Post the datablock event to the client. object->postNetEvent(new SimDataBlockEvent(pDataBlock, i, iCount, object->getDataBlockSequence())); } } } DefineEngineMethod( GameConnection, activateGhosting, void, (),, "@brief Called by the server during phase 2 of the mission download to start sending ghosts to the client.\n\n" "Ghosts represent objects on the server that are in scope for the client. These need " "to be synchronized with the client in order for the client to see and interact with them. " "This is typically done during the standard mission start phase 2 when following Torque's " "example mission startup sequence.\n\n" "@tsexample\n" "function serverCmdMissionStartPhase2Ack(%client, %seq, %playerDB)\n" "{\n" " // Make sure to ignore calls from a previous mission load\n" " if (%seq != $missionSequence || !$MissionRunning)\n" " return;\n" " if (%client.currentPhase != 1.5)\n" " return;\n" " %client.currentPhase = 2;\n" "\n" " // Set the player datablock choice\n" " %client.playerDB = %playerDB;\n" "\n" " // Update mod paths, this needs to get there before the objects.\n" " %client.transmitPaths();\n" "\n" " // Start ghosting objects to the client\n" " %client.activateGhosting();\n" "}\n" "@endtsexample\n\n" "@see @ref ghosting_scoping for a description of the ghosting system.\n\n") { object->activateGhosting(); } DefineEngineMethod( GameConnection, resetGhosting, void, (),, "@brief On the server, resets the connection to indicate that ghosting has been disabled.\n\n" "Typically when a mission has ended on the server, all connected clients are informed of this change " "and their connections are reset back to a starting state. This method resets a connection on the " "server to indicate that ghosts are no longer being transmitted. On the client end, all ghost " "information will be deleted.\n\n" "@tsexample\n" " // Inform the clients\n" " for (%clientIndex = 0; %clientIndex < ClientGroup.getCount(); %clientIndex++)\n" " {\n" " // clear ghosts and paths from all clients\n" " %cl = ClientGroup.getObject(%clientIndex);\n" " %cl.endMission();\n" " %cl.resetGhosting();\n" " %cl.clearPaths();\n" " }\n" "@endtsexample\n\n" "@see @ref ghosting_scoping for a description of the ghosting system.\n\n") { object->resetGhosting(); } DefineEngineMethod( GameConnection, setControlObject, bool, (GameBase* ctrlObj),, "@brief On the server, sets the object that the client will control.\n\n" "By default the control object is an instance of the Player class, but can also be an instance " "of Camera (when editing the mission, for example), or any other ShapeBase derived class as " "appropriate for the game.\n\n" "@param ctrlObj The GameBase object on the server to control.") { if(!ctrlObj) return false; object->setControlObject(ctrlObj); return true; } DefineEngineMethod( GameConnection, clearDisplayDevice, void, (),, "@brief Clear any display device.\n\n" "A display device may define a number of properties that are used during rendering.\n\n") { object->clearDisplayDevice(); } DefineEngineMethod( GameConnection, getControlObject, GameBase*, (),, "@brief On the server, returns the object that the client is controlling." "By default the control object is an instance of the Player class, but can also be an instance " "of Camera (when editing the mission, for example), or any other ShapeBase derived class as " "appropriate for the game.\n\n" "@see GameConnection::setControlObject()\n\n") { return object->getControlObject(); } DefineEngineMethod( GameConnection, isAIControlled, bool, (),, "@brief Returns true if this connection is AI controlled.\n\n" "@see AIConnection") { return object->isAIControlled(); } DefineEngineMethod( GameConnection, isControlObjectRotDampedCamera, bool, (),, "@brief Returns true if the object being controlled by the client is making use " "of a rotation damped camera.\n\n" "@see Camera") { return object->isControlObjectRotDampedCamera(); } DefineEngineMethod( GameConnection, play2D, bool, (SFXProfile* profile),, "@brief Used on the server to play a 2D sound that is not attached to any object.\n\n" "@param profile The SFXProfile that defines the sound to play.\n\n" "@tsexample\n" "function ServerPlay2D(%profile)\n" "{\n" " // Play the given sound profile on every client.\n" " // The sounds will be transmitted as an event, not attached to any object.\n" " for(%idx = 0; %idx < ClientGroup.getCount(); %idx++)\n" " ClientGroup.getObject(%idx).play2D(%profile);\n" "}\n" "@endtsexample\n\n") { if(!profile) return false; object->play2D(profile); return true; } DefineEngineMethod( GameConnection, play3D, bool, (SFXProfile* profile, TransformF location),, "@brief Used on the server to play a 3D sound that is not attached to any object.\n\n" "@param profile The SFXProfile that defines the sound to play.\n" "@param location The position and orientation of the 3D sound given in the form of \"x y z ax ay az aa\".\n\n" "@tsexample\n" "function ServerPlay3D(%profile,%transform)\n" "{\n" " // Play the given sound profile at the given position on every client\n" " // The sound will be transmitted as an event, not attached to any object.\n" " for(%idx = 0; %idx < ClientGroup.getCount(); %idx++)\n" " ClientGroup.getObject(%idx).play3D(%profile,%transform);\n" "}\n" "@endtsexample\n\n") { if(!profile) return false; MatrixF mat = location.getMatrix(); object->play3D(profile,&mat); return true; } DefineEngineMethod( GameConnection, chaseCam, bool, (S32 size),, "@brief Sets the size of the chase camera's matrix queue.\n\n" "@note This sets the queue size across all GameConnections.\n\n" "@note This is not currently hooked up.\n\n") { if (size != sChaseQueueSize) { SAFE_DELETE_ARRAY(sChaseQueue); sChaseQueueSize = size; sChaseQueueHead = sChaseQueueTail = 0; if (size) { sChaseQueue = new MatrixF[size]; return true; } } return false; } DefineEngineMethod( GameConnection, getControlCameraDefaultFov, F32, (),, "@brief Returns the default field of view as used by the control object's camera.\n\n") { F32 fov = 0.0f; if(!object->getControlCameraDefaultFov(&fov)) return(0.0f); return(fov); } DefineEngineMethod( GameConnection, setControlCameraFov, void, (F32 newFOV),, "@brief On the server, sets the control object's camera's field of view.\n\n" "@param newFOV New field of view (in degrees) to force the control object's camera to use. This value " "is clamped to be within the range of 1 to 179 degrees.\n\n" "@note When transmitted over the network to the client, the resolution is limited to " "one degree. Any fraction is dropped.") { object->setControlCameraFov(newFOV); } DefineEngineMethod( GameConnection, getControlCameraFov, F32, (),, "@brief Returns the field of view as used by the control object's camera.\n\n") { F32 fov = 0.0f; if(!object->getControlCameraFov(&fov)) return(0.0f); return(fov); } DefineEngineMethod( GameConnection, getDamageFlash, F32, (),, "@brief On the client, get the control object's damage flash level.\n\n" "@return flash level\n") { return object->getDamageFlash(); } DefineEngineMethod( GameConnection, getWhiteOut, F32, (),, "@brief On the client, get the control object's white-out level.\n\n" "@return white-out level\n") { return object->getWhiteOut(); } DefineEngineMethod( GameConnection, setBlackOut, void, (bool doFade, S32 timeMS),, "@brief On the server, sets the client's 3D display to fade to black.\n\n" "@param doFade Set to true to fade to black, and false to fade from black.\n" "@param timeMS Time it takes to perform the fade as measured in ms.\n\n" "@note Not currently hooked up, and is not synchronized over the network.") { object->setBlackOut(doFade, timeMS); } DefineEngineMethod( GameConnection, setMissionCRC, void, (S32 CRC),, "@brief On the server, transmits the mission file's CRC value to the client.\n\n" "Typically, during the standard mission start phase 1, the mission file's CRC value " "on the server is send to the client. This allows the client to determine if the mission " "has changed since the last time it downloaded this mission and act appropriately, such as " "rebuilt cached lightmaps.\n\n" "@param CRC The mission file's CRC value on the server.\n\n" "@tsexample\n" "function serverCmdMissionStartPhase1Ack(%client, %seq)\n" "{\n" " // Make sure to ignore calls from a previous mission load\n" " if (%seq != $missionSequence || !$MissionRunning)\n" " return;\n" " if (%client.currentPhase != 0)\n" " return;\n" " %client.currentPhase = 1;\n" "\n" " // Start with the CRC\n" " %client.setMissionCRC( $missionCRC );\n" "\n" " // Send over the datablocks...\n" " // OnDataBlocksDone will get called when have confirmation\n" " // that they've all been received.\n" " %client.transmitDataBlocks($missionSequence);\n" "}\n" "@endtsexample\n\n") { if(object->isConnectionToServer()) return; object->postNetEvent(new SetMissionCRCEvent(CRC)); } DefineEngineMethod( GameConnection, delete, void, (const char* reason), (""), "@brief On the server, disconnect a client and pass along an optional reason why.\n\n" "This method performs two operations: it disconnects a client connection from the server, " "and it deletes the connection object. The optional reason is sent in the disconnect packet " "and is often displayed to the user so they know why they've been disconnected.\n\n" "@param reason [optional] The reason why the user has been disconnected from the server.\n\n" "@tsexample\n" "function kick(%client)\n" "{\n" " messageAll( 'MsgAdminForce', '\\c2The Admin has kicked %1.', %client.playerName);\n" "\n" " if (!%client.isAIControlled())\n" " BanList::add(%client.guid, %client.getAddress(), $Pref::Server::KickBanTime);\n" " %client.delete(\"You have been kicked from this server\");\n" "}\n" "@endtsexample\n\n") { object->setDisconnectReason(reason); object->deleteObject(); } //-------------------------------------------------------------------------- void GameConnection::consoleInit() { Con::addVariable("$pref::Net::LagThreshold", TypeS32, &mLagThresholdMS, "@brief How long between received packets before the client is considered as lagging (in ms).\n\n" "This is used by GameConnection to determine if the client is lagging. " "If the client is indeed lagging, setLagIcon() is called to inform the user in some way. i.e. " "display an icon on screen.\n\n" "@see GameConnection, GameConnection::setLagIcon()\n\n" "@ingroup Networking\n"); // Con::addVariable("specialFog", TypeBool, &SceneGraph::useSpecial); } DefineEngineMethod( GameConnection, startRecording, void, (const char* fileName),, "@brief On the client, starts recording the network connection's traffic to a demo file.\n\n" "It is often useful to play back a game session. This could be for producing a " "demo of the game that will be shown at a later time, or for debugging a game. " "By recording the entire network stream it is possible to later play game the game " "exactly as it unfolded during the actual play session. This is because all user " "control and server results pass through the connection.\n\n" "@param fileName The file name to use for the demo recording.\n\n" "@see GameConnection::stopRecording(), GameConnection::playDemo()") { char expFileName[1024]; Con::expandScriptFilename(expFileName, sizeof(expFileName), fileName); object->startDemoRecord(expFileName); } DefineEngineMethod( GameConnection, stopRecording, void, (),, "@brief On the client, stops the recording of a connection's network traffic to a file.\n\n" "@see GameConnection::startRecording(), GameConnection::playDemo()") { object->stopRecording(); } DefineEngineMethod( GameConnection, playDemo, bool, (const char* demoFileName),, "@brief On the client, play back a previously recorded game session.\n\n" "It is often useful to play back a game session. This could be for producing a " "demo of the game that will be shown at a later time, or for debugging a game. " "By recording the entire network stream it is possible to later play game the game " "exactly as it unfolded during the actual play session. This is because all user " "control and server results pass through the connection.\n\n" "@returns True if the playback was successful. False if there was an issue, such as " "not being able to open the demo file for playback.\n\n" "@see GameConnection::startRecording(), GameConnection::stopRecording()") { char filename[1024]; Con::expandScriptFilename(filename, sizeof(filename), demoFileName); // Note that calling onConnectionEstablished will change the values in argv! object->onConnectionEstablished(true); object->setEstablished(); if(!object->replayDemoRecord(filename)) { Con::printf("Unable to open demo file %s.", filename); object->deleteObject(); return false; } // After demo has loaded, execute the scene re-light the scene //SceneLighting::lightScene(0, 0); GameConnection::smPlayingDemo.trigger(); return true; } DefineEngineMethod( GameConnection, isDemoPlaying, bool, (),, "@brief Returns true if a previously recorded demo file is now playing.\n\n" "@see GameConnection::playDemo()") { return object->isPlayingBack(); } DefineEngineMethod( GameConnection, isDemoRecording, bool, (),, "@brief Returns true if a demo file is now being recorded.\n\n" "@see GameConnection::startRecording(), GameConnection::stopRecording()") { return object->isRecording(); } DefineEngineMethod( GameConnection, listClassIDs, void, (),, "@brief List all of the classes that this connection knows about, and what their IDs are. Useful for debugging network problems.\n\n" "@note The list is sent to the console.\n\n") { Con::printf("--------------- Class ID Listing ----------------"); Con::printf(" id | name"); for(AbstractClassRep *rep = AbstractClassRep::getClassList(); rep; rep = rep->getNextClass()) { ConsoleObject *obj = rep->create(); if(obj && rep->getClassId(object->getNetClassGroup()) >= 0) Con::printf("%7.7d| %s", rep->getClassId(object->getNetClassGroup()), rep->getClassName()); delete obj; } } DefineEngineStaticMethod( GameConnection, getServerConnection, S32, (),, "@brief On the client, this static mehtod will return the connection to the server, if any.\n\n" "@returns The SimObject ID of the server connection, or -1 if none is found.\n\n") { if(GameConnection::getConnectionToServer()) return GameConnection::getConnectionToServer()->getId(); else { Con::errorf("GameConnection::getServerConnection - no connection available."); return -1; } } DefineEngineMethod( GameConnection, setCameraObject, bool, (GameBase* camera),, "@brief On the server, set the connection's camera object used when not viewing " "through the control object.\n\n" "@see GameConnection::getCameraObject() and GameConnection::clearCameraObject()\n\n") { if(!camera) return false; object->setCameraObject(camera); return true; } DefineEngineMethod( GameConnection, getCameraObject, SimObject*, (),, "@brief Returns the connection's camera object used when not viewing through the control object.\n\n" "@see GameConnection::setCameraObject() and GameConnection::clearCameraObject()\n\n") { SimObject *obj = dynamic_cast<SimObject*>(object->getCameraObject()); return obj; } DefineEngineMethod( GameConnection, clearCameraObject, void, (),, "@brief Clear the connection's camera object reference.\n\n" "@see GameConnection::setCameraObject() and GameConnection::getCameraObject()\n\n") { object->setCameraObject(NULL); } DefineEngineMethod( GameConnection, isFirstPerson, bool, (),, "@brief Returns true if this connection is in first person mode.\n\n" "@note Transition to first person occurs over time via mCameraPos, so this " "won't immediately return true after a set.\n\n") { // Note: Transition to first person occurs over time via mCameraPos, so this // won't immediately return true after a set. return object->isFirstPerson(); } DefineEngineMethod( GameConnection, setFirstPerson, void, (bool firstPerson),, "@brief On the server, sets this connection into or out of first person mode.\n\n" "@param firstPerson Set to true to put the connection into first person mode.\n\n") { object->setFirstPerson(firstPerson); } DefineEngineMethod( GameConnection, setControlSchemeParameters, void, (bool absoluteRotation, bool addYawToAbsRot, bool addPitchToAbsRot),, "@brief Set the control scheme that may be used by a connection's control object.\n\n" "@param absoluteRotation Use absolute rotation values from client, likely through ExtendedMove.\n" "@param addYawToAbsRot Add relative yaw control to the absolute rotation calculation. Only useful when absoluteRotation is true.\n\n" ) { object->setControlSchemeParameters(absoluteRotation, addYawToAbsRot, addPitchToAbsRot); } DefineEngineMethod( GameConnection, getControlSchemeAbsoluteRotation, bool, (),, "@brief Get the connection's control scheme absolute rotation property.\n\n" "@return True if the connection's control object should use an absolute rotation control scheme.\n\n" "@see GameConnection::setControlSchemeParameters()\n\n") { return object->getControlSchemeAbsoluteRotation(); } DefineEngineMethod( GameConnection, setVisibleGhostDistance, void, (F32 dist),, "@brief Sets the distance that objects around it will be ghosted. If set to 0, " "it may be defined by the LevelInfo.\n\n" "@dist - is the max distance\n\n" ) { object->setVisibleGhostDistance(dist); } DefineEngineMethod( GameConnection, getVisibleGhostDistance, F32, (),, "@brief Gets the distance that objects around the connection will be ghosted.\n\n" "@return S32 of distance.\n\n" ) { return object->getVisibleGhostDistance(); }
; A146511: Numbers congruent to {5, 17} modulo 66. ; 5,17,71,83,137,149,203,215,269,281,335,347,401,413,467,479,533,545,599,611,665,677,731,743,797,809,863,875,929,941,995,1007,1061,1073,1127,1139,1193,1205,1259,1271,1325,1337,1391,1403,1457,1469,1523,1535,1589,1601,1655,1667,1721,1733,1787,1799,1853,1865,1919,1931,1985,1997,2051,2063,2117,2129,2183,2195,2249,2261,2315,2327,2381,2393,2447,2459,2513,2525,2579,2591,2645,2657,2711,2723,2777,2789,2843,2855,2909,2921,2975,2987,3041,3053,3107,3119,3173,3185,3239,3251,3305,3317,3371,3383,3437,3449,3503,3515,3569,3581,3635,3647,3701,3713,3767,3779,3833,3845,3899,3911,3965,3977,4031,4043,4097,4109,4163,4175,4229,4241,4295,4307,4361,4373,4427,4439,4493,4505,4559,4571,4625,4637,4691,4703,4757,4769,4823,4835,4889,4901,4955,4967,5021,5033,5087,5099,5153,5165,5219,5231,5285,5297,5351,5363,5417,5429,5483,5495,5549,5561,5615,5627,5681,5693,5747,5759,5813,5825,5879,5891,5945,5957,6011,6023,6077,6089,6143,6155,6209,6221,6275,6287,6341,6353,6407,6419,6473,6485,6539,6551,6605,6617,6671,6683,6737,6749,6803,6815,6869,6881,6935,6947,7001,7013,7067,7079,7133,7145,7199,7211,7265,7277,7331,7343,7397,7409,7463,7475,7529,7541,7595,7607,7661,7673,7727,7739,7793,7805,7859,7871,7925,7937,7991,8003,8057,8069,8123,8135,8189,8201 mov $2,$0 div $0,2 mul $0,7 mul $2,2 add $0,$2 mov $1,$0 mul $1,6 add $1,5
%ifdef CONFIG { "RegData": { "MM0": "0xDFE0DFE0DFE0DFE0", "MM1": "0xDFE0DFE0DFE0DFE0" }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x4142434445464748 mov [rdx + 8 * 0], rax mov rax, 0x5152535455565758 mov [rdx + 8 * 1], rax mov rax, 0x6162636465666768 mov [rdx + 8 * 2], rax mov rax, 0x7172737475767778 mov [rdx + 8 * 3], rax movq mm0, [rdx + 8 * 0] movq mm1, [rdx + 8 * 0] movq mm2, [rdx + 8 * 2] psubsw mm0, mm2 psubsw mm1, [rdx + 8 * 2] hlt
/*************************************************************** * * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "startd.h" #include "startd_hibernator.h" #include "startd_named_classad_list.h" #include "classad_merge.h" #include "vm_common.h" #include "VMRegister.h" #include "overflow.h" #include <math.h> #include "credmon_interface.h" #include "condor_auth_passwd.h" #include "condor_netdb.h" #include "token_utils.h" #include "data_reuse.h" #include "slot_builder.h" #include "strcasestr.h" ResMgr::ResMgr() : extras_classad( NULL ), max_job_retirement_time_override(-1), m_token_requester(&ResMgr::token_request_callback, this) { totals_classad = NULL; config_classad = NULL; up_tid = -1; poll_tid = -1; m_cred_sweep_tid = -1; draining = false; draining_is_graceful = false; on_completion_of_draining = DRAIN_NOTHING_ON_COMPLETION; draining_id = 0; last_drain_start_time = 0; last_drain_stop_time = 0; expected_graceful_draining_completion = 0; expected_quick_draining_completion = 0; expected_graceful_draining_badput = 0; expected_quick_draining_badput = 0; total_draining_badput = 0; total_draining_unclaimed = 0; m_attr = new MachAttributes; #if HAVE_BACKFILL m_backfill_mgr = NULL; m_backfill_shutdown_pending = false; #endif #if HAVE_JOB_HOOKS m_hook_mgr = NULL; #endif #if HAVE_HIBERNATION m_netif = NetworkAdapterBase::createNetworkAdapter( daemonCore->InfoCommandSinfulString (), false ); StartdHibernator *hibernator = new StartdHibernator; m_hibernation_manager = new HibernationManager( hibernator ); if ( m_netif ) { m_hibernation_manager->addInterface( *m_netif ); } m_hibernate_tid = -1; NetworkAdapterBase *primary = m_hibernation_manager->getNetworkAdapter(); if ( NULL == primary ) { dprintf( D_FULLDEBUG, "No usable network interface: hibernation disabled\n" ); } else { dprintf( D_FULLDEBUG, "Using network interface %s for hibernation\n", primary->interfaceName() ); } m_hibernation_manager->initialize( ); MyString states; m_hibernation_manager->getSupportedStates(states); dprintf( D_FULLDEBUG, "Detected hibernation states: %s\n", states.Value() ); m_hibernating = FALSE; #endif id_disp = NULL; nresources = 0; resources = NULL; type_nums = NULL; new_type_nums = NULL; is_shutting_down = false; cur_time = last_in_use = time( NULL ); max_types = 0; num_updates = 0; startTime = 0; type_strings = NULL; m_startd_hook_shutdown_pending = false; } void ResMgr::Stats::Init() { STATS_POOL_ADD(daemonCore->dc_stats.Pool, "ResMgr", Compute, IF_VERBOSEPUB); STATS_POOL_ADD(daemonCore->dc_stats.Pool, "ResMgr", WalkEvalState, IF_VERBOSEPUB); STATS_POOL_ADD(daemonCore->dc_stats.Pool, "ResMgr", WalkUpdate, IF_VERBOSEPUB); STATS_POOL_ADD(daemonCore->dc_stats.Pool, "ResMgr", WalkOther, IF_VERBOSEPUB); STATS_POOL_ADD(daemonCore->dc_stats.Pool, "ResMgr", Drain, IF_VERBOSEPUB); } double ResMgr::Stats::BeginRuntime(stats_recent_counter_timer & /*probe*/) { return _condor_debug_get_time_double(); } double ResMgr::Stats::EndRuntime(stats_recent_counter_timer & probe, double before) { double now = _condor_debug_get_time_double(); probe.Add(now - before); return now; } double ResMgr::Stats::BeginWalk(VoidResourceMember /*memberfunc*/) { return _condor_debug_get_time_double(); } double ResMgr::Stats::EndWalk(VoidResourceMember memberfunc, double before) { stats_recent_counter_timer * probe = &WalkOther; if (memberfunc == &Resource::update) probe = &WalkUpdate; else if (memberfunc == &Resource::eval_state) probe = &WalkEvalState; return EndRuntime(*probe, before); } ResMgr::~ResMgr() { int i; if( extras_classad ) delete extras_classad; if( config_classad ) delete config_classad; if( totals_classad ) delete totals_classad; if( id_disp ) delete id_disp; #if HAVE_BACKFILL if( m_backfill_mgr ) { delete m_backfill_mgr; } #endif #if HAVE_JOB_HOOKS if (m_hook_mgr) { delete m_hook_mgr; } #endif #if HAVE_HIBERNATION cancelHibernateTimer(); if (m_hibernation_manager) { delete m_hibernation_manager; } if ( m_netif ) { delete m_netif; m_netif = NULL; } #endif /* HAVE_HIBERNATION */ if( resources ) { for( i = 0; i < nresources; i++ ) { delete resources[i]; } delete [] resources; } for( i=0; i<max_types; i++ ) { if( type_strings[i] ) { delete type_strings[i]; } } delete [] type_strings; delete [] type_nums; if( new_type_nums ) { delete [] new_type_nums; } delete m_attr; } void ResMgr::init_config_classad( void ) { if( config_classad ) delete config_classad; config_classad = new ClassAd(); // First, bring in everything we know we need configInsert( config_classad, "START", true ); configInsert( config_classad, "SUSPEND", true ); configInsert( config_classad, "CONTINUE", true ); configInsert( config_classad, "PREEMPT", true ); configInsert( config_classad, "KILL", true ); configInsert( config_classad, "WANT_SUSPEND", true ); configInsert( config_classad, "WANT_VACATE", true ); if( !configInsert( config_classad, "WANT_HOLD", false ) ) { // default's to false if undefined config_classad->AssignExpr("WANT_HOLD","False"); } configInsert( config_classad, "WANT_HOLD_REASON", false ); configInsert( config_classad, "WANT_HOLD_SUBCODE", false ); configInsert( config_classad, "CLAIM_WORKLIFE", false ); configInsert( config_classad, ATTR_MAX_JOB_RETIREMENT_TIME, false ); configInsert( config_classad, ATTR_MACHINE_MAX_VACATE_TIME, true ); // Now, bring in things that we might need configInsert( config_classad, "PERIODIC_CHECKPOINT", false ); configInsert( config_classad, "RunBenchmarks", false ); configInsert( config_classad, ATTR_RANK, false ); configInsert( config_classad, "SUSPEND_VANILLA", false ); configInsert( config_classad, "CONTINUE_VANILLA", false ); configInsert( config_classad, "PREEMPT_VANILLA", false ); configInsert( config_classad, "KILL_VANILLA", false ); configInsert( config_classad, "WANT_SUSPEND_VANILLA", false ); configInsert( config_classad, "WANT_VACATE_VANILLA", false ); #if HAVE_BACKFILL configInsert( config_classad, "START_BACKFILL", false ); configInsert( config_classad, "EVICT_BACKFILL", false ); #endif /* HAVE_BACKFILL */ #if HAVE_JOB_HOOKS configInsert( config_classad, ATTR_FETCH_WORK_DELAY, false ); #endif /* HAVE_JOB_HOOKS */ #if HAVE_HIBERNATION configInsert( config_classad, "HIBERNATE", false ); if( !configInsert( config_classad, ATTR_UNHIBERNATE, false ) ) { MyString default_expr; default_expr.formatstr("MY.%s =!= UNDEFINED",ATTR_MACHINE_LAST_MATCH_TIME); config_classad->AssignExpr( ATTR_UNHIBERNATE, default_expr.Value() ); } #endif /* HAVE_HIBERNATION */ if( !configInsert( config_classad, ATTR_SLOT_WEIGHT, false ) ) { config_classad->AssignExpr( ATTR_SLOT_WEIGHT, ATTR_CPUS ); } // First, try the IsOwner expression. If it's not there, try // what's defined in IS_OWNER (for backwards compatibility). // If that's not there, give them a reasonable default. if( ! configInsert(config_classad, ATTR_IS_OWNER, false) ) { if( ! configInsert(config_classad, "IS_OWNER", ATTR_IS_OWNER, false) ) { config_classad->AssignExpr( ATTR_IS_OWNER, "(START =?= False)" ); } } // Next, try the CpuBusy expression. If it's not there, try // what's defined in cpu_busy (for backwards compatibility). // If that's not there, give them a default of "False", // instead of leaving it undefined. if( ! configInsert(config_classad, ATTR_CPU_BUSY, false) ) { if( ! configInsert(config_classad, "cpu_busy", ATTR_CPU_BUSY, false) ) { config_classad->Assign( ATTR_CPU_BUSY, false ); } } // Publish all DaemonCore-specific attributes, which also handles // STARTD_ATTRS for us. daemonCore->publish(config_classad); } #if HAVE_BACKFILL void ResMgr::backfillMgrDone() { ASSERT( m_backfill_mgr ); dprintf( D_FULLDEBUG, "BackfillMgr now ready to be deleted\n" ); delete m_backfill_mgr; m_backfill_mgr = NULL; m_backfill_shutdown_pending = false; // We should call backfillConfig() again, since now that the // "old" manager is gone, we might want to allocate a new one backfillConfig(); } static bool verifyBackfillSystem( const char* sys ) { #if HAVE_BOINC if( ! strcasecmp(sys, "BOINC") ) { return true; } #endif /* HAVE_BOINC */ return false; } bool ResMgr::backfillConfig() { if( m_backfill_shutdown_pending ) { /* we're already in the middle of trying to reconfig the backfill manager, anyway. we can only get to this point if we had 1 backfill system running, then we either change the system we want or disable backfill entirely, and while we're waiting for the old system to cleanup, we get *another* reconfig. in this case, we do NOT want to act on the new reconfig until the old reconfig had a chance to complete. since we'll call backfillConfig() from backfillMgrDone(), anyway, there's no harm in just returning immediately at this point, and plenty of harm that could come from trying to proceed. ;) */ dprintf( D_ALWAYS, "Got another reconfig while waiting for the old " "backfill system to finish cleaning up, delaying\n" ); return true; } if( ! param_boolean("ENABLE_BACKFILL", false) ) { if( m_backfill_mgr ) { dprintf( D_ALWAYS, "ENABLE_BACKFILL is false, destroying BackfillMgr\n" ); if( m_backfill_mgr->destroy() ) { // nothing else to cleanup now, we can delete it // immediately... delete m_backfill_mgr; m_backfill_mgr = NULL; } else { // backfill_mgr told us we have to wait, so just // return for now and we'll finish deleting this // in ResMgr::backfillMgrDone(). dprintf( D_ALWAYS, "BackfillMgr still has cleanup to " "perform, postponing delete\n" ); m_backfill_shutdown_pending = true; } } return false; } char* new_system = param( "BACKFILL_SYSTEM" ); if( ! new_system ) { dprintf( D_ALWAYS, "ERROR: ENABLE_BACKFILL is TRUE, but " "BACKFILL_SYSTEM is undefined!\n" ); return false; } if( ! verifyBackfillSystem(new_system) ) { dprintf( D_ALWAYS, "ERROR: BACKFILL_SYSTEM '%s' not supported, ignoring\n", new_system ); free( new_system ); return false; } if( m_backfill_mgr ) { if( ! strcasecmp(new_system, m_backfill_mgr->backfillSystemName()) ) { // same as before free( new_system ); // since it's already here and we're keeping it, tell // it to reconfig (if that matters) m_backfill_mgr->reconfig(); // we're done return true; } else { // different! dprintf( D_ALWAYS, "BACKFILL_SYSTEM has changed " "(old: '%s', new: '%s'), re-initializing\n", m_backfill_mgr->backfillSystemName(), new_system ); if( m_backfill_mgr->destroy() ) { // nothing else to cleanup now, we can delete it // immediately... delete m_backfill_mgr; m_backfill_mgr = NULL; } else { // backfill_mgr told us we have to wait, so just // return for now and we'll finish deleting this // in ResMgr::backfillMgrDone(). dprintf( D_ALWAYS, "BackfillMgr still has cleanup to " "perform, postponing delete\n" ); m_backfill_shutdown_pending = true; free( new_system ); return true; } } } // if we got this far, it means we've got a valid system, but // no manager object. so, depending on the system, // instantiate the right thing. #if HAVE_BOINC if( ! strcasecmp(new_system, "BOINC") ) { m_backfill_mgr = new BOINC_BackfillMgr(); if( ! m_backfill_mgr->init() ) { dprintf( D_ALWAYS, "ERROR initializing BOINC_BackfillMgr\n" ); delete m_backfill_mgr; m_backfill_mgr = NULL; free( new_system ); return false; } } #endif /* HAVE_BOINC */ if( ! m_backfill_mgr ) { // this is impossible, since we've already verified above EXCEPT( "IMPOSSILE: unrecognized BACKFILL_SYSTEM: '%s'", new_system ); } dprintf( D_ALWAYS, "Created a %s Backfill Manager\n", m_backfill_mgr->backfillSystemName() ); free( new_system ); return true; } #endif /* HAVE_BACKFILL */ void ResMgr::init_resources( void ) { int i, num_res; CpuAttributes** new_cpu_attrs; stats.Init(); m_attr->init_machine_resources(); // These things can only be set once, at startup, so they // don't need to be in build_cpu_attrs() at all. max_types = param_integer("MAX_SLOT_TYPES", 10); max_types += 1; // The reason this isn't on the stack is b/c of the variable // nature of max_types. *sigh* type_strings = new StringList*[max_types]; memset( type_strings, 0, (sizeof(StringList*) * max_types) ); // Fill in the type_strings array with all the appropriate // string lists for each type definition. This only happens // once! If you change the type definitions, you must restart // the startd, or else too much weirdness is possible. SlotType::init_types(max_types, true); initTypes( max_types, type_strings, 1 ); // First, see how many slots of each type are specified. num_res = countTypes( max_types, num_cpus(), &type_nums, true ); if( ! num_res ) { // We're not configured to advertise any nodes. resources = NULL; id_disp = new IdDispenser( 1 ); return; } // See if the config file allows for a valid set of // CpuAttributes objects. Since this is the startup-code // we'll let it EXCEPT() if there is an error. new_cpu_attrs = buildCpuAttrs( m_attr, max_types, type_strings, num_res, type_nums, true ); if( ! new_cpu_attrs ) { EXCEPT( "buildCpuAttrs() failed and should have already EXCEPT'ed" ); } // Now, we can finally allocate our resources array, and // populate it. for( i=0; i<num_res; i++ ) { addResource( new Resource( new_cpu_attrs[i], i+1, num_res>1 ) ); } // We can now seed our IdDispenser with the right slot id. id_disp = new IdDispenser( i+1 ); // Finally, we can free up the space of the new_cpu_attrs // array itself, now that all the objects it was holding that // we still care about are stashed away in the various // Resource objects. Since it's an array of pointers, this // won't touch the objects at all. delete [] new_cpu_attrs; #if HAVE_BACKFILL backfillConfig(); #endif #if HAVE_JOB_HOOKS m_hook_mgr = new StartdHookMgr; m_hook_mgr->initialize(); #endif std::string reuse_dir; if (param(reuse_dir, "DATA_REUSE_DIRECTORY")) { if (!m_reuse_dir.get() || (m_reuse_dir->GetDirectory() != reuse_dir)) { m_reuse_dir.reset(new htcondor::DataReuseDirectory(reuse_dir, true)); } } else { m_reuse_dir.reset(); } } bool ResMgr::typeNumCmp( const int* a, const int* b ) const { int i; for( i=0; i<max_types; i++ ) { if( a[i] != b[i] ) { return false; } } return true; } bool ResMgr::reconfig_resources( void ) { int t, i, cur, num; CpuAttributes** new_cpu_attrs; int max_num = num_cpus(); int* cur_type_index; Resource*** sorted_resources; // Array of arrays of pointers. Resource* rip; dprintf(D_ALWAYS, "beginning reconfig_resources\n"); #if HAVE_BACKFILL backfillConfig(); #endif #if HAVE_JOB_HOOKS if ( m_hook_mgr ) { m_hook_mgr->reconfig(); } #endif #if HAVE_HIBERNATION updateHibernateConfiguration(); #endif /* HAVE_HIBERNATE */ m_attr->ReconfigOfflineDevIds(); // Tell each resource to reconfig itself. walk(&Resource::reconfig); // See if any new types were defined. Don't except if there's // any errors, just dprintf(). ASSERT(max_types > 0); SlotType::init_types(max_types, false); initTypes( max_types, type_strings, 0 ); // First, see how many slots of each type are specified. num = countTypes( max_types, num_cpus(), &new_type_nums, false ); if( typeNumCmp(new_type_nums, type_nums) ) { // We want the same number of each slot type that we've got // now. We're done! dprintf(D_ALWAYS, "no change to slot type config, exiting reconfig_resources\n"); delete [] new_type_nums; new_type_nums = NULL; return true; } // See if the config file allows for a valid set of // CpuAttributes objects. new_cpu_attrs = buildCpuAttrs( m_attr, max_types, type_strings, num, new_type_nums, false ); if( ! new_cpu_attrs ) { // There was an error, abort. We still return true to // indicate that we're done doing our thing... dprintf( D_ALWAYS, "Aborting slot type reconfig.\n" ); delete [] new_type_nums; new_type_nums = NULL; return true; } //////////////////////////////////////////////////// // Sort all our resources by type and state. //////////////////////////////////////////////////// // Allocate and initialize our arrays. sorted_resources = new Resource** [max_types]; ASSERT( sorted_resources != NULL ); for( i=0; i<max_types; i++ ) { sorted_resources[i] = new Resource* [max_num]; ASSERT(sorted_resources[i] != NULL); memset( sorted_resources[i], 0, (max_num*sizeof(Resource*)) ); } cur_type_index = new int [max_types]; memset( cur_type_index, 0, (max_types*sizeof(int)) ); // Populate our sorted_resources array by type. for( i=0; i<nresources; i++ ) { t = resources[i]->type(); (sorted_resources[t])[cur_type_index[t]] = resources[i]; cur_type_index[t]++; } // Now, for each type, sort our resources by state. for( t=0; t<max_types; t++ ) { ASSERT( cur_type_index[t] == type_nums[t] ); qsort( sorted_resources[t], type_nums[t], sizeof(Resource*), &claimedRankCmp ); } //////////////////////////////////////////////////// // Decide what we need to do. //////////////////////////////////////////////////// cur = -1; for( t=0; t<max_types; t++ ) { for( i=0; i<new_type_nums[t]; i++ ) { cur++; if( ! (sorted_resources[t])[i] ) { // If there are no more existing resources of this // type, we'll need to allocate one. alloc_list.Append( new_cpu_attrs[cur] ); continue; } if( (sorted_resources[t])[i]->type() == new_cpu_attrs[cur]->type() ) { // We've already got a Resource for this slot, so we // can delete it. delete new_cpu_attrs[cur]; continue; } } // We're done with the new slots of this type. See if there // are any Resources left over that need to be destroyed. for( ; i<max_num; i++ ) { if( (sorted_resources[t])[i] ) { destroy_list.Append( (sorted_resources[t])[i] ); } else { break; } } } //////////////////////////////////////////////////// // Finally, act on our decisions. //////////////////////////////////////////////////// // Everything we care about in new_cpu_attrs is saved // elsewhere, and the rest has already been deleted, so we // should now delete the array itself. delete [] new_cpu_attrs; // Cleanup our memory. for( i=0; i<max_types; i++ ) { delete [] sorted_resources[i]; } delete [] sorted_resources; delete [] cur_type_index; // See if there's anything to destroy, and if so, do it. destroy_list.Rewind(); while( destroy_list.Next(rip) ) { rip->dprintf( D_ALWAYS, "State change: resource no longer needed by configuration\n" ); rip->set_destination_state( delete_state ); } std::string reuse_dir; if (param(reuse_dir, "DATA_REUSE_DIRECTORY")) { if (!m_reuse_dir.get() || (m_reuse_dir->GetDirectory() != reuse_dir)) { m_reuse_dir.reset(new htcondor::DataReuseDirectory(reuse_dir, true)); } } else { m_reuse_dir.reset(); } // Finally, call our helper, so that if all the slots we need to // get rid of are gone by now, we'll allocate the new ones. return processAllocList(); } void ResMgr::walk( VoidResourceMember memberfunc ) { if( ! resources ) { return; } double currenttime = stats.BeginWalk(memberfunc); // Because the memberfunc might be an eval function, it can // result in resources being deleted. This means a straight // for loop on nresources will miss one resource for every one // deleted. To combat that, we copy the array and nresources // and iterate over it instead. int ncache = nresources; Resource **cache = new Resource*[ncache]; memcpy((void*)cache, (void*)resources, (sizeof(Resource*)*ncache)); for( int i = 0; i < ncache; i++ ) { (cache[i]->*(memberfunc))(); } delete [] cache; stats.EndWalk(memberfunc, currenttime); } void ResMgr::walk( ResourceMaskMember memberfunc, amask_t mask ) { if( ! resources ) { return; } int i; for( i = 0; i < nresources; i++ ) { (resources[i]->*(memberfunc))(mask); } } float ResMgr::sum( ResourceFloatMember memberfunc ) { if( ! resources ) { return 0; } int i; float tot = 0; for( i = 0; i < nresources; i++ ) { tot += (resources[i]->*(memberfunc))(); } return tot; } void ResMgr::resource_sort( ComparisonFunc compar ) { if( ! resources ) { return; } if( nresources > 1 ) { qsort( resources, nresources, sizeof(Resource*), compar ); } } // Methods to manipulate the supplemental ClassAd list int ResMgr::adlist_register( StartdNamedClassAd *ad ) { return extra_ads.Register( ad ); } StartdNamedClassAd * ResMgr::adlist_find( const char * name ) { NamedClassAd * nad = extra_ads.Find(name); return dynamic_cast<StartdNamedClassAd*>(nad); } int ResMgr::adlist_replace( const char *name, ClassAd *newAd, bool report_diff, const char *prefix ) { if( report_diff ) { StringList ignore_list; MyString ignore = prefix; ignore += "LastUpdate"; ignore_list.append( ignore.Value() ); return extra_ads.Replace( name, newAd, true, &ignore_list ); } else { return extra_ads.Replace( name, newAd ); } } int ResMgr::adlist_publish( unsigned r_id, ClassAd *resAd, amask_t mask, const char * r_id_str ) { // Check the mask if ( ( mask & ( A_PUBLIC | A_UPDATE ) ) != ( A_PUBLIC | A_UPDATE ) ) { return 0; } return extra_ads.Publish( resAd, r_id, r_id_str ); } bool ResMgr::needsPolling( void ) { if( ! resources ) { return false; } int i; for( i = 0; i < nresources; i++ ) { if( resources[i]->needsPolling() ) { return true; } } return false; } bool ResMgr::hasAnyClaim( void ) { if( ! resources ) { return false; } int i; for( i = 0; i < nresources; i++ ) { if( resources[i]->hasAnyClaim() ) { return true; } } return false; } Claim* ResMgr::getClaimByPid( pid_t pid ) { Claim* foo = NULL; if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( (foo = resources[i]->findClaimByPid(pid)) ) { return foo; } } return NULL; } Claim* ResMgr::getClaimById( const char* id ) { Claim* foo = NULL; if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( (foo = resources[i]->findClaimById(id)) ) { return foo; } } return NULL; } Claim* ResMgr::getClaimByGlobalJobId( const char* id ) { Claim* foo = NULL; if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( (foo = resources[i]->findClaimByGlobalJobId(id)) ) { return foo; } } return NULL; } Claim * ResMgr::getClaimByGlobalJobIdAndId( const char *job_id, const char *claimId) { Claim* foo = NULL; if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( (foo = resources[i]->findClaimByGlobalJobId(job_id)) ) { if( foo == resources[i]->findClaimById(claimId) ) { return foo; } } } return NULL; } Resource* ResMgr::findRipForNewCOD( ClassAd* ad ) { if( ! resources ) { return NULL; } bool requirements; int i; /* We always ensure that the request's Requirements, if any, are met. Other than that, we give out COD claims to Resources in the following order: 1) the Resource with the least # of existing COD claims (to ensure round-robin across resources 2) in case of a tie, the Resource in the best state (owner or unclaimed, not claimed) 3) in case of a tie, the Claimed resource with the lowest value of machine Rank for its claim */ // sort resources based on the above order resource_sort( newCODClaimCmp ); // find the first one that matches our requirements for( i = 0; i < nresources; i++ ) { if( EvalBool( ATTR_REQUIREMENTS, ad, resources[i]->r_classad, requirements ) == 0 ) { requirements = false; } if( requirements ) { return resources[i]; } } // put the resources back into a "natural" order resource_sort(naturalSlotOrderCmp); return NULL; } Resource* ResMgr::get_by_cur_id(const char* id ) { if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( resources[i]->r_cur->idMatches(id) ) { return resources[i]; } } return NULL; } Resource* ResMgr::get_by_any_id(const char* id, bool move_cp_claim ) { if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( resources[i]->r_cur->idMatches(id) ) { return resources[i]; } if( resources[i]->r_pre && resources[i]->r_pre->idMatches(id) ) { return resources[i]; } if( resources[i]->r_pre_pre && resources[i]->r_pre_pre->idMatches(id) ) { return resources[i]; } if (resources[i]->r_has_cp) { for (Resource::claims_t::iterator j(resources[i]->r_claims.begin()); j != resources[i]->r_claims.end(); ++j) { if ((*j)->idMatches(id)) { if ( move_cp_claim ) { delete resources[i]->r_cur; resources[i]->r_cur = *j; resources[i]->r_claims.erase(*j); resources[i]->r_claims.insert(new Claim(resources[i])); } return resources[i]; } } } } return NULL; } Resource* ResMgr::get_by_name(const char* name ) { if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( !strcmp(resources[i]->r_name, name) ) { return resources[i]; } } return NULL; } Resource* ResMgr::get_by_name_prefix(const char* name ) { if( ! resources ) { return NULL; } int len = (int)strlen(name); for (int i = 0; i < nresources; i++ ) { const char * pat = strchr(resources[i]->r_name, '@'); if (pat && (int)(pat - resources[i]->r_name) == len && strncasecmp(name, resources[i]->r_name, len) == MATCH) { return resources[i]; } } // not found, print possible names StringList names; for(int i = 0; i < nresources; i++ ) { names.append(resources[i]->r_name); if( !strcmp(resources[i]->r_name, name) ) { return resources[i]; } } auto_free_ptr namelist(names.print_to_string()); dprintf(D_ALWAYS, "%s not found, slot names are %s\n", name, namelist ? namelist.ptr() : "<empty>"); return NULL; } Resource* ResMgr::get_by_slot_id( int id ) { if( ! resources ) { return NULL; } int i; for( i = 0; i < nresources; i++ ) { if( resources[i]->r_id == id ) { return resources[i]; } } return NULL; } State ResMgr::state( void ) { if( ! resources ) { return owner_state; } State s = no_state; Resource* rip; int i, is_owner = 0; for( i = 0; i < nresources; i++ ) { rip = resources[i]; // if there are *any* COD claims at all (active or not), // we should say this slot is claimed so preen doesn't // try to clean up directories for the COD claim(s). if( rip->r_cod_mgr->numClaims() > 0 ) { return claimed_state; } s = rip->state(); switch( s ) { case claimed_state: case preempting_state: return s; break; case owner_state: is_owner = 1; break; default: break; } } if( is_owner ) { return owner_state; } else { return s; } } void ResMgr::final_update( void ) { if( ! resources ) { return; } walk( &Resource::final_update ); } int ResMgr::send_update( int cmd, ClassAd* public_ad, ClassAd* private_ad, bool nonblock ) { static bool first_time = true; // Increment the resmgr's count of updates. num_updates++; int res = daemonCore->sendUpdates(cmd, public_ad, private_ad, nonblock, &m_token_requester, DCTokenRequester::default_identity, "ADVERTISE_STARTD"); if (first_time) { first_time = false; dprintf( D_ALWAYS, "Initial update sent to collector(s)\n"); if ( ! param_boolean("STARTD_SEND_READY_AFTER_FIRST_UPDATE", true)) return res; // send a DC_SET_READY message to the master to indicate the STARTD is ready to go MyString master_sinful(daemonCore->InfoCommandSinfulString(-2)); if ( ! master_sinful.empty()) { dprintf( D_ALWAYS, "Sending DC_SET_READY message to master %s\n", master_sinful.c_str()); ClassAd readyAd; readyAd.Assign("DaemonPID", getpid()); readyAd.Assign("DaemonName", "STARTD"); // fix to use the environment readyAd.Assign("DaemonState", "Ready"); classy_counted_ptr<Daemon> dmn = new Daemon(DT_ANY,master_sinful.c_str()); classy_counted_ptr<ClassAdMsg> msg = new ClassAdMsg(DC_SET_READY, readyAd); dmn->sendMsg(msg.get()); } } return res; } void ResMgr::update_all( void ) { num_updates = 0; // NOTE: We do *NOT* eval_state and update in the same walk // over the resources. The reason we do not is the eval_state // may result in the deletion of a resource, e.g. if it ends // up in the delete_state. In such a case we'll be calling // eval_state on a resource we delete and then call update on // the same resource. As a result, you might be lucky enough // to get a SEGV immediately, but if you aren't you'll get a // SEGV later on when the timer Resource::update registers // fires. That delay will make it rather difficult to find the // root cause of the SEGV, believe me. Generally, nothing // should mess with a resource immediately after eval_state is // called on it. To avoid this problem, the eval and update // process is split here. The Resource::update will only be // called on resources that are still alive. - matt 1 Oct 09 // Evaluate the state change policy expressions (like PREEMPT) // For certain changes this will trigger an update to the collector // (all that really does is register a timer) walk( &Resource::eval_state ); // If we didn't update b/c of the eval_state, we need to // actually do the update now. Tj 2020 sez: this is a lie, was it ever true? // What this actually does is insure that the update timers have been registered for all slots walk( &Resource::update ); report_updates(); check_polling(); check_use(); } void ResMgr::eval_and_update_all( void ) { #if HAVE_HIBERNATION if ( !hibernating () ) { #endif compute_dynamic(true); update_all(); #if HAVE_HIBERNATION } #endif } void ResMgr::eval_all( void ) { #if HAVE_HIBERNATION if ( !hibernating () ) { #endif num_updates = 0; compute_dynamic(false); walk( &Resource::eval_state ); report_updates(); check_polling(); #if HAVE_HIBERNATION } #endif } void ResMgr::report_updates( void ) const { if( !num_updates ) { return; } CollectorList* collectors = daemonCore->getCollectorList(); if( collectors ) { MyString list; Daemon * collector; collectors->rewind(); while (collectors->next (collector)) { list += collector->fullHostname(); list += " "; } dprintf( D_FULLDEBUG, "Sent %d update(s) to the collector (%s)\n", num_updates, list.Value()); } } void ResMgr::compute_static() { // each time we reconfig (or on startup) we must populate // static machine attributes and per-slot config that depends on resource allocation m_attr->compute_config(); walk(&Resource::initial_compute); } // Resource is passed when creating a new d-slot // void ResMgr::compute_dynamic(bool for_update, Resource * rip) { if( ! resources ) { return; } Resource * parent = NULL; if (rip) { parent = rip->get_parent(); } //PRAGMA_REMIND("tj: is this where we clear out the r_classad ?") //tj: Not until we make it so rollup happens in a separate layer and cross-slot doesn't depend on stale values to work double runtime = stats.BeginRuntime(stats.Compute); // Since lots of things want to know this, just get it from // the kernel once and share the value... cur_time = time( 0 ); compute_draining_attrs(); // for updates, we recompute some machine attributes (like virtual mem) // and that may require a recompute of the resources that reference them if (for_update) { m_attr->compute_for_update(); if (rip) { rip->compute_shared(); if (parent) parent->compute_shared(); } else { walk(&Resource::compute_shared); //TODO: Tj can I kill this? I'm pretty sure the vmapi stuff doesn't work anymore if it ever did if (vmapi_is_virtual_machine()) { vmapi_request_host_classAd(); } } } // update machine load and idle values, also dynamic WinReg attributes m_attr->compute_for_policy(); // update per-slot disk and cpu usage/load values if (rip) { rip->compute_unshared(); if (parent) parent->compute_unshared(); } else { walk(&Resource::compute_unshared); // how_much & ~(A_SHARED) } // now sum the updated slot load values to get a system wide load value m_attr->update_condor_load(sum(&Resource::condor_load)); // if Resource was passed, that's because it's a new slot, or one that just changed // state and we want a quick init/refresh pass on it. So instead of walking // all of the resources, update just the slot and it's parent (if it has one) if (rip) { rip->refresh_classad_for_update(); if (parent) parent->refresh_classad_for_update(); rip->compute_evaluated(); if (parent) parent->compute_evaluated(); rip->refresh_classad_evaluated(); if (parent) parent->refresh_classad_evaluated(); // TODO: it's hard to know what the correct order of thse two is // it depends on specifically *what* slot attrs that we want to cross post rip->refresh_classad_slot_attrs(); if (parent) parent->refresh_classad_slot_attrs(); // if passed a resource, refresh ONLY that resource's ad return; } // Sort the resources so when we're assigning owner load // average and keyboard activity, we get to them in the // following state order: Owner, Unclaimed, Matched, Claimed // Preempting resource_sort( ownerStateCmp ); assign_load(); assign_keyboard(); if (for_update) { // this does A_UPDATE and also A_TIMEOUT walk(&Resource::refresh_classad_for_update); } else { walk(&Resource::refresh_classad_for_policy); } // Now that we have an updated internal classad for each // resource, we can "compute" anything where we need to // evaluate classad expressions to get the answer. walk( &Resource::compute_evaluated ); // Next, we can publish any results from that to our internal // classads to make sure those are still up-to-date walk( &Resource::refresh_classad_evaluated ); // Finally, now that all the internal classads are up to date // with all the attributes they could possibly have, we can // publish the cross-slot attributes desired from // STARTD_SLOT_ATTRS into each slots's internal ClassAd. walk( &Resource::refresh_classad_slot_attrs ); if (IsFulldebug(D_FULLDEBUG) && for_update && m_attr->always_recompute_disk()) { // on update (~10min) we report the new value of DISK walk(&Resource::display_total_disk); } if (IsDebugLevel(D_LOAD) || IsDebugLevel(D_KEYBOARD)) { // Now that we're done, we can display all the values. walk(&Resource::display_load, for_update ? A_UPDATE : 0); } // put the resources back into a "natural" order resource_sort(naturalSlotOrderCmp); stats.EndRuntime(stats.Compute, runtime); } void ResMgr::publish_dynamic(ClassAd* cp) { cp->Assign(ATTR_TOTAL_SLOTS, numSlots()); if (m_reuse_dir) { m_reuse_dir->Publish(*cp); } m_vmuniverse_mgr.publish(cp); startd_stats.Publish(*cp, 0); startd_stats.Tick(time(0)); #if HAVE_HIBERNATION m_hibernation_manager->publish(*cp); #endif if (extras_classad) { cp->Update(*extras_classad); } } void ResMgr::updateExtrasClassAd( ClassAd * cap ) { // It turns out to be colossal pain to use the ClassAd for persistence. static classad::References offlineUniverses; if( ! cap ) { return; } if( ! extras_classad ) { extras_classad = new ClassAd(); } int topping = 0; int obsolete_univ = false; // // The startd maintains the set offline universes, and the offline // universe timestamps. // // We start with the current set of offline universes, and add or remove // universes as directed by the update ad. This obviates the need for // the need for the starter to know anything about the state of the rest // of the machine. // ExprTree * expr = NULL; const char * attr = NULL; for ( auto itr = cap->begin(); itr != cap->end(); itr++ ) { attr = itr->first.c_str(); expr = itr->second; // // Copy the whole ad over, excepting special or computed attributes. // if( strcasecmp( attr, "MyType" ) == 0 ) { continue; } if( strcasecmp( attr, "TargetType" ) == 0 ) { continue; } if( strcasecmp( attr, "OfflineUniverses" ) == 0 ) { continue; } if( strcasestr( attr, "OfflineReason" ) != NULL ) { continue; } if( strcasestr( attr, "OfflineTime" ) != NULL ) { continue; } ExprTree * copy = expr->Copy(); extras_classad->Insert( attr, copy ); // // Adjust OfflineUniverses based on the Has<Universe> attributes. // const char * uo = strcasestr( attr, "Has" ); if( uo != attr ) { continue; } std::string universeName( attr + 3 ); int univ = CondorUniverseInfo( universeName.c_str(), &topping, &obsolete_univ ); if( univ == 0 || obsolete_univ) { continue; } // convert universe name to canonical form universeName = CondorUniverseOrToppingName(univ, topping); std::string reasonTime = universeName + "OfflineTime"; std::string reasonName = universeName + "OfflineReason"; bool universeOnline = false; ASSERT( cap->LookupBool( attr, universeOnline ) ); if( ! universeOnline ) { offlineUniverses.insert( universeName ); extras_classad->Assign( reasonTime, time( NULL ) ); std::string reason = "[unknown reason]"; cap->LookupString( reasonName, reason ); extras_classad->Assign( reasonName, reason ); } else { // The universe is online, so it can't have an offline reason // or a time that it entered the offline state. offlineUniverses.erase( universeName ); extras_classad->AssignExpr( reasonTime, "undefined" ); extras_classad->AssignExpr( reasonName, "undefined" ); } } // // Construct the OfflineUniverses attribute and set it in extras_classad. // std::string ouListString; ouListString.reserve(10 + offlineUniverses.size()*20); ouListString = "{"; classad::References::const_iterator i = offlineUniverses.begin(); for( ; i != offlineUniverses.end(); ++i ) { int univ = CondorUniverseInfo( i->c_str(), &topping, &obsolete_univ ); if ( ! univ || obsolete_univ) { continue; } if (ouListString.size() > 1) { ouListString += ", "; } formatstr_cat(ouListString, "\"%s\"", i->c_str() ); if ( ! topping) { formatstr_cat(ouListString, ",%d", univ ); } } ouListString += "}"; dprintf( D_ALWAYS, "OfflineUniverses = %s\n", ouListString.c_str() ); extras_classad->AssignExpr( "OfflineUniverses", ouListString.c_str() ); } void ResMgr::publishSlotAttrs( ClassAd* cap ) { if( ! resources ) { return; } // experimental flags new for 8.9.7, evaluate STARTD_SLOT_ATTRS and insert valid literals only bool as_literal = param_boolean("STARTD_EVAL_SLOT_ATTRS", false); bool valid_only = ! param_boolean("STARTD_EVAL_SLOT_ATTRS_DEBUG", false); int i; for( i = 0; i < nresources; i++ ) { resources[i]->publishSlotAttrs( cap, as_literal, valid_only ); } } void ResMgr::assign_load( void ) { if( ! resources ) { return; } int i; float total_owner_load = m_attr->load() - m_attr->condor_load(); if( total_owner_load < 0 ) { total_owner_load = 0; } if( is_smp() ) { // Print out the totals we already know. if( IsDebugVerbose( D_LOAD ) ) { dprintf( D_LOAD | D_VERBOSE, "%s %.3f\t%s %.3f\t%s %.3f\n", "SystemLoad:", m_attr->load(), "TotalCondorLoad:", m_attr->condor_load(), "TotalOwnerLoad:", total_owner_load ); } // Initialize everything to 0. Only need this for SMP // machines, since on single CPU machines, we just assign // all OwnerLoad to the 1 CPU. for( i = 0; i < nresources; i++ ) { resources[i]->set_owner_load( 0 ); } } // So long as there's at least two more resources and the // total owner load is greater than 1.0, assign an owner load // of 1.0 to each CPU. Once we get below 1.0, we assign all // the rest to the next CPU. So, for non-SMP machines, we // never hit this code, and always assign all owner load to // cpu1 (since i will be initialized to 0 but we'll never // enter the for loop). for( i = 0; i < (nresources - 1) && total_owner_load > 1; i++ ) { resources[i]->set_owner_load( 1.0 ); total_owner_load -= 1.0; } resources[i]->set_owner_load( total_owner_load ); } void ResMgr::assign_keyboard( void ) { if( ! resources ) { return; } int i; time_t console = m_attr->console_idle(); time_t keyboard = m_attr->keyboard_idle(); time_t max; // First, initialize all CPUs to the max idle time we've got, // which is some configurable amount of minutes longer than // the time since we started up. max = (cur_time - startd_startup) + disconnected_keyboard_boost; for( i = 0; i < nresources; i++ ) { resources[i]->r_attr->set_console( max ); resources[i]->r_attr->set_keyboard( max ); } // Now, assign console activity to all CPUs that care. // Notice, we should also assign keyboard here, since if // there's console activity, there's (by definition) keyboard // activity as well. for( i = 0; i < console_slots && i < nresources; i++ ) { resources[i]->r_attr->set_console( console ); resources[i]->r_attr->set_keyboard( console ); } // Finally, assign keyboard activity to all CPUS that care. for( i = 0; i < keyboard_slots && i < nresources; i++ ) { resources[i]->r_attr->set_keyboard( keyboard ); } } void ResMgr::check_polling( void ) { if( ! resources ) { return; } if( needsPolling() || m_attr->condor_load() > 0 ) { start_poll_timer(); } else { cancel_poll_timer(); } } void ResMgr::sweep_timer_handler( void ) const { dprintf(D_FULLDEBUG, "STARTD: calling and resetting sweep_timer_handler()\n"); auto_free_ptr cred_dir(param("SEC_CREDENTIAL_DIRECTORY_KRB")); credmon_sweep_creds(cred_dir, credmon_type_KRB); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 300); daemonCore->Reset_Timer (m_cred_sweep_tid, sec_cred_sweep_interval, sec_cred_sweep_interval); } int ResMgr::start_sweep_timer( void ) { // only sweep if we have a cred dir auto_free_ptr p(param("SEC_CREDENTIAL_DIRECTORY_KRB")); if(!p) { return TRUE; } dprintf(D_FULLDEBUG, "STARTD: setting start_sweep_timer()\n"); int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 300); m_cred_sweep_tid = daemonCore->Register_Timer( sec_cred_sweep_interval, sec_cred_sweep_interval, (TimerHandlercpp)&ResMgr::sweep_timer_handler, "sweep_timer_handler", this ); return TRUE; } int ResMgr::start_update_timer( void ) { int initial_interval; if ( update_offset ) { initial_interval = update_offset; dprintf( D_FULLDEBUG, "Delaying initial update by %d seconds\n", update_offset ); } else { initial_interval = update_interval; update_all( ); } up_tid = daemonCore->Register_Timer( initial_interval, update_interval, (TimerHandlercpp)&ResMgr::eval_and_update_all, "eval_and_update_all", this ); if( up_tid < 0 ) { EXCEPT( "Can't register DaemonCore timer" ); } return TRUE; } int ResMgr::start_poll_timer( void ) { if( poll_tid >= 0 ) { // Timer already started. return TRUE; } poll_tid = daemonCore->Register_Timer( polling_interval, polling_interval, (TimerHandlercpp)&ResMgr::eval_all, "poll_resources", this ); if( poll_tid < 0 ) { EXCEPT( "Can't register DaemonCore timer" ); } dprintf( D_FULLDEBUG, "Started polling timer.\n" ); return TRUE; } void ResMgr::cancel_poll_timer( void ) { int rval; if( poll_tid != -1 ) { rval = daemonCore->Cancel_Timer( poll_tid ); if( rval < 0 ) { dprintf( D_ALWAYS, "Failed to cancel polling timer (%d): " "daemonCore error\n", poll_tid ); } else { dprintf( D_FULLDEBUG, "Canceled polling timer (%d)\n", poll_tid ); } poll_tid = -1; } } void ResMgr::reset_timers( void ) { if ( update_offset ) { dprintf( D_FULLDEBUG, "Delaying update after reconfig by %d seconds\n", update_offset ); } if( poll_tid != -1 ) { daemonCore->Reset_Timer( poll_tid, polling_interval, polling_interval ); } if( up_tid != -1 ) { daemonCore->Reset_Timer( up_tid, update_offset, update_interval ); } int sec_cred_sweep_interval = param_integer("SEC_CREDENTIAL_SWEEP_INTERVAL", 300); if( m_cred_sweep_tid != -1 ) { daemonCore->Reset_Timer( m_cred_sweep_tid, sec_cred_sweep_interval, sec_cred_sweep_interval ); } #if HAVE_HIBERNATION resetHibernateTimer(); #endif /* HAVE_HIBERNATE */ // Clear out any pending token requests. m_token_client_id = ""; m_token_request_id = ""; // This is a borrowed reference; do not delete. m_token_daemon = nullptr; } void ResMgr::addResource( Resource *rip ) { Resource** new_resources = NULL; if( !rip ) { EXCEPT("Error: attempt to add a NULL resource"); } calculateAffinityMask(rip); new_resources = new Resource*[nresources + 1]; if( !new_resources ) { EXCEPT("Failed to allocate memory for new resource"); } // Copy over the old Resource pointers. If nresources is 0 // (b/c we used to be configured to have no slots), this won't // copy anything (and won't seg fault). memcpy( (void*)new_resources, (void*)resources, (sizeof(Resource*)*nresources) ); new_resources[nresources] = rip; if( resources ) { delete [] resources; } resources = new_resources; nresources++; // if this newly added slot is part of a pair, fixup the pair pointers dprintf(D_FULLDEBUG, "Setting up slot pairings\n"); if (rip->r_pair_name && rip->r_pair_name[0] == '#') { int slot_type = atoi(rip->r_pair_name+1); dprintf(D_ALWAYS, "\t searching for type %d to pair with %s (%s)\n", slot_type, rip->r_id_str, rip->r_pair_name); for (int ix = 0; ix < nresources-1; ++ix) { Resource * ripT = resources[ix]; if (ripT->type() == slot_type) { if ( ! ripT->r_pair_name || ripT->r_pair_name[0] == '#') { // ok pair these two. free(rip->r_pair_name); free(ripT->r_pair_name); rip->r_pair_name = strdup(ripT->r_name); ripT->r_pair_name = strdup(rip->r_name); break; } } } } // If this newly added slot is dynamic, add it to // its parent's children if( rip->get_feature() == Resource::DYNAMIC_SLOT) { Resource *parent = rip->get_parent(); if (parent) { parent->add_dynamic_child(rip); } } } bool ResMgr::removeResource( Resource* rip ) { int i, j; Resource** new_resources = NULL; Resource* rip2; if( nresources > 1 ) { // There are still more resources after this one is // deleted, so we'll need to make a new resources array // without this resource. new_resources = new Resource* [ nresources - 1 ]; ASSERT(new_resources != NULL); j = 0; for( i = 0; i < nresources; i++ ) { if( resources[i] != rip ) { new_resources[j++] = resources[i]; } } if ( j == nresources ) { // j == i would work too // The resource was not found, which should never happen delete [] new_resources; return false; } } // Remove this rip from our destroy_list. destroy_list.Rewind(); while( destroy_list.Next(rip2) ) { if( rip2 == rip ) { destroy_list.DeleteCurrent(); break; } } // Now, delete the old array and start using the new one, if // it's there at all. If not, it'll be NULL and this will all // still be what we want. delete [] resources; resources = new_resources; nresources--; // Return this Resource's ID to the dispenser. // If it is a dynamic slot it's reusing its partitionable // parent's id, so we don't want to free the id. if( Resource::DYNAMIC_SLOT != rip->get_feature() ) { id_disp->insert( rip->r_id ); } // Tell the collector this Resource is gone. rip->final_update(); // If this was a dynamic slot, remove it from parent if( rip->get_feature() == Resource::DYNAMIC_SLOT) { Resource *parent = rip->get_parent(); if (parent) { parent->remove_dynamic_child(rip); } } // Log a message that we're going away rip->dprintf( D_ALWAYS, "Resource no longer needed, deleting\n" ); // At last, we can delete the object itself. delete rip; return true; } void ResMgr::calculateAffinityMask( Resource *rip) { int firstCore = 0; int numCores = m_attr->num_real_cpus(); numCores -= firstCore; int *coreOccupancy = new int[numCores]; for (int i = 0; i < numCores; i++) { coreOccupancy[i] = 0; } // Invert the slots' affinity mask to figure out // which cpu core is already used the least. for( int i = 0; i < nresources; i++ ) { std::list<int> *cores = resources[i]->get_affinity_set(); for (std::list<int>::iterator it = cores->begin(); it != cores->end(); it++) { int used_core_num = *it; if (used_core_num < numCores) { coreOccupancy[used_core_num]++; } } } int coresToAssign = rip->r_attr->num_cpus(); while (coresToAssign--) { int leastUsedCore = 0; int leastUsedCoreUsage = coreOccupancy[0]; for (int i = 0; i < numCores; i++) { if (coreOccupancy[i] < leastUsedCoreUsage) { leastUsedCore = i; leastUsedCoreUsage = coreOccupancy[i]; } } rip->get_affinity_set()->push_back(leastUsedCore); coreOccupancy[leastUsedCore]++; } delete [] coreOccupancy; } void ResMgr::deleteResource( Resource* rip ) { if( ! removeResource( rip ) ) { // Didn't find it. This is where we'll hit if resources // is NULL. We should never get here, anyway (we'll never // call deleteResource() if we don't have any resources. EXCEPT( "ResMgr::deleteResource() failed: couldn't find resource" ); } // Now that a Resource is gone, see if we're done deleting // Resources and see if we should allocate any. if( processAllocList() ) { // We're done allocating, so we can finish our reconfig. finish_main_config(); } } // return the count of claims on this machine associated with this user // used to decide when to delete credentials int ResMgr::claims_for_this_user(const char * user) { if ( ! user || ! user[0]) { return 0; } int num_matches = 0; for (int ii = 0; ii < nresources; ++ii) { Resource * res = resources[ii]; if (res && res->r_cur && res->r_cur->client() && res->r_cur->client()->user()) { if (MATCH == strcmp(res->r_cur->client()->user(), user)) { num_matches += 1; } } } return num_matches; } static void clean_private_attrs(ClassAd & ad) { for (auto i = ad.begin(); i != ad.end(); ++i) { const std::string & name = i->first; if (ClassAdAttributeIsPrivate(name)) { // TODO: redact these while still providing some info, perhaps return the HASH? ad.Assign(name, "<redacted>"); } } } void ResMgr::makeAdList( ClassAdList & list, ClassAd & queryAd ) { std::string stats_config; int dc_publish_flags = daemonCore->dc_stats.PublishFlags; queryAd.LookupString("STATISTICS_TO_PUBLISH",stats_config); if ( ! stats_config.empty()) { #if 0 // HACK to test swapping claims without a schedd dprintf(D_ALWAYS, "Got QUERY_STARTD_ADS with stats config: %s\n", stats_config.c_str()); if (starts_with_ignore_case(stats_config.c_str(), "swap:")) { StringList swap_args(stats_config.c_str()+5); hack_test_claim_swap(swap_args); } else #endif daemonCore->dc_stats.PublishFlags = generic_stats_ParseConfigString(stats_config.c_str(), "DC", "DAEMONCORE", dc_publish_flags); } bool snapshot = false; if (!queryAd.LookupBool("Snapshot", snapshot)) { snapshot = false; } int limit_results = -1; if (!queryAd.LookupInteger(ATTR_LIMIT_RESULTS, limit_results)) { limit_results = -1; } // Make sure everything is current unless we have been asked for a snapshot of the current internal state Resource::Purpose purp = Resource::Purpose::for_query; if (snapshot) { purp = Resource::Purpose::for_snap; } else { purp = Resource::Purpose::for_query; compute_dynamic(true); } // we will put the Machine ads we intend to return here temporarily std::map <YourString, ClassAd*, CaseIgnLTYourString> ads; // these get filled in with Resource and Job(Claim) ads only when snapshot == true std::map <YourString, ClassAd*, CaseIgnLTYourString> res_ads; std::map <YourString, ClassAd*, CaseIgnLTYourString> cfg_ads; std::map <YourString, ClassAd*, CaseIgnLTYourString> claim_ads; // We want to insert ATTR_LAST_HEARD_FROM into each ad. The // collector normally does this, so if we're servicing a // QUERY_STARTD_ADS commannd, we need to do this ourselves or // some timing stuff won't work. int num_ads = 0; for (int ii=0; ii<nresources; ++ii) { if (limit_results >= 0 && num_ads >= limit_results) { dprintf(D_ALWAYS, "result limit of %d reached, completing direct query\n", num_ads); break; } ClassAd * res_ad = NULL; if (snapshot && resources[ii]->r_classad) { resources[ii]->r_classad->Unchain(); res_ad = new ClassAd(*resources[ii]->r_classad); resources[ii]->r_classad->ChainToAd(resources[ii]->r_config_classad); SetMyTypeName(*res_ad, "Slot.State"); res_ad->Assign(ATTR_NAME, resources[ii]->r_name); // stuff a name because the name attribute is in the base ad } ClassAd * cfg_ad = NULL; if (snapshot && resources[ii]->r_config_classad) { cfg_ad = new ClassAd(*resources[ii]->r_config_classad); SetMyTypeName(*cfg_ad, "Slot.Config"); } ClassAd * claim_ad = NULL; if (snapshot && resources[ii]->r_cur && resources[ii]->r_cur->ad()) { claim_ad = new ClassAd(*resources[ii]->r_cur->ad()); clean_private_attrs(*claim_ad); SetMyTypeName(*claim_ad, "Slot.Claim"); } ClassAd * ad = new ClassAd; resources[ii]->publish_single_slot_ad(*ad, cur_time, purp); if (IsAHalfMatch(&queryAd, ad) /* || (claim_ad && IsAHalfMatch(&queryAd, claim_ad))*/) { ads[resources[ii]->r_name] = ad; if (res_ad) { res_ads[resources[ii]->r_name] = res_ad; } if (cfg_ad) { cfg_ads[resources[ii]->r_name] = cfg_ad; } if (claim_ad) { claim_ads[resources[ii]->r_name] = claim_ad; } ++num_ads; } else { delete ad; delete res_ad; delete cfg_ad; delete claim_ad; } } // put Machine ads and their associated snapshot ads into the return // as we do this we erase the snap ads so that we can detect any leftover snap ads if ( ! ads.empty()) { for (auto it = ads.begin(); it != ads.end(); ++it) { list.Insert(it->second); auto foundb = cfg_ads.find(it->first); if (foundb != cfg_ads.end()) { list.Insert(foundb->second); cfg_ads.erase(foundb); } auto foundr = res_ads.find(it->first); if (foundr != res_ads.end()) { list.Insert(foundr->second); res_ads.erase(foundr); } auto foundj = claim_ads.find(it->first); if (foundj != claim_ads.end()) { list.Insert(foundj->second); claim_ads.erase(foundj); } } } // also return any leftover snap ads, this puts leftover snap ads at the end for (auto it = res_ads.begin(); it != res_ads.end(); ++it) { list.Insert(it->second); } for (auto it = cfg_ads.begin(); it != cfg_ads.end(); ++it) { list.Insert(it->second); } for (auto it = claim_ads.begin(); it != claim_ads.end(); ++it) { list.Insert(it->second); } // also return the raw STARTD cron ads if (snapshot) { for (auto it = extra_ads.Enum().begin(); it != extra_ads.Enum().end(); ++it) { ClassAd * named_ad = (*it)->GetAd(); if (named_ad) { ClassAd * ad = new ClassAd(*named_ad); SetMyTypeName(*ad, "Machine.Extra"); ad->Assign(ATTR_NAME, (*it)->GetName()); list.Insert(ad); } } } // restore the dc stats publish flags if ( ! stats_config.empty()) { daemonCore->dc_stats.PublishFlags = dc_publish_flags; } } bool ResMgr::processAllocList( void ) { if( ! destroy_list.IsEmpty() ) { // Can't start allocating until everything has been // destroyed. return false; } if( alloc_list.IsEmpty() ) { return true; // Since there's nothing to allocate... } // We're done destroying, and there's something to allocate. bool multiple_slots = (alloc_list.Number() + numSlots()) > 1; // Create the new Resource objects. CpuAttributes* cap; alloc_list.Rewind(); while( alloc_list.Next(cap) ) { addResource( new Resource( cap, nextId(), multiple_slots ) ); alloc_list.DeleteCurrent(); } delete [] type_nums; type_nums = new_type_nums; new_type_nums = NULL; return true; // Since we're done allocating. } #if HAVE_HIBERNATION HibernationManager const& ResMgr::getHibernationManager(void) const { return *m_hibernation_manager; } void ResMgr::updateHibernateConfiguration() { m_hibernation_manager->update(); if ( m_hibernation_manager->wantsHibernate() ) { if ( -1 == m_hibernate_tid ) { startHibernateTimer(); } } else { if ( -1 != m_hibernate_tid ) { cancelHibernateTimer(); } } } int ResMgr::allHibernating( std::string &target ) const { // fail if there is no resource or if we are // configured not to hibernate if ( !resources || !m_hibernation_manager->wantsHibernate() ) { dprintf( D_FULLDEBUG, "allHibernating: doesn't want hibernate\n" ); return 0; } // The following may evaluate to true even if there // is a claim on one or more of the resources, so we // don't bother checking for claims first. // // We take largest value as the representative // hibernation level for this machine target = ""; std::string str; int level = 0; bool activity = false; for( int i = 0; i < nresources; i++ ) { str = ""; if ( !resources[i]->evaluateHibernate ( str ) ) { return 0; } int tmp = m_hibernation_manager->stringToSleepState ( str.c_str () ); dprintf ( D_FULLDEBUG, "allHibernating: resource #%d: '%s' (0x%x)\n", i + 1, str.c_str (), tmp ); if ( 0 == tmp ) { activity = true; } if ( tmp > level ) { target = str; level = tmp; } } return activity ? 0 : level; } void ResMgr::checkHibernate( void ) { // If we have already issued the command to hibernate, then // don't bother re-entering the check/evaluation. if ( hibernating () ) { return; } // If all resources have gone unused for some time // then put the machine to sleep std::string target; int level = allHibernating( target ); if( level > 0 ) { if( !m_hibernation_manager->canHibernate() ) { dprintf ( D_ALWAYS, "ResMgr: ERROR: Ignoring " "HIBERNATE: Machine does not support any " "sleep states.\n" ); return; } if( !m_hibernation_manager->canWake() ) { NetworkAdapterBase *netif = m_hibernation_manager->getNetworkAdapter(); if ( param_boolean( "HIBERNATION_OVERRIDE_WOL", false ) ) { dprintf ( D_ALWAYS, "ResMgr: " "HIBERNATE: Machine cannot be woken by its " "public network adapter (%s); hibernating anyway\n", netif->interfaceName() ); } else { dprintf ( D_ALWAYS, "ResMgr: ERROR: Ignoring " "HIBERNATE: Machine cannot be woken by its " "public network adapter (%s).\n", netif->interfaceName() ); return; } } dprintf ( D_ALWAYS, "ResMgr: This machine is about to " "enter hibernation\n" ); // // Set the hibernation state, shutdown the machine's slot // and hibernate the machine. We turn off the local slots // so the StartD will remove any jobs that are currently // running as well as stop accepting new ones, since--on // Windows anyway--there is the possibility that a job // may be matched to this machine between the time it // is told hibernate and the time it actually does. // // Setting the state here also ensures the Green Computing // plug-in will know the this ad belongs to it when the // Collector invalidates it. // if ( disableResources( target ) ) { m_hibernation_manager->switchToTargetState( ); } # if !defined( WIN32 ) sleep(10); m_hibernation_manager->setTargetState ( HibernatorBase::NONE ); for ( int i = 0; i < nresources; ++i ) { resources[i]->enable(); resources[i]->update(); m_hibernating = false; } # endif } } int ResMgr::startHibernateTimer( void ) { int interval = m_hibernation_manager->getCheckInterval(); m_hibernate_tid = daemonCore->Register_Timer( interval, interval, (TimerHandlercpp)&ResMgr::checkHibernate, "ResMgr::startHibernateTimer()", this ); if( m_hibernate_tid < 0 ) { EXCEPT( "Can't register hibernation timer" ); } dprintf( D_FULLDEBUG, "Started hibernation timer.\n" ); return TRUE; } void ResMgr::resetHibernateTimer( void ) { if ( m_hibernation_manager->wantsHibernate() ) { if( m_hibernate_tid != -1 ) { int interval = m_hibernation_manager->getCheckInterval(); daemonCore->Reset_Timer( m_hibernate_tid, interval, interval ); } } } void ResMgr::cancelHibernateTimer( void ) { int rval; if( m_hibernate_tid != -1 ) { rval = daemonCore->Cancel_Timer( m_hibernate_tid ); if( rval < 0 ) { dprintf( D_ALWAYS, "Failed to cancel hibernation timer (%d): " "daemonCore error\n", m_hibernate_tid ); } else { dprintf( D_FULLDEBUG, "Canceled hibernation timer (%d)\n", m_hibernate_tid ); } m_hibernate_tid = -1; } } int ResMgr::disableResources( const std::string &state_str ) { dprintf ( D_FULLDEBUG, "In ResMgr::disableResources ()\n" ); int i; /* stupid VC6 */ /* set the sleep state so the plugin will pickup on the fact that we are sleeping */ m_hibernation_manager->setTargetState ( state_str.c_str() ); /* update the CM */ bool ok = true; for ( i = 0; i < nresources && ok; ++i ) { ok = resources[i]->update_with_ack(); } dprintf ( D_FULLDEBUG, "All resources disabled: %s.\n", ok ? "yes" : "no" ); /* if any of the updates failed, then re-enable all the resources and try again later (next time HIBERNATE evaluates to a value>0) */ if ( !ok ) { m_hibernation_manager->setTargetState ( HibernatorBase::NONE ); } else { /* Boot off any running jobs and disable all resource on this machine so we don't allow new jobs to start while we are in the middle of hibernating. We disable _after_ sending our update_with_ack(), because we want our machine to still be matchable while broken. The negotiator knows to treat this state specially. */ for ( i = 0; i < nresources; ++i ) { resources[i]->disable(); } } dprintf ( D_FULLDEBUG, "All resources disabled: %s.\n", ok ? "yes" : "no" ); /* record if we we are hibernating or not */ m_hibernating = ok; return ok; } bool ResMgr::hibernating () const { return m_hibernating; } #endif /* HAVE_HIBERNATION */ void ResMgr::check_use( void ) { int current_time = time(NULL); if( hasAnyClaim() ) { last_in_use = current_time; } if( ! startd_noclaim_shutdown ) { // Nothing to do. return; } if( current_time - last_in_use > startd_noclaim_shutdown ) { // We've been unused for too long, send a SIGTERM to our // parent, the condor_master. dprintf( D_ALWAYS, "No resources have been claimed for %d seconds\n", startd_noclaim_shutdown ); dprintf( D_ALWAYS, "Shutting down Condor on this machine.\n" ); daemonCore->Send_Signal( daemonCore->getppid(), SIGTERM ); } } int naturalSlotOrderCmp( const void* a, const void* b ) { const Resource *rip1 = *((Resource* const *)a); const Resource *rip2 = *((Resource* const *)b); int diff = rip1->r_id - rip2->r_id; if (diff) { return diff; } return rip1->r_sub_id - rip2->r_sub_id; } int ownerStateCmp( const void* a, const void* b ) { const Resource *rip1, *rip2; int val1, val2, diff; float fval1, fval2; State s; rip1 = *((Resource* const *)a); rip2 = *((Resource* const *)b); // Since the State enum is already in the "right" order for // this kind of sort, we don't need to do anything fancy, we // just cast the state enum to an int and we're done. s = rip1->state(); val1 = (int)s; val2 = (int)rip2->state(); diff = val1 - val2; if( diff ) { return diff; } // We're still here, means we've got the same state. If that // state is "Claimed" or "Preempting", we want to break ties // w/ the Rank expression, else, don't worry about ties. if( s == claimed_state || s == preempting_state ) { fval1 = rip1->r_cur->rank(); fval2 = rip2->r_cur->rank(); diff = (int)(fval1 - fval2); return diff; } return 0; } // This is basically the same as above, except we want it in exactly // the opposite order, so reverse the signs. int claimedRankCmp( const void* a, const void* b ) { const Resource *rip1, *rip2; int val1, val2, diff; float fval1, fval2; State s; rip1 = *((Resource* const *)a); rip2 = *((Resource* const *)b); s = rip1->state(); val1 = (int)s; val2 = (int)rip2->state(); diff = val2 - val1; if( diff ) { return diff; } // We're still here, means we've got the same state. If that // state is "Claimed" or "Preempting", we want to break ties // w/ the Rank expression, else, don't worry about ties. if( s == claimed_state || s == preempting_state ) { fval1 = rip1->r_cur->rank(); fval2 = rip2->r_cur->rank(); diff = (int)(fval2 - fval1); return diff; } return 0; } /* Sort resource so their in the right order to give out a new COD Claim. We give out COD claims in the following order: 1) the Resource with the least # of existing COD claims (to ensure round-robin across resources 2) in case of a tie, the Resource in the best state (owner or unclaimed, not claimed) 3) in case of a tie, the Claimed resource with the lowest value of machine Rank for its claim */ int newCODClaimCmp( const void* a, const void* b ) { const Resource *rip1, *rip2; int val1, val2, diff; int numCOD1, numCOD2; float fval1, fval2; State s; rip1 = *((Resource* const *)a); rip2 = *((Resource* const *)b); numCOD1 = rip1->r_cod_mgr->numClaims(); numCOD2 = rip2->r_cod_mgr->numClaims(); // In the first case, sort based on # of COD claims diff = numCOD1 - numCOD2; if( diff ) { return diff; } // If we're still here, we've got same # of COD claims, so // sort based on State. Since the state enum is already in // the "right" order for this kind of sort, we don't need to // do anything fancy, we just cast the state enum to an int // and we're done. s = rip1->state(); val1 = (int)s; val2 = (int)rip2->state(); diff = val1 - val2; if( diff ) { return diff; } // We're still here, means we've got the same number of COD // claims and the same state. If that state is "Claimed" or // "Preempting", we want to break ties w/ the Rank expression, // else, don't worry about ties. if( s == claimed_state || s == preempting_state ) { fval1 = rip1->r_cur->rank(); fval2 = rip2->r_cur->rank(); diff = (int)(fval1 - fval2); return diff; } return 0; } void ResMgr::FillExecuteDirsList( class StringList *list ) { ASSERT( list ); for( int i=0; i<nresources; i++ ) { if( resources[i] ) { char const *execute_dir = resources[i]->executeDir(); if( !list->contains( execute_dir ) ) { list->append(execute_dir); } } } } ExprTree * globalDrainingStartExpr = NULL; bool ResMgr::startDraining( int how_fast, const std::string & reason, int on_completion, ExprTree *check_expr, ExprTree *start_expr, std::string &new_request_id, std::string &error_msg, int &error_code) { // For now, let's assume that that you never want to change the start // expression while draining. if( draining ) { new_request_id = ""; error_msg = "Draining already in progress."; error_code = DRAINING_ALREADY_IN_PROGRESS; return false; } if( check_expr ) { for( int i = 0; i < nresources; i++ ) { classad::Value v; bool check_ok = false; classad::EvalState eval_state; eval_state.SetScopes( resources[i]->r_classad ); if( !check_expr->Evaluate( eval_state, v ) ) { formatstr(error_msg,"Failed to evaluate draining check expression against %s.", resources[i]->r_name ); error_code = DRAINING_CHECK_EXPR_FAILED; return false; } if( !v.IsBooleanValue(check_ok) ) { formatstr(error_msg,"Draining check expression does not evaluate to a bool on %s.", resources[i]->r_name ); error_code = DRAINING_CHECK_EXPR_FAILED; return false; } if( !check_ok ) { formatstr(error_msg,"Draining check expression is false on %s.", resources[i]->r_name ); error_code = DRAINING_CHECK_EXPR_FAILED; return false; } } } draining = true; last_drain_start_time = time(NULL); draining_id += 1; formatstr(new_request_id,"%d",draining_id); this->on_completion_of_draining = on_completion; this->drain_reason = reason; // Insert draining attributes into the resource ads, in case the // retirement expression uses them. for( int i = 0; i < nresources; i++ ) { ClassAd &ad = *(resources[i]->r_classad); // put these into the resources ClassAd now, they are also set by this->publish ad.InsertAttr( ATTR_DRAIN_REASON, reason ); ad.InsertAttr( ATTR_DRAINING, true ); ad.InsertAttr( ATTR_DRAINING_REQUEST_ID, new_request_id ); ad.InsertAttr( ATTR_LAST_DRAIN_START_TIME, last_drain_start_time ); ad.InsertAttr( ATTR_LAST_DRAIN_STOP_TIME, last_drain_stop_time ); } if( how_fast <= DRAIN_GRACEFUL ) { // retirement time and vacate time are honored draining_is_graceful = true; int graceful_retirement = gracefulDrainingTimeRemaining(); dprintf(D_ALWAYS,"Initiating graceful draining.\n"); if( graceful_retirement > 0 ) { dprintf(D_ALWAYS, "Coordinating retirement of draining slots; retirement of all draining slots ends in %ds.\n", graceful_retirement); } // we do not know yet if these jobs will be evicted or if // they will finish within their retirement time, so do // not call setBadputCausedByDraining() yet // Even if we could pass start_expr through walk(), it turns out, // beceause ResState::enter_action() calls unavail() as well, we // really do need to keep the global. To that end, we /want/ to // assign the NULL value here if that's what we got, so that we // do the right thing if we drain without a START expression after // draining with one. delete globalDrainingStartExpr; if (start_expr) { globalDrainingStartExpr = start_expr->Copy(); } else { ConstraintHolder start(param("DEFAULT_DRAINING_START_EXPR")); if (!start.empty() && !start.Expr()) { dprintf(D_ALWAYS, "Warning: DEFAULT_DRAINING_START_EXPR is not valid : %s\n", start.c_str()); } // if empty or invalid, detach() returns NULL, which is what we want here if the expr is invalid globalDrainingStartExpr = start.detach(); } walk(&Resource::releaseAllClaimsReversibly); } else if( how_fast <= DRAIN_QUICK ) { // retirement time will not be honored, but vacate time will dprintf(D_ALWAYS,"Initiating quick draining.\n"); draining_is_graceful = false; walk(&Resource::setBadputCausedByDraining); walk(&Resource::releaseAllClaims); } else if( how_fast > DRAIN_QUICK ) { // DRAIN_FAST // neither retirement time nor vacate time will be honored dprintf(D_ALWAYS,"Initiating fast draining.\n"); draining_is_graceful = false; walk(&Resource::setBadputCausedByDraining); walk(&Resource::killAllClaims); } update_all(); return true; } bool ResMgr::cancelDraining(std::string request_id,std::string &error_msg,int &error_code) { if( !this->draining ) { if( request_id.empty() ) { return true; } } if( !request_id.empty() && atoi(request_id.c_str()) != this->draining_id ) { formatstr(error_msg,"No matching draining request id %s.",request_id.c_str()); error_code = DRAINING_NO_MATCHING_REQUEST_ID; return false; } draining = false; drain_reason.clear(); // If we want to record when a non-resuming drain actually finished, we // should only call this here if we've started draining since the last // time we stopped. // if( last_drain_start_time > last_drain_stop_time ) { setLastDrainStopTime(); } setLastDrainStopTime(); walk(&Resource::enable); update_all(); return true; } bool ResMgr::isSlotDraining(Resource * /*rip*/) const { return draining; } int ResMgr::gracefulDrainingTimeRemaining() { return gracefulDrainingTimeRemaining(NULL); } int ResMgr::gracefulDrainingTimeRemaining(Resource * /*rip*/) { if( !draining || !draining_is_graceful ) { return 0; } // If we have 100s of slots, we may want to cache the // result of the following computation to avoid // poor scaling. For now, we just compute it every // time. int longest_retirement_remaining = 0; for( int i = 0; i < nresources; i++ ) { // The max job retirement time of jobs accepted while draining is // implicitly zero. Otherwise, we'd need to record the result of // this computation at the instant we entered draining state and // set a timer to vacate all slots at that point. This would // probably be more efficient, but would be a small semantic change, // because jobs would no longer be able to voluntarily reduce their // max job retirement time after retirement began. if(! resources[i]->wasAcceptedWhileDraining()) { int retirement_remaining = resources[i]->evalRetirementRemaining(); if( retirement_remaining > longest_retirement_remaining ) { longest_retirement_remaining = retirement_remaining; } } } return longest_retirement_remaining; } bool ResMgr::drainingIsComplete(Resource * /*rip*/) { if( !draining ) { return false; } for( int i = 0; i < nresources; i++ ) { if( resources[i]->state() != drained_state ) { return false; } } return true; } bool ResMgr::considerResumingAfterDraining() { if( !draining || !on_completion_of_draining ) { return false; } for( int i = 0; i < nresources; i++ ) { if( resources[i]->state() != drained_state || resources[i]->activity() != idle_act ) { return false; } } if (on_completion_of_draining != DRAIN_RESUME_ON_COMPLETION) { bool restart = (on_completion_of_draining != DRAIN_EXIT_ON_COMPLETION); dprintf(D_ALWAYS,"As specified in draining request, %s after completion of draining.\n", restart ? "restarting" : "exiting"); const bool fast = false; daemonCore->beginDaemonRestart(fast, restart); return true; } dprintf(D_ALWAYS,"As specified in draining request, resuming normal operation after completion of draining.\n"); std::string error_msg; int error_code = 0; if( !cancelDraining("",error_msg,error_code) ) { // should never happen! EXCEPT("failed to cancel draining: (code %d) %s",error_code,error_msg.c_str()); } return true; } void ResMgr::publish_draining_attrs(Resource *rip, ClassAd *cap) { if( isSlotDraining(rip) ) { cap->Assign( ATTR_DRAINING, true ); cap->Assign(ATTR_DRAIN_REASON, this->drain_reason); std::string request_id; if (draining) { formatstr(request_id, "%d", draining_id); } cap->Assign( ATTR_DRAINING_REQUEST_ID, request_id ); } else { // in case we are writing into resource->r_classad, do a deep delete caDeleteThruParent(cap, ATTR_DRAINING); caDeleteThruParent(cap, ATTR_DRAIN_REASON); caDeleteThruParent(cap, ATTR_DRAINING_REQUEST_ID ); } cap->Assign( ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_BADPUT, expected_graceful_draining_badput ); cap->Assign( ATTR_EXPECTED_MACHINE_QUICK_DRAINING_BADPUT, expected_quick_draining_badput ); cap->Assign( ATTR_EXPECTED_MACHINE_GRACEFUL_DRAINING_COMPLETION, expected_graceful_draining_completion ); cap->Assign( ATTR_EXPECTED_MACHINE_QUICK_DRAINING_COMPLETION, expected_quick_draining_completion ); if( total_draining_badput ) { cap->Assign( ATTR_TOTAL_MACHINE_DRAINING_BADPUT, total_draining_badput ); } if( total_draining_unclaimed ) { cap->Assign( ATTR_TOTAL_MACHINE_DRAINING_UNCLAIMED_TIME, total_draining_unclaimed ); } if( last_drain_start_time != 0 ) { cap->Assign( ATTR_LAST_DRAIN_START_TIME, (int)last_drain_start_time ); } if( last_drain_stop_time != 0 ) { cap->Assign( ATTR_LAST_DRAIN_STOP_TIME, (int)last_drain_stop_time ); } } void ResMgr::compute_draining_attrs() { // Using long long for int math in this function so // MaxJobRetirementTime=MAX_INT or MaxVacateTime=MAX_INT do // not cause overflow. long long ll_expected_graceful_draining_completion = 0; long long ll_expected_quick_draining_completion = 0; long long ll_expected_graceful_draining_badput = 0; long long ll_expected_quick_draining_badput = 0; long long ll_total_draining_unclaimed = 0; bool is_drained = true; for( int i = 0; i < nresources; i++ ) { Resource *rip = resources[i]; if( rip->r_cur ) { long long runtime = rip->r_cur->getJobTotalRunTime(); long long retirement_remaining = rip->evalRetirementRemaining(); long long max_vacate_time = rip->evalMaxVacateTime(); long long cpus = rip->r_attr->num_cpus(); if (rip->r_cur->isActive()) { is_drained = false; } ll_expected_quick_draining_badput += cpus*(runtime + max_vacate_time); ll_expected_graceful_draining_badput += cpus*runtime; int graceful_time_remaining; if( retirement_remaining < max_vacate_time ) { // vacate would happen immediately graceful_time_remaining = max_vacate_time; } else { // vacate would be delayed to finish by end of retirement graceful_time_remaining = retirement_remaining; } ll_expected_graceful_draining_badput += cpus*graceful_time_remaining; if( graceful_time_remaining > ll_expected_graceful_draining_completion ) { ll_expected_graceful_draining_completion = graceful_time_remaining; } if( max_vacate_time > ll_expected_quick_draining_completion ) { ll_expected_quick_draining_completion = max_vacate_time; } ll_total_draining_unclaimed += rip->r_state->timeDrainingUnclaimed(); } } if (is_drained) { // once the slot is drained we only want to change the expected completion time // if we have never set it before, or if we finished draining early. if (0 == expected_graceful_draining_completion || expected_graceful_draining_completion > cur_time) expected_graceful_draining_completion = cur_time; if (0 == expected_quick_draining_completion || expected_quick_draining_completion > cur_time) expected_quick_draining_completion = cur_time; } else { // convert time estimates from relative time to absolute time ll_expected_graceful_draining_completion += cur_time; ll_expected_quick_draining_completion += cur_time; expected_graceful_draining_completion = cap_int(ll_expected_graceful_draining_completion); expected_quick_draining_completion = cap_int(ll_expected_quick_draining_completion); } expected_graceful_draining_badput = cap_int(ll_expected_graceful_draining_badput); expected_quick_draining_badput = cap_int(ll_expected_quick_draining_badput); total_draining_unclaimed = cap_int(ll_total_draining_unclaimed); } void ResMgr::addToDrainingBadput( int badput ) { total_draining_badput += badput; } void ResMgr::adlist_reset_monitors( unsigned r_id, ClassAd * forWhom ) { extra_ads.reset_monitors( r_id, forWhom ); } void ResMgr::adlist_unset_monitors( unsigned r_id, ClassAd * forWhom ) { extra_ads.unset_monitors( r_id, forWhom ); } void ResMgr::checkForDrainCompletion() { if( ! resources ) { return; } bool allAcceptedWhileDraining = true; for( int i = 0; i < nresources; ++i ) { if(! resources[i]->wasAcceptedWhileDraining()) { // Not sure how COD and draining are supposed to interact, but // the partitionable slot is never accepted-while-draining, // nor claimed, nor should it block drain from completing. if(! resources[i]->hasAnyClaim()) { continue; } allAcceptedWhileDraining = false; } } if(! allAcceptedWhileDraining) { return; } dprintf( D_ALWAYS, "Initiating final draining (all original jobs complete).\n" ); // This (auto-reversibly) sets START to false when we release all claims. delete globalDrainingStartExpr; globalDrainingStartExpr = NULL; // Invalidate all claim IDs. This prevents the schedd from claiming // resources that were negotiated before draining finished. walk( &Resource::invalidateAllClaimIDs ); // Set MAXJOBRETIREMENTTIME to 0. This will be reset in ResState::eval() // when draining completes. this->max_job_retirement_time_override = 0; walk( & Resource::refresh_draining_attrs ); // Initiate final draining. walk( & Resource::releaseAllClaimsReversibly ); } void ResMgr::token_request_callback(bool success, void *miscdata) { auto self = reinterpret_cast<ResMgr *>(miscdata); // In the successful case, instantly re-fire the timer // that will send an update to the collector. if (success && (self->up_tid != -1)) { daemonCore->Reset_Timer( self->up_tid, update_offset, update_interval ); } } bool OtherSlotEval( const char * name, const classad::ArgumentList &arg_list, classad::EvalState &state, classad::Value &result) { classad::Value arg; std::string slotname; ASSERT( resmgr ); dprintf(D_MACHINE|D_VERBOSE, "OtherSlotEval called\n"); // Must have two argument if ( arg_list.size() != 2 ) { result.SetErrorValue(); return( true ); } // Evaluate slotname argument if( !arg_list[0]->Evaluate( state, arg ) ) { result.SetErrorValue(); return false; } // If argument isn't a string, then the result is an error. if( !arg.IsStringValue( slotname ) ) { result.SetErrorValue(); return true; } // this is an invocation intended to produce a slot<n>_<attr> name if (*name == '*') { classad::ExprTree * expr = arg_list[1]; if (! expr) { result.SetErrorValue(); } else { std::string attr(""); if (!ExprTreeIsAttrRef(expr, attr)) { attr = "expr_"; } slotname += "_"; slotname += attr; result.SetStringValue(slotname); } return true; } Resource* res = resmgr->get_by_name_prefix(slotname.c_str()); if (! res) { result.SetUndefinedValue(); dprintf(D_MACHINE|D_VERBOSE, "OtherSlotEval(%s) - slot not found\n", slotname.c_str()); } else { classad::ExprTree * expr = arg_list[1]; if (! expr) { result.SetErrorValue(); dprintf(D_MACHINE|D_VERBOSE, "OtherSlotEval(%s) - empty expr\n", slotname.c_str()); } else { std::string attr(""); if (ExprTreeIsAttrRef(expr, attr) && starts_with_ignore_case(attr, "Child") && false) { // fetch attr, but disable special Child* processing attr = attr.substr(5); // strip "Child" prefix #if 0 // TODO: parse expr and insert it into result value, or change rollup so it returns an ExprList? std::string expr; res->rollupChildAttrs(expr, attr); classad_shared_ptr<classad::ExprList> lst( new classad::ExprList() ); ASSERT(lst); //lst->push_back(classad::Literal::MakeLiteral(first)); result.SetSListValue(lst); #endif } else { const classad::ClassAd * parent = expr->GetParentScope(); res->r_classad->EvaluateExpr(expr, result); expr->SetParentScope(parent); // put the parent scope back to where it was if (IsDebugCatAndVerbosity((D_MACHINE|D_VERBOSE))) { dprintf(D_MACHINE|D_VERBOSE, "OtherSlotEval(%s,expr) %s evalutes to %s\n", slotname.c_str(), attr.c_str(), ClassAdValueToString(result)); } } } } return true; } // check to see if an expr tree is just a single SlotEval function call bool ExprTreeIsSlotEval(classad::ExprTree * tree) { if (! tree || tree->GetKind() != classad::ExprTree::FN_CALL_NODE) return false; std::string fnName; std::vector<classad::ExprTree*> args; ((const classad::FunctionCall*)tree)->GetComponents( fnName, args ); return (MATCH == strcasecmp(fnName.c_str(), "SlotEval")); } // walk an ExprTree, calling a function each time a ATTRREF_NODE is found. // int ExprHasSlotEval(classad::ExprTree * tree) { int iret = 0; if ( ! tree) return 0; switch (tree->GetKind()) { case classad::ExprTree::LITERAL_NODE: break; case classad::ExprTree::ATTRREF_NODE: { const classad::AttributeReference* atref = reinterpret_cast<const classad::AttributeReference*>(tree); classad::ExprTree *expr; std::string ref; std::string tmp; bool absolute; atref->GetComponents(expr, ref, absolute); // if there is a non-trivial left hand side (something other than X from X.Y attrib ref) // then recurse it. if (expr && ! ExprTreeIsAttrRef(expr, tmp)) { iret += ExprHasSlotEval(expr); } } break; case classad::ExprTree::OP_NODE: { classad::Operation::OpKind op; classad::ExprTree *t1, *t2, *t3; ((const classad::Operation*)tree)->GetComponents( op, t1, t2, t3 ); if (t1) iret += ExprHasSlotEval(t1); //if (iret && stop_on_first_match) return iret; if (t2) iret += ExprHasSlotEval(t2); //if (iret && stop_on_first_match) return iret; if (t3) iret += ExprHasSlotEval(t3); } break; case classad::ExprTree::FN_CALL_NODE: { std::string fnName; std::vector<classad::ExprTree*> args; ((const classad::FunctionCall*)tree)->GetComponents( fnName, args ); if (MATCH == strcasecmp(fnName.c_str(), "SlotEval")) { iret += 1; break; // no need to look deeper } for (std::vector<classad::ExprTree*>::iterator it = args.begin(); it != args.end(); ++it) { iret += ExprHasSlotEval(*it); if (iret) return iret; } } break; case classad::ExprTree::CLASSAD_NODE: { std::vector< std::pair<std::string, classad::ExprTree*> > attrs; ((const classad::ClassAd*)tree)->GetComponents(attrs); for (std::vector< std::pair<std::string, classad::ExprTree*> >::iterator it = attrs.begin(); it != attrs.end(); ++it) { iret += ExprHasSlotEval(it->second); if (iret) return iret; } } break; case classad::ExprTree::EXPR_LIST_NODE: { std::vector<classad::ExprTree*> exprs; ((const classad::ExprList*)tree)->GetComponents( exprs ); for (std::vector<classad::ExprTree*>::iterator it = exprs.begin(); it != exprs.end(); ++it) { iret += ExprHasSlotEval(*it); if (iret) return iret; } } break; case classad::ExprTree::EXPR_ENVELOPE: { classad::ExprTree * expr = SkipExprEnvelope(const_cast<classad::ExprTree*>(tree)); if (expr) iret += ExprHasSlotEval(expr); } break; default: // unknown or unallowed node. ASSERT(0); break; } return iret; }
#include "../cpudef.asm" move r1, 5 move r2, 3 add r1, r2 add r1, 2 if.ne r1, 10 error halt
// // write_at.hpp // ~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_WRITE_AT_HPP #define ASIO_WRITE_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "RCF/external/asio/asio/detail/config.hpp" #include <cstddef> #include <boost/cstdint.hpp> #include "RCF/external/asio/asio/basic_streambuf_fwd.hpp" #include "RCF/external/asio/asio/error.hpp" #include "RCF/external/asio/asio/detail/push_options.hpp" namespace asio { /** * @defgroup write_at asio::write_at * * @brief Write a certain amount of data at a specified offset before returning. */ /*@{*/ /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write_at(d, 42, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, offset, buffers, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, const ConstBufferSequence& buffers); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::write_at(d, 42, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. The sum * of the buffer sizes indicates the maximum number of bytes to write to the * device. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec); #if !defined(BOOST_NO_IOSTREAM) /// Write all of the supplied data at the specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::write_at( * d, 42, b, * asio::transfer_all()); @endcode */ template <typename SyncRandomAccessWriteDevice, typename Allocator> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, basic_streambuf<Allocator>& b); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition); /// Write a certain amount of data at a specified offset before returning. /** * This function is used to write a certain number of bytes of data to a random * access device at a specified offset. The call will block until one of the * following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * write_some_at function. * * @param d The device to which the data is to be written. The type must support * the SyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b The basic_streambuf object from which data will be written. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's write_some_at function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition> std::size_t write_at(SyncRandomAccessWriteDevice& d, boost::uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec); #endif // !defined(BOOST_NO_IOSTREAM) /*@}*/ /** * @defgroup async_write_at asio::async_write_at * * @brief Start an asynchronous operation to write a certain amount of data at * the specified offset. */ /*@{*/ /// Start an asynchronous operation to write all of the supplied data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. The function call * always returns immediately. The asynchronous operation will continue until * one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of * the handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * asio::async_write_at(d, 42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename AsyncRandomAccessWriteDevice, typename ConstBufferSequence, typename WriteHandler> void async_write_at(AsyncRandomAccessWriteDevice& d, boost::uint64_t offset, const ConstBufferSequence& buffers, WriteHandler handler); /// Start an asynchronous operation to write a certain amount of data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. The function call * always returns immediately. The asynchronous operation will continue until * one of the following conditions is true: * * @li All of the data in the supplied buffers has been written. That is, the * bytes transferred is equal to the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param buffers One or more buffers containing the data to be written. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's async_write_some_at function. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code asio::async_write_at(d, 42, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename AsyncRandomAccessWriteDevice, typename ConstBufferSequence, typename CompletionCondition, typename WriteHandler> void async_write_at(AsyncRandomAccessWriteDevice& d, boost::uint64_t offset, const ConstBufferSequence& buffers, CompletionCondition completion_condition, WriteHandler handler); #if !defined(BOOST_NO_IOSTREAM) /// Start an asynchronous operation to write all of the supplied data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. The function call * always returns immediately. The asynchronous operation will continue until * one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). */ template <typename AsyncRandomAccessWriteDevice, typename Allocator, typename WriteHandler> void async_write_at(AsyncRandomAccessWriteDevice& d, boost::uint64_t offset, basic_streambuf<Allocator>& b, WriteHandler handler); /// Start an asynchronous operation to write a certain amount of data at the /// specified offset. /** * This function is used to asynchronously write a certain number of bytes of * data to a random access device at a specified offset. The function call * always returns immediately. The asynchronous operation will continue until * one of the following conditions is true: * * @li All of the data in the supplied basic_streambuf has been written. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the device's * async_write_some_at function. * * @param d The device to which the data is to be written. The type must support * the AsyncRandomAccessWriteDevice concept. * * @param offset The offset at which the data will be written. * * @param b A basic_streambuf object from which data will be written. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the write operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_write_some_at operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the write operation is complete. A * non-zero return value indicates the maximum number of bytes to be written on * the next call to the device's async_write_some_at function. * * @param handler The handler to be called when the write operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes written from the buffers. If an error * // occurred, this will be less than the sum of the buffer sizes. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). */ template <typename AsyncRandomAccessWriteDevice, typename Allocator, typename CompletionCondition, typename WriteHandler> void async_write_at(AsyncRandomAccessWriteDevice& d, boost::uint64_t offset, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, WriteHandler handler); #endif // !defined(BOOST_NO_IOSTREAM) /*@}*/ } // namespace asio #include "RCF/external/asio/asio/detail/pop_options.hpp" #include "RCF/external/asio/asio/impl/write_at.hpp" #endif // ASIO_WRITE_AT_HPP
; A101875: Number of Abelian groups of order 4n+2. ; 1,1,1,1,2,1,1,1,1,1,1,1,2,3,1,1,1,1,1,1,1,1,2,1,2,1,1,1,1,1,1,2,1,1,1,1,1,2,1,1,5,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,2,1,2,1,3,1,1,1,1,3,1,1,1,1,1,2,1,1,2,1,1,1,1,1,1,1,2,2,1,2,1,1,1,1,1,1,3,1,1,1,1,1 mul $0,2 seq $0,46660 ; Excess of n = number of prime divisors (with multiplicity) - number of prime divisors (without multiplicity). seq $0,65090 ; Natural numbers which are not odd primes: composites plus 1 and 2. add $0,1 mul $0,19 div $0,26
include w2.inc include noxport.inc include consts.inc include structs.inc createSeg exp_PCODE,exp,byte,public,CODE ; DEBUGGING DECLARATIONS ; EXTERNAL FUNCTIONS externFP <CbAllocSb, CbReallocSb, FreeSb, ReloadSb, CbSizeSb> sBegin data ; EXTERNALS externW mpsbps externW sbMac sEnd data ; CODE SEGMENT _EXP sBegin exp assumes cs,exp assumes ds,dgroup assumes ss,dgroup ;------------------------------------------------------------------------- ; LPushMacroArgs (qProc, rgw, cw) ;------------------------------------------------------------------------- ; %%Function:LPushMacroArgs %%Owner:bradch cProc LPushMacroArgs,<PUBLIC,FAR>,<si,di> ParmD <qProc> ParmW <rgw> ParmW <cw> cBegin mov di,sp mov si,[rgw] mov cx,[cw] jcxz PMA04 PMA03: lodsw push ax loop PMA03 PMA04: call dword ptr ([qProc]) mov sp,di cEnd ;------------------------------------------------------------------------- ; MemUsed (memType) ; ; memType = 1 for conventional, 2 for expanded, 3 for both ; ; Taken directly from Excel's memutil.asm. 8/12/88 TDK. ;------------------------------------------------------------------------- ; %%Function:MemUsed %%Owner:bradch cProc MemUsed,<PUBLIC,FAR>,<si,di> ParmW memType cBegin xor si,si xor di,di mov bx,1 dec bx mf1a: inc bx cmp bx,[sbMac] jae mfx shl bx,1 mov cx,[bx+mpsbps] shr bx,1 jcxz mf1a push bx cCall CbSizeSb,<bx> pop bx ; ; Determine if memory is conventional or expanded ; mov cl,00000001b ; assume conventional or dx,dx ; no Emm, must be conventional jz mf1c mov cl,00000010b ; mark as expanded mf1c: test byte ptr (memType),cl jz mf1a add si,ax adc di,0 jmp mf1a mfx: mov ax,si mov dx,di cEnd sEnd exp end
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The LightPayCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingLeft = 14; int paddingTop = 465; int titleVersionVSpace = 17; int titleCopyrightVSpace = 32; float fontFactor = 1.0; // define text to place QString titleText = tr("Rubika Core"); QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion())); QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers")); QString copyrightTextPivx = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PIVX Core developers")); QString copyrightTextLpc = QChar(0xA9) + QString(tr(" 2018 The LightPayCoin Core developers")); QString copyrightTextRbk = QChar(0xA9) + QString(tr(" 2018 The Rubika Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // load the bitmap for writing some text over it pixmap = networkStyle->getSplashImage(); QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100, 100, 100)); // check font size and drawing with pixPaint.setFont(QFont(font, 28 * fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 25 * fontFactor)); fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); pixPaint.drawText(paddingLeft, paddingTop, titleText); pixPaint.setFont(QFont(font, 15 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPivx); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 36, copyrightTextLpc); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 48, copyrightTextRbk); // draw additional text if special network if (!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10 * fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), pixmap.size()); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget* mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen* splash, const std::string& message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter), Q_ARG(QColor, QColor(100, 100, 100))); } static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen* splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent* event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
.include "defaults_mod.asm" table_file_jp equ "exe4-utf8.tbl" table_file_en equ "bn4-utf8.tbl" game_code_len equ 3 game_code equ 0x4234574A // B4WJ game_code_2 equ 0x42345745 // B4WE game_code_3 equ 0x42345750 // B4WP card_type equ 1 card_id equ 104 card_no equ "104" card_sub equ "Mod Card 104" card_sub_x equ 64 card_desc_len equ 3 card_desc_1 equ "Address 0E" card_desc_2 equ "Charge FullCust 2/2" card_desc_3 equ "Buggy" card_name_jp_full equ "チャージフルカスタム2/2" card_name_jp_game equ "チャージフルカスタム2/2" card_name_en_full equ "Charge FullCust 2/2" card_name_en_game equ "Charge FullCust 2/2" card_address equ "0E" card_address_id equ 4 card_bug equ 1 card_wrote_en equ "Charge FullCust 2/2" card_wrote_jp equ "チャージフルカスタム2/2"
; --COPYRIGHT--,BSD_EX ; Copyright (c) 2012, Texas Instruments Incorporated ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; ; * Neither the name of Texas Instruments Incorporated 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. ; ; ****************************************************************************** ; ; MSP430 CODE EXAMPLE DISCLAIMER ; ; MSP430 code examples are self-contained low-level programs that typically ; demonstrate a single peripheral function or device feature in a highly ; concise manner. For this the code may rely on the device's power-on default ; register values and settings such as the clock configuration and care must ; be taken when combining code from several examples to avoid potential side ; effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware ; for an API functional library-approach to peripheral configuration. ; ; --/COPYRIGHT-- ;******************************************************************************* ; MSP430G2xx3 Demo - Timer_A, Ultra-Low Pwr UART 2400 Echo, 32kHz ACLK ; ; Description: Use Timer_A CCR0 hardware output modes and SCCI data latch ; to implement UART function @ 2400 baud. Software does not directly read and ; write to RX and TX pins, instead proper use of output modes and SCCI data ; latch are demonstrated. Use of these hardware features eliminates ISR ; latency effects as hardware insures that output and input bit latching and ; timing are perfectly synchronised with Timer_A regardless of other ; software activity. In the Mainloop the UART function readies the UART to ; receive one character and waits in LPM3 with all activity interrupt driven. ; After a character has been received, the UART receive function forces exit ; from LPM3 in the Mainloop which echo's back the received character. ; ACLK = TACLK = LFXT1 = 32768Hz, MCLK = SMCLK = default DCO ; //* An external watch crystal is required on XIN XOUT for ACLK *// ; ; MSP430G2xx3 ; ----------------- ; /|\| XIN|- ; | | | 32kHz ; --|RST XOUT|- ; | | ; | CCI0B/TXD/P1.5|--------> ; | | 2400 8N1 ; | CCI0A/RXD/P1.1|<-------- ; RXD .equ 002h ; RXD on P1.1 TXD .equ 020h ; TXD on P1.5 ; ; CPU Registers Used RXTXData .equ R4 BitCnt .equ R5 ; ; Conditions for 2400 Baud SW UART, ACLK = 32768 Bitime_5 .equ 6 ; ~0.5 bit length + small adjustment Bitime .equ 14 ; 427us bit length ~ 2341 baud ; ; D. Dang ; Texas Instruments Inc. ; December 2010 ; Built with Code Composer Essentials Version: 4.2.0 ;******************************************************************************* .cdecls C,LIST, "msp430.h" ;------------------------------------------------------------------------------ .text ; Program Start ;------------------------------------------------------------------------------ RESET mov.w #0280h,SP ; Initialize stackpointer StopWDT mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop Watchdog Timer SetupTA mov.w #TASSEL_1+MC_2,&TACTL ; ACLK, continuous mode SetupC0 mov.w #OUT,&CCTL0 ; TXD Idle as Mark SetupP1 bis.b #TXD+RXD,&P1SEL ; bis.b #TXD,&P1DIR ; ; Mainloop call #RX_Ready ; UART ready to RX one Byte bis.w #LPM3+GIE,SR ; Enter LPM3 w/ int until Byte RXed call #TX_Byte ; TX Back RXed Byte Received jmp Mainloop ; ; ;------------------------------------------------------------------------------- TX_Byte ; Subroutine Transmits Character from RXTXData Buffer ;------------------------------------------------------------------------------- TX_1 mov.w &TAR,&CCR0 ; Current state of TA counter cmp.w &TAR,&CCR0 ; !!Prevent async capature!! jne TX_1 ; add.w #Bitime,&CCR0 ; Some time till first bit bis.w #0100h, RXTXData ; Add mark stop bit to RXTXData rla.w RXTXData ; Add space start bit mov.w #10,BitCnt ; Load Bit counter, 8data + ST/SP mov.w #CCIS0+OUTMOD0+CCIE,&CCTL0 ; TXD = mark = idle TX_Wait bit.w #CCIE,&CCTL0 ; Wait for TX completion jnz TX_Wait ; ret ; ; ;------------------------------------------------------------------------------- RX_Ready ; Subroutine Readies UART to Receive Character into RXTXData Buffer ;------------------------------------------------------------------------------- mov.w #8,BitCnt ; Load Bit Counter, 8 data bits SetupRX mov.w #CM1+SCS+OUTMOD0+CAP+CCIE,&CCTL0 ; Neg Edge,Sync,cap ret ; ; ;------------------------------------------------------------------------------- TA0_ISR ; RXTXData Buffer holds UART Data ;------------------------------------------------------------------------------- add.w #Bitime,&CCR0 ; Time to next bit bit.w #CCIS0,&CCTL0 ; RX on CCI0B? jnz UART_TX ; Jump --> TX UART_RX bit.w #CAP,&CCTL0 ; Capture mode = start bit edge jz RX_Bit ; Start bit edge? RX_Edge bic.w #CAP,&CCTL0 ; Switch to compare mode add.w #Bitime_5,&CCR0 ; First databit 1.5 bits from edge reti ; RX_Bit bit.w #SCCI,&CCTL0 ; Get bit waiting in receive latch rrc.b RXTXData ; Store received bit RX_Test dec.w BitCnt ; All bits RXed? jnz RX_Next ; Next bit? ;>>>>>>>>>> Decode of Received Byte Here <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< RX_Comp bic.w #CCIE,&CCTL0 ; All bits RXed, disable interrupt mov.w #GIE,0(SP) ; Decode byte = active in Mainloop ;>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< RX_Next reti ; ; UART_TX cmp.w #00h,BitCnt ; jne TX_Next ; Next bit? bic.w #CCIE,&CCTL0 ; All Bits TX or RX, Disable Int. reti ; TX_Next bic.w #OUTMOD2,&CCTL0 ; TX Mark rra.w RXTXData ; LSB is shifted to carry jc TX_Test ; Jump --> bit = 1 TX_Space bis.w #OUTMOD2,&CCTL0 ; TX Space TX_Test dec.w BitCnt ; All bits sent (or received)? reti ; ; ;------------------------------------------------------------------------------ ; Interrupt Vectors ;------------------------------------------------------------------------------ .sect ".reset" ; MSP430 RESET Vector .short RESET ; .sect ".int09" ; Timer_A0 Vector .short TA0_ISR ; .end
CALL LOAD ; Altprogramı çağır LXI B, 0200H LXI H, 0202H LXI D, 0204H STC ; Eldeyi 1 yap CMC ; Eldeyi tümle C=0 MVI A, 2 ; A=2 (sayılar 2 byte tan oluşuyor) MORE: STA TMP ; A yı sakla LDAX B ; BC deki veriyi A ya yükle ADC M ; A=A+[HL]+C STAX D ; A yı D adresine kaydet INX B INX H ; 1 er arttır INX D LDA TMP ; TMP deki veriyi A ya yükle DCR A ; A-=1 JNZ MORE ; 0 değilse atla HLT TMP: DS 1 ; 1 byte boyutunda değişken ; Sırayla sayıları belleğe yükler. LOAD: MVI A, 38H STA 0200H MVI A, 21H STA 0201H MVI A, 29H STA 0202H MVI A, 1FH STA 0203H RET
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0x181e2, %rbp nop nop nop nop nop cmp %r14, %r14 mov $0x6162636465666768, %rcx movq %rcx, %xmm4 vmovups %ymm4, (%rbp) nop nop nop nop and $7857, %rdx lea addresses_WT_ht+0xfbe2, %r12 nop add $2447, %rbx vmovups (%r12), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %rdx nop dec %rcx lea addresses_UC_ht+0x1d2e2, %rsi lea addresses_normal_ht+0x18962, %rdi cmp $14012, %rdx mov $36, %rcx rep movsb nop nop nop nop and %rbx, %rbx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %rbp push %rbx push %rcx push %rsi // Store lea addresses_normal+0x281a, %r15 nop nop add %r11, %r11 movl $0x51525354, (%r15) nop nop sub $461, %r11 // Faulty Load mov $0x1ffdad0000000fe2, %rcx nop and %rsi, %rsi mov (%rcx), %rbx lea oracles, %rbp and $0xff, %rbx shlq $12, %rbx mov (%rbp,%rbx,1), %rbx pop %rsi pop %rcx pop %rbx pop %rbp pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_NC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 9, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
// // This file is part of www.nand2tetris.org // // and the book "The Elements of Computing Systems" // // by Nisan and Schocken, MIT Press. // // File name: projects/07/MemoryAccess/StaticTest/StaticTest.vm // // // Executes pop and push commands using the static segment. // push constant 111 @111 D=A @SP A=M M=D @SP M=M+1 // push constant 333 @333 D=A @SP A=M M=D @SP M=M+1 // push constant 888 @888 D=A @SP A=M M=D @SP M=M+1 // pop static 8 @SP M=M-1 A=M D=M @Static.8 M=D // pop static 3 @SP M=M-1 A=M D=M @Static.3 M=D // pop static 1 @SP M=M-1 A=M D=M @Static.1 M=D // push static 3 @Static.3 D=M @SP A=M M=D @SP M=M+1 // push static 1 @Static.1 D=M @SP A=M M=D @SP M=M+1 // sub @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M-D @SP M=M+1 // push static 8 @Static.8 D=M @SP A=M M=D @SP M=M+1 // add @SP M=M-1 A=M D=M @SP M=M-1 A=M M=M+D @SP M=M+1 (END) @END 0;JMP
#include<iostream> using namespace std; \ string getDayOfWeek(int dayNum){ string dayName; switch (dayNum) { case 0: dayName = "Sunday"; break; case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; case 4: dayName = "Thursday"; break; case 5: dayName = "Friday"; break; case 6: dayName = "Saturday"; break; default: break; } return dayName; } int main(){ cout << getDayOfWeek(0)<< endl; return 0; }
BITS 64 ; 64bit mode default rel ; relative mode SIGSTOP equ 19 ; Pushes an auxv pair to the stack. ; Arg1: auxv type, use the AT_n macros above ; Arg2: The value of the auxv entry %macro PUSH_AUX_ENT 2 push %1 push %2 %endmacro ; Calls sys_munmap. ; Arg1: Address to start unmapping from. Must be page aligned. ; Arg2: Number of bytes to free. Must be a multiple of page size. ; Return value: Stored in rax %macro sys_munmap 2 mov rax, 11 ; sys_munmap mov rdi, %1 mov rsi, %2 syscall %endmacro ; Calls sys_mmap. ; Arg1: Address to allocate memory at ; Arg2: Number of bytes to allocate ; Arg3: Allocation protections ; Arg4: Allocation flags ; Arg5: File descriptor ; Arg6: Offset ; Return value: Stored in rax %macro sys_mmap 6 mov rax, 9 ; sys_mmap mov rdi, %1 mov rsi, %2 mov rdx, %3 mov r10, %4 mov r8, %5 mov r9, %6 syscall %endmacro ; Calls sys_kill (sends a signal) ; Arg1: Pid to send a signal to ; Arg2: Signal to send ; Return value: Stored in rax %macro sys_kill 2 mov rax, 62 ; sys_kill mov rdi, %1 mov rsi, %2 syscall %endmacro ; Calls sys_getpid (gets current PID) ; Return value: Stored in rax %macro sys_getpid 0 mov rax, 39 ; sys_getpid syscall %endmacro ; Load parameters passed by caller mov [alloc_list_addr], rdi mov [entry_point], rsi mov [stack_end], rdx mov [desired_argc], rcx ; Now we need to allocate memory for the new process. Pointer to beginning ; of list is in alloc_list_addr, process this structure, which looks like: ; entry_count, alloc_type, address_to_allocate_at, length_of_allocation, .... mov r12, [alloc_list_addr] ; Get pointer to alloc list mov rcx, [r12] ; Move list length into rcx so we can loop over it add r12, 8 ; Skip to first entry in the list map_loop: mov r14, [r12] ; Get type of allocation (dealloc/alloc?) add r12, 8 ; Skip to next array value mov rdi, [r12] ; Get address to allocate at add r12, 8 ; Skip to next array value mov rsi, [r12] ; Get length of allocation add r12, 8 ; Skip to next array value push rcx ; rcx will be lost by syscall, save it mov r13, rdi ; Make a copy of the address we're allocating, into a preserved register cmp r14, 0 ; If this is an alloc, then jump to alloc branch je alloc_branch sys_munmap rdi, rsi ; We didn't jump, so this is a dealloc entry. Call sys_munmap. jmp skip_alloc ; Skip over the alloc block as we've just done a dealloc alloc_branch: sys_mmap rdi, rsi, 6, 50, -1, 0 ; Allocate memory using PROT_EXEC | PROT_WRITE. And mapping MAP_ANONYMOUS | MAP_PRIVATE | MAP_FIXED skip_alloc: pop rcx ; restore rcx loop map_loop ; Keep going through each entry ; Suspend ourselves, so that our parent can write in the sections sys_getpid ; Get our own pid so we can signal ourselves. Ret stored in RAX. mov rdi, rax ; Pid argument should be in RDI, so move from RAX sys_kill rdi, SIGSTOP ; Signal ourselves ; We must have been resumed, setup the stack/registers then jump to entry point mov rsp, [stack_end] ; Reset the stack pointer to our parent's argv, let's us skip setting up an auxv table mov rdx, 0 ; Contains a function pointer to be registered with atexit, don't register any! mov rbp, 0 ; rbp is expected to be 0 mov r9, [desired_argc] ; Push correct argc value to top of stack, as parent will have popped this off push r9 jmp [entry_point] ; Jump to the entry point, yeet ; call sys_exit. ; rdi: Exit code of process exit: mov rax, 60 syscall section .data alloc_list_addr dq 0 entry_point dq 0 stack_end dq 0 desired_argc dq 0
// (C) Copyright Gennadiy Rozental 2001-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : included (vs. linked ) version of Program Execution Monitor // *************************************************************************** #ifndef BOOST_INCLUDED_PRG_EXEC_MONITOR_HPP_071894GER #define BOOST_INCLUDED_PRG_EXEC_MONITOR_HPP_071894GER #include <boost/test/impl/execution_monitor.ipp> #include <boost/test/impl/debug.ipp> #include <boost/test/impl/cpp_main.ipp> #define BOOST_TEST_INCLUDED #include <boost/test/prg_exec_monitor.hpp> #endif // BOOST_INCLUDED_PRG_EXEC_MONITOR_HPP_071894GER
/* * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "memory/resourceArea.hpp" #include "utilities/array.hpp" #ifdef TARGET_OS_FAMILY_linux # include "thread_linux.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_solaris # include "thread_solaris.inline.hpp" #endif #ifdef TARGET_OS_FAMILY_windows # include "thread_windows.inline.hpp" #endif #ifdef ASSERT void ResourceArray::init_nesting() { _nesting = Thread::current()->resource_area()->nesting(); } #endif void ResourceArray::sort(size_t esize, ftype f) { if (!is_empty()) qsort(_data, length(), esize, f); } void CHeapArray::sort(size_t esize, ftype f) { if (!is_empty()) qsort(_data, length(), esize, f); } void ResourceArray::expand(size_t esize, int i, int& size) { // make sure we are expanding within the original resource mark assert( _nesting == Thread::current()->resource_area()->nesting(), "allocating outside original resource mark" ); // determine new size if (size == 0) size = 4; // prevent endless loop while (i >= size) size *= 2; // allocate and initialize new data section void* data = resource_allocate_bytes(esize * size); memcpy(data, _data, esize * length()); _data = data; } void CHeapArray::expand(size_t esize, int i, int& size) { // determine new size if (size == 0) size = 4; // prevent endless loop while (i >= size) size *= 2; // allocate and initialize new data section void* data = NEW_C_HEAP_ARRAY(char*, esize * size); memcpy(data, _data, esize * length()); FREE_C_HEAP_ARRAY(char*, _data); _data = data; } void ResourceArray::remove_at(size_t esize, int i) { assert(0 <= i && i < length(), "index out of bounds"); _length--; void* dst = (char*)_data + i*esize; void* src = (char*)dst + esize; size_t cnt = (length() - i)*esize; memmove(dst, src, cnt); } void CHeapArray::remove_at(size_t esize, int i) { assert(0 <= i && i < length(), "index out of bounds"); _length--; void* dst = (char*)_data + i*esize; void* src = (char*)dst + esize; size_t cnt = (length() - i)*esize; memmove(dst, src, cnt); }
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2019, Jens Petit * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Jens Petit */ #include <gtest/gtest.h> #include <ros/ros.h> #include <moveit/collision_detection_bullet/bullet_integration/bullet_cast_bvh_manager.h> #include <moveit/collision_detection_bullet/bullet_integration/bullet_discrete_bvh_manager.h> #include <moveit/collision_detection/collision_common.h> #include <moveit/robot_model/robot_model.h> #include <moveit/robot_state/robot_state.h> #include <moveit/utils/robot_model_test_utils.h> #include <moveit/collision_detection_bullet/collision_env_bullet.h> #include <moveit/collision_detection_bullet/bullet_integration/basic_types.h> #include <urdf_parser/urdf_parser.h> #include <geometric_shapes/shape_operations.h> namespace cb = collision_detection_bullet; /** \brief Brings the panda robot in user defined home position */ inline void setToHome(moveit::core::RobotState& panda_state) { panda_state.setToDefaultValues(); double joint2 = -0.785; double joint4 = -2.356; double joint6 = 1.571; double joint7 = 0.785; panda_state.setJointPositions("panda_joint2", &joint2); panda_state.setJointPositions("panda_joint4", &joint4); panda_state.setJointPositions("panda_joint6", &joint6); panda_state.setJointPositions("panda_joint7", &joint7); panda_state.update(); } class BulletCollisionDetectionTester : public testing::Test { protected: void SetUp() override { robot_model_ = moveit::core::loadTestingRobotModel("panda"); robot_model_ok_ = static_cast<bool>(robot_model_); acm_ = std::make_shared<collision_detection::AllowedCollisionMatrix>(*robot_model_->getSRDF()); cenv_ = std::make_shared<collision_detection::CollisionEnvBullet>(robot_model_); robot_state_ = std::make_shared<moveit::core::RobotState>(robot_model_); setToHome(*robot_state_); } void TearDown() override { } protected: bool robot_model_ok_; moveit::core::RobotModelPtr robot_model_; collision_detection::CollisionEnvPtr cenv_; collision_detection::AllowedCollisionMatrixPtr acm_; moveit::core::RobotStatePtr robot_state_; }; void addCollisionObjects(cb::BulletCastBVHManager& checker) { //////////////////////////// // Add static box to checker //////////////////////////// shapes::ShapePtr static_box(new shapes::Box(1, 1, 1)); Eigen::Isometry3d static_box_pose; static_box_pose.setIdentity(); std::vector<shapes::ShapeConstPtr> obj1_shapes; cb::AlignedVector<Eigen::Isometry3d> obj1_poses; std::vector<cb::CollisionObjectType> obj1_types; obj1_shapes.push_back(static_box); obj1_poses.push_back(static_box_pose); obj1_types.push_back(cb::CollisionObjectType::USE_SHAPE_TYPE); cb::CollisionObjectWrapperPtr cow_1(new cb::CollisionObjectWrapper( "static_box_link", collision_detection::BodyType::WORLD_OBJECT, obj1_shapes, obj1_poses, obj1_types)); checker.addCollisionObject(cow_1); //////////////////////////// // Add moving box to checker //////////////////////////// shapes::ShapePtr moving_box(new shapes::Box(0.2, 0.2, 0.2)); Eigen::Isometry3d moving_box_pose; moving_box_pose.setIdentity(); moving_box_pose.translation() = Eigen::Vector3d(0.5, -0.5, 0); std::vector<shapes::ShapeConstPtr> obj2_shapes; cb::AlignedVector<Eigen::Isometry3d> obj2_poses; std::vector<cb::CollisionObjectType> obj2_types; obj2_shapes.push_back(moving_box); obj2_poses.push_back(moving_box_pose); obj2_types.push_back(cb::CollisionObjectType::USE_SHAPE_TYPE); cb::CollisionObjectWrapperPtr cow_2(new cb::CollisionObjectWrapper( "moving_box_link", collision_detection::BodyType::WORLD_OBJECT, obj2_shapes, obj2_poses, obj2_types)); checker.addCollisionObject(cow_2); } void addCollisionObjectsMesh(cb::BulletCastBVHManager& checker) { //////////////////////////// // Add static box to checker //////////////////////////// shapes::ShapePtr static_box(new shapes::Box(0.3, 0.3, 0.3)); Eigen::Isometry3d static_box_pose; static_box_pose.setIdentity(); std::vector<shapes::ShapeConstPtr> obj1_shapes; cb::AlignedVector<Eigen::Isometry3d> obj1_poses; std::vector<cb::CollisionObjectType> obj1_types; obj1_shapes.push_back(static_box); obj1_poses.push_back(static_box_pose); obj1_types.push_back(cb::CollisionObjectType::USE_SHAPE_TYPE); cb::CollisionObjectWrapperPtr cow_1(new cb::CollisionObjectWrapper( "static_box_link", collision_detection::BodyType::WORLD_OBJECT, obj1_shapes, obj1_poses, obj1_types)); checker.addCollisionObject(cow_1); //////////////////////////// // Add moving mesh to checker //////////////////////////// std::vector<shapes::ShapeConstPtr> obj2_shapes; cb::AlignedVector<Eigen::Isometry3d> obj2_poses; std::vector<cb::CollisionObjectType> obj2_types; obj1_poses.push_back(static_box_pose); obj1_types.push_back(cb::CollisionObjectType::USE_SHAPE_TYPE); Eigen::Isometry3d s_pose; s_pose.setIdentity(); std::string kinect = "package://moveit_resources_panda_description/meshes/collision/hand.stl"; auto s = std::shared_ptr<shapes::Shape>{ shapes::createMeshFromResource(kinect) }; obj2_shapes.push_back(s); obj2_types.push_back(cb::CollisionObjectType::CONVEX_HULL); obj2_poses.push_back(s_pose); cb::CollisionObjectWrapperPtr cow_2(new cb::CollisionObjectWrapper( "moving_box_link", collision_detection::BodyType::WORLD_OBJECT, obj2_shapes, obj2_poses, obj2_types)); checker.addCollisionObject(cow_2); } void runTest(cb::BulletCastBVHManager& checker, collision_detection::CollisionResult& result, std::vector<collision_detection::Contact>& result_vector, Eigen::Isometry3d& start_pos, Eigen::Isometry3d& end_pos) { ////////////////////////////////////// // Test when object is inside another ////////////////////////////////////// checker.setActiveCollisionObjects({ "moving_box_link" }); checker.setContactDistanceThreshold(0.1); // Set the collision object transforms checker.setCollisionObjectsTransform("static_box_link", Eigen::Isometry3d::Identity()); checker.setCastCollisionObjectsTransform("moving_box_link", start_pos, end_pos); // Perform collision check collision_detection::CollisionRequest request; request.contacts = true; // cb::ContactResultMap result; checker.contactTest(result, request, nullptr, false); for (const auto& contacts_all : result.contacts) { for (const auto& contact : contacts_all.second) { result_vector.push_back(contact); } } } // TODO(j-petit): Add continuous to continuous collision checking /** \brief Continuous self collision checks are not supported yet by the bullet integration */ TEST_F(BulletCollisionDetectionTester, DISABLED_ContinuousCollisionSelf) { collision_detection::CollisionRequest req; collision_detection::CollisionResult res; moveit::core::RobotState state1(robot_model_); moveit::core::RobotState state2(robot_model_); setToHome(state1); double joint2 = 0.15; double joint4 = -3.0; double joint5 = -0.8; double joint7 = -0.785; state1.setJointPositions("panda_joint2", &joint2); state1.setJointPositions("panda_joint4", &joint4); state1.setJointPositions("panda_joint5", &joint5); state1.setJointPositions("panda_joint7", &joint7); state1.update(); cenv_->checkSelfCollision(req, res, state1, *acm_); ASSERT_FALSE(res.collision); res.clear(); setToHome(state2); double joint_5_other = 0.8; state2.setJointPositions("panda_joint2", &joint2); state2.setJointPositions("panda_joint4", &joint4); state2.setJointPositions("panda_joint5", &joint_5_other); state2.setJointPositions("panda_joint7", &joint7); state2.update(); cenv_->checkSelfCollision(req, res, state2, *acm_); ASSERT_FALSE(res.collision); res.clear(); ROS_INFO_STREAM("Continous to continous collisions are not supported yet, therefore fail here."); ASSERT_TRUE(res.collision); res.clear(); } /** \brief Two similar robot poses are used as start and end pose of a continuous collision check. */ TEST_F(BulletCollisionDetectionTester, ContinuousCollisionWorld) { collision_detection::CollisionRequest req; req.contacts = true; req.max_contacts = 10; collision_detection::CollisionResult res; moveit::core::RobotState state1(robot_model_); moveit::core::RobotState state2(robot_model_); setToHome(state1); state1.update(); setToHome(state2); double joint_2{ 0.05 }; double joint_4{ -1.6 }; state2.setJointPositions("panda_joint2", &joint_2); state2.setJointPositions("panda_joint4", &joint_4); state2.update(); cenv_->checkRobotCollision(req, res, state1, state2, *acm_); ASSERT_FALSE(res.collision); res.clear(); // Adding the box which is not in collision with the individual states but with the casted one. shapes::Shape* shape = new shapes::Box(0.1, 0.1, 0.1); shapes::ShapeConstPtr shape_ptr(shape); Eigen::Isometry3d pos{ Eigen::Isometry3d::Identity() }; pos.translation().x() = 0.43; pos.translation().y() = 0; pos.translation().z() = 0.55; cenv_->getWorld()->addToObject("box", shape_ptr, pos); cenv_->checkRobotCollision(req, res, state1, *acm_); ASSERT_FALSE(res.collision); res.clear(); cenv_->checkRobotCollision(req, res, state2, *acm_); ASSERT_FALSE(res.collision); res.clear(); cenv_->checkRobotCollision(req, res, state1, state2, *acm_); ASSERT_TRUE(res.collision); ASSERT_EQ(res.contact_count, 4u); // test contact types for (auto& contact_pair : res.contacts) { for (collision_detection::Contact& contact : contact_pair.second) { collision_detection::BodyType contact_type1 = contact.body_name_1 == "box" ? collision_detection::BodyType::WORLD_OBJECT : collision_detection::BodyType::ROBOT_LINK; collision_detection::BodyType contact_type2 = contact.body_name_2 == "box" ? collision_detection::BodyType::WORLD_OBJECT : collision_detection::BodyType::ROBOT_LINK; ASSERT_EQ(contact.body_type_1, contact_type1); ASSERT_EQ(contact.body_type_2, contact_type2); } } res.clear(); } TEST(ContinuousCollisionUnit, BulletCastBVHCollisionBoxBoxUnit) { collision_detection::CollisionResult result; std::vector<collision_detection::Contact> result_vector; Eigen::Isometry3d start_pos, end_pos; start_pos.setIdentity(); start_pos.translation().x() = -2; end_pos.setIdentity(); end_pos.translation().x() = 2; cb::BulletCastBVHManager checker; addCollisionObjects(checker); runTest(checker, result, result_vector, start_pos, end_pos); ASSERT_TRUE(result.collision); EXPECT_NEAR(result_vector[0].depth, -0.6, 0.001); EXPECT_NEAR(result_vector[0].percent_interpolation, 0.6, 0.001); } TEST(ContinuousCollisionUnit, BulletCastMeshVsBox) { cb::BulletCastBVHManager checker; addCollisionObjectsMesh(checker); Eigen::Isometry3d start_pos, end_pos; start_pos.setIdentity(); start_pos.translation().x() = -1.9; end_pos.setIdentity(); end_pos.translation().x() = 1.9; collision_detection::CollisionResult result; std::vector<collision_detection::Contact> result_vector; runTest(checker, result, result_vector, start_pos, end_pos); ASSERT_TRUE(result.collision); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
; A223082: Number of n-digit numbers N with distinct digits such that N divides the reversal of N. ; 9,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $3,$0 add $0,2 mul $0,2 add $0,6 mov $4,2 mov $1,$$3 trn $1,1
//===- llvm/CodeGen/TileShapeInfo.h - ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file Pass to transform <256 x i32> /// <256 x i32> is mapped to AMX tile register on X86, AMX instruction set only /// provides simple operation on tile register. The basic elementwise operation /// is not supported by AMX. Since we define the AMX tile as vector <256 x i32> /// and only AMX intrinsics can operate on the type, we need transform /// load/store <256 x i32> instruction to AMX load/store. Besides, we split /// <256 x i32> to 2 <128 x i32> if the vector is not used or defined by AMX /// intrinsics, so that in instruction selection it can be lowered to proper /// size which HW can support. // //===----------------------------------------------------------------------===// // #include "X86.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Analysis/OptimizationRemarkEmitter.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/ValueTypes.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/IntrinsicsX86.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "lower-amx-type" namespace { class X86LowerAMXType { Function &Func; const DataLayout &DL; DenseSet<Instruction *> LDSet; DenseSet<Instruction *> STSet; DenseMap<Value *, std::pair<LoadInst *, LoadInst *>> LoadMap; public: X86LowerAMXType(Function &F) : Func(F), DL(F.getParent()->getDataLayout()) {} bool visit(); bool visitLD(); bool visitST(); void splitST(Instruction *Inst); void splitLD(Instruction *Inst); }; // Split v256i32 load/store to 2 v128i32, so that ISel can // lower it to proper vector size. void X86LowerAMXType::splitST(Instruction *Inst) { StoreInst *ST = dyn_cast<StoreInst>(Inst); IRBuilder<> Builder(ST); LLVMContext &Ctx = Builder.getContext(); Type *Ty = ST->getValueOperand()->getType(); EVT VT = EVT::getEVT(Ty); EVT HalfVT = VT.getHalfNumVectorElementsVT(Ctx); Type *HalfTy = HalfVT.getTypeForEVT(Ctx); LoadInst *Lo, *Hi; std::tie(Lo, Hi) = LoadMap[ST->getValueOperand()]; Value *Ptr = ST->getPointerOperand(); PointerType *HalfPtrTy = HalfTy->getPointerTo(ST->getPointerAddressSpace()); Value *HalfPtr = Builder.CreateBitCast(Ptr, HalfPtrTy); // The HW require the alignment for AMX tile is 64, but front-end generate // code for the vector alignment which is the vector size. uint64_t HalfTySize = HalfTy->getPrimitiveSizeInBits().getFixedSize() / 8; Align Alignment = std::min(Lo->getAlign(), Align(HalfTySize)); Builder.CreateAlignedStore(Lo, HalfPtr, Alignment, ST->isVolatile()); HalfPtr = Builder.CreateGEP(HalfTy, HalfPtr, Builder.getInt32(1)); Builder.CreateAlignedStore(Hi, HalfPtr, Alignment, ST->isVolatile()); } bool X86LowerAMXType::visitST() { if (STSet.empty()) return false; for (auto *Inst : STSet) { Value *Row, *Col; const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst->getOperand(0)); if (!II) Row = Col = nullptr; else { switch (II->getIntrinsicID()) { default: Row = Col = nullptr; break; case Intrinsic::x86_tileloadd64_internal: case Intrinsic::x86_tdpbssd_internal: { Row = II->getArgOperand(0); Col = II->getArgOperand(1); break; } } } if (!Row) { splitST(Inst); continue; } IRBuilder<> Builder(Inst); LLVMContext &Ctx = Builder.getContext(); // Use the maximun column as stride. It must be the same with load stride. Value *Stride = Builder.getInt64(64); Value *I8Ptr = Builder.CreateBitCast(Inst->getOperand(1), Type::getInt8PtrTy(Ctx)); std::array<Value *, 5> Args = {Row, Col, I8Ptr, Stride, Inst->getOperand(0)}; Builder.CreateIntrinsic(Intrinsic::x86_tilestored64_internal, None, Args); } return true; } void X86LowerAMXType::splitLD(Instruction *Inst) { LoadInst *LD = dyn_cast<LoadInst>(Inst); IRBuilder<> Builder(LD); LLVMContext &Ctx = Builder.getContext(); Type *Ty = LD->getType(); EVT VT = EVT::getEVT(Ty); EVT HalfVT = VT.getHalfNumVectorElementsVT(Ctx); Type *HalfTy = HalfVT.getTypeForEVT(Ctx); Value *Ptr = LD->getPointerOperand(); PointerType *HalfPtrTy = HalfTy->getPointerTo(LD->getPointerAddressSpace()); Value *HalfPtr = Builder.CreateBitCast(Ptr, HalfPtrTy); // The HW require the alignment for AMX tile is 64, but front-end generate // code for the vector alignment which is the vector size. uint64_t HalfTySize = HalfTy->getPrimitiveSizeInBits().getFixedSize() / 8; Align Alignment = std::min(LD->getAlign(), Align(HalfTySize)); auto *Lo = Builder.CreateAlignedLoad(HalfTy, HalfPtr, Alignment, LD->isVolatile()); HalfPtr = Builder.CreateGEP(HalfTy, HalfPtr, Builder.getInt32(1)); auto *Hi = Builder.CreateAlignedLoad(HalfTy, HalfPtr, Alignment, LD->isVolatile()); LoadMap[Inst] = std::make_pair(Lo, Hi); } bool X86LowerAMXType::visitLD() { if (LDSet.empty()) return false; for (auto &Inst : LDSet) { int Count = 0; Value *NewInst = nullptr; // The user should be all AMX intrinsics or all LLVM instruction. // Don't support it is used by both AMX intrinsics and LLVM instructions. for (auto I = Inst->use_begin(), E = Inst->use_end(); I != E;) { Use &U = *I++; const IntrinsicInst *II = dyn_cast<IntrinsicInst>(U.getUser()); if (!II) { Count++; continue; } if (NewInst) continue; Value *Row, *Col; switch (II->getIntrinsicID()) { default: report_fatal_error("Non-AMX intrinsic use tile type."); break; case Intrinsic::x86_tdpbssd_internal: { unsigned OpNo = U.getOperandNo(); switch (OpNo) { case 3: Row = II->getArgOperand(0); Col = II->getArgOperand(1); break; case 4: Row = II->getArgOperand(0); Col = II->getArgOperand(2); break; case 5: Row = II->getArgOperand(2); Col = II->getArgOperand(1); break; } break; } case Intrinsic::x86_tilestored64_internal: { Row = II->getArgOperand(0); Col = II->getArgOperand(1); break; } } assert(Count == 0 && "Can NOT mix amx intrinsic and LLVM instruction"); // FIXME: The shape def should be ahead of load. IRBuilder<> Builder(Inst); LLVMContext &Ctx = Builder.getContext(); // Use the maximun column as stride. Value *Stride = Builder.getInt64(64); Value *I8Ptr = Builder.CreateBitCast(Inst->getOperand(0), Type::getInt8PtrTy(Ctx)); std::array<Value *, 4> Args = {Row, Col, I8Ptr, Stride}; NewInst = Builder.CreateIntrinsic(Intrinsic::x86_tileloadd64_internal, None, Args); Inst->replaceAllUsesWith(NewInst); } if (!NewInst) splitLD(Inst); } return true; } bool X86LowerAMXType::visit() { bool C; auto IsAMXType = [](FixedVectorType *VTy) { if (!VTy) return false; if (!VTy->getScalarType()->isIntegerTy(32)) return false; if (VTy->getNumElements() != 256) return false; return true; }; for (BasicBlock &BB : Func) { for (Instruction &Inst : BB) { LoadInst *LD = dyn_cast<LoadInst>(&Inst); // Check load instruction. // %3 = load <256 x i32>, <256 x i32>* %1, align 64 if (LD) { FixedVectorType *VTy = dyn_cast<FixedVectorType>(Inst.getType()); if (!IsAMXType(VTy)) continue; LDSet.insert(&Inst); continue; } // Check store instruction. // store <256 x i32> %3, <256 x i32>* %2, align 64 StoreInst *ST = dyn_cast<StoreInst>(&Inst); if (!ST) continue; FixedVectorType *VTy = dyn_cast<FixedVectorType>(ST->getOperand(0)->getType()); if (!IsAMXType(VTy)) continue; STSet.insert(&Inst); } } C = visitLD() | visitST(); for (auto *Inst : STSet) Inst->eraseFromParent(); for (auto *Inst : LDSet) Inst->eraseFromParent(); return C; } } // anonymous namespace namespace { class X86LowerAMXTypeLegacyPass : public FunctionPass { public: static char ID; X86LowerAMXTypeLegacyPass() : FunctionPass(ID) { initializeX86LowerAMXTypeLegacyPassPass(*PassRegistry::getPassRegistry()); } bool runOnFunction(Function &F) override { X86LowerAMXType LAT(F); bool C = LAT.visit(); return C; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); } }; } // anonymous namespace static const char PassName[] = "Lower AMX type for load/store"; char X86LowerAMXTypeLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(X86LowerAMXTypeLegacyPass, DEBUG_TYPE, PassName, false, false) INITIALIZE_PASS_END(X86LowerAMXTypeLegacyPass, DEBUG_TYPE, PassName, false, false) FunctionPass *llvm::createX86LowerAMXTypePass() { return new X86LowerAMXTypeLegacyPass(); }
ParryNoMatchText: text "Nothing can match" line "my @" text_ram wStringBuffer4 text " now." done UnknownText_0x66fc0: text "Yeah, we KO'd a" line "wild @" text_ram wStringBuffer4 text "!" para "That was OK, but I" line "wanted to get it…" done UnknownText_0x67001: text "And yesterday, we" line "spotted a wild" para "@" text_ram wStringBuffer4 text "." line "We were debating" para "whether to catch" line "it or beat it." para "When along came" line "another guy who" para "caught it!" line "How about that!" done UnknownText_0x67096: text "You're thinking" line "you'd like to" para "battle me. Am I" line "right or what?" para "Yep! We'll meet on" line "@" text_ram wStringBuffer5 text "!" done UnknownText_0x670eb: text "OK, give me a call" line "again!" done ParryBattleWithMeText: text "You'll battle with" line "me again, right?" done ParryHaventYouGottenToText: text "Haven't you gotten" line "to @" text_ram wStringBuffer5 text "?" para "Waiting here isn't" line "bad, but I'd sure" cont "like to battle!" done
// Copyright (c) 2014-2016, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <algorithm> #include <cstdio> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/filesystem.hpp> #include "include_base_utils.h" #include "cryptonote_basic_impl.h" #include "tx_pool.h" #include "blockchain.h" #include "blockchain_db/blockchain_db.h" #include "cryptonote_format_utils.h" #include "cryptonote_boost_serialization.h" #include "cryptonote_config.h" #include "miner.h" #include "misc_language.h" #include "profile_tools.h" #include "file_io_utils.h" #include "common/int-util.h" #include "common/boost_serialization_helper.h" #include "warnings.h" #include "crypto/hash.h" #include "cryptonote_core/checkpoints.h" #include "cryptonote_core/cryptonote_core.h" #include "ringct/rctSigs.h" #include "common/perf_timer.h" #if defined(PER_BLOCK_CHECKPOINT) #include "blocks/blocks.h" #endif //#include "serialization/json_archive.h" /* TODO: * Clean up code: * Possibly change how outputs are referred to/indexed in blockchain and wallets * */ using namespace cryptonote; using epee::string_tools::pod_to_hex; extern "C" void slow_hash_allocate_state(); extern "C" void slow_hash_free_state(); DISABLE_VS_WARNINGS(4267) static const struct { uint8_t version; uint64_t height; uint8_t threshold; time_t time; } mainnet_hard_forks[] = { // version 1 from the start of the blockchain { 1, 1, 0, 1341378000 }, // version 2 starts from block 1009827, which is on or around the 20th of March, 2016. Fork time finalised on 2015-09-20. No fork voting occurs for the v2 fork. { 2, 1009827, 0, 1442763710 }, // version 3 starts from block 1141317, which is on or around the 24th of September, 2016. Fork time finalised on 2016-03-21. { 3, 1141317, 0, 1458558528 }, // version 4 starts from block 1220517, which is on or around the 5th of January, 2017. Fork time finalised on 2016-09-18. { 4, 1220517, 0, 1483574400 }, // version 5 starts from block 1406997, which is on or around the 20th of September, 2017. Fork time finalised on 2016-09-18. { 5, 1406997, 0, 1505865600 }, }; static const uint64_t mainnet_hard_fork_version_1_till = 1009826; static const struct { uint8_t version; uint64_t height; uint8_t threshold; time_t time; } testnet_hard_forks[] = { // version 1 from the start of the blockchain { 1, 1, 0, 1341378000 }, // version 2 starts from block 624634, which is on or around the 23rd of November, 2015. Fork time finalised on 2015-11-20. No fork voting occurs for the v2 fork. { 2, 624634, 0, 1445355000 }, // versions 3-5 were passed in rapid succession from September 18th, 2016 { 3, 800500, 0, 1472415034 }, { 4, 801220, 0, 1472415035 }, { 5, 802660, 0, 1472415036 }, }; static const uint64_t testnet_hard_fork_version_1_till = 624633; //------------------------------------------------------------------ Blockchain::Blockchain(tx_memory_pool& tx_pool) : m_db(), m_tx_pool(tx_pool), m_hardfork(NULL), m_timestamps_and_difficulties_height(0), m_current_block_cumul_sz_limit(0), m_is_in_checkpoint_zone(false), m_is_blockchain_storing(false), m_enforce_dns_checkpoints(false), m_max_prepare_blocks_threads(4), m_db_blocks_per_sync(1), m_db_sync_mode(db_async), m_fast_sync(true), m_show_time_stats(false), m_sync_counter(0) { LOG_PRINT_L3("Blockchain::" << __func__); } //------------------------------------------------------------------ bool Blockchain::have_tx(const crypto::hash &id) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_db->tx_exists(id); } //------------------------------------------------------------------ bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_db->has_key_image(key_im); } //------------------------------------------------------------------ // This function makes sure that each "input" in an input (mixins) exists // and collects the public key for each from the transaction it was included in // via the visitor passed to it. template <class visitor_t> bool Blockchain::scan_outputkeys_for_indexes(size_t tx_version, const txin_to_key& tx_in_to_key, visitor_t &vis, const crypto::hash &tx_prefix_hash, uint64_t* pmax_related_block_height) const { LOG_PRINT_L3("Blockchain::" << __func__); // ND: Disable locking and make method private. //CRITICAL_REGION_LOCAL(m_blockchain_lock); // verify that the input has key offsets (that it exists properly, really) if(!tx_in_to_key.key_offsets.size()) return false; // cryptonote_format_utils uses relative offsets for indexing to the global // outputs list. that is to say that absolute offset #2 is absolute offset // #1 plus relative offset #2. // TODO: Investigate if this is necessary / why this is done. std::vector<uint64_t> absolute_offsets = relative_output_offsets_to_absolute(tx_in_to_key.key_offsets); std::vector<output_data_t> outputs; bool found = false; auto it = m_scan_table.find(tx_prefix_hash); if (it != m_scan_table.end()) { auto its = it->second.find(tx_in_to_key.k_image); if (its != it->second.end()) { outputs = its->second; found = true; } } if (!found) { try { m_db->get_output_key(tx_in_to_key.amount, absolute_offsets, outputs); } catch (...) { LOG_PRINT_L0("Output does not exist! amount = " << tx_in_to_key.amount); return false; } } else { // check for partial results and add the rest if needed; if (outputs.size() < absolute_offsets.size() && outputs.size() > 0) { LOG_PRINT_L1("Additional outputs needed: " << absolute_offsets.size() - outputs.size()); std::vector < uint64_t > add_offsets; std::vector<output_data_t> add_outputs; for (size_t i = outputs.size(); i < absolute_offsets.size(); i++) add_offsets.push_back(absolute_offsets[i]); try { m_db->get_output_key(tx_in_to_key.amount, add_offsets, add_outputs); } catch (...) { LOG_PRINT_L0("Output does not exist! amount = " << tx_in_to_key.amount); return false; } outputs.insert(outputs.end(), add_outputs.begin(), add_outputs.end()); } } size_t count = 0; for (const uint64_t& i : absolute_offsets) { try { output_data_t output_index; try { // get tx hash and output index for output if (count < outputs.size()) output_index = outputs.at(count); else output_index = m_db->get_output_key(tx_in_to_key.amount, i); // call to the passed boost visitor to grab the public key for the output if (!vis.handle_output(output_index.unlock_time, output_index.pubkey, output_index.commitment)) { LOG_PRINT_L0("Failed to handle_output for output no = " << count << ", with absolute offset " << i); return false; } } catch (...) { LOG_PRINT_L0("Output does not exist! amount = " << tx_in_to_key.amount << ", absolute_offset = " << i); return false; } // if on last output and pmax_related_block_height not null pointer if(++count == absolute_offsets.size() && pmax_related_block_height) { // set *pmax_related_block_height to tx block height for this output auto h = output_index.height; if(*pmax_related_block_height < h) { *pmax_related_block_height = h; } } } catch (const OUTPUT_DNE& e) { LOG_PRINT_L0("Output does not exist: " << e.what()); return false; } catch (const TX_DNE& e) { LOG_PRINT_L0("Transaction does not exist: " << e.what()); return false; } } return true; } //------------------------------------------------------------------ uint64_t Blockchain::get_current_blockchain_height() const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_db->height(); } //------------------------------------------------------------------ //FIXME: possibly move this into the constructor, to avoid accidentally // dereferencing a null BlockchainDB pointer bool Blockchain::init(BlockchainDB* db, const bool testnet, const cryptonote::test_options *test_options) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); bool fakechain = test_options != NULL; if (db == nullptr) { LOG_ERROR("Attempted to init Blockchain with null DB"); return false; } if (!db->is_open()) { LOG_ERROR("Attempted to init Blockchain with unopened DB"); return false; } m_db = db; m_testnet = testnet; if (m_hardfork == nullptr) { if (fakechain) m_hardfork = new HardFork(*db, 1, 0); else if (m_testnet) m_hardfork = new HardFork(*db, 1, testnet_hard_fork_version_1_till); else m_hardfork = new HardFork(*db, 1, mainnet_hard_fork_version_1_till); } if (fakechain) { for (size_t n = 0; test_options->hard_forks[n].first; ++n) m_hardfork->add_fork(test_options->hard_forks[n].first, test_options->hard_forks[n].second, 0, n + 1); } else if (m_testnet) { for (size_t n = 0; n < sizeof(testnet_hard_forks) / sizeof(testnet_hard_forks[0]); ++n) m_hardfork->add_fork(testnet_hard_forks[n].version, testnet_hard_forks[n].height, testnet_hard_forks[n].threshold, testnet_hard_forks[n].time); } else { for (size_t n = 0; n < sizeof(mainnet_hard_forks) / sizeof(mainnet_hard_forks[0]); ++n) m_hardfork->add_fork(mainnet_hard_forks[n].version, mainnet_hard_forks[n].height, mainnet_hard_forks[n].threshold, mainnet_hard_forks[n].time); } m_hardfork->init(); m_db->set_hard_fork(m_hardfork); // if the blockchain is new, add the genesis block // this feels kinda kludgy to do it this way, but can be looked at later. // TODO: add function to create and store genesis block, // taking testnet into account if(!m_db->height()) { LOG_PRINT_L0("Blockchain not loaded, generating genesis block."); block bl = boost::value_initialized<block>(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); if (m_testnet) { generate_genesis_block(bl, config::testnet::GENESIS_TX, config::testnet::GENESIS_NONCE); } else { generate_genesis_block(bl, config::GENESIS_TX, config::GENESIS_NONCE); } add_new_block(bl, bvc); CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain"); } // TODO: if blockchain load successful, verify blockchain against both // hard-coded and runtime-loaded (and enforced) checkpoints. else { } if (!fakechain) { // ensure we fixup anything we found and fix in the future m_db->fixup(); } m_db->block_txn_start(true); // check how far behind we are uint64_t top_block_timestamp = m_db->get_top_block_timestamp(); uint64_t timestamp_diff = time(NULL) - top_block_timestamp; // genesis block has no timestamp, could probably change it to have timestamp of 1341378000... if(!top_block_timestamp) timestamp_diff = time(NULL) - 1341378000; // create general purpose async service queue m_async_work_idle = std::unique_ptr < boost::asio::io_service::work > (new boost::asio::io_service::work(m_async_service)); // we only need 1 m_async_pool.create_thread(boost::bind(&boost::asio::io_service::run, &m_async_service)); #if defined(PER_BLOCK_CHECKPOINT) if (!fakechain) load_compiled_in_block_hashes(); #endif LOG_PRINT_GREEN("Blockchain initialized. last block: " << m_db->height() - 1 << ", " << epee::misc_utils::get_time_interval_string(timestamp_diff) << " time ago, current difficulty: " << get_difficulty_for_next_block(), LOG_LEVEL_0); m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ bool Blockchain::init(BlockchainDB* db, HardFork*& hf, const bool testnet) { if (hf != nullptr) m_hardfork = hf; bool res = init(db, testnet, NULL); if (hf == nullptr) hf = m_hardfork; return res; } //------------------------------------------------------------------ bool Blockchain::store_blockchain() { LOG_PRINT_L3("Blockchain::" << __func__); // lock because the rpc_thread command handler also calls this CRITICAL_REGION_LOCAL(m_db->m_synchronization_lock); TIME_MEASURE_START(save); // TODO: make sure sync(if this throws that it is not simply ignored higher // up the call stack try { m_db->sync(); } catch (const std::exception& e) { LOG_PRINT_L0(std::string("Error syncing blockchain db: ") + e.what() + "-- shutting down now to prevent issues!"); throw; } catch (...) { LOG_PRINT_L0("There was an issue storing the blockchain, shutting down now to prevent issues!"); throw; } TIME_MEASURE_FINISH(save); if(m_show_time_stats) LOG_PRINT_L0("Blockchain stored OK, took: " << save << " ms"); return true; } //------------------------------------------------------------------ bool Blockchain::deinit() { LOG_PRINT_L3("Blockchain::" << __func__); LOG_PRINT_L1("Stopping blockchain read/write activity"); // stop async service m_async_work_idle.reset(); m_async_pool.join_all(); m_async_service.stop(); // as this should be called if handling a SIGSEGV, need to check // if m_db is a NULL pointer (and thus may have caused the illegal // memory operation), otherwise we may cause a loop. if (m_db == NULL) { throw new DB_ERROR("The db pointer is null in Blockchain, the blockchain may be corrupt!"); } try { m_db->close(); LOG_PRINT_L1("Local blockchain read/write activity stopped successfully"); } catch (const std::exception& e) { LOG_ERROR(std::string("Error closing blockchain db: ") + e.what()); } catch (...) { LOG_ERROR("There was an issue closing/storing the blockchain, shutting down now to prevent issues!"); } delete m_hardfork; delete m_db; return true; } //------------------------------------------------------------------ // This function tells BlockchainDB to remove the top block from the // blockchain and then returns all transactions (except the miner tx, of course) // from it to the tx_pool block Blockchain::pop_block_from_blockchain() { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; block popped_block; std::vector<transaction> popped_txs; try { m_db->pop_block(popped_block, popped_txs); } // anything that could cause this to throw is likely catastrophic, // so we re-throw catch (const std::exception& e) { LOG_ERROR("Error popping block from blockchain: " << e.what()); throw; } catch (...) { LOG_ERROR("Error popping block from blockchain, throwing!"); throw; } // return transactions from popped block to the tx_pool for (transaction& tx : popped_txs) { if (!is_coinbase(tx)) { cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc); // FIXME: HardFork // Besides the below, popping a block should also remove the last entry // in hf_versions. // // FIXME: HardFork // This is not quite correct, as we really want to add the txes // to the pool based on the version determined after all blocks // are popped. uint8_t version = get_current_hard_fork_version(); // We assume that if they were in a block, the transactions are already // known to the network as a whole. However, if we had mined that block, // that might not be always true. Unlikely though, and always relaying // these again might cause a spike of traffic as many nodes re-relay // all the transactions in a popped block when a reorg happens. bool r = m_tx_pool.add_tx(tx, tvc, true, true, version); if (!r) { LOG_ERROR("Error returning transaction to tx_pool"); } } } update_next_cumulative_size_limit(); m_tx_pool.on_blockchain_dec(m_db->height()-1, get_tail_id()); return popped_block; } //------------------------------------------------------------------ bool Blockchain::reset_and_set_genesis_block(const block& b) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_alternative_chains.clear(); m_db->reset(); m_hardfork->init(); block_verification_context bvc = boost::value_initialized<block_verification_context>(); add_new_block(b, bvc); return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed; } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id(uint64_t& height) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); height = m_db->height() - 1; return get_tail_id(); } //------------------------------------------------------------------ crypto::hash Blockchain::get_tail_id() const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_db->top_block_hash(); } //------------------------------------------------------------------ /*TODO: this function was...poorly written. As such, I'm not entirely * certain on what it was supposed to be doing. Need to look into this, * but it doesn't seem terribly important just yet. * * puts into list <ids> a list of hashes representing certain blocks * from the blockchain in reverse chronological order * * the blocks chosen, at the time of this writing, are: * the most recent 11 * powers of 2 less recent from there, so 13, 17, 25, etc... * */ bool Blockchain::get_short_chain_history(std::list<crypto::hash>& ids) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t i = 0; uint64_t current_multiplier = 1; uint64_t sz = m_db->height(); if(!sz) return true; m_db->block_txn_start(true); bool genesis_included = false; uint64_t current_back_offset = 1; while(current_back_offset < sz) { ids.push_back(m_db->get_block_hash_from_height(sz - current_back_offset)); if(sz-current_back_offset == 0) { genesis_included = true; } if(i < 10) { ++current_back_offset; } else { current_multiplier *= 2; current_back_offset += current_multiplier; } ++i; } if (!genesis_included) { ids.push_back(m_db->get_block_hash_from_height(0)); } m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ crypto::hash Blockchain::get_block_id_by_height(uint64_t height) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); try { return m_db->get_block_hash_from_height(height); } catch (const BLOCK_DNE& e) { } catch (const std::exception& e) { LOG_PRINT_L0(std::string("Something went wrong fetching block hash by height: ") + e.what()); throw; } catch (...) { LOG_PRINT_L0(std::string("Something went wrong fetching block hash by height")); throw; } return null_hash; } //------------------------------------------------------------------ bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // try to find block in main chain try { blk = m_db->get_block(h); return true; } // try to find block in alternative chain catch (const BLOCK_DNE& e) { blocks_ext_by_hash::const_iterator it_alt = m_alternative_chains.find(h); if (m_alternative_chains.end() != it_alt) { blk = it_alt->second.bl; return true; } } catch (const std::exception& e) { LOG_PRINT_L0(std::string("Something went wrong fetching block by hash: ") + e.what()); throw; } catch (...) { LOG_PRINT_L0(std::string("Something went wrong fetching block hash by hash")); throw; } return false; } //------------------------------------------------------------------ //FIXME: this function does not seem to be called from anywhere, but // if it ever is, should probably change std::list for std::vector void Blockchain::get_all_known_block_ids(std::list<crypto::hash> &main, std::list<crypto::hash> &alt, std::list<crypto::hash> &invalid) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); for (auto& a : m_db->get_hashes_range(0, m_db->height() - 1)) { main.push_back(a); } for (const blocks_ext_by_hash::value_type &v: m_alternative_chains) alt.push_back(v.first); for (const blocks_ext_by_hash::value_type &v: m_invalid_blocks) invalid.push_back(v.first); } //------------------------------------------------------------------ // This function aggregates the cumulative difficulties and timestamps of the // last DIFFICULTY_BLOCKS_COUNT blocks and passes them to next_difficulty, // returning the result of that call. Ignores the genesis block, and can use // less blocks than desired if there aren't enough. difficulty_type Blockchain::get_difficulty_for_next_block() { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); std::vector<uint64_t> timestamps; std::vector<difficulty_type> difficulties; auto height = m_db->height(); // ND: Speedup // 1. Keep a list of the last 735 (or less) blocks that is used to compute difficulty, // then when the next block difficulty is queried, push the latest height data and // pop the oldest one from the list. This only requires 1x read per height instead // of doing 735 (DIFFICULTY_BLOCKS_COUNT). if (m_timestamps_and_difficulties_height != 0 && ((height - m_timestamps_and_difficulties_height) == 1)) { uint64_t index = height - 1; m_timestamps.push_back(m_db->get_block_timestamp(index)); m_difficulties.push_back(m_db->get_block_cumulative_difficulty(index)); while (m_timestamps.size() > DIFFICULTY_BLOCKS_COUNT) m_timestamps.erase(m_timestamps.begin()); while (m_difficulties.size() > DIFFICULTY_BLOCKS_COUNT) m_difficulties.erase(m_difficulties.begin()); m_timestamps_and_difficulties_height = height; timestamps = m_timestamps; difficulties = m_difficulties; } else { size_t offset = height - std::min < size_t > (height, static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)); if (offset == 0) ++offset; timestamps.clear(); difficulties.clear(); for (; offset < height; offset++) { timestamps.push_back(m_db->get_block_timestamp(offset)); difficulties.push_back(m_db->get_block_cumulative_difficulty(offset)); } m_timestamps_and_difficulties_height = height; m_timestamps = timestamps; m_difficulties = difficulties; } size_t target = get_current_hard_fork_version() < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2; return next_difficulty(timestamps, difficulties, target); } //------------------------------------------------------------------ // This function removes blocks from the blockchain until it gets to the // position where the blockchain switch started and then re-adds the blocks // that had been removed. bool Blockchain::rollback_blockchain_switching(std::list<block>& original_chain, uint64_t rollback_height) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // fail if rollback_height passed is too high if (rollback_height > m_db->height()) { return true; } m_timestamps_and_difficulties_height = 0; // remove blocks from blockchain until we get back to where we should be. while (m_db->height() != rollback_height) { pop_block_from_blockchain(); } //return back original chain for (auto& bl : original_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_block_to_main_chain(bl, bvc); CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC! failed to add (again) block while chain switching during the rollback!"); } m_hardfork->reorganize_from_chain_height(rollback_height); LOG_PRINT_L1("Rollback to height " << rollback_height << " was successful."); if (original_chain.size()) { LOG_PRINT_L1("Restoration to previous blockchain successful as well."); } return true; } //------------------------------------------------------------------ // This function attempts to switch to an alternate chain, returning // boolean based on success therein. bool Blockchain::switch_to_alternative_blockchain(std::list<blocks_ext_by_hash::iterator>& alt_chain, bool discard_disconnected_chain) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; // if empty alt chain passed (not sure how that could happen), return false CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed"); // verify that main chain has front of alt chain's parent block if (!m_db->block_exists(alt_chain.front()->second.bl.prev_id)) { LOG_ERROR("Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!"); return false; } // pop blocks from the blockchain until the top block is the parent // of the front block of the alt chain. std::list<block> disconnected_chain; while (m_db->top_block_hash() != alt_chain.front()->second.bl.prev_id) { block b = pop_block_from_blockchain(); disconnected_chain.push_front(b); } auto split_height = m_db->height(); //connecting new alternative chain for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++) { auto ch_ent = *alt_ch_iter; block_verification_context bvc = boost::value_initialized<block_verification_context>(); // add block to main chain bool r = handle_block_to_main_chain(ch_ent->second.bl, bvc); // if adding block to main chain failed, rollback to previous state and // return false if(!r || !bvc.m_added_to_main_chain) { LOG_PRINT_L1("Failed to switch to alternative blockchain"); // rollback_blockchain_switching should be moved to two different // functions: rollback and apply_chain, but for now we pretend it is // just the latter (because the rollback was done above). rollback_blockchain_switching(disconnected_chain, split_height); // FIXME: Why do we keep invalid blocks around? Possibly in case we hear // about them again so we can immediately dismiss them, but needs some // looking into. add_block_as_invalid(ch_ent->second, get_block_hash(ch_ent->second.bl)); LOG_PRINT_L1("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl)); m_alternative_chains.erase(ch_ent); for(auto alt_ch_to_orph_iter = ++alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); alt_ch_to_orph_iter++) { add_block_as_invalid((*alt_ch_iter)->second, (*alt_ch_iter)->first); m_alternative_chains.erase(*alt_ch_to_orph_iter); } return false; } } // if we're to keep the disconnected blocks, add them as alternates if(!discard_disconnected_chain) { //pushing old chain as alternative chain for (auto& old_ch_ent : disconnected_chain) { block_verification_context bvc = boost::value_initialized<block_verification_context>(); bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc); if(!r) { LOG_PRINT_L1("Failed to push ex-main chain blocks to alternative chain "); // previously this would fail the blockchain switching, but I don't // think this is bad enough to warrant that. } } } //removing alt_chain entries from alternative chains container for (auto ch_ent: alt_chain) { m_alternative_chains.erase(ch_ent); } m_hardfork->reorganize_from_chain_height(split_height); LOG_PRINT_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_db->height(), LOG_LEVEL_0); return true; } //------------------------------------------------------------------ // This function calculates the difficulty target for the block being added to // an alternate chain. difficulty_type Blockchain::get_next_difficulty_for_alternative_chain(const std::list<blocks_ext_by_hash::iterator>& alt_chain, block_extended_info& bei) const { LOG_PRINT_L3("Blockchain::" << __func__); std::vector<uint64_t> timestamps; std::vector<difficulty_type> cumulative_difficulties; // if the alt chain isn't long enough to calculate the difficulty target // based on its blocks alone, need to get more blocks from the main chain if(alt_chain.size()< DIFFICULTY_BLOCKS_COUNT) { CRITICAL_REGION_LOCAL(m_blockchain_lock); // Figure out start and stop offsets for main chain blocks size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front()->second.height : bei.height; size_t main_chain_count = DIFFICULTY_BLOCKS_COUNT - std::min(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT), alt_chain.size()); main_chain_count = std::min(main_chain_count, main_chain_stop_offset); size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count; if(!main_chain_start_offset) ++main_chain_start_offset; //skip genesis block // get difficulties and timestamps from relevant main chain blocks for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset) { timestamps.push_back(m_db->get_block_timestamp(main_chain_start_offset)); cumulative_difficulties.push_back(m_db->get_block_cumulative_difficulty(main_chain_start_offset)); } // make sure we haven't accidentally grabbed too many blocks...maybe don't need this check? CHECK_AND_ASSERT_MES((alt_chain.size() + timestamps.size()) <= DIFFICULTY_BLOCKS_COUNT, false, "Internal error, alt_chain.size()[" << alt_chain.size() << "] + vtimestampsec.size()[" << timestamps.size() << "] NOT <= DIFFICULTY_WINDOW[]" << DIFFICULTY_BLOCKS_COUNT); for (auto it : alt_chain) { timestamps.push_back(it->second.bl.timestamp); cumulative_difficulties.push_back(it->second.cumulative_difficulty); } } // if the alt chain is long enough for the difficulty calc, grab difficulties // and timestamps from it alone else { timestamps.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)); cumulative_difficulties.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)); size_t count = 0; size_t max_i = timestamps.size()-1; // get difficulties and timestamps from most recent blocks in alt chain BOOST_REVERSE_FOREACH(auto it, alt_chain) { timestamps[max_i - count] = it->second.bl.timestamp; cumulative_difficulties[max_i - count] = it->second.cumulative_difficulty; count++; if(count >= DIFFICULTY_BLOCKS_COUNT) break; } } // FIXME: This will fail if fork activation heights are subject to voting size_t target = get_ideal_hard_fork_version(bei.height) < 2 ? DIFFICULTY_TARGET_V1 : DIFFICULTY_TARGET_V2; // calculate the difficulty target for the block and return it return next_difficulty(timestamps, cumulative_difficulties, target); } //------------------------------------------------------------------ // This function does a sanity check on basic things that all miner // transactions have in common, such as: // one input, of type txin_gen, with height set to the block's height // correct miner tx unlock time // a non-overflowing tx amount (dubious necessity on this check) bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height) { LOG_PRINT_L3("Blockchain::" << __func__); CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs"); CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type"); if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height) { LOG_PRINT_RED_L1("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height); return false; } CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW, false, "coinbase transaction transaction has the wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW); //check outs overflow //NOTE: not entirely sure this is necessary, given that this function is // designed simply to make sure the total amount for a transaction // does not overflow a uint64_t, and this transaction *is* a uint64_t... if(!check_outs_overflow(b.miner_tx)) { LOG_PRINT_RED_L1("miner transaction has money overflow in block " << get_block_hash(b)); return false; } return true; } //------------------------------------------------------------------ // This function validates the miner transaction reward bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_size, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, bool &partial_block_reward, uint8_t version) { LOG_PRINT_L3("Blockchain::" << __func__); //validate reward uint64_t money_in_use = 0; for (auto& o: b.miner_tx.vout) money_in_use += o.amount; partial_block_reward = false; if (version == 3) { for (auto &o: b.miner_tx.vout) { if (!is_valid_decomposed_amount(o.amount)) { LOG_PRINT_L1("miner tx output " << print_money(o.amount) << " is not a valid decomposed amount"); return false; } } } std::vector<size_t> last_blocks_sizes; get_last_n_blocks_sizes(last_blocks_sizes, CRYPTONOTE_REWARD_BLOCKS_WINDOW); if (!get_block_reward(epee::misc_utils::median(last_blocks_sizes), cumulative_block_size, already_generated_coins, base_reward, version)) { LOG_PRINT_L1("block size " << cumulative_block_size << " is bigger than allowed for this blockchain"); return false; } if(base_reward + fee < money_in_use) { LOG_PRINT_L1("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")"); return false; } // From hard fork 2, we allow a miner to claim less block reward than is allowed, in case a miner wants less dust if (m_hardfork->get_current_version() < 2) { if(base_reward + fee != money_in_use) { LOG_PRINT_L1("coinbase transaction doesn't use full amount of block reward: spent: " << money_in_use << ", block reward " << base_reward + fee << "(" << base_reward << "+" << fee << ")"); return false; } } else { // from hard fork 2, since a miner can claim less than the full block reward, we update the base_reward // to show the amount of coins that were actually generated, the remainder will be pushed back for later // emission. This modifies the emission curve very slightly. CHECK_AND_ASSERT_MES(money_in_use - fee <= base_reward, false, "base reward calculation bug"); if(base_reward + fee != money_in_use) partial_block_reward = true; base_reward = money_in_use - fee; } return true; } //------------------------------------------------------------------ // get the block sizes of the last <count> blocks, and return by reference <sz>. void Blockchain::get_last_n_blocks_sizes(std::vector<size_t>& sz, size_t count) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); auto h = m_db->height(); // this function is meaningless for an empty blockchain...granted it should never be empty if(h == 0) return; m_db->block_txn_start(true); // add size of last <count> blocks to vector <sz> (or less, if blockchain size < count) size_t start_offset = h - std::min<size_t>(h, count); for(size_t i = start_offset; i < h; i++) { sz.push_back(m_db->get_block_size(i)); } m_db->block_txn_stop(); } //------------------------------------------------------------------ uint64_t Blockchain::get_current_cumulative_blocksize_limit() const { LOG_PRINT_L3("Blockchain::" << __func__); return m_current_block_cumul_sz_limit; } //------------------------------------------------------------------ //TODO: This function only needed minor modification to work with BlockchainDB, // and *works*. As such, to reduce the number of things that might break // in moving to BlockchainDB, this function will remain otherwise // unchanged for the time being. // // This function makes a new block for a miner to mine the hash for // // FIXME: this codebase references #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) // in a lot of places. That flag is not referenced in any of the code // nor any of the makefiles, howeve. Need to look into whether or not it's // necessary at all. bool Blockchain::create_block_template(block& b, const account_public_address& miner_address, difficulty_type& diffic, uint64_t& height, const blobdata& ex_nonce) { LOG_PRINT_L3("Blockchain::" << __func__); size_t median_size; uint64_t already_generated_coins; CRITICAL_REGION_BEGIN(m_blockchain_lock); height = m_db->height(); b.major_version = m_hardfork->get_current_version(); b.minor_version = m_hardfork->get_ideal_version(); b.prev_id = get_tail_id(); b.timestamp = time(NULL); diffic = get_difficulty_for_next_block(); CHECK_AND_ASSERT_MES(diffic, false, "difficulty overhead."); median_size = m_current_block_cumul_sz_limit / 2; already_generated_coins = m_db->get_block_already_generated_coins(height - 1); CRITICAL_REGION_END(); size_t txs_size; uint64_t fee; if (!m_tx_pool.fill_block_template(b, median_size, already_generated_coins, txs_size, fee)) { return false; } #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) size_t real_txs_size = 0; uint64_t real_fee = 0; CRITICAL_REGION_BEGIN(m_tx_pool.m_transactions_lock); for(crypto::hash &cur_hash: b.tx_hashes) { auto cur_res = m_tx_pool.m_transactions.find(cur_hash); if (cur_res == m_tx_pool.m_transactions.end()) { LOG_ERROR("Creating block template: error: transaction not found"); continue; } tx_memory_pool::tx_details &cur_tx = cur_res->second; real_txs_size += cur_tx.blob_size; real_fee += cur_tx.fee; if (cur_tx.blob_size != get_object_blobsize(cur_tx.tx)) { LOG_ERROR("Creating block template: error: invalid transaction size"); } if (cur_tx.tx.version == 1) { uint64_t inputs_amount; if (!get_inputs_money_amount(cur_tx.tx, inputs_amount)) { LOG_ERROR("Creating block template: error: cannot get inputs amount"); } else if (cur_tx.fee != inputs_amount - get_outs_money_amount(cur_tx.tx)) { LOG_ERROR("Creating block template: error: invalid fee"); } } else { if (cur_tx.fee != cur_tx.tx.rct_signatures.txnFee) { LOG_ERROR("Creating block template: error: invalid fee"); } } } if (txs_size != real_txs_size) { LOG_ERROR("Creating block template: error: wrongly calculated transaction size"); } if (fee != real_fee) { LOG_ERROR("Creating block template: error: wrongly calculated fee"); } CRITICAL_REGION_END(); LOG_PRINT_L1("Creating block template: height " << height << ", median size " << median_size << ", already generated coins " << already_generated_coins << ", transaction size " << txs_size << ", fee " << fee); #endif /* two-phase miner transaction generation: we don't know exact block size until we prepare block, but we don't know reward until we know block size, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block size */ //make blocks coin-base tx looks close to real coinbase tx to get truthful blob size uint8_t hf_version = m_hardfork->get_current_version(); size_t max_outs = hf_version >= 4 ? 1 : 11; bool r = construct_miner_tx(height, median_size, already_generated_coins, txs_size, fee, miner_address, b.miner_tx, ex_nonce, max_outs, hf_version); CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance"); size_t cumulative_size = txs_size + get_object_blobsize(b.miner_tx); #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) LOG_PRINT_L1("Creating block template: miner tx size " << get_object_blobsize(b.miner_tx) << ", cumulative size " << cumulative_size); #endif for (size_t try_count = 0; try_count != 10; ++try_count) { r = construct_miner_tx(height, median_size, already_generated_coins, cumulative_size, fee, miner_address, b.miner_tx, ex_nonce, max_outs, hf_version); CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, second chance"); size_t coinbase_blob_size = get_object_blobsize(b.miner_tx); if (coinbase_blob_size > cumulative_size - txs_size) { cumulative_size = txs_size + coinbase_blob_size; #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size << ", cumulative size " << cumulative_size << " is greater then before"); #endif continue; } if (coinbase_blob_size < cumulative_size - txs_size) { size_t delta = cumulative_size - txs_size - coinbase_blob_size; #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size << ", cumulative size " << txs_size + coinbase_blob_size << " is less then before, adding " << delta << " zero bytes"); #endif b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0); //here could be 1 byte difference, because of extra field counter is varint, and it can become from 1-byte len to 2-bytes len. if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) { CHECK_AND_ASSERT_MES(cumulative_size + 1 == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " + 1 is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx)); b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1); if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) { //fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_size LOG_PRINT_RED("Miner tx creation has no luck with delta_extra size = " << delta << " and " << delta - 1 , LOG_LEVEL_2); cumulative_size += delta - 1; continue; } LOG_PRINT_GREEN("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count, LOG_LEVEL_1); } } CHECK_AND_ASSERT_MES(cumulative_size == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx)); #if defined(DEBUG_CREATE_BLOCK_TEMPLATE) LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size << ", cumulative size " << cumulative_size << " is now good"); #endif return true; } LOG_ERROR("Failed to create_block_template with " << 10 << " tries"); return false; } //------------------------------------------------------------------ // for an alternate chain, get the timestamps from the main chain to complete // the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps) { LOG_PRINT_L3("Blockchain::" << __func__); if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) return true; CRITICAL_REGION_LOCAL(m_blockchain_lock); size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size(); CHECK_AND_ASSERT_MES(start_top_height < m_db->height(), false, "internal error: passed start_height not < " << " m_db->height() -- " << start_top_height << " >= " << m_db->height()); size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements : 0; while (start_top_height != stop_offset) { timestamps.push_back(m_db->get_block_timestamp(start_top_height)); --start_top_height; } return true; } //------------------------------------------------------------------ // If a block is to be added and its parent block is not the current // main chain top block, then we need to see if we know about its parent block. // If its parent block is part of a known forked chain, then we need to see // if that chain is long enough to become the main chain and re-org accordingly // if so. If not, we need to hang on to the block in case it becomes part of // a long forked chain eventually. bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_timestamps_and_difficulties_height = 0; uint64_t block_height = get_block_height(b); if(0 == block_height) { LOG_PRINT_L1("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative), but miner tx says height is 0."); bvc.m_verifivation_failed = true; return false; } // this basically says if the blockchain is smaller than the first // checkpoint then alternate blocks are allowed. Alternatively, if the // last checkpoint *before* the end of the current chain is also before // the block to be added, then this is fine. if (!m_checkpoints.is_alternative_block_allowed(get_current_blockchain_height(), block_height)) { LOG_PRINT_RED_L1("Block with id: " << id << std::endl << " can't be accepted for alternative chain, block height: " << block_height << std::endl << " blockchain height: " << get_current_blockchain_height()); bvc.m_verifivation_failed = true; return false; } //block is not related with head of main chain //first of all - look in alternative chains container auto it_prev = m_alternative_chains.find(b.prev_id); bool parent_in_main = m_db->block_exists(b.prev_id); if(it_prev != m_alternative_chains.end() || parent_in_main) { //we have new block in alternative chain //build alternative subchain, front -> mainchain, back -> alternative head blocks_ext_by_hash::iterator alt_it = it_prev; //m_alternative_chains.find() std::list<blocks_ext_by_hash::iterator> alt_chain; std::vector<uint64_t> timestamps; while(alt_it != m_alternative_chains.end()) { alt_chain.push_front(alt_it); timestamps.push_back(alt_it->second.bl.timestamp); alt_it = m_alternative_chains.find(alt_it->second.bl.prev_id); } // if block to be added connects to known blocks that aren't part of the // main chain -- that is, if we're adding on to an alternate chain if(alt_chain.size()) { // make sure alt chain doesn't somehow start past the end of the main chain CHECK_AND_ASSERT_MES(m_db->height() > alt_chain.front()->second.height, false, "main blockchain wrong height"); // make sure that the blockchain contains the block that should connect // this alternate chain with it. if (!m_db->block_exists(alt_chain.front()->second.bl.prev_id)) { LOG_PRINT_L1("alternate chain does not appear to connect to main chain..."); return false; } // make sure block connects correctly to the main chain auto h = m_db->get_block_hash_from_height(alt_chain.front()->second.height - 1); CHECK_AND_ASSERT_MES(h == alt_chain.front()->second.bl.prev_id, false, "alternative chain has wrong connection to main chain"); complete_timestamps_vector(m_db->get_block_height(alt_chain.front()->second.bl.prev_id), timestamps); } // if block not associated with known alternate chain else { // if block parent is not part of main chain or an alternate chain, // we ignore it CHECK_AND_ASSERT_MES(parent_in_main, false, "internal error: broken imperative condition: parent_in_main"); complete_timestamps_vector(m_db->get_block_height(b.prev_id), timestamps); } // verify that the block's timestamp is within the acceptable range // (not earlier than the median of the last X blocks) if(!check_block_timestamp(timestamps, b)) { LOG_PRINT_RED_L1("Block with id: " << id << std::endl << " for alternative chain, has invalid timestamp: " << b.timestamp); bvc.m_verifivation_failed = true; return false; } // FIXME: consider moving away from block_extended_info at some point block_extended_info bei = boost::value_initialized<block_extended_info>(); bei.bl = b; bei.height = alt_chain.size() ? it_prev->second.height + 1 : m_db->get_block_height(b.prev_id) + 1; bool is_a_checkpoint; if(!m_checkpoints.check_block(bei.height, id, is_a_checkpoint)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; return false; } // Check the block's hash against the difficulty target for its alt chain m_is_in_checkpoint_zone = false; difficulty_type current_diff = get_next_difficulty_for_alternative_chain(alt_chain, bei); CHECK_AND_ASSERT_MES(current_diff, false, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!"); crypto::hash proof_of_work = null_hash; get_block_longhash(bei.bl, proof_of_work, bei.height); if(!check_hash(proof_of_work, current_diff)) { LOG_PRINT_RED_L1("Block with id: " << id << std::endl << " for alternative chain, does not have enough proof of work: " << proof_of_work << std::endl << " expected difficulty: " << current_diff); bvc.m_verifivation_failed = true; return false; } if(!prevalidate_miner_transaction(b, bei.height)) { LOG_PRINT_RED_L1("Block with id: " << epee::string_tools::pod_to_hex(id) << " (as alternative) has incorrect miner transaction."); bvc.m_verifivation_failed = true; return false; } // FIXME: // this brings up an interesting point: consider allowing to get block // difficulty both by height OR by hash, not just height. difficulty_type main_chain_cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->height() - 1); if (alt_chain.size()) { bei.cumulative_difficulty = it_prev->second.cumulative_difficulty; } else { // passed-in block's previous block's cumulative difficulty, found on the main chain bei.cumulative_difficulty = m_db->get_block_cumulative_difficulty(m_db->get_block_height(b.prev_id)); } bei.cumulative_difficulty += current_diff; // add block to alternate blocks storage, // as well as the current "alt chain" container auto i_res = m_alternative_chains.insert(blocks_ext_by_hash::value_type(id, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "insertion of new alternative block returned as it already exist"); alt_chain.push_back(i_res.first); // FIXME: is it even possible for a checkpoint to show up not on the main chain? if(is_a_checkpoint) { //do reorganize! LOG_PRINT_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_db->height() - 1 << ", checkpoint is found in alternative chain on height " << bei.height, LOG_LEVEL_0); bool r = switch_to_alternative_blockchain(alt_chain, true); if(r) bvc.m_added_to_main_chain = true; else bvc.m_verifivation_failed = true; return r; } else if(main_chain_cumulative_difficulty < bei.cumulative_difficulty) //check if difficulty bigger then in main chain { //do reorganize! LOG_PRINT_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_db->height() - 1 << " with cum_difficulty " << m_db->get_block_cumulative_difficulty(m_db->height() - 1) << std::endl << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << bei.cumulative_difficulty, LOG_LEVEL_0); bool r = switch_to_alternative_blockchain(alt_chain, false); if (r) bvc.m_added_to_main_chain = true; else bvc.m_verifivation_failed = true; return r; } else { LOG_PRINT_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << bei.height << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "difficulty:\t" << current_diff, LOG_LEVEL_0); return true; } } else { //block orphaned bvc.m_marked_as_orphaned = true; LOG_PRINT_RED_L1("Block recognized as orphaned and rejected, id = " << id); } return true; } //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks, std::list<transaction>& txs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_offset > m_db->height()) return false; if (!get_blocks(start_offset, count, blocks)) { return false; } for(const block& blk : blocks) { std::list<crypto::hash> missed_ids; get_transactions(blk.tx_hashes, txs, missed_ids); CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "has missed transactions in own block in main blockchain"); } return true; } //------------------------------------------------------------------ bool Blockchain::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(start_offset > m_db->height()) return false; for(size_t i = start_offset; i < start_offset + count && i < m_db->height();i++) { blocks.push_back(m_db->get_block_from_height(i)); } return true; } //------------------------------------------------------------------ //TODO: This function *looks* like it won't need to be rewritten // to use BlockchainDB, as it calls other functions that were, // but it warrants some looking into later. // //FIXME: This function appears to want to return false if any transactions // that belong with blocks are missing, but not if blocks themselves // are missing. bool Blockchain::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_db->block_txn_start(true); rsp.current_blockchain_height = get_current_blockchain_height(); std::list<block> blocks; get_blocks(arg.blocks, blocks, rsp.missed_ids); for (const auto& bl: blocks) { std::list<crypto::hash> missed_tx_ids; std::list<transaction> txs; // FIXME: s/rsp.missed_ids/missed_tx_id/ ? Seems like rsp.missed_ids // is for missed blocks, not missed transactions as well. get_transactions(bl.tx_hashes, txs, missed_tx_ids); if (missed_tx_ids.size() != 0) { LOG_ERROR("Error retrieving blocks, missed " << missed_tx_ids.size() << " transactions for block with hash: " << get_block_hash(bl) << std::endl ); // append missed transaction hashes to response missed_ids field, // as done below if any standalone transactions were requested // and missed. rsp.missed_ids.splice(rsp.missed_ids.end(), missed_tx_ids); m_db->block_txn_stop(); return false; } rsp.blocks.push_back(block_complete_entry()); block_complete_entry& e = rsp.blocks.back(); //pack block e.block = t_serializable_object_to_blob(bl); //pack transactions for (transaction& tx: txs) e.txs.push_back(t_serializable_object_to_blob(tx)); } //get another transactions, if need std::list<transaction> txs; get_transactions(arg.txs, txs, rsp.missed_ids); //pack aside transactions for (const auto& tx: txs) rsp.txs.push_back(t_serializable_object_to_blob(tx)); m_db->block_txn_stop(); return true; } //------------------------------------------------------------------ bool Blockchain::get_alternative_blocks(std::list<block>& blocks) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); for (const auto& alt_bl: m_alternative_chains) { blocks.push_back(alt_bl.second.bl); } return true; } //------------------------------------------------------------------ size_t Blockchain::get_alternative_blocks_count() const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_alternative_chains.size(); } //------------------------------------------------------------------ // This function adds the output specified by <amount, i> to the result_outs container // unlocked and other such checks should be done by here. void Blockchain::add_out_to_get_random_outs(COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs, uint64_t amount, size_t i) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& oen = *result_outs.outs.insert(result_outs.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry()); oen.global_amount_index = i; output_data_t data = m_db->get_output_key(amount, i); oen.out_key = data.pubkey; } //------------------------------------------------------------------ // This function takes an RPC request for mixins and creates an RPC response // with the requested mixins. // TODO: figure out why this returns boolean / if we should be returning false // in some cases bool Blockchain::get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // for each amount that we need to get mixins for, get <n> random outputs // from BlockchainDB where <n> is req.outs_count (number of mixins). for (uint64_t amount : req.amounts) { auto num_outs = m_db->get_num_outputs(amount); // ensure we don't include outputs that aren't yet eligible to be used // outpouts are sorted by height while (num_outs > 0) { const tx_out_index toi = m_db->get_output_tx_and_index(amount, num_outs - 1); const uint64_t height = m_db->get_tx_block_height(toi.first); if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= m_db->height()) break; --num_outs; } // create outs_for_amount struct and populate amount field COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs = *res.outs.insert(res.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount()); result_outs.amount = amount; std::unordered_set<uint64_t> seen_indices; // if there aren't enough outputs to mix with (or just enough), // use all of them. Eventually this should become impossible. if (num_outs <= req.outs_count) { for (uint64_t i = 0; i < num_outs; i++) { // get tx_hash, tx_out_index from DB tx_out_index toi = m_db->get_output_tx_and_index(amount, i); // if tx is unlocked, add output to result_outs if (is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first))) { add_out_to_get_random_outs(result_outs, amount, i); } } } else { // while we still need more mixins while (result_outs.outs.size() < req.outs_count) { // if we've gone through every possible output, we've gotten all we can if (seen_indices.size() == num_outs) { break; } // get a random output index from the DB. If we've already seen it, // return to the top of the loop and try again, otherwise add it to the // list of output indices we've seen. // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); uint64_t i = (uint64_t)(frac*num_outs); // just in case rounding up to 1 occurs after sqrt if (i == num_outs) --i; if (seen_indices.count(i)) { continue; } seen_indices.emplace(i); // get tx_hash, tx_out_index from DB tx_out_index toi = m_db->get_output_tx_and_index(amount, i); // if the output's transaction is unlocked, add the output's index to // our list. if (is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first))) { add_out_to_get_random_outs(result_outs, amount, i); } } } } return true; } //------------------------------------------------------------------ // This function adds the ringct output at index i to the list // unlocked and other such checks should be done by here. void Blockchain::add_out_to_get_rct_random_outs(std::list<COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::out_entry>& outs, uint64_t amount, size_t i) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::out_entry& oen = *outs.insert(outs.end(), COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::out_entry()); oen.amount = amount; oen.global_amount_index = i; output_data_t data = m_db->get_output_key(amount, i); oen.out_key = data.pubkey; oen.commitment = data.commitment; } //------------------------------------------------------------------ // This function takes an RPC request for mixins and creates an RPC response // with the requested mixins. // TODO: figure out why this returns boolean / if we should be returning false // in some cases bool Blockchain::get_random_rct_outs(const COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::request& req, COMMAND_RPC_GET_RANDOM_RCT_OUTPUTS::response& res) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // for each amount that we need to get mixins for, get <n> random outputs // from BlockchainDB where <n> is req.outs_count (number of mixins). auto num_outs = m_db->get_num_outputs(0); // ensure we don't include outputs that aren't yet eligible to be used // outpouts are sorted by height while (num_outs > 0) { const tx_out_index toi = m_db->get_output_tx_and_index(0, num_outs - 1); const uint64_t height = m_db->get_tx_block_height(toi.first); if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= m_db->height()) break; --num_outs; } std::unordered_set<uint64_t> seen_indices; // if there aren't enough outputs to mix with (or just enough), // use all of them. Eventually this should become impossible. if (num_outs <= req.outs_count) { for (uint64_t i = 0; i < num_outs; i++) { // get tx_hash, tx_out_index from DB tx_out_index toi = m_db->get_output_tx_and_index(0, i); // if tx is unlocked, add output to result_outs if (is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first))) { add_out_to_get_rct_random_outs(res.outs, 0, i); } } } else { // while we still need more mixins while (res.outs.size() < req.outs_count) { // if we've gone through every possible output, we've gotten all we can if (seen_indices.size() == num_outs) { break; } // get a random output index from the DB. If we've already seen it, // return to the top of the loop and try again, otherwise add it to the // list of output indices we've seen. // triangular distribution over [a,b) with a=0, mode c=b=up_index_limit uint64_t r = crypto::rand<uint64_t>() % ((uint64_t)1 << 53); double frac = std::sqrt((double)r / ((uint64_t)1 << 53)); uint64_t i = (uint64_t)(frac*num_outs); // just in case rounding up to 1 occurs after sqrt if (i == num_outs) --i; if (seen_indices.count(i)) { continue; } seen_indices.emplace(i); // get tx_hash, tx_out_index from DB tx_out_index toi = m_db->get_output_tx_and_index(0, i); // if the output's transaction is unlocked, add the output's index to // our list. if (is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first))) { add_out_to_get_rct_random_outs(res.outs, 0, i); } } } if (res.outs.size() < req.outs_count) return false; #if 0 // if we do not have enough RCT inputs, we can pick from the non RCT ones // which will have a zero mask if (res.outs.size() < req.outs_count) { LOG_PRINT_L0("Out of RCT inputs (" << res.outs.size() << "/" << req.outs_count << "), using regular ones"); // TODO: arbitrary selection, needs better COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request req2 = AUTO_VAL_INIT(req2); COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response res2 = AUTO_VAL_INIT(res2); req2.outs_count = req.outs_count - res.outs.size(); static const uint64_t amounts[] = {1, 10, 20, 50, 100, 200, 500, 1000, 10000}; for (uint64_t a: amounts) req2.amounts.push_back(a); if (!get_random_outs_for_amounts(req2, res2)) return false; // pick random ones from there while (res.outs.size() < req.outs_count) { int list_idx = rand() % (sizeof(amounts)/sizeof(amounts[0])); if (!res2.outs[list_idx].outs.empty()) { const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry oe = res2.outs[list_idx].outs.back(); res2.outs[list_idx].outs.pop_back(); add_out_to_get_rct_random_outs(res.outs, res2.outs[list_idx].amount, oe.global_amount_index); } } } #endif return true; } //------------------------------------------------------------------ bool Blockchain::get_outs(const COMMAND_RPC_GET_OUTPUTS::request& req, COMMAND_RPC_GET_OUTPUTS::response& res) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); res.outs.clear(); res.outs.reserve(req.outputs.size()); for (const auto &i: req.outputs) { // get tx_hash, tx_out_index from DB const output_data_t od = m_db->get_output_key(i.amount, i.index); tx_out_index toi = m_db->get_output_tx_and_index(i.amount, i.index); bool unlocked = is_tx_spendtime_unlocked(m_db->get_tx_unlock_time(toi.first)); res.outs.push_back({od.pubkey, od.commitment, unlocked}); } return true; } //------------------------------------------------------------------ // This function takes a list of block hashes from another node // on the network to find where the split point is between us and them. // This is used to see what to send another node that needs to sync. bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // make sure the request includes at least the genesis block, otherwise // how can we expect to sync from the client that the block list came from? if(!qblock_ids.size() /*|| !req.m_total_height*/) { LOG_PRINT_L1("Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << /*", m_height=" << req.m_total_height <<*/ ", dropping connection"); return false; } m_db->block_txn_start(true); // make sure that the last block in the request's block list matches // the genesis block auto gen_hash = m_db->get_block_hash_from_height(0); if(qblock_ids.back() != gen_hash) { LOG_PRINT_L1("Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block missmatch: " << std::endl << "id: " << qblock_ids.back() << ", " << std::endl << "expected: " << gen_hash << "," << std::endl << " dropping connection"); m_db->block_txn_abort(); return false; } // Find the first block the foreign chain has that we also have. // Assume qblock_ids is in reverse-chronological order. auto bl_it = qblock_ids.begin(); uint64_t split_height = 0; for(; bl_it != qblock_ids.end(); bl_it++) { try { if (m_db->block_exists(*bl_it, &split_height)) break; } catch (const std::exception& e) { LOG_PRINT_L1("Non-critical error trying to find block by hash in BlockchainDB, hash: " << *bl_it); m_db->block_txn_abort(); return false; } } m_db->block_txn_stop(); // this should be impossible, as we checked that we share the genesis block, // but just in case... if(bl_it == qblock_ids.end()) { LOG_PRINT_L1("Internal error handling connection, can't find split point"); return false; } //we start to put block ids INCLUDING last known id, just to make other side be sure starter_offset = split_height; return true; } //------------------------------------------------------------------ uint64_t Blockchain::block_difficulty(uint64_t i) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); try { return m_db->get_block_difficulty(i); } catch (const BLOCK_DNE& e) { LOG_PRINT_L0("Attempted to get block difficulty for height above blockchain height"); } return 0; } //------------------------------------------------------------------ //TODO: return type should be void, throw on exception // alternatively, return true only if no blocks missed template<class t_ids_container, class t_blocks_container, class t_missed_container> bool Blockchain::get_blocks(const t_ids_container& block_ids, t_blocks_container& blocks, t_missed_container& missed_bs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); for (const auto& block_hash : block_ids) { try { blocks.push_back(m_db->get_block(block_hash)); } catch (const BLOCK_DNE& e) { missed_bs.push_back(block_hash); } catch (const std::exception& e) { return false; } } return true; } //------------------------------------------------------------------ //TODO: return type should be void, throw on exception // alternatively, return true only if no transactions missed template<class t_ids_container, class t_tx_container, class t_missed_container> bool Blockchain::get_transactions(const t_ids_container& txs_ids, t_tx_container& txs, t_missed_container& missed_txs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); for (const auto& tx_hash : txs_ids) { try { txs.push_back(m_db->get_tx(tx_hash)); } catch (const TX_DNE& e) { missed_txs.push_back(tx_hash); } catch (const std::exception& e) { return false; } } return true; } //------------------------------------------------------------------ void Blockchain::print_blockchain(uint64_t start_index, uint64_t end_index) const { LOG_PRINT_L3("Blockchain::" << __func__); std::stringstream ss; CRITICAL_REGION_LOCAL(m_blockchain_lock); auto h = m_db->height(); if(start_index > h) { LOG_PRINT_L1("Wrong starter index set: " << start_index << ", expected max index " << h); return; } for(size_t i = start_index; i <= h && i != end_index; i++) { ss << "height " << i << ", timestamp " << m_db->get_block_timestamp(i) << ", cumul_dif " << m_db->get_block_cumulative_difficulty(i) << ", size " << m_db->get_block_size(i) << "\nid\t\t" << m_db->get_block_hash_from_height(i) << "\ndifficulty\t\t" << m_db->get_block_difficulty(i) << ", nonce " << m_db->get_block_from_height(i).nonce << ", tx_count " << m_db->get_block_from_height(i).tx_hashes.size() << std::endl; } LOG_PRINT_L1("Current blockchain:" << std::endl << ss.str()); LOG_PRINT_L0("Blockchain printed with log level 1"); } //------------------------------------------------------------------ void Blockchain::print_blockchain_index() const { LOG_PRINT_L3("Blockchain::" << __func__); std::stringstream ss; CRITICAL_REGION_LOCAL(m_blockchain_lock); auto height = m_db->height(); if (height != 0) { for(uint64_t i = 0; i <= height; i++) { ss << "height: " << i << ", hash: " << m_db->get_block_hash_from_height(i); } } LOG_PRINT_L0("Current blockchain index:" << std::endl << ss.str()); } //------------------------------------------------------------------ //TODO: remove this function and references to it void Blockchain::print_blockchain_outs(const std::string& file) const { LOG_PRINT_L3("Blockchain::" << __func__); return; } //------------------------------------------------------------------ // Find the split point between us and foreign blockchain and return // (by reference) the most recent common block hash along with up to // BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT additional (more recent) hashes. bool Blockchain::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // if we can't find the split point, return false if(!find_blockchain_supplement(qblock_ids, resp.start_height)) { return false; } resp.total_height = get_current_blockchain_height(); size_t count = 0; for(size_t i = resp.start_height; i < resp.total_height && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++) { resp.m_block_ids.push_back(m_db->get_block_hash_from_height(i)); } return true; } //------------------------------------------------------------------ //FIXME: change argument to std::vector, low priority // find split point between ours and foreign blockchain (or start at // blockchain height <req_start_block>), and return up to max_count FULL // blocks by reference. bool Blockchain::find_blockchain_supplement(const uint64_t req_start_block, const std::list<crypto::hash>& qblock_ids, std::list<std::pair<block, std::list<transaction> > >& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // if a specific start height has been requested if(req_start_block > 0) { // if requested height is higher than our chain, return false -- we can't help if (req_start_block >= m_db->height()) { return false; } start_height = req_start_block; } else { if(!find_blockchain_supplement(qblock_ids, start_height)) { return false; } } total_height = get_current_blockchain_height(); size_t count = 0; for(size_t i = start_height; i < total_height && count < max_count; i++, count++) { blocks.resize(blocks.size()+1); blocks.back().first = m_db->get_block_from_height(i); std::list<crypto::hash> mis; get_transactions(blocks.back().first.tx_hashes, blocks.back().second, mis); CHECK_AND_ASSERT_MES(!mis.size(), false, "internal error, transaction from block not found"); } return true; } //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(const block& bl, const crypto::hash& h) { LOG_PRINT_L3("Blockchain::" << __func__); block_extended_info bei = AUTO_VAL_INIT(bei); bei.bl = bl; return add_block_as_invalid(bei, h); } //------------------------------------------------------------------ bool Blockchain::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei)); CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed"); LOG_PRINT_L1("BLOCK ADDED AS INVALID: " << h << std::endl << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size()); return true; } //------------------------------------------------------------------ bool Blockchain::have_block(const crypto::hash& id) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(m_db->block_exists(id)) { LOG_PRINT_L3("block exists in main chain"); return true; } if(m_alternative_chains.count(id)) { LOG_PRINT_L3("block found in m_alternative_chains"); return true; } if(m_invalid_blocks.count(id)) { LOG_PRINT_L3("block found in m_invalid_blocks"); return true; } return false; } //------------------------------------------------------------------ bool Blockchain::handle_block_to_main_chain(const block& bl, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); crypto::hash id = get_block_hash(bl); return handle_block_to_main_chain(bl, id, bvc); } //------------------------------------------------------------------ size_t Blockchain::get_total_transactions() const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); return m_db->get_tx_count(); } //------------------------------------------------------------------ // This function checks each input in the transaction <tx> to make sure it // has not been used already, and adds its key to the container <keys_this_block>. // // This container should be managed by the code that validates blocks so we don't // have to store the used keys in a given block in the permanent storage only to // remove them later if the block fails validation. bool Blockchain::check_for_double_spend(const transaction& tx, key_images_container& keys_this_block) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); struct add_transaction_input_visitor: public boost::static_visitor<bool> { key_images_container& m_spent_keys; BlockchainDB* m_db; add_transaction_input_visitor(key_images_container& spent_keys, BlockchainDB* db) : m_spent_keys(spent_keys), m_db(db) { } bool operator()(const txin_to_key& in) const { const crypto::key_image& ki = in.k_image; // attempt to insert the newly-spent key into the container of // keys spent this block. If this fails, the key was spent already // in this block, return false to flag that a double spend was detected. // // if the insert into the block-wide spent keys container succeeds, // check the blockchain-wide spent keys container and make sure the // key wasn't used in another block already. auto r = m_spent_keys.insert(ki); if(!r.second || m_db->has_key_image(ki)) { //double spend detected return false; } // if no double-spend detected, return true return true; } bool operator()(const txin_gen& tx) const { return true; } bool operator()(const txin_to_script& tx) const { return false; } bool operator()(const txin_to_scripthash& tx) const { return false; } }; for (const txin_v& in : tx.vin) { if(!boost::apply_visitor(add_transaction_input_visitor(keys_this_block, m_db), in)) { LOG_ERROR("Double spend detected!"); return false; } } return true; } //------------------------------------------------------------------ bool Blockchain::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs) const { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); uint64_t tx_index; if (!m_db->tx_exists(tx_id, tx_index)) { LOG_PRINT_RED_L1("warning: get_tx_outputs_gindexs failed to find transaction with id = " << tx_id); return false; } // get amount output indexes, currently referred to in parts as "output global indices", but they are actually specific to amounts indexs = m_db->get_tx_amount_output_indices(tx_index); if (indexs.empty()) { // empty indexs is only valid if the vout is empty, which is legal but rare cryptonote::transaction tx = m_db->get_tx(tx_id); CHECK_AND_ASSERT_MES(tx.vout.empty(), false, "internal error: global indexes for transaction " << tx_id << " is empty, and tx vout is not"); } return true; } //------------------------------------------------------------------ //FIXME: it seems this function is meant to be merely a wrapper around // another function of the same name, this one adding one bit of // functionality. Should probably move anything more than that // (getting the hash of the block at height max_used_block_id) // to the other function to keep everything in one place. // This function overloads its sister function with // an extra value (hash of highest block that holds an output used as input) // as a return-by-reference. bool Blockchain::check_tx_inputs(transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id, tx_verification_context &tvc, bool kept_by_block) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); #if defined(PER_BLOCK_CHECKPOINT) // check if we're doing per-block checkpointing // FIXME: investigate why this block returns if (m_db->height() < m_blocks_hash_check.size() && kept_by_block) { TIME_MEASURE_START(a); m_blocks_txs_check.push_back(get_transaction_hash(tx)); max_used_block_id = null_hash; max_used_block_height = 0; TIME_MEASURE_FINISH(a); if(m_show_time_stats) LOG_PRINT_L0("HASH: " << "-" << " VIN/VOUT: " << tx.vin.size() << "/" << tx.vout.size() << " H: " << 0 << " chcktx: " << a); return true; } #endif TIME_MEASURE_START(a); bool res = check_tx_inputs(tx, tvc, &max_used_block_height); TIME_MEASURE_FINISH(a); if(m_show_time_stats) LOG_PRINT_L0("HASH: " << "+" << " VIN/VOUT: " << tx.vin.size() << "/" << tx.vout.size() << " H: " << max_used_block_height << " chcktx: " << a + m_fake_scan_time); if (!res) return false; CHECK_AND_ASSERT_MES(max_used_block_height < m_db->height(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_db->height()); max_used_block_id = m_db->get_block_hash_from_height(max_used_block_height); return true; } //------------------------------------------------------------------ bool Blockchain::check_tx_outputs(const transaction& tx, tx_verification_context &tvc) { LOG_PRINT_L3("Blockchain::" << __func__); CRITICAL_REGION_LOCAL(m_blockchain_lock); // from hard fork 2, we forbid dust and compound outputs if (m_hardfork->get_current_version() >= 2) { for (auto &o: tx.vout) { if (tx.version == 1) { if (!is_valid_decomposed_amount(o.amount)) { tvc.m_invalid_output = true; return false; } } } } // in a v2 tx, all outputs must have 0 amount if (m_hardfork->get_current_version() >= 3) { if (tx.version >= 2) { for (auto &o: tx.vout) { if (o.amount != 0) { tvc.m_invalid_output = true; return false; } } } } return true; } //------------------------------------------------------------------ bool Blockchain::have_tx_keyimges_as_spent(const transaction &tx) const { LOG_PRINT_L3("Blockchain::" << __func__); for (const txin_v& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true); if(have_tx_keyimg_as_spent(in_to_key.k_image)) return true; } return false; } bool Blockchain::expand_transaction_2(transaction &tx, const crypto::hash &tx_prefix_hash, const std::vector<std::vector<rct::ctkey>> &pubkeys) { PERF_TIMER(expand_transaction_2); CHECK_AND_ASSERT_MES(tx.version == 2, false, "Transaction version is not 2"); rct::rctSig &rv = tx.rct_signatures; // message - hash of the transaction prefix rv.message = rct::hash2rct(tx_prefix_hash); // mixRing - full and simple store it in opposite ways if (rv.type == rct::RCTTypeFull) { rv.mixRing.resize(pubkeys[0].size()); for (size_t m = 0; m < pubkeys[0].size(); ++m) rv.mixRing[m].clear(); for (size_t n = 0; n < pubkeys.size(); ++n) { CHECK_AND_ASSERT_MES(pubkeys[n].size() <= pubkeys[0].size(), false, "More inputs that first ring"); for (size_t m = 0; m < pubkeys[n].size(); ++m) { rv.mixRing[m].push_back(pubkeys[n][m]); } } } else if (rv.type == rct::RCTTypeSimple) { rv.mixRing.resize(pubkeys.size()); for (size_t n = 0; n < pubkeys.size(); ++n) { rv.mixRing[n].clear(); for (size_t m = 0; m < pubkeys[n].size(); ++m) { rv.mixRing[n].push_back(pubkeys[n][m]); } } } else { CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type)); } // II if (rv.type == rct::RCTTypeFull) { rv.p.MGs.resize(1); rv.p.MGs[0].II.resize(tx.vin.size()); for (size_t n = 0; n < tx.vin.size(); ++n) rv.p.MGs[0].II[n] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image); } else if (rv.type == rct::RCTTypeSimple) { CHECK_AND_ASSERT_MES(rv.p.MGs.size() == tx.vin.size(), false, "Bad MGs size"); for (size_t n = 0; n < tx.vin.size(); ++n) { rv.p.MGs[n].II.resize(1); rv.p.MGs[n].II[0] = rct::ki2rct(boost::get<txin_to_key>(tx.vin[n]).k_image); } } else { CHECK_AND_ASSERT_MES(false, false, "Unsupported rct tx type: " + boost::lexical_cast<std::string>(rv.type)); } // outPk CHECK_AND_ASSERT_MES(rv.outPk.size() == tx.vout.size(), false, "Bad outPk size"); for (size_t n = 0; n < tx.rct_signatures.outPk.size(); ++n) rv.outPk[n].dest = rct::pk2rct(boost::get<txout_to_key>(tx.vout[n].target).key); return true; } //------------------------------------------------------------------ // This function validates transaction inputs and their keys. // FIXME: consider moving functionality specific to one input into // check_tx_input() rather than here, and use this function simply // to iterate the inputs as necessary (splitting the task // using threads, etc.) bool Blockchain::check_tx_inputs(transaction& tx, tx_verification_context &tvc, uint64_t* pmax_used_block_height) { PERF_TIMER(check_tx_inputs); LOG_PRINT_L3("Blockchain::" << __func__); size_t sig_index = 0; if(pmax_used_block_height) *pmax_used_block_height = 0; crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx); const uint8_t hf_version = m_hardfork->get_current_version(); // from hard fork 2, we require mixin at least 2 unless one output cannot mix with 2 others // if one output cannot mix with 2 others, we accept at most 1 output that can mix if (hf_version >= 2) { size_t n_unmixable = 0, n_mixable = 0; size_t mixin = std::numeric_limits<size_t>::max(); const size_t min_mixin = hf_version >= 5 ? 4 : 2; for (const auto& txin : tx.vin) { // non txin_to_key inputs will be rejected below if (txin.type() == typeid(txin_to_key)) { const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); if (in_to_key.amount == 0) { // always consider rct inputs mixable. Even if there's not enough rct // inputs on the chain to mix with, this is going to be the case for // just a few blocks right after the fork at most ++n_mixable; } else { uint64_t n_outputs = m_db->get_num_outputs(in_to_key.amount); LOG_PRINT_L2("output size " << print_money(in_to_key.amount) << ": " << n_outputs << " available"); // n_outputs includes the output we're considering if (n_outputs <= min_mixin) ++n_unmixable; else ++n_mixable; } if (in_to_key.key_offsets.size() - 1 < mixin) mixin = in_to_key.key_offsets.size() - 1; } } if (mixin < min_mixin) { if (n_unmixable == 0) { LOG_PRINT_L1("Tx " << get_transaction_hash(tx) << " has too low mixin (" << mixin << "), and no unmixable inputs"); tvc.m_low_mixin = true; return false; } if (n_mixable > 1) { LOG_PRINT_L1("Tx " << get_transaction_hash(tx) << " has too low mixin (" << mixin << "), and more than one mixable input with unmixable inputs"); tvc.m_low_mixin = true; return false; } } // min/max tx version based on HF, and we accept v1 txes if having a non mixable const size_t max_tx_version = (hf_version <= 3) ? 1 : 2; if (tx.version > max_tx_version) { LOG_PRINT_L1("transaction version " << (unsigned)tx.version << " is higher than max accepted version " << max_tx_version); tvc.m_verifivation_failed = true; return false; } const size_t min_tx_version = (n_unmixable > 0 ? 1 : (hf_version >= 5) ? 2 : 1); if (tx.version < min_tx_version) { LOG_PRINT_L1("transaction version " << (unsigned)tx.version << " is lower than min accepted version " << min_tx_version); tvc.m_verifivation_failed = true; return false; } } auto it = m_check_txin_table.find(tx_prefix_hash); if(it == m_check_txin_table.end()) { m_check_txin_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, bool>()); it = m_check_txin_table.find(tx_prefix_hash); assert(it != m_check_txin_table.end()); } uint64_t t_t1 = 0; std::vector<std::vector<rct::ctkey>> pubkeys(tx.vin.size()); std::vector < uint64_t > results; results.resize(tx.vin.size(), 0); int threads = tools::get_max_concurrency(); boost::asio::io_service ioservice; boost::thread_group threadpool; bool ioservice_active = false; std::unique_ptr < boost::asio::io_service::work > work(new boost::asio::io_service::work(ioservice)); if(threads > 1) { for (int i = 0; i < threads; i++) { threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioservice)); } ioservice_active = true; } #define KILL_IOSERVICE() \ if(ioservice_active) \ { \ work.reset(); \ while (!ioservice.stopped()) ioservice.poll(); \ threadpool.join_all(); \ ioservice.stop(); \ ioservice_active = false; \ } epee::misc_utils::auto_scope_leave_caller ioservice_killer = epee::misc_utils::create_scope_leave_handler([&]() { KILL_IOSERVICE(); }); for (const auto& txin : tx.vin) { // make sure output being spent is of type txin_to_key, rather than // e.g. txin_gen, which is only used for miner transactions CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at Blockchain::check_tx_inputs"); const txin_to_key& in_to_key = boost::get<txin_to_key>(txin); // make sure tx output has key offset(s) (is signed to be used) CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "empty in_to_key.key_offsets in transaction with id " << get_transaction_hash(tx)); if(have_tx_keyimg_as_spent(in_to_key.k_image)) { LOG_PRINT_L1("Key image already spent in blockchain: " << epee::string_tools::pod_to_hex(in_to_key.k_image)); tvc.m_double_spend = true; return false; } if (tx.version == 1) { // basically, make sure number of inputs == number of signatures CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index); #if defined(CACHE_VIN_RESULTS) auto itk = it->second.find(in_to_key.k_image); if(itk != it->second.end()) { if(!itk->second) { LOG_PRINT_L1("Failed ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); return false; } // txin has been verified already, skip sig_index++; continue; } #endif } // make sure that output being spent matches up correctly with the // signature spending it. if (!check_tx_input(tx.version, in_to_key, tx_prefix_hash, tx.version == 1 ? tx.signatures[sig_index] : std::vector<crypto::signature>(), tx.rct_signatures, pubkeys[sig_index], pmax_used_block_height)) { it->second[in_to_key.k_image] = false; LOG_PRINT_L1("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { LOG_PRINT_L1(" *pmax_used_block_height: " << *pmax_used_block_height); } return false; } if (tx.version == 1) { if (threads > 1) { // ND: Speedup // 1. Thread ring signature verification if possible. ioservice.dispatch(boost::bind(&Blockchain::check_ring_signature, this, std::cref(tx_prefix_hash), std::cref(in_to_key.k_image), std::cref(pubkeys[sig_index]), std::cref(tx.signatures[sig_index]), std::ref(results[sig_index]))); } else { check_ring_signature(tx_prefix_hash, in_to_key.k_image, pubkeys[sig_index], tx.signatures[sig_index], results[sig_index]); if (!results[sig_index]) { it->second[in_to_key.k_image] = false; LOG_PRINT_L1("Failed to check ring signature for tx " << get_transaction_hash(tx) << " vin key with k_image: " << in_to_key.k_image << " sig_index: " << sig_index); if (pmax_used_block_height) // a default value of NULL is used when called from Blockchain::handle_block_to_main_chain() { LOG_PRINT_L1("*pmax_used_block_height: " << *pmax_used_block_height); } return false; } it->second[in_to_key.k_image] = true; } } sig_index++; } KILL_IOSERVICE(); if (tx.version == 1) { if (threads > 1) { // save results to table, passed or otherwise bool failed = false; for (size_t i = 0; i < tx.vin.size(); i++) { const txin_to_key& in_to_key = boost::get<txin_to_key>(tx.vin[i]); it->second[in_to_key.k_image] = results[i]; if(!failed && !results[i]) failed = true; } if (failed) { LOG_PRINT_L1("Failed to check ring signatures!, t_loop: " << t_t1); return false; } } } else { if (!expand_transaction_2(tx, tx_prefix_hash, pubkeys)) { LOG_PRINT_L1("Failed to expand rct signatures!"); return false; } // from version 2, check ringct signatures // obviously, the original and simple rct APIs use a mixRing that's indexes // in opposite orders, because it'd be too simple otherwise... const rct::rctSig &rv = tx.rct_signatures; switch (rv.type) { case rct::RCTTypeNull: { // we only accept no signatures for coinbase txes LOG_PRINT_L1("Null rct signature on non-coinbase tx"); return false; } case rct::RCTTypeSimple: { // check all this, either recontructed (so should really pass), or not { if (pubkeys.size() != rv.mixRing.size()) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t i = 0; i < pubkeys.size(); ++i) { if (pubkeys[i].size() != rv.mixRing[i].size()) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } } for (size_t n = 0; n < pubkeys.size(); ++n) { for (size_t m = 0; m < pubkeys[n].size(); ++m) { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[n][m].dest)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[n][m].mask)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); return false; } } } } if (rv.p.MGs.size() != tx.vin.size()) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched MGs/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[n].II[0], 32)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched key image"); return false; } } if (!rct::verRctSimple(rv)) { LOG_PRINT_L1("Failed to check ringct signatures!"); return false; } break; } case rct::RCTTypeFull: { // check all this, either recontructed (so should really pass), or not { bool size_matches = true; for (size_t i = 0; i < pubkeys.size(); ++i) size_matches &= pubkeys[i].size() == rv.mixRing.size(); for (size_t i = 0; i < rv.mixRing.size(); ++i) size_matches &= pubkeys.size() == rv.mixRing[i].size(); if (!size_matches) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched pubkeys/mixRing size"); return false; } for (size_t n = 0; n < pubkeys.size(); ++n) { for (size_t m = 0; m < pubkeys[n].size(); ++m) { if (pubkeys[n][m].dest != rct::rct2pk(rv.mixRing[m][n].dest)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched pubkey at vin " << n << ", index " << m); return false; } if (pubkeys[n][m].mask != rct::rct2pk(rv.mixRing[m][n].mask)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched commitment at vin " << n << ", index " << m); return false; } } } } if (rv.p.MGs.size() != 1) { LOG_PRINT_L1("Failed to check ringct signatures: Bad MGs size"); return false; } if (rv.p.MGs[0].II.size() != tx.vin.size()) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched II/vin sizes"); return false; } for (size_t n = 0; n < tx.vin.size(); ++n) { if (memcmp(&boost::get<txin_to_key>(tx.vin[n]).k_image, &rv.p.MGs[0].II[n], 32)) { LOG_PRINT_L1("Failed to check ringct signatures: mismatched II/vin sizes"); return false; } } if (!rct::verRct(rv)) { LOG_PRINT_L1("Failed to check ringct signatures!"); return false; } break; } default: LOG_PRINT_L1("Unsupported rct type: " << rv.type); return false; } } return true; } //------------------------------------------------------------------ void Blockchain::check_ring_signature(const crypto::hash &tx_prefix_hash, const crypto::key_image &key_image, const std::vector<rct::ctkey> &pubkeys, const std::vector<crypto::signature>& sig, uint64_t &result) { if (m_is_in_checkpoint_zone) { result = true; return; } std::vector<const crypto::public_key *> p_output_keys; for (auto &key : pubkeys) { // rct::key and crypto::public_key have the same structure, avoid object ctor/memcpy p_output_keys.push_back(&(const crypto::public_key&)key.dest); } result = crypto::check_ring_signature(tx_prefix_hash, key_image, p_output_keys, sig.data()) ? 1 : 0; } //------------------------------------------------------------------ uint64_t Blockchain::get_dynamic_per_kb_fee(uint64_t block_reward, size_t median_block_size) { if (median_block_size < CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2) median_block_size = CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2; uint64_t unscaled_fee_per_kb = (DYNAMIC_FEE_PER_KB_BASE_FEE * CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2 / median_block_size); uint64_t hi, lo = mul128(unscaled_fee_per_kb, block_reward, &hi); static_assert(DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD % 1000000 == 0, "DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD must be divisible by 1000000"); static_assert(DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD / 1000000 <= std::numeric_limits<uint32_t>::max(), "DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD is too large"); // divide in two steps, since the divisor must be 32 bits, but DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD isn't div128_32(hi, lo, DYNAMIC_FEE_PER_KB_BASE_BLOCK_REWARD / 1000000, &hi, &lo); div128_32(hi, lo, 1000000, &hi, &lo); assert(hi == 0); return lo; } //------------------------------------------------------------------ bool Blockchain::check_fee(size_t blob_size, uint64_t fee) const { const uint8_t version = get_current_hard_fork_version(); uint64_t fee_per_kb; if (version < HF_VERSION_DYNAMIC_FEE) { fee_per_kb = FEE_PER_KB; } else { uint64_t median = m_current_block_cumul_sz_limit / 2; uint64_t already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; uint64_t base_reward; if (!get_block_reward(median, 1, already_generated_coins, base_reward, version)) return false; fee_per_kb = get_dynamic_per_kb_fee(base_reward, median); } LOG_PRINT_L2("Using " << print_money(fee) << "/kB fee"); uint64_t needed_fee = blob_size / 1024; needed_fee += (blob_size % 1024) ? 1 : 0; needed_fee *= fee_per_kb; if (fee < needed_fee) { LOG_PRINT_L1("transaction fee is not enough: " << print_money(fee) << ", minimum fee: " << print_money(needed_fee)); return false; } return true; } //------------------------------------------------------------------ uint64_t Blockchain::get_dynamic_per_kb_fee_estimate(uint64_t grace_blocks) const { const uint8_t version = get_current_hard_fork_version(); if (version < HF_VERSION_DYNAMIC_FEE) return FEE_PER_KB; if (grace_blocks >= CRYPTONOTE_REWARD_BLOCKS_WINDOW) grace_blocks = CRYPTONOTE_REWARD_BLOCKS_WINDOW - 1; std::vector<size_t> sz; get_last_n_blocks_sizes(sz, CRYPTONOTE_REWARD_BLOCKS_WINDOW - grace_blocks); for (size_t i = 0; i < grace_blocks; ++i) sz.push_back(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2); uint64_t median = epee::misc_utils::median(sz); if(median <= CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2) median = CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2; uint64_t already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; uint64_t base_reward; if (!get_block_reward(median, 1, already_generated_coins, base_reward, version)) return false; uint64_t fee = get_dynamic_per_kb_fee(base_reward, median); LOG_PRINT_L2("Estimating " << grace_blocks << "-block fee at " << print_money(fee) << "/kB"); return fee; } //------------------------------------------------------------------ // This function checks to see if a tx is unlocked. unlock_time is either // a block index or a unix time. bool Blockchain::is_tx_spendtime_unlocked(uint64_t unlock_time) const { LOG_PRINT_L3("Blockchain::" << __func__); if(unlock_time < CRYPTONOTE_MAX_BLOCK_NUMBER) { // ND: Instead of calling get_current_blockchain_height(), call m_db->height() // directly as get_current_blockchain_height() locks the recursive mutex. if(m_db->height()-1 + CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time) return true; else return false; } else { //interpret as time uint64_t current_time = static_cast<uint64_t>(time(NULL)); if(current_time + (get_current_hard_fork_version() < 2 ? CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V1 : CRYPTONOTE_LOCKED_TX_ALLOWED_DELTA_SECONDS_V2) >= unlock_time) return true; else return false; } return false; } //------------------------------------------------------------------ // This function locates all outputs associated with a given input (mixins) // and validates that they exist and are usable. It also checks the ring // signature for each input. bool Blockchain::check_tx_input(size_t tx_version, const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, const rct::rctSig &rct_signatures, std::vector<rct::ctkey> &output_keys, uint64_t* pmax_related_block_height) { LOG_PRINT_L3("Blockchain::" << __func__); // ND: // 1. Disable locking and make method private. //CRITICAL_REGION_LOCAL(m_blockchain_lock); struct outputs_visitor { std::vector<rct::ctkey >& m_output_keys; const Blockchain& m_bch; outputs_visitor(std::vector<rct::ctkey>& output_keys, const Blockchain& bch) : m_output_keys(output_keys), m_bch(bch) { } bool handle_output(uint64_t unlock_time, const crypto::public_key &pubkey, const rct::key &commitment) { //check tx unlock time if (!m_bch.is_tx_spendtime_unlocked(unlock_time)) { LOG_PRINT_L1("One of outputs for one of inputs has wrong tx.unlock_time = " << unlock_time); return false; } // The original code includes a check for the output corresponding to this input // to be a txout_to_key. This is removed, as the database does not store this info, // but only txout_to_key outputs are stored in the DB in the first place, done in // Blockchain*::add_output m_output_keys.push_back(rct::ctkey({rct::pk2rct(pubkey), commitment})); return true; } }; output_keys.clear(); // collect output keys outputs_visitor vi(output_keys, *this); if (!scan_outputkeys_for_indexes(tx_version, txin, vi, tx_prefix_hash, pmax_related_block_height)) { LOG_PRINT_L1("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size()); return false; } if(txin.key_offsets.size() != output_keys.size()) { LOG_PRINT_L1("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size()); return false; } if (tx_version == 1) { CHECK_AND_ASSERT_MES(sig.size() == output_keys.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << output_keys.size()); } // rct_signatures will be expanded after this return true; } //------------------------------------------------------------------ //TODO: Is this intended to do something else? Need to look into the todo there. uint64_t Blockchain::get_adjusted_time() const { LOG_PRINT_L3("Blockchain::" << __func__); //TODO: add collecting median time return time(NULL); } //------------------------------------------------------------------ //TODO: revisit, has changed a bit on upstream bool Blockchain::check_block_timestamp(std::vector<uint64_t>& timestamps, const block& b) const { LOG_PRINT_L3("Blockchain::" << __func__); uint64_t median_ts = epee::misc_utils::median(timestamps); if(b.timestamp < median_ts) { LOG_PRINT_L1("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts); return false; } return true; } //------------------------------------------------------------------ // This function grabs the timestamps from the most recent <n> blocks, // where n = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW. If there are not those many // blocks in the blockchain, the timestap is assumed to be valid. If there // are, this function returns: // true if the block's timestamp is not less than the timestamp of the // median of the selected blocks // false otherwise bool Blockchain::check_block_timestamp(const block& b) const { LOG_PRINT_L3("Blockchain::" << __func__); if(b.timestamp > get_adjusted_time() + CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT) { LOG_PRINT_L1("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + 2 hours"); return false; } // if not enough blocks, no proper median yet, return true if(m_db->height() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW) { return true; } std::vector<uint64_t> timestamps; auto h = m_db->height(); // need most recent 60 blocks, get index of first of those size_t offset = h - BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW; for(;offset < h; ++offset) { timestamps.push_back(m_db->get_block_timestamp(offset)); } return check_block_timestamp(timestamps, b); } //------------------------------------------------------------------ void Blockchain::return_tx_to_pool(const std::vector<transaction> &txs) { uint8_t version = get_current_hard_fork_version(); for (auto& tx : txs) { cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc); // We assume that if they were in a block, the transactions are already // known to the network as a whole. However, if we had mined that block, // that might not be always true. Unlikely though, and always relaying // these again might cause a spike of traffic as many nodes re-relay // all the transactions in a popped block when a reorg happens. if (!m_tx_pool.add_tx(tx, tvc, true, true, version)) { LOG_PRINT_L0("Failed to return taken transaction with hash: " << get_transaction_hash(tx) << " to tx_pool"); } } } //------------------------------------------------------------------ bool Blockchain::flush_txes_from_pool(const std::list<crypto::hash> &txids) { CRITICAL_REGION_LOCAL(m_tx_pool); bool res = true; for (const auto &txid: txids) { cryptonote::transaction tx; size_t blob_size; uint64_t fee; bool relayed; LOG_PRINT_L1("Removing txid " << txid << " from the pool"); if(m_tx_pool.have_tx(txid) && !m_tx_pool.take_tx(txid, tx, blob_size, fee, relayed)) { LOG_PRINT_L0("Failed to remove txid " << txid << " from the pool"); res = false; } } return res; } //------------------------------------------------------------------ // Needs to validate the block and acquire each transaction from the // transaction mem_pool, then pass the block and transactions to // m_db->add_block() bool Blockchain::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); TIME_MEASURE_START(block_processing_time); CRITICAL_REGION_LOCAL(m_blockchain_lock); TIME_MEASURE_START(t1); m_db->block_txn_start(true); if(bl.prev_id != get_tail_id()) { LOG_PRINT_L1("Block with id: " << id << std::endl << "has wrong prev_id: " << bl.prev_id << std::endl << "expected: " << get_tail_id()); leave: m_db->block_txn_stop(); return false; } // this is a cheap test if (!m_hardfork->check(bl)) { LOG_PRINT_L1("Block with id: " << id << std::endl << "has old version: " << (unsigned)bl.major_version << std::endl << "current: " << (unsigned)m_hardfork->get_current_version()); bvc.m_verifivation_failed = true; goto leave; } TIME_MEASURE_FINISH(t1); TIME_MEASURE_START(t2); // make sure block timestamp is not less than the median timestamp // of a set number of the most recent blocks. if(!check_block_timestamp(bl)) { LOG_PRINT_L1("Block with id: " << id << std::endl << "has invalid timestamp: " << bl.timestamp); bvc.m_verifivation_failed = true; goto leave; } TIME_MEASURE_FINISH(t2); //check proof of work TIME_MEASURE_START(target_calculating_time); // get the target difficulty for the block. // the calculation can overflow, among other failure cases, // so we need to check the return type. // FIXME: get_difficulty_for_next_block can also assert, look into // changing this to throwing exceptions instead so we can clean up. difficulty_type current_diffic = get_difficulty_for_next_block(); CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!"); TIME_MEASURE_FINISH(target_calculating_time); TIME_MEASURE_START(longhash_calculating_time); crypto::hash proof_of_work = null_hash; // Formerly the code below contained an if loop with the following condition // !m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height()) // however, this caused the daemon to not bother checking PoW for blocks // before checkpoints, which is very dangerous behaviour. We moved the PoW // validation out of the next chunk of code to make sure that we correctly // check PoW now. // FIXME: height parameter is not used...should it be used or should it not // be a parameter? // validate proof_of_work versus difficulty target bool precomputed = false; bool fast_check = false; #if defined(PER_BLOCK_CHECKPOINT) if (m_db->height() < m_blocks_hash_check.size()) { auto hash = get_block_hash(bl); if (memcmp(&hash, &m_blocks_hash_check[m_db->height()], sizeof(hash)) != 0) { LOG_PRINT_L1("Block with id is INVALID: " << id); bvc.m_verifivation_failed = true; goto leave; } fast_check = true; } else #endif { auto it = m_blocks_longhash_table.find(id); if (it != m_blocks_longhash_table.end()) { precomputed = true; proof_of_work = it->second; } else proof_of_work = get_block_longhash(bl, m_db->height()); // validate proof_of_work versus difficulty target if(!check_hash(proof_of_work, current_diffic)) { LOG_PRINT_L1("Block with id: " << id << std::endl << "does not have enough proof of work: " << proof_of_work << std::endl << "unexpected difficulty: " << current_diffic); bvc.m_verifivation_failed = true; goto leave; } } // If we're at a checkpoint, ensure that our hardcoded checkpoint hash // is correct. if(m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height())) { if(!m_checkpoints.check_block(get_current_blockchain_height(), id)) { LOG_ERROR("CHECKPOINT VALIDATION FAILED"); bvc.m_verifivation_failed = true; goto leave; } } TIME_MEASURE_FINISH(longhash_calculating_time); if (precomputed) longhash_calculating_time += m_fake_pow_calc_time; TIME_MEASURE_START(t3); // sanity check basic miner tx properties; if(!prevalidate_miner_transaction(bl, m_db->height())) { LOG_PRINT_L1("Block with id: " << id << " failed to pass prevalidation"); bvc.m_verifivation_failed = true; goto leave; } size_t coinbase_blob_size = get_object_blobsize(bl.miner_tx); size_t cumulative_block_size = coinbase_blob_size; std::vector<transaction> txs; key_images_container keys; uint64_t fee_summary = 0; uint64_t t_checktx = 0; uint64_t t_exists = 0; uint64_t t_pool = 0; uint64_t t_dblspnd = 0; TIME_MEASURE_FINISH(t3); // XXX old code adds miner tx here int tx_index = 0; // Iterate over the block's transaction hashes, grabbing each // from the tx_pool and validating them. Each is then added // to txs. Keys spent in each are added to <keys> by the double spend check. for (const crypto::hash& tx_id : bl.tx_hashes) { transaction tx; size_t blob_size = 0; uint64_t fee = 0; bool relayed = false; TIME_MEASURE_START(aa); // XXX old code does not check whether tx exists if (m_db->tx_exists(tx_id)) { LOG_PRINT_L1("Block with id: " << id << " attempting to add transaction already in blockchain with id: " << tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(aa); t_exists += aa; TIME_MEASURE_START(bb); // get transaction with hash <tx_id> from tx_pool if(!m_tx_pool.take_tx(tx_id, tx, blob_size, fee, relayed)) { LOG_PRINT_L1("Block with id: " << id << " has at least one unknown transaction with id: " << tx_id); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(bb); t_pool += bb; // add the transaction to the temp list of transactions, so we can either // store the list of transactions all at once or return the ones we've // taken from the tx_pool back to it if the block fails verification. txs.push_back(tx); TIME_MEASURE_START(dd); // FIXME: the storage should not be responsible for validation. // If it does any, it is merely a sanity check. // Validation is the purview of the Blockchain class // - TW // // ND: this is not needed, db->add_block() checks for duplicate k_images and fails accordingly. // if (!check_for_double_spend(tx, keys)) // { // LOG_PRINT_L0("Double spend detected in transaction (id: " << tx_id); // bvc.m_verifivation_failed = true; // break; // } TIME_MEASURE_FINISH(dd); t_dblspnd += dd; TIME_MEASURE_START(cc); #if defined(PER_BLOCK_CHECKPOINT) if (!fast_check) #endif { // validate that transaction inputs and the keys spending them are correct. tx_verification_context tvc; if(!check_tx_inputs(tx, tvc)) { LOG_PRINT_L1("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); //TODO: why is this done? make sure that keeping invalid blocks makes sense. add_block_as_invalid(bl, id); LOG_PRINT_L1("Block with id " << id << " added as invalid because of wrong inputs in transactions"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } } #if defined(PER_BLOCK_CHECKPOINT) else { // ND: if fast_check is enabled for blocks, there is no need to check // the transaction inputs, but do some sanity checks anyway. if (memcmp(&m_blocks_txs_check[tx_index++], &tx_id, sizeof(tx_id)) != 0) { LOG_PRINT_L1("Block with id: " << id << " has at least one transaction (id: " << tx_id << ") with wrong inputs."); //TODO: why is this done? make sure that keeping invalid blocks makes sense. add_block_as_invalid(bl, id); LOG_PRINT_L1("Block with id " << id << " added as invalid because of wrong inputs in transactions"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } } #endif TIME_MEASURE_FINISH(cc); t_checktx += cc; fee_summary += fee; cumulative_block_size += blob_size; } m_blocks_txs_check.clear(); TIME_MEASURE_START(vmt); uint64_t base_reward = 0; uint64_t already_generated_coins = m_db->height() ? m_db->get_block_already_generated_coins(m_db->height() - 1) : 0; if(!validate_miner_transaction(bl, cumulative_block_size, fee_summary, base_reward, already_generated_coins, bvc.m_partial_block_reward, m_hardfork->get_current_version())) { LOG_PRINT_L1("Block with id: " << id << " has incorrect miner transaction"); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); goto leave; } TIME_MEASURE_FINISH(vmt); size_t block_size; difficulty_type cumulative_difficulty; // populate various metadata about the block to be stored alongside it. block_size = cumulative_block_size; cumulative_difficulty = current_diffic; // In the "tail" state when the minimum subsidy (implemented in get_block_reward) is in effect, the number of // coins will eventually exceed MONEY_SUPPLY and overflow a uint64. To prevent overflow, cap already_generated_coins // at MONEY_SUPPLY. already_generated_coins is only used to compute the block subsidy and MONEY_SUPPLY yields a // subsidy of 0 under the base formula and therefore the minimum subsidy >0 in the tail state. already_generated_coins = base_reward < (MONEY_SUPPLY-already_generated_coins) ? already_generated_coins + base_reward : MONEY_SUPPLY; if(m_db->height()) cumulative_difficulty += m_db->get_block_cumulative_difficulty(m_db->height() - 1); TIME_MEASURE_FINISH(block_processing_time); if(precomputed) block_processing_time += m_fake_pow_calc_time; m_db->block_txn_stop(); TIME_MEASURE_START(addblock); uint64_t new_height = 0; if (!bvc.m_verifivation_failed) { try { new_height = m_db->add_block(bl, block_size, cumulative_difficulty, already_generated_coins, txs); } catch (const KEY_IMAGE_EXISTS& e) { LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); bvc.m_verifivation_failed = true; return_tx_to_pool(txs); return false; } catch (const std::exception& e) { //TODO: figure out the best way to deal with this failure LOG_ERROR("Error adding block with hash: " << id << " to blockchain, what = " << e.what()); return_tx_to_pool(txs); return false; } } else { LOG_ERROR("Blocks that failed verification should not reach here"); } TIME_MEASURE_FINISH(addblock); // do this after updating the hard fork state since the size limit may change due to fork update_next_cumulative_size_limit(); LOG_PRINT_L1("+++++ BLOCK SUCCESSFULLY ADDED" << std::endl << "id:\t" << id << std::endl << "PoW:\t" << proof_of_work << std::endl << "HEIGHT " << new_height-1 << ", difficulty:\t" << current_diffic << std::endl << "block reward: " << print_money(fee_summary + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_summary) << "), coinbase_blob_size: " << coinbase_blob_size << ", cumulative size: " << cumulative_block_size << ", " << block_processing_time << "(" << target_calculating_time << "/" << longhash_calculating_time << ")ms"); if(m_show_time_stats) { LOG_PRINT_L0("Height: " << new_height << " blob: " << coinbase_blob_size << " cumm: " << cumulative_block_size << " p/t: " << block_processing_time << " (" << target_calculating_time << "/" << longhash_calculating_time << "/" << t1 << "/" << t2 << "/" << t3 << "/" << t_exists << "/" << t_pool << "/" << t_checktx << "/" << t_dblspnd << "/" << vmt << "/" << addblock << ")ms"); } bvc.m_added_to_main_chain = true; ++m_sync_counter; // appears to be a NOP *and* is called elsewhere. wat? m_tx_pool.on_blockchain_inc(new_height, id); return true; } //------------------------------------------------------------------ bool Blockchain::update_next_cumulative_size_limit() { uint64_t full_reward_zone = get_current_hard_fork_version() < 2 ? CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V1 : CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE_V2; LOG_PRINT_L3("Blockchain::" << __func__); std::vector<size_t> sz; get_last_n_blocks_sizes(sz, CRYPTONOTE_REWARD_BLOCKS_WINDOW); uint64_t median = epee::misc_utils::median(sz); if(median <= full_reward_zone) median = full_reward_zone; m_current_block_cumul_sz_limit = median*2; return true; } //------------------------------------------------------------------ bool Blockchain::add_new_block(const block& bl_, block_verification_context& bvc) { LOG_PRINT_L3("Blockchain::" << __func__); //copy block here to let modify block.target block bl = bl_; crypto::hash id = get_block_hash(bl); CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process CRITICAL_REGION_LOCAL1(m_blockchain_lock); m_db->block_txn_start(true); if(have_block(id)) { LOG_PRINT_L3("block with id = " << id << " already exists"); bvc.m_already_exists = true; m_db->block_txn_stop(); return false; } //check that block refers to chain tail if(!(bl.prev_id == get_tail_id())) { //chain switching or wrong block bvc.m_added_to_main_chain = false; m_db->block_txn_stop(); return handle_alternative_block(bl, id, bvc); //never relay alternative blocks } m_db->block_txn_stop(); return handle_block_to_main_chain(bl, id, bvc); } //------------------------------------------------------------------ //TODO: Refactor, consider returning a failure height and letting // caller decide course of action. void Blockchain::check_against_checkpoints(const checkpoints& points, bool enforce) { const auto& pts = points.get_points(); CRITICAL_REGION_LOCAL(m_blockchain_lock); m_db->batch_start(); for (const auto& pt : pts) { // if the checkpoint is for a block we don't have yet, move on if (pt.first >= m_db->height()) { continue; } if (!points.check_block(pt.first, m_db->get_block_hash_from_height(pt.first))) { // if asked to enforce checkpoints, roll back to a couple of blocks before the checkpoint if (enforce) { LOG_ERROR("Local blockchain failed to pass a checkpoint, rolling back!"); std::list<block> empty; rollback_blockchain_switching(empty, pt.first - 2); } else { LOG_ERROR("WARNING: local blockchain failed to pass a MoneroPulse checkpoint, and you could be on a fork. You should either sync up from scratch, OR download a fresh blockchain bootstrap, OR enable checkpoint enforcing with the --enforce-dns-checkpointing command-line option"); } } } m_db->batch_stop(); } //------------------------------------------------------------------ // returns false if any of the checkpoints loading returns false. // That should happen only if a checkpoint is added that conflicts // with an existing checkpoint. bool Blockchain::update_checkpoints(const std::string& file_path, bool check_dns) { if (!m_checkpoints.load_checkpoints_from_json(file_path)) { return false; } // if we're checking both dns and json, load checkpoints from dns. // if we're not hard-enforcing dns checkpoints, handle accordingly if (m_enforce_dns_checkpoints && check_dns) { if (!m_checkpoints.load_checkpoints_from_dns()) { return false; } } else if (check_dns) { checkpoints dns_points; dns_points.load_checkpoints_from_dns(); if (m_checkpoints.check_for_conflicts(dns_points)) { check_against_checkpoints(dns_points, false); } else { LOG_PRINT_L0("One or more checkpoints fetched from DNS conflicted with existing checkpoints!"); } } check_against_checkpoints(m_checkpoints, true); return true; } //------------------------------------------------------------------ void Blockchain::set_enforce_dns_checkpoints(bool enforce_checkpoints) { m_enforce_dns_checkpoints = enforce_checkpoints; } //------------------------------------------------------------------ void Blockchain::block_longhash_worker(const uint64_t height, const std::vector<block> &blocks, std::unordered_map<crypto::hash, crypto::hash> &map) const { TIME_MEASURE_START(t); slow_hash_allocate_state(); //FIXME: height should be changing here, as get_block_longhash expects // the height of the block passed to it for (const auto & block : blocks) { crypto::hash id = get_block_hash(block); crypto::hash pow = get_block_longhash(block, height); map.emplace(id, pow); } slow_hash_free_state(); TIME_MEASURE_FINISH(t); } //------------------------------------------------------------------ bool Blockchain::cleanup_handle_incoming_blocks(bool force_sync) { LOG_PRINT_YELLOW("Blockchain::" << __func__, LOG_LEVEL_3); CRITICAL_REGION_LOCAL(m_blockchain_lock); TIME_MEASURE_START(t1); if (m_sync_counter > 0) { if (force_sync) { if(m_db_sync_mode != db_nosync) store_blockchain(); m_sync_counter = 0; } else if (m_db_blocks_per_sync && m_sync_counter >= m_db_blocks_per_sync) { if(m_db_sync_mode == db_async) { m_sync_counter = 0; m_async_service.dispatch(boost::bind(&Blockchain::store_blockchain, this)); } else if(m_db_sync_mode == db_sync) { store_blockchain(); } else // db_nosync { // DO NOTHING, not required to call sync. } } } TIME_MEASURE_FINISH(t1); m_blocks_longhash_table.clear(); m_scan_table.clear(); m_blocks_txs_check.clear(); m_check_txin_table.clear(); return true; } //------------------------------------------------------------------ //FIXME: unused parameter txs void Blockchain::output_scan_worker(const uint64_t amount, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs, std::unordered_map<crypto::hash, cryptonote::transaction> &txs) const { try { m_db->get_output_key(amount, offsets, outputs); } catch (const std::exception& e) { LOG_PRINT_L1("EXCEPTION: " << e.what()); } catch (...) { } } //------------------------------------------------------------------ // ND: Speedups: // 1. Thread long_hash computations if possible (m_max_prepare_blocks_threads = nthreads, default = 4) // 2. Group all amounts (from txs) and related absolute offsets and form a table of tx_prefix_hash // vs [k_image, output_keys] (m_scan_table). This is faster because it takes advantage of bulk queries // and is threaded if possible. The table (m_scan_table) will be used later when querying output // keys. bool Blockchain::prepare_handle_incoming_blocks(const std::list<block_complete_entry> &blocks_entry) { LOG_PRINT_YELLOW("Blockchain::" << __func__, LOG_LEVEL_3); TIME_MEASURE_START(prepare); CRITICAL_REGION_LOCAL(m_blockchain_lock); if(blocks_entry.size() == 0) return false; if ((m_db->height() + blocks_entry.size()) < m_blocks_hash_check.size()) return true; bool blocks_exist = false; uint64_t threads = tools::get_max_concurrency(); if (blocks_entry.size() > 1 && threads > 1 && m_max_prepare_blocks_threads > 1) { // limit threads, default limit = 4 if(threads > m_max_prepare_blocks_threads) threads = m_max_prepare_blocks_threads; uint64_t height = m_db->height(); std::vector<boost::thread *> thread_list; int batches = blocks_entry.size() / threads; int extra = blocks_entry.size() % threads; LOG_PRINT_L1("block_batches: " << batches); std::vector<std::unordered_map<crypto::hash, crypto::hash>> maps(threads); std::vector < std::vector < block >> blocks(threads); auto it = blocks_entry.begin(); for (uint64_t i = 0; i < threads; i++) { for (int j = 0; j < batches; j++) { block block; if (!parse_and_validate_block_from_blob(it->block, block)) { std::advance(it, 1); continue; } // check first block and skip all blocks if its not chained properly if (i == 0 && j == 0) { crypto::hash tophash = m_db->top_block_hash(); if (block.prev_id != tophash) { LOG_PRINT_L1("Skipping prepare blocks. New blocks don't belong to chain."); return true; } } if (have_block(get_block_hash(block))) { blocks_exist = true; break; } blocks[i].push_back(block); std::advance(it, 1); } } for (int i = 0; i < extra && !blocks_exist; i++) { block block; if (!parse_and_validate_block_from_blob(it->block, block)) { std::advance(it, 1); continue; } if (have_block(get_block_hash(block))) { blocks_exist = true; break; } blocks[i].push_back(block); std::advance(it, 1); } if (!blocks_exist) { m_blocks_longhash_table.clear(); for (uint64_t i = 0; i < threads; i++) { thread_list.push_back(new boost::thread(&Blockchain::block_longhash_worker, this, height + (i * batches), std::cref(blocks[i]), std::ref(maps[i]))); } for (size_t j = 0; j < thread_list.size(); j++) { thread_list[j]->join(); delete thread_list[j]; } thread_list.clear(); for (const auto & map : maps) { m_blocks_longhash_table.insert(map.begin(), map.end()); } } } if (blocks_exist) { LOG_PRINT_L0("Skipping prepare blocks. Blocks exist."); return true; } m_fake_scan_time = 0; m_fake_pow_calc_time = 0; m_scan_table.clear(); m_check_txin_table.clear(); TIME_MEASURE_FINISH(prepare); m_fake_pow_calc_time = prepare / blocks_entry.size(); if (blocks_entry.size() > 1 && threads > 1 && m_show_time_stats) LOG_PRINT_L0("Prepare blocks took: " << prepare << " ms"); TIME_MEASURE_START(scantable); // [input] stores all unique amounts found std::vector < uint64_t > amounts; // [input] stores all absolute_offsets for each amount std::map<uint64_t, std::vector<uint64_t>> offset_map; // [output] stores all output_data_t for each absolute_offset std::map<uint64_t, std::vector<output_data_t>> tx_map; #define SCAN_TABLE_QUIT(m) \ do { \ LOG_PRINT_L0(m) ;\ m_scan_table.clear(); \ return false; \ } while(0); \ // generate sorted tables for all amounts and absolute offsets for (const auto &entry : blocks_entry) { for (const auto &tx_blob : entry.txs) { crypto::hash tx_hash = null_hash; crypto::hash tx_prefix_hash = null_hash; transaction tx; if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash, tx_prefix_hash)) SCAN_TABLE_QUIT("Could not parse tx from incoming blocks."); auto its = m_scan_table.find(tx_prefix_hash); if (its != m_scan_table.end()) SCAN_TABLE_QUIT("Duplicate tx found from incoming blocks."); m_scan_table.emplace(tx_prefix_hash, std::unordered_map<crypto::key_image, std::vector<output_data_t>>()); its = m_scan_table.find(tx_prefix_hash); assert(its != m_scan_table.end()); // get all amounts from tx.vin(s) for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); // check for duplicate auto it = its->second.find(in_to_key.k_image); if (it != its->second.end()) SCAN_TABLE_QUIT("Duplicate key_image found from incoming blocks."); amounts.push_back(in_to_key.amount); } // sort and remove duplicate amounts from amounts list std::sort(amounts.begin(), amounts.end()); auto last = std::unique(amounts.begin(), amounts.end()); amounts.erase(last, amounts.end()); // add amount to the offset_map and tx_map for (const uint64_t &amount : amounts) { if (offset_map.find(amount) == offset_map.end()) offset_map.emplace(amount, std::vector<uint64_t>()); if (tx_map.find(amount) == tx_map.end()) tx_map.emplace(amount, std::vector<output_data_t>()); } // add new absolute_offsets to offset_map for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); // no need to check for duplicate here. auto absolute_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets); for (const auto & offset : absolute_offsets) offset_map[in_to_key.amount].push_back(offset); } // sort and remove duplicate absolute_offsets in offset_map for (auto &offsets : offset_map) { std::sort(offsets.second.begin(), offsets.second.end()); auto last = std::unique(offsets.second.begin(), offsets.second.end()); offsets.second.erase(last, offsets.second.end()); } } } // [output] stores all transactions for each tx_out_index::hash found std::vector<std::unordered_map<crypto::hash, cryptonote::transaction>> transactions(amounts.size()); threads = tools::get_max_concurrency(); if (!m_db->can_thread_bulk_indices()) threads = 1; if (threads > 1) { boost::asio::io_service ioservice; boost::thread_group threadpool; std::unique_ptr < boost::asio::io_service::work > work(new boost::asio::io_service::work(ioservice)); for (uint64_t i = 0; i < threads; i++) { threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioservice)); } for (size_t i = 0; i < amounts.size(); i++) { uint64_t amount = amounts[i]; ioservice.dispatch(boost::bind(&Blockchain::output_scan_worker, this, amount, std::cref(offset_map[amount]), std::ref(tx_map[amount]), std::ref(transactions[i]))); } work.reset(); threadpool.join_all(); ioservice.stop(); } else { for (size_t i = 0; i < amounts.size(); i++) { uint64_t amount = amounts[i]; output_scan_worker(amount, offset_map[amount], tx_map[amount], transactions[i]); } } int total_txs = 0; // now generate a table for each tx_prefix and k_image hashes for (const auto &entry : blocks_entry) { for (const auto &tx_blob : entry.txs) { crypto::hash tx_hash = null_hash; crypto::hash tx_prefix_hash = null_hash; transaction tx; if (!parse_and_validate_tx_from_blob(tx_blob, tx, tx_hash, tx_prefix_hash)) SCAN_TABLE_QUIT("Could not parse tx from incoming blocks."); ++total_txs; auto its = m_scan_table.find(tx_prefix_hash); if (its == m_scan_table.end()) SCAN_TABLE_QUIT("Tx not found on scan table from incoming blocks."); for (const auto &txin : tx.vin) { const txin_to_key &in_to_key = boost::get < txin_to_key > (txin); auto needed_offsets = relative_output_offsets_to_absolute(in_to_key.key_offsets); std::vector<output_data_t> outputs; for (const uint64_t & offset_needed : needed_offsets) { size_t pos = 0; bool found = false; for (const uint64_t &offset_found : offset_map[in_to_key.amount]) { if (offset_needed == offset_found) { found = true; break; } ++pos; } if (found && pos < tx_map[in_to_key.amount].size()) outputs.push_back(tx_map[in_to_key.amount].at(pos)); else break; } its->second.emplace(in_to_key.k_image, outputs); } } } TIME_MEASURE_FINISH(scantable); if (total_txs > 0) { m_fake_scan_time = scantable / total_txs; if(m_show_time_stats) LOG_PRINT_L0("Prepare scantable took: " << scantable << " ms"); } return true; } void Blockchain::set_user_options(uint64_t maxthreads, uint64_t blocks_per_sync, blockchain_db_sync_mode sync_mode, bool fast_sync) { m_db_sync_mode = sync_mode; m_fast_sync = fast_sync; m_db_blocks_per_sync = blocks_per_sync; m_max_prepare_blocks_threads = maxthreads; } HardFork::State Blockchain::get_hard_fork_state() const { return m_hardfork->get_state(); } bool Blockchain::get_hard_fork_voting_info(uint8_t version, uint32_t &window, uint32_t &votes, uint32_t &threshold, uint64_t &earliest_height, uint8_t &voting) const { return m_hardfork->get_voting_info(version, window, votes, threshold, earliest_height, voting); } std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> Blockchain:: get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff) const { return m_db->get_output_histogram(amounts, unlocked, recent_cutoff); } #if defined(PER_BLOCK_CHECKPOINT) void Blockchain::load_compiled_in_block_hashes() { if (m_fast_sync && get_blocks_dat_start(m_testnet) != nullptr) { if (get_blocks_dat_size(m_testnet) > 4) { const unsigned char *p = get_blocks_dat_start(m_testnet); const uint32_t nblocks = *p | ((*(p+1))<<8) | ((*(p+2))<<16) | ((*(p+3))<<24); const size_t size_needed = 4 + nblocks * sizeof(crypto::hash); if(nblocks > 0 && nblocks > m_db->height() && get_blocks_dat_size(m_testnet) >= size_needed) { LOG_PRINT_L0("Loading precomputed blocks: " << nblocks); p += sizeof(uint32_t); for (uint32_t i = 0; i < nblocks; i++) { crypto::hash hash; memcpy(hash.data, p, sizeof(hash.data)); p += sizeof(hash.data); m_blocks_hash_check.push_back(hash); } // FIXME: clear tx_pool because the process might have been // terminated and caused it to store txs kept by blocks. // The core will not call check_tx_inputs(..) for these // transactions in this case. Consequently, the sanity check // for tx hashes will fail in handle_block_to_main_chain(..) std::list<transaction> txs; m_tx_pool.get_transactions(txs); size_t blob_size; uint64_t fee; bool relayed; transaction pool_tx; for(const transaction &tx : txs) { crypto::hash tx_hash = get_transaction_hash(tx); m_tx_pool.take_tx(tx_hash, pool_tx, blob_size, fee, relayed); } } } } } #endif bool Blockchain::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const { return m_db->for_all_key_images(f); } bool Blockchain::for_all_blocks(std::function<bool(uint64_t, const crypto::hash&, const block&)> f) const { return m_db->for_all_blocks(f); } bool Blockchain::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f) const { return m_db->for_all_transactions(f); } bool Blockchain::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, size_t tx_idx)> f) const { return m_db->for_all_outputs(f);; }
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ // // vie_autotest_loopback.cc // // This code is also used as sample code for ViE 3.0 // // =================================================================== // // BEGIN: VideoEngine 3.0 Sample Code // #include <iostream> #include "webrtc/base/scoped_ptr.h" #include "webrtc/common_types.h" #include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h" #include "webrtc/test/channel_transport/include/channel_transport.h" #include "webrtc/video_engine/include/vie_base.h" #include "webrtc/video_engine/include/vie_capture.h" #include "webrtc/video_engine/include/vie_codec.h" #include "webrtc/video_engine/include/vie_external_codec.h" #include "webrtc/video_engine/include/vie_network.h" #include "webrtc/video_engine/include/vie_render.h" #include "webrtc/video_engine/include/vie_rtp_rtcp.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest.h" #include "webrtc/video_engine/test/auto_test/interface/vie_autotest_defines.h" #include "webrtc/video_engine/test/libvietest/include/tb_external_transport.h" #include "webrtc/voice_engine/include/voe_base.h" const uint32_t kSsrc = 0x01234567; const uint32_t kRtxSsrc = 0x01234568; const int kRtxPayloadType = 98; #define VCM_RED_PAYLOAD_TYPE 96 #define VCM_ULPFEC_PAYLOAD_TYPE 97 int VideoEngineSampleCode(void* window1, void* window2) { //******************************************************** // Begin create/initialize Video Engine for testing //******************************************************** int error = 0; // // Create a VideoEngine instance // webrtc::VideoEngine* ptrViE = NULL; ptrViE = webrtc::VideoEngine::Create(); if (ptrViE == NULL) { printf("ERROR in VideoEngine::Create\n"); return -1; } error = ptrViE->SetTraceFilter(webrtc::kTraceAll); if (error == -1) { printf("ERROR in VideoEngine::SetTraceFilter\n"); return -1; } std::string trace_file = ViETest::GetResultOutputPath() + "ViELoopbackCall_trace.txt"; error = ptrViE->SetTraceFile(trace_file.c_str()); if (error == -1) { printf("ERROR in VideoEngine::SetTraceFile\n"); return -1; } // // Init VideoEngine and create a channel // webrtc::ViEBase* ptrViEBase = webrtc::ViEBase::GetInterface(ptrViE); if (ptrViEBase == NULL) { printf("ERROR in ViEBase::GetInterface\n"); return -1; } error = ptrViEBase->Init(); if (error == -1) { printf("ERROR in ViEBase::Init\n"); return -1; } webrtc::ViERTP_RTCP* ptrViERtpRtcp = webrtc::ViERTP_RTCP::GetInterface(ptrViE); if (ptrViERtpRtcp == NULL) { printf("ERROR in ViERTP_RTCP::GetInterface\n"); return -1; } int videoChannel = -1; error = ptrViEBase->CreateChannel(videoChannel); if (error == -1) { printf("ERROR in ViEBase::CreateChannel\n"); return -1; } // // List available capture devices, allocate and connect. // webrtc::ViECapture* ptrViECapture = webrtc::ViECapture::GetInterface(ptrViE); if (ptrViEBase == NULL) { printf("ERROR in ViECapture::GetInterface\n"); return -1; } const unsigned int KMaxDeviceNameLength = 128; const unsigned int KMaxUniqueIdLength = 256; char deviceName[KMaxDeviceNameLength]; memset(deviceName, 0, KMaxDeviceNameLength); char uniqueId[KMaxUniqueIdLength]; memset(uniqueId, 0, KMaxUniqueIdLength); printf("Available capture devices:\n"); int captureIdx = 0; for (captureIdx = 0; captureIdx < ptrViECapture->NumberOfCaptureDevices(); captureIdx++) { memset(deviceName, 0, KMaxDeviceNameLength); memset(uniqueId, 0, KMaxUniqueIdLength); error = ptrViECapture->GetCaptureDevice(captureIdx, deviceName, KMaxDeviceNameLength, uniqueId, KMaxUniqueIdLength); if (error == -1) { printf("ERROR in ViECapture::GetCaptureDevice\n"); return -1; } printf("\t %d. %s\n", captureIdx + 1, deviceName); } printf("\nChoose capture device: "); #ifdef WEBRTC_ANDROID captureIdx = 0; printf("0\n"); #else if (scanf("%d", &captureIdx) != 1) { printf("Error in scanf()\n"); return -1; } getc(stdin); captureIdx = captureIdx - 1; // Compensate for idx start at 1. #endif error = ptrViECapture->GetCaptureDevice(captureIdx, deviceName, KMaxDeviceNameLength, uniqueId, KMaxUniqueIdLength); if (error == -1) { printf("ERROR in ViECapture::GetCaptureDevice\n"); return -1; } int captureId = 0; error = ptrViECapture->AllocateCaptureDevice(uniqueId, KMaxUniqueIdLength, captureId); if (error == -1) { printf("ERROR in ViECapture::AllocateCaptureDevice\n"); return -1; } error = ptrViECapture->ConnectCaptureDevice(captureId, videoChannel); if (error == -1) { printf("ERROR in ViECapture::ConnectCaptureDevice\n"); return -1; } error = ptrViECapture->StartCapture(captureId); if (error == -1) { printf("ERROR in ViECapture::StartCapture\n"); return -1; } // // RTP/RTCP settings // error = ptrViERtpRtcp->SetRTCPStatus(videoChannel, webrtc::kRtcpCompound_RFC4585); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetRTCPStatus\n"); return -1; } error = ptrViERtpRtcp->SetKeyFrameRequestMethod( videoChannel, webrtc::kViEKeyFrameRequestPliRtcp); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetKeyFrameRequestMethod\n"); return -1; } error = ptrViERtpRtcp->SetRembStatus(videoChannel, true, true); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetTMMBRStatus\n"); return -1; } // Setting SSRC manually (arbitrary value), as otherwise we will get a clash // (loopback), and a new SSRC will be set, which will reset the receiver. error = ptrViERtpRtcp->SetLocalSSRC(videoChannel, kSsrc); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetLocalSSRC\n"); return -1; } error = ptrViERtpRtcp->SetLocalSSRC(videoChannel, kRtxSsrc, webrtc::kViEStreamTypeRtx, 0); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetLocalSSRC\n"); return -1; } error = ptrViERtpRtcp->SetRemoteSSRCType(videoChannel, webrtc::kViEStreamTypeRtx, kRtxSsrc); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetRtxReceivePayloadType\n"); return -1; } error = ptrViERtpRtcp->SetRtxSendPayloadType(videoChannel, kRtxPayloadType); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetRtxSendPayloadType\n"); return -1; } error = ptrViERtpRtcp->SetRtxReceivePayloadType(videoChannel, kRtxPayloadType); if (error == -1) { printf("ERROR in ViERTP_RTCP::SetRtxReceivePayloadType\n"); return -1; } // // Set up rendering // webrtc::ViERender* ptrViERender = webrtc::ViERender::GetInterface(ptrViE); if (ptrViERender == NULL) { printf("ERROR in ViERender::GetInterface\n"); return -1; } error = ptrViERender->AddRenderer(captureId, window1, 0, 0.0, 0.0, 1.0, 1.0); if (error == -1) { printf("ERROR in ViERender::AddRenderer\n"); return -1; } error = ptrViERender->StartRender(captureId); if (error == -1) { printf("ERROR in ViERender::StartRender\n"); return -1; } error = ptrViERender->AddRenderer(videoChannel, window2, 1, 0.0, 0.0, 1.0, 1.0); if (error == -1) { printf("ERROR in ViERender::AddRenderer\n"); return -1; } error = ptrViERender->StartRender(videoChannel); if (error == -1) { printf("ERROR in ViERender::StartRender\n"); return -1; } // // Setup codecs // webrtc::ViECodec* ptrViECodec = webrtc::ViECodec::GetInterface(ptrViE); if (ptrViECodec == NULL) { printf("ERROR in ViECodec::GetInterface\n"); return -1; } // Check available codecs and prepare receive codecs printf("\nAvailable codecs:\n"); webrtc::VideoCodec videoCodec; memset(&videoCodec, 0, sizeof(webrtc::VideoCodec)); int codecIdx = 0; for (codecIdx = 0; codecIdx < ptrViECodec->NumberOfCodecs(); codecIdx++) { error = ptrViECodec->GetCodec(codecIdx, videoCodec); if (error == -1) { printf("ERROR in ViECodec::GetCodec\n"); return -1; } // try to keep the test frame size small when I420 if (videoCodec.codecType == webrtc::kVideoCodecI420) { videoCodec.width = 176; videoCodec.height = 144; } error = ptrViECodec->SetReceiveCodec(videoChannel, videoCodec); if (error == -1) { printf("ERROR in ViECodec::SetReceiveCodec\n"); return -1; } if (videoCodec.codecType != webrtc::kVideoCodecRED && videoCodec.codecType != webrtc::kVideoCodecULPFEC) { printf("\t %d. %s\n", codecIdx + 1, videoCodec.plName); } } printf("%d. VP8 over Generic.\n", ptrViECodec->NumberOfCodecs() + 1); printf("Choose codec: "); #ifdef WEBRTC_ANDROID codecIdx = 0; printf("0\n"); #else if (scanf("%d", &codecIdx) != 1) { printf("Error in scanf()\n"); return -1; } getc(stdin); codecIdx = codecIdx - 1; // Compensate for idx start at 1. #endif // VP8 over generic transport gets this special one. if (codecIdx == ptrViECodec->NumberOfCodecs()) { for (codecIdx = 0; codecIdx < ptrViECodec->NumberOfCodecs(); ++codecIdx) { error = ptrViECodec->GetCodec(codecIdx, videoCodec); assert(error != -1); if (videoCodec.codecType == webrtc::kVideoCodecVP8) break; } assert(videoCodec.codecType == webrtc::kVideoCodecVP8); videoCodec.codecType = webrtc::kVideoCodecGeneric; // Any plName should work with generic strcpy(videoCodec.plName, "VP8-GENERIC"); uint8_t pl_type = 127; videoCodec.plType = pl_type; webrtc::ViEExternalCodec* external_codec = webrtc::ViEExternalCodec ::GetInterface(ptrViE); assert(external_codec != NULL); error = external_codec->RegisterExternalSendCodec(videoChannel, pl_type, webrtc::VP8Encoder::Create(), false); assert(error != -1); error = external_codec->RegisterExternalReceiveCodec(videoChannel, pl_type, webrtc::VP8Decoder::Create(), false); assert(error != -1); } else { error = ptrViECodec->GetCodec(codecIdx, videoCodec); if (error == -1) { printf("ERROR in ViECodec::GetCodec\n"); return -1; } } // Set spatial resolution option std::string str; std::cout << std::endl; std::cout << "Enter frame size option (default is CIF):" << std::endl; std::cout << "1. QCIF (176X144) " << std::endl; std::cout << "2. CIF (352X288) " << std::endl; std::cout << "3. VGA (640X480) " << std::endl; std::cout << "4. 4CIF (704X576) " << std::endl; std::cout << "5. WHD (1280X720) " << std::endl; std::cout << "6. FHD (1920X1080) " << std::endl; std::getline(std::cin, str); int resolnOption = atoi(str.c_str()); switch (resolnOption) { case 1: videoCodec.width = 176; videoCodec.height = 144; break; case 2: videoCodec.width = 352; videoCodec.height = 288; break; case 3: videoCodec.width = 640; videoCodec.height = 480; break; case 4: videoCodec.width = 704; videoCodec.height = 576; break; case 5: videoCodec.width = 1280; videoCodec.height = 720; break; case 6: videoCodec.width = 1920; videoCodec.height = 1080; break; } // Set number of temporal layers. std::cout << std::endl; std::cout << "Choose number of temporal layers for VP8 (1 to 4). "; std::cout << "Press enter for default (=1) for other codecs: \n"; std::getline(std::cin, str); int numTemporalLayers = atoi(str.c_str()); if (numTemporalLayers != 0 && videoCodec.codecType == webrtc::kVideoCodecVP8) { videoCodec.codecSpecific.VP8.numberOfTemporalLayers = numTemporalLayers; } else if (videoCodec.codecType == webrtc::kVideoCodecVP9) { // Temporal layers for vp9 not yet supported in webrtc. numTemporalLayers = 1; videoCodec.codecSpecific.VP9.numberOfTemporalLayers = 1; } // Set start bit rate std::cout << std::endl; std::cout << "Choose start rate (in kbps). Press enter for default: "; std::getline(std::cin, str); int startRate = atoi(str.c_str()); if(startRate != 0) { videoCodec.startBitrate=startRate; } error = ptrViECodec->SetSendCodec(videoChannel, videoCodec); assert(error != -1); error = ptrViECodec->SetReceiveCodec(videoChannel, videoCodec); assert(error != -1); // // Choose Protection Mode // std::cout << std::endl; std::cout << "Enter Protection Method:" << std::endl; std::cout << "0. None" << std::endl; std::cout << "1. FEC" << std::endl; std::cout << "2. NACK" << std::endl; std::cout << "3. NACK+FEC" << std::endl; std::getline(std::cin, str); int protectionMethod = atoi(str.c_str()); error = 0; bool temporalToggling = true; switch (protectionMethod) { case 0: // None: default is no protection break; case 1: // FEC only error = ptrViERtpRtcp->SetFECStatus(videoChannel, true, VCM_RED_PAYLOAD_TYPE, VCM_ULPFEC_PAYLOAD_TYPE); temporalToggling = false; break; case 2: // Nack only error = ptrViERtpRtcp->SetNACKStatus(videoChannel, true); break; case 3: // Hybrid NAck and FEC error = ptrViERtpRtcp->SetHybridNACKFECStatus( videoChannel, true, VCM_RED_PAYLOAD_TYPE, VCM_ULPFEC_PAYLOAD_TYPE); temporalToggling = false; break; } if (error < 0) { printf("ERROR in ViERTP_RTCP::SetProtectionStatus\n"); } // Set up buffering delay. std::cout << std::endl; std::cout << "Set buffering delay (mS). Press enter for default(0mS): "; std::getline(std::cin, str); int buffering_delay = atoi(str.c_str()); if (buffering_delay != 0) { error = ptrViERtpRtcp->SetSenderBufferingMode(videoChannel, buffering_delay); if (error < 0) printf("ERROR in ViERTP_RTCP::SetSenderBufferingMode\n"); error = ptrViERtpRtcp->SetReceiverBufferingMode(videoChannel, buffering_delay); if (error < 0) printf("ERROR in ViERTP_RTCP::SetReceiverBufferingMode\n"); } // // Address settings // webrtc::ViENetwork* ptrViENetwork = webrtc::ViENetwork::GetInterface(ptrViE); if (ptrViENetwork == NULL) { printf("ERROR in ViENetwork::GetInterface\n"); return -1; } // Setup transport. TbExternalTransport* extTransport = NULL; webrtc::test::VideoChannelTransport* video_channel_transport = NULL; int testMode = 0; std::cout << std::endl; std::cout << "Enter 1 for testing packet loss and delay with " "external transport: "; std::string test_str; std::getline(std::cin, test_str); testMode = atoi(test_str.c_str()); if (testMode == 1) { // Avoid changing SSRC due to collision. error = ptrViERtpRtcp->SetLocalSSRC(videoChannel, 1); extTransport = new TbExternalTransport(*ptrViENetwork, videoChannel, NULL); error = ptrViENetwork->RegisterSendTransport(videoChannel, *extTransport); if (error == -1) { printf("ERROR in ViECodec::RegisterSendTransport \n"); return -1; } // Setting uniform loss. Actual values will be set by user. NetworkParameters network; network.loss_model = kUniformLoss; // Set up packet loss value std::cout << "Enter Packet Loss Percentage" << std::endl; std::string rate_str; std::getline(std::cin, rate_str); network.packet_loss_rate = atoi(rate_str.c_str()); if (network.packet_loss_rate > 0) { temporalToggling = false; } // Set network delay value std::cout << "Enter network delay value [mS]" << std::endl; std::string delay_str; std::getline(std::cin, delay_str); network.mean_one_way_delay = atoi(delay_str.c_str()); extTransport->SetNetworkParameters(network); if (numTemporalLayers > 1 && temporalToggling) { extTransport->SetTemporalToggle(numTemporalLayers); } else { // Disabled extTransport->SetTemporalToggle(0); } } else { video_channel_transport = new webrtc::test::VideoChannelTransport( ptrViENetwork, videoChannel); const char* ipAddress = "127.0.0.1"; const unsigned short rtpPort = 6000; std::cout << std::endl; std::cout << "Using rtp port: " << rtpPort << std::endl; std::cout << std::endl; error = video_channel_transport->SetLocalReceiver(rtpPort); if (error == -1) { printf("ERROR in SetLocalReceiver\n"); return -1; } error = video_channel_transport->SetSendDestination(ipAddress, rtpPort); if (error == -1) { printf("ERROR in SetSendDestination\n"); return -1; } } error = ptrViEBase->StartReceive(videoChannel); if (error == -1) { printf("ERROR in ViENetwork::StartReceive\n"); return -1; } error = ptrViEBase->StartSend(videoChannel); if (error == -1) { printf("ERROR in ViENetwork::StartSend\n"); return -1; } //******************************************************** // Engine started //******************************************************** // Call started printf("\nLoopback call started\n\n"); printf("Press enter to stop..."); while ((getc(stdin)) != '\n') ; //******************************************************** // Testing finished. Tear down Video Engine //******************************************************** error = ptrViEBase->StopReceive(videoChannel); if (error == -1) { printf("ERROR in ViEBase::StopReceive\n"); return -1; } error = ptrViEBase->StopSend(videoChannel); if (error == -1) { printf("ERROR in ViEBase::StopSend\n"); return -1; } error = ptrViERender->StopRender(captureId); if (error == -1) { printf("ERROR in ViERender::StopRender\n"); return -1; } error = ptrViERender->RemoveRenderer(captureId); if (error == -1) { printf("ERROR in ViERender::RemoveRenderer\n"); return -1; } error = ptrViERender->StopRender(videoChannel); if (error == -1) { printf("ERROR in ViERender::StopRender\n"); return -1; } error = ptrViERender->RemoveRenderer(videoChannel); if (error == -1) { printf("ERROR in ViERender::RemoveRenderer\n"); return -1; } error = ptrViECapture->StopCapture(captureId); if (error == -1) { printf("ERROR in ViECapture::StopCapture\n"); return -1; } error = ptrViECapture->DisconnectCaptureDevice(videoChannel); if (error == -1) { printf("ERROR in ViECapture::DisconnectCaptureDevice\n"); return -1; } error = ptrViECapture->ReleaseCaptureDevice(captureId); if (error == -1) { printf("ERROR in ViECapture::ReleaseCaptureDevice\n"); return -1; } error = ptrViEBase->DeleteChannel(videoChannel); if (error == -1) { printf("ERROR in ViEBase::DeleteChannel\n"); return -1; } delete video_channel_transport; delete extTransport; int remainingInterfaces = 0; remainingInterfaces = ptrViECodec->Release(); remainingInterfaces += ptrViECapture->Release(); remainingInterfaces += ptrViERtpRtcp->Release(); remainingInterfaces += ptrViERender->Release(); remainingInterfaces += ptrViENetwork->Release(); remainingInterfaces += ptrViEBase->Release(); if (remainingInterfaces > 0) { printf("ERROR: Could not release all interfaces\n"); return -1; } bool deleted = webrtc::VideoEngine::Delete(ptrViE); if (deleted == false) { printf("ERROR in VideoEngine::Delete\n"); return -1; } return 0; // // END: VideoEngine 3.0 Sample Code // // =================================================================== } int ViEAutoTest::ViELoopbackCall() { ViETest::Log(" "); ViETest::Log("========================================"); ViETest::Log(" ViE Autotest Loopback Call\n"); if (VideoEngineSampleCode(_window1, _window2) == 0) { ViETest::Log(" "); ViETest::Log(" ViE Autotest Loopback Call Done"); ViETest::Log("========================================"); ViETest::Log(" "); return 0; } ViETest::Log(" "); ViETest::Log(" ViE Autotest Loopback Call Failed"); ViETest::Log("========================================"); ViETest::Log(" "); return 1; }
/****************************************************************************** * * Project: CouchDB Translator * Purpose: Implements OGRCouchDBDriver. * Author: Even Rouault, even dot rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2011, Even Rouault <even dot rouault at spatialys.com> * * 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 "ogr_couchdb.h" // g++ -g -Wall -fPIC -shared -o ogr_CouchDB.so -Iport -Igcore -Iogr -Iogr/ogrsf_frmts -Iogr/ogrsf_frmts/couchdb ogr/ogrsf_frmts/couchdb/*.c* -L. -lgdal -Iogr/ogrsf_frmts/geojson/jsonc CPL_CVSID("$Id$") extern "C" void RegisterOGRCouchDB(); /************************************************************************/ /* OGRCouchDBDriverIdentify() */ /************************************************************************/ static int OGRCouchDBDriverIdentify( GDALOpenInfo* poOpenInfo ) { if (STARTS_WITH(poOpenInfo->pszFilename, "http://") || STARTS_WITH(poOpenInfo->pszFilename, "https://")) { return -1; } else if (STARTS_WITH_CI(poOpenInfo->pszFilename, "CouchDB:")) return 1; else return 0; } /************************************************************************/ /* OGRCouchDBDriverOpen() */ /************************************************************************/ static GDALDataset* OGRCouchDBDriverOpen( GDALOpenInfo* poOpenInfo ) { if( OGRCouchDBDriverIdentify(poOpenInfo) == 0 ) return nullptr; OGRCouchDBDataSource *poDS = new OGRCouchDBDataSource(); if( !poDS->Open( poOpenInfo->pszFilename, poOpenInfo->eAccess == GA_Update ) ) { delete poDS; poDS = nullptr; } if( !GDALIsDriverDeprecatedForGDAL35StillEnabled("COUCHDB") ) { delete poDS; return nullptr; } return poDS; } /************************************************************************/ /* CreateDataSource() */ /************************************************************************/ static GDALDataset* OGRCouchDBDriverCreate( const char * pszName, int /* nXSize */, int /* nYSize */, int /* nBands */, GDALDataType /* eDT */, char ** /* papszOptions */ ) { if( !GDALIsDriverDeprecatedForGDAL35StillEnabled("COUCHDB") ) return nullptr; OGRCouchDBDataSource *poDS = new OGRCouchDBDataSource(); if( !poDS->Open( pszName, TRUE ) ) { delete poDS; poDS = nullptr; } return poDS; } /************************************************************************/ /* RegisterOGRCouchDB() */ /************************************************************************/ void RegisterOGRCouchDB() { if( GDALGetDriverByName( "CouchDB" ) != nullptr ) return; GDALDriver *poDriver = new GDALDriver(); poDriver->SetDescription( "CouchDB" ); poDriver->SetMetadataItem( GDAL_DCAP_VECTOR, "YES" ); poDriver->SetMetadataItem( GDAL_DMD_LONGNAME, "CouchDB / GeoCouch" ); poDriver->SetMetadataItem( GDAL_DMD_HELPTOPIC, "drivers/vector/couchdb.html" ); poDriver->SetMetadataItem( GDAL_DMD_CONNECTION_PREFIX, "CouchDB:" ); poDriver->SetMetadataItem( GDAL_DMD_CREATIONOPTIONLIST, "<CreationOptionList/>"); poDriver->SetMetadataItem( GDAL_DS_LAYER_CREATIONOPTIONLIST, "<LayerCreationOptionList>" " <Option name='UPDATE_PERMISSIONS' type='string' description='Update permissions for the new layer.'/>" " <Option name='GEOJSON' type='boolean' description='Whether to write documents as GeoJSON documents.' default='YES'/>" " <Option name='COORDINATE_PRECISION' type='int' description='Maximum number of figures after decimal separator to write in coordinates.' default='15'/>" "</LayerCreationOptionList>"); poDriver->SetMetadataItem( GDAL_DMD_CREATIONFIELDDATATYPES, "Integer Integer64 Real String Date DateTime " "Time IntegerList Integer64List RealList " "StringList Binary" ); poDriver->pfnIdentify = OGRCouchDBDriverIdentify; poDriver->pfnOpen = OGRCouchDBDriverOpen; poDriver->pfnCreate = OGRCouchDBDriverCreate; GetGDALDriverManager()->RegisterDriver( poDriver ); }
; A288699: Decimal representation of the diagonal from the corner to the origin of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 494", based on the 5-celled von Neumann neighborhood. ; 1,1,0,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1 trn $0,1 sub $0,2 mod $0,2 add $0,1 mov $1,$0
/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "php_swoole_server.h" #include "php_swoole_process.h" #include "swoole_msg_queue.h" #include "ext/standard/php_var.h" #include "zend_smart_str.h" #ifdef SW_HAVE_ZLIB #include <zlib.h> #endif using namespace swoole; struct ConnectionIterator { int current_fd; SessionId session_id; Server *serv; ListenPort *port; int index; }; struct ServerEvent { enum php_swoole_server_callback_type type; std::string name; ServerEvent(enum php_swoole_server_callback_type type, std::string &&name) : type(type), name(name) {} }; // clang-format off static std::unordered_map<std::string, ServerEvent> server_event_map({ { "start", ServerEvent(SW_SERVER_CB_onStart, "Start") }, { "shutdown", ServerEvent(SW_SERVER_CB_onShutdown, "Shutdown") }, { "workerstart", ServerEvent(SW_SERVER_CB_onWorkerStart, "WorkerStart") }, { "workerstop", ServerEvent(SW_SERVER_CB_onWorkerStop, "WorkerStop") }, { "beforereload", ServerEvent(SW_SERVER_CB_onBeforeReload, "BeforeReload") }, { "afterreload", ServerEvent(SW_SERVER_CB_onAfterReload, "AfterReload") }, { "task", ServerEvent(SW_SERVER_CB_onTask, "Task") }, { "finish", ServerEvent(SW_SERVER_CB_onFinish, "Finish") }, { "workerexit", ServerEvent(SW_SERVER_CB_onWorkerExit, "WorkerExit") }, { "workererror", ServerEvent(SW_SERVER_CB_onWorkerError, "WorkerError") }, { "managerstart", ServerEvent(SW_SERVER_CB_onManagerStart, "ManagerStart") }, { "managerstop", ServerEvent(SW_SERVER_CB_onManagerStop, "ManagerStop") }, { "pipemessage", ServerEvent(SW_SERVER_CB_onPipeMessage, "PipeMessage") }, }); // clang-format on static int php_swoole_task_finish(Server *serv, zval *zdata, EventData *current_task); static void php_swoole_onPipeMessage(Server *serv, EventData *req); static void php_swoole_onStart(Server *); static void php_swoole_onShutdown(Server *); static void php_swoole_server_onWorkerStart(Server *, int worker_id); static void php_swoole_server_onBeforeReload(Server *serv); static void php_swoole_server_onAfterReload(Server *serv); static void php_swoole_server_onWorkerStop(Server *, int worker_id); static void php_swoole_server_onWorkerExit(Server *serv, int worker_id); static void php_swoole_onUserWorkerStart(Server *serv, Worker *worker); static int php_swoole_server_onTask(Server *, EventData *task); static int php_swoole_server_onFinish(Server *, EventData *task); static void php_swoole_server_onWorkerError(Server *serv, int worker_id, const ExitStatus &exit_status); static void php_swoole_server_onManagerStart(Server *serv); static void php_swoole_server_onManagerStop(Server *serv); static void php_swoole_server_onSendTimeout(Timer *timer, TimerNode *tnode); static enum swReturn_code php_swoole_server_send_resume(Server *serv, FutureTask *context, SessionId fd); static void php_swoole_task_onTimeout(Timer *timer, TimerNode *tnode); static int php_swoole_server_dispatch_func(Server *serv, Connection *conn, SendData *data); static zval *php_swoole_server_add_port(ServerObject *server_object, ListenPort *port); /** * Worker Buffer */ static void **php_swoole_server_worker_create_buffers(Server *serv, uint buffer_num); static void php_swoole_server_worker_free_buffers(Server *serv, uint buffer_num, void **buffers); static void *php_swoole_server_worker_get_buffer(Server *serv, DataHead *info); static size_t php_swoole_server_worker_get_buffer_len(Server *serv, DataHead *info); static void php_swoole_server_worker_add_buffer_len(Server *serv, DataHead *info, size_t len); static void php_swoole_server_worker_move_buffer(Server *serv, PipeBuffer *buffer); static size_t php_swoole_server_worker_get_packet(Server *serv, EventData *req, char **data_ptr); void php_swoole_server_rshutdown() { if (!sw_server()) { return; } Server *serv = sw_server(); serv->drain_worker_pipe(); if (serv->is_started() && !serv->is_user_worker()) { if (php_swoole_is_fatal_error()) { swoole_error_log(SW_LOG_ERROR, SW_ERROR_PHP_FATAL_ERROR, "Fatal error: %s in %s on line %d", #if PHP_VERSION_ID < 80000 PG(last_error_message), #else PG(last_error_message)->val, #endif PG(last_error_file) ? PG(last_error_file) : "-", PG(last_error_lineno)); } else { swoole_error_log( SW_LOG_NOTICE, SW_ERROR_SERVER_WORKER_TERMINATED, "worker process is terminated by exit()/die()"); } } } zend_class_entry *swoole_server_ce; zend_object_handlers swoole_server_handlers; zend_class_entry *swoole_connection_iterator_ce; static zend_object_handlers swoole_connection_iterator_handlers; static zend_class_entry *swoole_server_task_ce; static zend_object_handlers swoole_server_task_handlers; static zend_class_entry *swoole_server_event_ce; static zend_object_handlers swoole_server_event_handlers; static zend_class_entry *swoole_server_packet_ce; static zend_object_handlers swoole_server_packet_handlers; static zend_class_entry *swoole_server_pipe_message_ce; static zend_object_handlers swoole_server_pipe_message_handlers; static zend_class_entry *swoole_server_status_info_ce; static zend_object_handlers swoole_server_status_info_handlers; static zend_class_entry *swoole_server_task_result_ce; static zend_object_handlers swoole_server_task_result_handlers; static sw_inline ServerObject *server_fetch_object(zend_object *obj) { return (ServerObject *) ((char *) obj - swoole_server_handlers.offset); } static sw_inline Server *server_get_ptr(zval *zobject) { return server_fetch_object(Z_OBJ_P(zobject))->serv; } Server *php_swoole_server_get_and_check_server(zval *zobject) { Server *serv = server_get_ptr(zobject); if (UNEXPECTED(!serv)) { php_swoole_fatal_error(E_ERROR, "Invaild instance of %s", SW_Z_OBJCE_NAME_VAL_P(zobject)); } return serv; } bool php_swoole_server_isset_callback(Server *serv, ListenPort *port, int event_type) { ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); return server_object->isset_callback(port, event_type); } static sw_inline void server_set_ptr(zval *zobject, Server *serv) { server_fetch_object(Z_OBJ_P(zobject))->serv = serv; } static void server_free_object(zend_object *object) { ServerObject *server_object = server_fetch_object(object); ServerProperty *property = server_object->property; Server *serv = server_object->serv; if (serv) { if (serv->private_data_3) { sw_zend_fci_cache_discard((zend_fcall_info_cache *) serv->private_data_3); efree(serv->private_data_3); } if (serv->private_data_2) { efree(serv->private_data_2); } for (int i = 0; i < PHP_SWOOLE_SERVER_CALLBACK_NUM; i++) { zend_fcall_info_cache *fci_cache = property->callbacks[i]; if (fci_cache) { efree(fci_cache); property->callbacks[i] = nullptr; } } for (auto i = property->user_processes.begin(); i != property->user_processes.end(); i++) { sw_zval_free(*i); } for (auto zport : property->ports) { php_swoole_server_port_deref(Z_OBJ_P(zport)); efree(zport); } server_object->serv = nullptr; } delete property; zend_object_std_dtor(object); if (serv && serv->is_master()) { delete serv; } } static zend_object *server_create_object(zend_class_entry *ce) { ServerObject *server_object = (ServerObject *) zend_object_alloc(sizeof(ServerObject), ce); zend_object_std_init(&server_object->std, ce); object_properties_init(&server_object->std, ce); server_object->std.handlers = &swoole_server_handlers; server_object->property = new ServerProperty(); return &server_object->std; } struct ConnectionIteratorObject { ConnectionIterator iterator; zend_object std; }; static sw_inline ConnectionIteratorObject *php_swoole_connection_iterator_fetch_object(zend_object *obj) { return (ConnectionIteratorObject *) ((char *) obj - swoole_connection_iterator_handlers.offset); } static sw_inline ConnectionIterator *php_swoole_connection_iterator_get_ptr(zval *zobject) { return &php_swoole_connection_iterator_fetch_object(Z_OBJ_P(zobject))->iterator; } ConnectionIterator *php_swoole_connection_iterator_get_and_check_ptr(zval *zobject) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_ptr(zobject); if (UNEXPECTED(!iterator->serv)) { php_swoole_fatal_error(E_ERROR, "Invaild instance of %s", SW_Z_OBJCE_NAME_VAL_P(zobject)); } return iterator; } static void php_swoole_connection_iterator_free_object(zend_object *object) { zend_object_std_dtor(object); } static zend_object *php_swoole_connection_iterator_create_object(zend_class_entry *ce) { ConnectionIteratorObject *connection = (ConnectionIteratorObject *) zend_object_alloc(sizeof(ConnectionIteratorObject), ce); zend_object_std_init(&connection->std, ce); object_properties_init(&connection->std, ce); connection->std.handlers = &swoole_connection_iterator_handlers; return &connection->std; } struct ServerTaskObject { Server *serv; DataHead info; zend_object std; }; static sw_inline ServerTaskObject *php_swoole_server_task_fetch_object(zend_object *obj) { return (ServerTaskObject *) ((char *) obj - swoole_server_task_handlers.offset); } static sw_inline Server *php_swoole_server_task_get_server(zval *zobject) { Server *serv = php_swoole_server_task_fetch_object(Z_OBJ_P(zobject))->serv; if (!serv) { php_swoole_fatal_error(E_ERROR, "Invaild instance of %s", SW_Z_OBJCE_NAME_VAL_P(zobject)); } return serv; } static sw_inline void php_swoole_server_task_set_server(zval *zobject, Server *serv) { php_swoole_server_task_fetch_object(Z_OBJ_P(zobject))->serv = serv; } static sw_inline DataHead *php_swoole_server_task_get_info(zval *zobject) { ServerTaskObject *task = php_swoole_server_task_fetch_object(Z_OBJ_P(zobject)); if (!task->serv) { php_swoole_fatal_error(E_ERROR, "Invaild instance of %s", SW_Z_OBJCE_NAME_VAL_P(zobject)); } return &task->info; } static sw_inline void php_swoole_server_task_set_info(zval *zobject, DataHead *info) { php_swoole_server_task_fetch_object(Z_OBJ_P(zobject))->info = *info; } static void php_swoole_server_task_free_object(zend_object *object) { zend_object_std_dtor(object); } static zend_object *php_swoole_server_task_create_object(zend_class_entry *ce) { ServerTaskObject *server_task = (ServerTaskObject *) zend_object_alloc(sizeof(ServerTaskObject), ce); zend_object_std_init(&server_task->std, ce); object_properties_init(&server_task->std, ce); server_task->std.handlers = &swoole_server_task_handlers; return &server_task->std; } // arginfo server // clang-format off ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_void, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server__construct, 0, 0, 1) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, sock_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_set, 0, 0, 1) ZEND_ARG_ARRAY_INFO(0, settings, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_send, 0, 0, 2) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, send_data) ZEND_ARG_INFO(0, server_socket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_sendwait, 0, 0, 2) ZEND_ARG_INFO(0, conn_fd) ZEND_ARG_INFO(0, send_data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_exists, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_protect, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, is_protected) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_sendto, 0, 0, 3) ZEND_ARG_INFO(0, ip) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, send_data) ZEND_ARG_INFO(0, server_socket) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_sendfile, 0, 0, 2) ZEND_ARG_INFO(0, conn_fd) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, offset) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_close, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, reset) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_pause, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_resume, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() #ifdef SWOOLE_SOCKETS_SUPPORT ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_getSocket, 0, 0, 0) ZEND_ARG_INFO(0, port) ZEND_END_ARG_INFO() #endif ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_on, 0, 0, 2) ZEND_ARG_INFO(0, event_name) ZEND_ARG_CALLABLE_INFO(0, callback, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_getCallback, 0, 0, 1) ZEND_ARG_INFO(0, event_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_listen, 0, 0, 3) ZEND_ARG_INFO(0, host) ZEND_ARG_INFO(0, port) ZEND_ARG_INFO(0, sock_type) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_task, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, worker_id) ZEND_ARG_CALLABLE_INFO(0, finish_callback, 1) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_taskwait, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, timeout) ZEND_ARG_INFO(0, worker_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_taskCo, 0, 0, 1) ZEND_ARG_ARRAY_INFO(0, tasks, 0) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_taskWaitMulti, 0, 0, 1) ZEND_ARG_ARRAY_INFO(0, tasks, 0) ZEND_ARG_INFO(0, timeout) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_finish, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_task_pack, 0, 0, 1) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_reload, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_heartbeat, 0, 0, 1) ZEND_ARG_INFO(0, reactor_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_stop, 0, 0, 0) ZEND_ARG_INFO(0, worker_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_bind, 0, 0, 2) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, uid) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_sendMessage, 0, 0, 2) ZEND_ARG_INFO(0, message) ZEND_ARG_INFO(0, dst_worker_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_addProcess, 0, 0, 1) ZEND_ARG_OBJ_INFO(0, process, swoole_process, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_getClientInfo, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, reactor_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_getWorkerStatus, 0, 0, 0) ZEND_ARG_INFO(0, worker_id) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_server_getClientList, 0, 0, 1) ZEND_ARG_INFO(0, start_fd) ZEND_ARG_INFO(0, find_count) ZEND_END_ARG_INFO() //arginfo connection_iterator ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_connection_iterator_offsetExists, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_connection_iterator_offsetGet, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_connection_iterator_offsetUnset, 0, 0, 1) ZEND_ARG_INFO(0, fd) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_connection_iterator_offsetSet, 0, 0, 2) ZEND_ARG_INFO(0, fd) ZEND_ARG_INFO(0, value) ZEND_END_ARG_INFO() //arginfo end // clang-format on SW_EXTERN_C_BEGIN static PHP_METHOD(swoole_server, __construct); static PHP_METHOD(swoole_server, __destruct); static PHP_METHOD(swoole_server, set); static PHP_METHOD(swoole_server, on); static PHP_METHOD(swoole_server, getCallback); static PHP_METHOD(swoole_server, listen); static PHP_METHOD(swoole_server, sendMessage); static PHP_METHOD(swoole_server, addProcess); static PHP_METHOD(swoole_server, start); static PHP_METHOD(swoole_server, stop); static PHP_METHOD(swoole_server, send); static PHP_METHOD(swoole_server, sendfile); static PHP_METHOD(swoole_server, stats); static PHP_METHOD(swoole_server, bind); static PHP_METHOD(swoole_server, sendto); static PHP_METHOD(swoole_server, sendwait); static PHP_METHOD(swoole_server, exists); static PHP_METHOD(swoole_server, protect); static PHP_METHOD(swoole_server, close); static PHP_METHOD(swoole_server, pause); static PHP_METHOD(swoole_server, resume); static PHP_METHOD(swoole_server, task); static PHP_METHOD(swoole_server, taskwait); static PHP_METHOD(swoole_server, taskWaitMulti); static PHP_METHOD(swoole_server, taskCo); static PHP_METHOD(swoole_server, finish); static PHP_METHOD(swoole_server, reload); static PHP_METHOD(swoole_server, shutdown); static PHP_METHOD(swoole_server, heartbeat); static PHP_METHOD(swoole_server, getClientList); static PHP_METHOD(swoole_server, getClientInfo); static PHP_METHOD(swoole_server, getWorkerId); static PHP_METHOD(swoole_server, getWorkerPid); static PHP_METHOD(swoole_server, getWorkerStatus); static PHP_METHOD(swoole_server, getManagerPid); static PHP_METHOD(swoole_server, getMasterPid); #ifdef SWOOLE_SOCKETS_SUPPORT static PHP_METHOD(swoole_server, getSocket); #endif /** * Server\Connection */ static PHP_METHOD(swoole_connection_iterator, count); static PHP_METHOD(swoole_connection_iterator, rewind); static PHP_METHOD(swoole_connection_iterator, next); static PHP_METHOD(swoole_connection_iterator, current); static PHP_METHOD(swoole_connection_iterator, key); static PHP_METHOD(swoole_connection_iterator, valid); static PHP_METHOD(swoole_connection_iterator, offsetExists); static PHP_METHOD(swoole_connection_iterator, offsetGet); static PHP_METHOD(swoole_connection_iterator, offsetSet); static PHP_METHOD(swoole_connection_iterator, offsetUnset); static PHP_METHOD(swoole_connection_iterator, __construct); static PHP_METHOD(swoole_connection_iterator, __destruct); /** * Server\Task */ static PHP_METHOD(swoole_server_task, finish); static PHP_METHOD(swoole_server_task, pack); SW_EXTERN_C_END // clang-format off static zend_function_entry swoole_server_methods[] = { PHP_ME(swoole_server, __construct, arginfo_swoole_server__construct, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, __destruct, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, listen, arginfo_swoole_server_listen, ZEND_ACC_PUBLIC) PHP_MALIAS(swoole_server, addlistener, listen, arginfo_swoole_server_listen, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, on, arginfo_swoole_server_on, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getCallback, arginfo_swoole_server_getCallback, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, set, arginfo_swoole_server_set, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, start, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, send, arginfo_swoole_server_send, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, sendto, arginfo_swoole_server_sendto, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, sendwait, arginfo_swoole_server_sendwait, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, exists, arginfo_swoole_server_exists, ZEND_ACC_PUBLIC) PHP_MALIAS(swoole_server, exist, exists, arginfo_swoole_server_exists, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, protect, arginfo_swoole_server_protect, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, sendfile, arginfo_swoole_server_sendfile, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, close, arginfo_swoole_server_close, ZEND_ACC_PUBLIC) PHP_MALIAS(swoole_server, confirm, resume, arginfo_swoole_server_resume, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, pause, arginfo_swoole_server_pause, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, resume, arginfo_swoole_server_resume, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, task, arginfo_swoole_server_task, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, taskwait, arginfo_swoole_server_taskwait, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, taskWaitMulti, arginfo_swoole_server_taskWaitMulti, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, taskCo, arginfo_swoole_server_taskCo, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, finish, arginfo_swoole_server_finish, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, reload, arginfo_swoole_server_reload, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, shutdown, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, stop, arginfo_swoole_server_stop, ZEND_ACC_PUBLIC) PHP_FALIAS(getLastError, swoole_last_error, arginfo_swoole_void) PHP_ME(swoole_server, heartbeat, arginfo_swoole_server_heartbeat, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getClientInfo, arginfo_swoole_server_getClientInfo, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getClientList, arginfo_swoole_server_getClientList, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getWorkerId, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getWorkerPid, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getWorkerStatus, arginfo_swoole_server_getWorkerStatus, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getManagerPid, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, getMasterPid, arginfo_swoole_void, ZEND_ACC_PUBLIC) //psr-0 style PHP_MALIAS(swoole_server, connection_info, getClientInfo, arginfo_swoole_server_getClientInfo, ZEND_ACC_PUBLIC) PHP_MALIAS(swoole_server, connection_list, getClientList, arginfo_swoole_server_getClientList, ZEND_ACC_PUBLIC) //process PHP_ME(swoole_server, sendMessage, arginfo_swoole_server_sendMessage, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, addProcess, arginfo_swoole_server_addProcess, ZEND_ACC_PUBLIC) PHP_ME(swoole_server, stats, arginfo_swoole_void, ZEND_ACC_PUBLIC) #ifdef SWOOLE_SOCKETS_SUPPORT PHP_ME(swoole_server, getSocket, arginfo_swoole_server_getSocket, ZEND_ACC_PUBLIC) #endif PHP_ME(swoole_server, bind, arginfo_swoole_server_bind, ZEND_ACC_PUBLIC) {nullptr, nullptr, nullptr} }; static const zend_function_entry swoole_connection_iterator_methods[] = { PHP_ME(swoole_connection_iterator, __construct, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, __destruct, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, rewind, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, next, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, current, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, key, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, valid, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, count, arginfo_swoole_void, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, offsetExists, arginfo_swoole_connection_iterator_offsetExists, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, offsetGet, arginfo_swoole_connection_iterator_offsetGet, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, offsetSet, arginfo_swoole_connection_iterator_offsetSet, ZEND_ACC_PUBLIC) PHP_ME(swoole_connection_iterator, offsetUnset, arginfo_swoole_connection_iterator_offsetUnset, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry swoole_server_task_methods[] = { PHP_ME(swoole_server_task, finish, arginfo_swoole_server_finish, ZEND_ACC_PUBLIC) PHP_ME(swoole_server_task, pack, arginfo_swoole_server_task_pack, ZEND_ACC_PUBLIC | ZEND_ACC_STATIC) PHP_FE_END }; // clang-format on void php_swoole_server_minit(int module_number) { // ---------------------------------------Server------------------------------------- SW_INIT_CLASS_ENTRY(swoole_server, "Swoole\\Server", "swoole_server", nullptr, swoole_server_methods); SW_SET_CLASS_SERIALIZABLE(swoole_server, zend_class_serialize_deny, zend_class_unserialize_deny); SW_SET_CLASS_CLONEABLE(swoole_server, sw_zend_class_clone_deny); SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_server, sw_zend_class_unset_property_deny); SW_SET_CLASS_CUSTOM_OBJECT(swoole_server, server_create_object, server_free_object, ServerObject, std); SW_FUNCTION_ALIAS(&swoole_timer_ce->function_table, "after", &swoole_server_ce->function_table, "after"); SW_FUNCTION_ALIAS(&swoole_timer_ce->function_table, "tick", &swoole_server_ce->function_table, "tick"); SW_FUNCTION_ALIAS(&swoole_timer_ce->function_table, "clear", &swoole_server_ce->function_table, "clearTimer"); SW_FUNCTION_ALIAS(&swoole_event_ce->function_table, "defer", &swoole_server_ce->function_table, "defer"); // ---------------------------------------Task------------------------------------- SW_INIT_CLASS_ENTRY( swoole_server_task, "Swoole\\Server\\Task", "swoole_server_task", nullptr, swoole_server_task_methods); swoole_server_task_ce->ce_flags |= ZEND_ACC_FINAL; SW_SET_CLASS_SERIALIZABLE(swoole_server_task, zend_class_serialize_deny, zend_class_unserialize_deny); SW_SET_CLASS_CLONEABLE(swoole_server_task, sw_zend_class_clone_deny); SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_server_task, sw_zend_class_unset_property_deny); SW_SET_CLASS_CUSTOM_OBJECT(swoole_server_task, php_swoole_server_task_create_object, php_swoole_server_task_free_object, ServerTaskObject, std); zend_declare_property_null(swoole_server_task_ce, ZEND_STRL("data"), ZEND_ACC_PUBLIC); zend_declare_property_double(swoole_server_task_ce, ZEND_STRL("dispatch_time"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_task_ce, ZEND_STRL("id"), -1, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_task_ce, ZEND_STRL("worker_id"), -1, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_task_ce, ZEND_STRL("flags"), 0, ZEND_ACC_PUBLIC); // ---------------------------------------Event------------------------------------- SW_INIT_CLASS_ENTRY_DATA_OBJECT(swoole_server_event, "Swoole\\Server\\Event"); zend_declare_property_long(swoole_server_event_ce, ZEND_STRL("reactor_id"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_event_ce, ZEND_STRL("fd"), 0, ZEND_ACC_PUBLIC); zend_declare_property_double(swoole_server_event_ce, ZEND_STRL("dispatch_time"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_event_ce, ZEND_STRL("data"), ZEND_ACC_PUBLIC); // ---------------------------------------Packet------------------------------------- SW_INIT_CLASS_ENTRY_DATA_OBJECT(swoole_server_packet, "Swoole\\Server\\Packet"); zend_declare_property_long(swoole_server_packet_ce, ZEND_STRL("server_socket"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_packet_ce, ZEND_STRL("server_port"), 0, ZEND_ACC_PUBLIC); zend_declare_property_double(swoole_server_packet_ce, ZEND_STRL("dispatch_time"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_packet_ce, ZEND_STRL("address"), ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_packet_ce, ZEND_STRL("port"), 0, ZEND_ACC_PUBLIC); // ---------------------------------------PipeMessage------------------------------------- SW_INIT_CLASS_ENTRY_DATA_OBJECT(swoole_server_pipe_message, "Swoole\\Server\\PipeMessage"); zend_declare_property_long(swoole_server_pipe_message_ce, ZEND_STRL("source_worker_id"), 0, ZEND_ACC_PUBLIC); zend_declare_property_double(swoole_server_pipe_message_ce, ZEND_STRL("dispatch_time"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_pipe_message_ce, ZEND_STRL("data"), ZEND_ACC_PUBLIC); // ---------------------------------------StatusInfo------------------------------------- SW_INIT_CLASS_ENTRY_DATA_OBJECT(swoole_server_status_info, "Swoole\\Server\\StatusInfo"); zend_declare_property_long(swoole_server_status_info_ce, ZEND_STRL("worker_id"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_status_info_ce, ZEND_STRL("worker_pid"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_status_info_ce, ZEND_STRL("status"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_status_info_ce, ZEND_STRL("exit_code"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_status_info_ce, ZEND_STRL("signal"), 0, ZEND_ACC_PUBLIC); // ---------------------------------------TaskResult------------------------------------- SW_INIT_CLASS_ENTRY_DATA_OBJECT(swoole_server_task_result, "Swoole\\Server\\TaskResult"); zend_declare_property_long(swoole_server_task_result_ce, ZEND_STRL("task_id"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_task_result_ce, ZEND_STRL("task_worker_id"), 0, ZEND_ACC_PUBLIC); zend_declare_property_double(swoole_server_task_result_ce, ZEND_STRL("dispatch_time"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_task_result_ce, ZEND_STRL("data"), ZEND_ACC_PUBLIC); // ---------------------------------------Connection Iterator------------------------------------- SW_INIT_CLASS_ENTRY(swoole_connection_iterator, "Swoole\\Connection\\Iterator", "swoole_connection_iterator", nullptr, swoole_connection_iterator_methods); SW_SET_CLASS_SERIALIZABLE(swoole_connection_iterator, zend_class_serialize_deny, zend_class_unserialize_deny); SW_SET_CLASS_CLONEABLE(swoole_connection_iterator, sw_zend_class_clone_deny); SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_connection_iterator, sw_zend_class_unset_property_deny); SW_SET_CLASS_CUSTOM_OBJECT(swoole_connection_iterator, php_swoole_connection_iterator_create_object, php_swoole_connection_iterator_free_object, ConnectionIteratorObject, std); zend_class_implements(swoole_connection_iterator_ce, 2, zend_ce_iterator, zend_ce_arrayaccess); #ifdef SW_HAVE_COUNTABLE zend_class_implements(swoole_connection_iterator_ce, 1, zend_ce_countable); #endif // ---------------------------------------Server Property------------------------------------- zend_declare_property_null(swoole_server_ce, ZEND_STRL("onStart"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onShutdown"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onWorkerStart"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onWorkerStop"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onBeforeReload"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onAfterReload"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onWorkerExit"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onWorkerError"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onTask"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onFinish"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onManagerStart"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onManagerStop"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("onPipeMessage"), ZEND_ACC_PRIVATE); zend_declare_property_null(swoole_server_ce, ZEND_STRL("setting"), ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_ce, ZEND_STRL("connections"), ZEND_ACC_PUBLIC); zend_declare_property_string(swoole_server_ce, ZEND_STRL("host"), "", ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("port"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("type"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("mode"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_ce, ZEND_STRL("ports"), ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("master_pid"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("manager_pid"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("worker_id"), -1, ZEND_ACC_PUBLIC); zend_declare_property_bool(swoole_server_ce, ZEND_STRL("taskworker"), 0, ZEND_ACC_PUBLIC); zend_declare_property_long(swoole_server_ce, ZEND_STRL("worker_pid"), 0, ZEND_ACC_PUBLIC); zend_declare_property_null(swoole_server_ce, ZEND_STRL("stats_timer"), ZEND_ACC_PUBLIC); SW_REGISTER_LONG_CONSTANT("SWOOLE_DISPATCH_RESULT_DISCARD_PACKET", SW_DISPATCH_RESULT_DISCARD_PACKET); SW_REGISTER_LONG_CONSTANT("SWOOLE_DISPATCH_RESULT_CLOSE_CONNECTION", SW_DISPATCH_RESULT_CLOSE_CONNECTION); SW_REGISTER_LONG_CONSTANT("SWOOLE_DISPATCH_RESULT_USERFUNC_FALLBACK", SW_DISPATCH_RESULT_USERFUNC_FALLBACK); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_TMPFILE", SW_TASK_TMPFILE); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_SERIALIZE", SW_TASK_SERIALIZE); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_NONBLOCK", SW_TASK_NONBLOCK); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_CALLBACK", SW_TASK_CALLBACK); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_WAITALL", SW_TASK_WAITALL); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_COROUTINE", SW_TASK_COROUTINE); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_PEEK", SW_TASK_PEEK); SW_REGISTER_LONG_CONSTANT("SWOOLE_TASK_NOREPLY", SW_TASK_NOREPLY); SW_REGISTER_LONG_CONSTANT("SWOOLE_WORKER_BUSY", SW_WORKER_BUSY); SW_REGISTER_LONG_CONSTANT("SWOOLE_WORKER_IDLE", SW_WORKER_IDLE); SW_REGISTER_LONG_CONSTANT("SWOOLE_WORKER_EXIT", SW_WORKER_EXIT); } zend_fcall_info_cache *php_swoole_server_get_fci_cache(Server *serv, int server_fd, int event_type) { ListenPort *port = serv->get_port_by_server_fd(server_fd); ServerPortProperty *property; zend_fcall_info_cache *fci_cache; ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); if (sw_unlikely(!port)) { return nullptr; } if ((property = (ServerPortProperty *) port->ptr) && (fci_cache = property->caches[event_type])) { return fci_cache; } else { return server_object->property->primary_port->caches[event_type]; } } int php_swoole_create_dir(const char *path, size_t length) { if (access(path, F_OK) == 0) { return 0; } return php_stream_mkdir(path, 0777, PHP_STREAM_MKDIR_RECURSIVE | REPORT_ERRORS, nullptr) ? 0 : -1; } TaskId php_swoole_task_pack(EventData *task, zval *zdata) { smart_str serialized_data = {}; php_serialize_data_t var_hash; task->info.type = SW_SERVER_EVENT_TASK; task->info.fd = SwooleG.current_task_id++; task->info.reactor_id = SwooleG.process_id; task->info.time = swoole::microtime(); swTask_type(task) = 0; char *task_data_str; size_t task_data_len = 0; // need serialize if (Z_TYPE_P(zdata) != IS_STRING) { // serialize swTask_type(task) |= SW_TASK_SERIALIZE; PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&serialized_data, zdata, &var_hash); PHP_VAR_SERIALIZE_DESTROY(var_hash); if (!serialized_data.s) { return -1; } task_data_str = ZSTR_VAL(serialized_data.s); task_data_len = ZSTR_LEN(serialized_data.s); } else { task_data_str = Z_STRVAL_P(zdata); task_data_len = Z_STRLEN_P(zdata); } if (!task->pack(task_data_str, task_data_len)) { php_swoole_fatal_error(E_WARNING, "large task pack failed"); task->info.fd = SW_ERR; task->info.len = 0; } smart_str_free(&serialized_data); return task->info.fd; } void php_swoole_get_recv_data(Server *serv, zval *zdata, RecvData *req) { const char *data = req->data; uint32_t length = req->info.len; if (length == 0) { ZVAL_EMPTY_STRING(zdata); } else { if (req->info.flags & SW_EVENT_DATA_OBJ_PTR) { zend_string *worker_buffer = zend::fetch_zend_string_by_val((char *) data); ZVAL_STR(zdata, worker_buffer); } else if (req->info.flags & SW_EVENT_DATA_POP_PTR) { String *recv_buffer = serv->get_recv_buffer(serv->get_connection_by_session_id(req->info.fd)->socket); sw_set_zend_string(zdata, recv_buffer->pop(serv->recv_buffer_size), length); } else { ZVAL_STRINGL(zdata, data, length); } } } static sw_inline int php_swoole_check_task_param(Server *serv, zend_long dst_worker_id) { if (UNEXPECTED(serv->task_worker_num == 0)) { php_swoole_fatal_error(E_WARNING, "task method can't be executed without task worker"); return SW_ERR; } if (UNEXPECTED(dst_worker_id > 0 && dst_worker_id >= serv->task_worker_num)) { php_swoole_fatal_error(E_WARNING, "worker_id must be less than task_worker_num[%u]", serv->task_worker_num); return SW_ERR; } if (UNEXPECTED(serv->is_task_worker())) { php_swoole_fatal_error(E_WARNING, "Server->task() cannot use in the task-worker"); return SW_ERR; } return SW_OK; } zval *php_swoole_task_unpack(EventData *task_result) { zval *result_data, *result_unserialized_data; char *result_data_str; size_t result_data_len = 0; php_unserialize_data_t var_hash; /** * Large result package */ if (swTask_type(task_result) & SW_TASK_TMPFILE) { if (!task_result->unpack(sw_tg_buffer())) { return nullptr; } result_data_str = sw_tg_buffer()->str; result_data_len = sw_tg_buffer()->length; } else { result_data_str = task_result->data; result_data_len = task_result->info.len; } if (swTask_type(task_result) & SW_TASK_SERIALIZE) { result_unserialized_data = sw_malloc_zval(); PHP_VAR_UNSERIALIZE_INIT(var_hash); // unserialize success if (php_var_unserialize(result_unserialized_data, (const unsigned char **) &result_data_str, (const unsigned char *) (result_data_str + result_data_len), &var_hash)) { result_data = result_unserialized_data; } // failed else { result_data = sw_malloc_zval(); ZVAL_STRINGL(result_data, result_data_str, result_data_len); } PHP_VAR_UNSERIALIZE_DESTROY(var_hash); } else { result_data = sw_malloc_zval(); ZVAL_STRINGL(result_data, result_data_str, result_data_len); } return result_data; } static void php_swoole_task_wait_co( Server *serv, EventData *req, double timeout, int dst_worker_id, INTERNAL_FUNCTION_PARAMETERS) { ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); swTask_type(req) |= (SW_TASK_NONBLOCK | SW_TASK_COROUTINE); TaskCo *task_co = (TaskCo *) emalloc(sizeof(TaskCo)); sw_memset_zero(task_co, sizeof(*task_co)); task_co->count = 1; Z_LVAL(task_co->context.coro_params) = req->info.fd; sw_atomic_fetch_add(&serv->gs->tasking_num, 1); if (serv->gs->task_workers.dispatch(req, &dst_worker_id) < 0) { sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); RETURN_FALSE; } else { server_object->property->task_coroutine_map[req->info.fd] = task_co; } long ms = (long) (timeout * 1000); TimerNode *timer = swoole_timer_add(ms, false, php_swoole_task_onTimeout, task_co); if (timer) { task_co->timer = timer; } task_co->server_object = server_object; PHPCoroutine::yield_m(return_value, &task_co->context); } static void php_swoole_task_onTimeout(Timer *timer, TimerNode *tnode) { TaskCo *task_co = (TaskCo *) tnode->data; FutureTask *context = &task_co->context; // Server->taskwait, single task if (task_co->list == nullptr) { zval result; ZVAL_FALSE(&result); PHPCoroutine::resume_m(context, &result); task_co->server_object->property->task_coroutine_map.erase(Z_LVAL(context->coro_params)); efree(task_co); return; } uint32_t i; zval *result = task_co->result; for (i = 0; i < task_co->count; i++) { if (!zend_hash_index_exists(Z_ARRVAL_P(result), i)) { add_index_bool(result, i, 0); task_co->server_object->property->task_coroutine_map.erase(task_co->list[i]); } } PHPCoroutine::resume_m(context, result); sw_zval_free(result); efree(task_co); } extern ListenPort *php_swoole_server_port_get_and_check_ptr(zval *zobject); extern void php_swoole_server_port_set_ptr(zval *zobject, ListenPort *port); extern ServerPortProperty *php_swoole_server_port_get_property(zval *zobject); static zval *php_swoole_server_add_port(ServerObject *server_object, ListenPort *port) { /* port */ zval *zport; Server *serv = server_object->serv; zport = sw_malloc_zval(); object_init_ex(zport, swoole_server_port_ce); server_object->property->ports.push_back(zport); /* port ptr */ php_swoole_server_port_set_ptr(zport, port); /* port property */ ServerPortProperty *property = php_swoole_server_port_get_property(zport); property->serv = serv; property->port = port; /* linked */ port->ptr = property; zend_update_property_string(swoole_server_port_ce, SW_Z8_OBJ_P(zport), ZEND_STRL("host"), port->get_host()); zend_update_property_long(swoole_server_port_ce, SW_Z8_OBJ_P(zport), ZEND_STRL("port"), port->get_port()); zend_update_property_long(swoole_server_port_ce, SW_Z8_OBJ_P(zport), ZEND_STRL("type"), port->get_type()); zend_update_property_long(swoole_server_port_ce, SW_Z8_OBJ_P(zport), ZEND_STRL("sock"), port->get_fd()); do { zval *zserv = (zval *) serv->private_data_2; zval *zports = sw_zend_read_and_convert_property_array(Z_OBJCE_P(zserv), zserv, ZEND_STRL("ports"), 0); (void) add_next_index_zval(zports, zport); } while (0); /* iterator */ do { zval connection_iterator; object_init_ex(&connection_iterator, swoole_connection_iterator_ce); ConnectionIterator *iterator = php_swoole_connection_iterator_get_ptr(&connection_iterator); iterator->serv = serv; iterator->port = port; zend_update_property(swoole_server_port_ce, SW_Z8_OBJ_P(zport), ZEND_STRL("connections"), &connection_iterator); zval_ptr_dtor(&connection_iterator); } while (0); return zport; } void ServerObject::on_before_start() { /** * create swoole server */ if (serv->create() < 0) { php_swoole_fatal_error(E_ERROR, "failed to create the server. Error: %s", sw_error); return; } zval *zobject = get_object(); auto primary_port = serv->get_primary_port(); #ifdef SW_LOG_TRACE_OPEN swTraceLog(SW_TRACE_SERVER, "Create Server: host=%s, port=%d, mode=%d, type=%d", primary_port->host.c_str(), (int) primary_port->port, serv->is_base_mode() ? Server::MODE_BASE : Server::MODE_PROCESS, (int) primary_port->type); #endif if (serv->enable_coroutine) { serv->reload_async = 1; } if (serv->send_yield) { if (serv->onClose == nullptr && serv->is_support_unsafe_events()) { serv->onClose = php_swoole_server_onClose; } } /** * init method */ serv->create_buffers = php_swoole_server_worker_create_buffers; serv->free_buffers = php_swoole_server_worker_free_buffers; serv->get_buffer = php_swoole_server_worker_get_buffer; serv->get_buffer_len = php_swoole_server_worker_get_buffer_len; serv->add_buffer_len = php_swoole_server_worker_add_buffer_len; serv->move_buffer = php_swoole_server_worker_move_buffer; serv->get_packet = php_swoole_server_worker_get_packet; if (serv->is_base_mode()) { serv->buffer_allocator = sw_zend_string_allocator(); } /** * Master Process ID */ zend_update_property_long(get_ce(), SW_Z8_OBJ_P(zobject), ZEND_STRL("master_pid"), getpid()); zval *zsetting = sw_zend_read_and_convert_property_array(get_ce(), zobject, ZEND_STRL("setting"), 0); if (!zend_hash_str_exists(Z_ARRVAL_P(zsetting), ZEND_STRL("worker_num"))) { add_assoc_long(zsetting, "worker_num", serv->worker_num); } if (!zend_hash_str_exists(Z_ARRVAL_P(zsetting), ZEND_STRL("task_worker_num"))) { add_assoc_long(zsetting, "task_worker_num", serv->task_worker_num); } if (!zend_hash_str_exists(Z_ARRVAL_P(zsetting), ZEND_STRL("output_buffer_size"))) { add_assoc_long(zsetting, "output_buffer_size", serv->output_buffer_size); } if (!zend_hash_str_exists(Z_ARRVAL_P(zsetting), ZEND_STRL("max_connection"))) { add_assoc_long(zsetting, "max_connection", serv->get_max_connection()); } bool find_http_port = false; if (is_redis_server()) { add_assoc_bool(zsetting, "open_redis_protocol", 1); add_assoc_bool(zsetting, "open_http_protocol", 0); add_assoc_bool(zsetting, "open_mqtt_protocol", 0); add_assoc_bool(zsetting, "open_eof_check", 0); add_assoc_bool(zsetting, "open_length_check", 0); primary_port->clear_protocol(); primary_port->open_redis_protocol = 1; serv->onReceive = php_swoole_redis_server_onReceive; } else if (is_http_server()) { if (is_websocket_server()) { if (!isset_callback(primary_port, SW_SERVER_CB_onMessage)) { php_swoole_fatal_error(E_ERROR, "require onMessage callback"); return; } } else if (!isset_callback(primary_port, SW_SERVER_CB_onRequest)) { php_swoole_fatal_error(E_ERROR, "require onRequest callback"); return; } add_assoc_bool(zsetting, "open_http_protocol", 1); add_assoc_bool(zsetting, "open_mqtt_protocol", 0); add_assoc_bool(zsetting, "open_eof_check", 0); add_assoc_bool(zsetting, "open_length_check", 0); enum protocol_flags { SW_HTTP2_PROTOCOL = 1u << 1, SW_WEBSOCKET_PROTOCOL = 1u << 2 }; uint8_t protocol_flag = 0; if (primary_port->open_http2_protocol) { add_assoc_bool(zsetting, "open_http2_protocol", 1); protocol_flag |= SW_HTTP2_PROTOCOL; } if (primary_port->open_websocket_protocol || is_websocket_server()) { add_assoc_bool(zsetting, "open_websocket_protocol", 1); protocol_flag |= SW_WEBSOCKET_PROTOCOL; } primary_port->clear_protocol(); primary_port->open_http_protocol = 1; primary_port->open_http2_protocol = !!(protocol_flag & SW_HTTP2_PROTOCOL); primary_port->open_websocket_protocol = !!(protocol_flag & SW_WEBSOCKET_PROTOCOL); find_http_port = true; serv->onReceive = php_swoole_http_server_onReceive; } else { if (serv->if_require_packet_callback(primary_port, isset_callback(primary_port, SW_SERVER_CB_onPacket))) { php_swoole_fatal_error(E_ERROR, "require onPacket callback"); return; } if (serv->if_require_receive_callback(primary_port, isset_callback(primary_port, SW_SERVER_CB_onReceive))) { php_swoole_fatal_error(E_ERROR, "require onReceive callback"); return; } serv->onReceive = php_swoole_server_onReceive; } for (size_t i = 1; i < property->ports.size(); i++) { zval *zport = property->ports.at(i); zval *zport_setting = sw_zend_read_property_ex(swoole_server_port_ce, zport, SW_ZSTR_KNOWN(SW_ZEND_STR_SETTING), 0); // use swoole_server->setting if (zport_setting == nullptr || ZVAL_IS_NULL(zport_setting)) { Z_TRY_ADDREF_P(zport); sw_zend_call_method_with_1_params(zport, swoole_server_port_ce, nullptr, "set", nullptr, zsetting); } } for (size_t i = 0; i < property->ports.size(); i++) { zval *zport = property->ports.at(i); ListenPort *port = php_swoole_server_port_get_and_check_ptr(zport); if (serv->if_require_packet_callback(port, isset_callback(port, SW_SERVER_CB_onPacket))) { php_swoole_fatal_error(E_ERROR, "require onPacket callback"); return; } #ifdef SW_USE_OPENSSL if (port->ssl_context && port->ssl_context->verify_peer && port->ssl_context->client_cert_file.empty()) { php_swoole_fatal_error(E_ERROR, "server open verify peer require client_cert_file config"); return; } #endif if (port->open_http2_protocol && !serv->is_hash_dispatch_mode()) { php_swoole_fatal_error( E_ERROR, "server dispatch mode should be FDMOD(%d) or IPMOD(%d) if open_http2_protocol is true", SW_DISPATCH_FDMOD, SW_DISPATCH_IPMOD); return; } if (!port->open_http_protocol) { port->open_http_protocol = port->open_websocket_protocol || port->open_http2_protocol; } if (port->open_http_protocol) { find_http_port = true; if (port->open_websocket_protocol) { if (!isset_callback(port, SW_SERVER_CB_onMessage) && !isset_callback(port, SW_SERVER_CB_onReceive)) { php_swoole_fatal_error(E_ERROR, "require onMessage callback"); return; } } else if (port->open_http_protocol && !isset_callback(port, SW_SERVER_CB_onRequest) && !isset_callback(port, SW_SERVER_CB_onReceive)) { php_swoole_fatal_error(E_ERROR, "require onRequest callback"); return; } if (!is_http_server() && isset_callback(port, SW_SERVER_CB_onRequest)) { php_swoole_error( E_WARNING, "use %s class and open http related protocols may lead to some errors (inconsistent class type)", SW_Z_OBJCE_NAME_VAL_P(zobject)); } } else if (!port->open_redis_protocol) { // redis server does not require to set receive callback if (port->is_stream() && !isset_callback(port, SW_SERVER_CB_onReceive)) { php_swoole_fatal_error(E_ERROR, "require onReceive callback"); return; } } } if (find_http_port) { serv->onReceive = php_swoole_http_server_onReceive; if (serv->is_support_unsafe_events()) { serv->onClose = php_swoole_http_server_onClose; } php_swoole_http_server_init_global_variant(); } } void ServerObject::register_callback() { /* * optional callback */ if (property->callbacks[SW_SERVER_CB_onStart] != nullptr) { serv->onStart = php_swoole_onStart; } serv->onShutdown = php_swoole_onShutdown; /** * require callback, set the master/manager/worker PID */ serv->onWorkerStart = php_swoole_server_onWorkerStart; if (property->callbacks[SW_SERVER_CB_onBeforeReload] != nullptr) { serv->onBeforeReload = php_swoole_server_onBeforeReload; } if (property->callbacks[SW_SERVER_CB_onAfterReload] != nullptr) { serv->onAfterReload = php_swoole_server_onAfterReload; } if (property->callbacks[SW_SERVER_CB_onWorkerStop] != nullptr) { serv->onWorkerStop = php_swoole_server_onWorkerStop; } serv->onWorkerExit = php_swoole_server_onWorkerExit; /** * Task Worker */ if (property->callbacks[SW_SERVER_CB_onTask] != nullptr) { serv->onTask = php_swoole_server_onTask; serv->onFinish = php_swoole_server_onFinish; } if (property->callbacks[SW_SERVER_CB_onWorkerError] != nullptr) { serv->onWorkerError = php_swoole_server_onWorkerError; } if (property->callbacks[SW_SERVER_CB_onManagerStart] != nullptr) { serv->onManagerStart = php_swoole_server_onManagerStart; } if (property->callbacks[SW_SERVER_CB_onManagerStop] != nullptr) { serv->onManagerStop = php_swoole_server_onManagerStop; } if (property->callbacks[SW_SERVER_CB_onPipeMessage] != nullptr) { serv->onPipeMessage = php_swoole_onPipeMessage; } if (serv->send_yield && serv->is_support_unsafe_events()) { serv->onBufferEmpty = php_swoole_server_onBufferEmpty; } } static int php_swoole_task_finish(Server *serv, zval *zdata, EventData *current_task) { int flags = 0; smart_str serialized_data = {}; php_serialize_data_t var_hash; char *data_str; size_t data_len = 0; int ret; // need serialize if (Z_TYPE_P(zdata) != IS_STRING) { // serialize flags |= SW_TASK_SERIALIZE; PHP_VAR_SERIALIZE_INIT(var_hash); php_var_serialize(&serialized_data, zdata, &var_hash); PHP_VAR_SERIALIZE_DESTROY(var_hash); data_str = ZSTR_VAL(serialized_data.s); data_len = ZSTR_LEN(serialized_data.s); } else { data_str = Z_STRVAL_P(zdata); data_len = Z_STRLEN_P(zdata); } ret = serv->reply_task_result(data_str, data_len, flags, current_task); smart_str_free(&serialized_data); return ret; } static void php_swoole_onPipeMessage(Server *serv, EventData *req) { ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); zend_fcall_info_cache *fci_cache = server_object->property->callbacks[SW_SERVER_CB_onPipeMessage]; zval *zserv = (zval *) serv->private_data_2; zval *zdata = php_swoole_task_unpack(req); if (UNEXPECTED(zdata == nullptr)) { return; } swTraceLog(SW_TRACE_SERVER, "PipeMessage: fd=%d|len=%d|src_worker_id=%d|data=%.*s\n", req->info.fd, req->info.len, req->info.reactor_id, req->info.len, req->data); zval args[3]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; object_init_ex(object, swoole_server_pipe_message_ce); zend_update_property_long(swoole_server_pipe_message_ce, SW_Z8_OBJ_P(object), ZEND_STRL("worker_id"), (zend_long) req->info.reactor_id); zend_update_property_double( swoole_server_pipe_message_ce, SW_Z8_OBJ_P(object), ZEND_STRL("dispatch_time"), req->info.time); zend_update_property(swoole_server_pipe_message_ce, SW_Z8_OBJ_P(object), ZEND_STRL("data"), zdata); argc = 2; } else { ZVAL_LONG(&args[1], (zend_long) req->info.reactor_id); args[2] = *zdata; argc = 3; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->is_enable_coroutine()))) { php_swoole_error(E_WARNING, "%s->onPipeMessage handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (serv->event_object) { zval_ptr_dtor(&args[1]); } sw_zval_free(zdata); } int php_swoole_server_onReceive(Server *serv, RecvData *req) { auto fci_cache = php_swoole_server_get_fci_cache(serv, req->info.server_fd, SW_SERVER_CB_onReceive); if (fci_cache) { zval *zserv = (zval *) serv->private_data_2; zval args[4]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; zval data; object_init_ex(object, swoole_server_event_ce); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("fd"), (zend_long) req->info.fd); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("reactor_id"), (zend_long) req->info.reactor_id); zend_update_property_double( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("dispatch_time"), req->info.time); php_swoole_get_recv_data(serv, &data, req); zend_update_property(swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("data"), &data); zval_ptr_dtor(&data); argc = 2; } else { ZVAL_LONG(&args[1], (zend_long) req->info.fd); ZVAL_LONG(&args[2], (zend_long) req->info.reactor_id); php_swoole_get_recv_data(serv, &args[3], req); argc = 4; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onReceive handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); serv->close(req->info.fd, false); } if (serv->event_object) { zval_ptr_dtor(&args[1]); } else { zval_ptr_dtor(&args[3]); } } return SW_OK; } int php_swoole_server_onPacket(Server *serv, RecvData *req) { zval *zserv = (zval *) serv->private_data_2; zval args[3]; int argc; args[0] = *zserv; DgramPacket *packet = (DgramPacket *) req->data; if (serv->event_object) { zval zobject; object_init_ex(&zobject, swoole_server_packet_ce); zend_update_property_long( swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("server_socket"), req->info.server_fd); zend_update_property_double( swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("dispatch_time"), req->info.time); Connection *server_sock = serv->get_connection(req->info.server_fd); if (server_sock) { zend_update_property_long( swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("server_port"), server_sock->info.get_port()); } char address[INET6_ADDRSTRLEN]; if (packet->socket_type == SW_SOCK_UDP) { inet_ntop(AF_INET, &packet->socket_addr.addr.inet_v4.sin_addr, address, sizeof(address)); zend_update_property_string(swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("address"), address); zend_update_property_long(swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("port"), ntohs(packet->socket_addr.addr.inet_v4.sin_port)); } else if (packet->socket_type == SW_SOCK_UDP6) { inet_ntop(AF_INET6, &packet->socket_addr.addr.inet_v6.sin6_addr, address, sizeof(address)); zend_update_property_string(swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("address"), address); zend_update_property_long(swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("port"), ntohs(packet->socket_addr.addr.inet_v6.sin6_port)); } else if (packet->socket_type == SW_SOCK_UNIX_DGRAM) { zend_update_property_string(swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("address"), packet->socket_addr.addr.un.sun_path); } zend_update_property_stringl( swoole_server_packet_ce, SW_Z8_OBJ_P(&zobject), ZEND_STRL("data"), packet->data, packet->length); args[1] = zobject; argc = 2; } else { zval zaddr; array_init(&zaddr); add_assoc_long(&zaddr, "server_socket", req->info.server_fd); add_assoc_double(&zaddr, "dispatch_time", req->info.time); Connection *server_sock = serv->get_connection(req->info.server_fd); if (server_sock) { add_assoc_long(&zaddr, "server_port", server_sock->info.get_port()); } char address[INET6_ADDRSTRLEN]; if (packet->socket_type == SW_SOCK_UDP) { inet_ntop(AF_INET, &packet->socket_addr.addr.inet_v4.sin_addr, address, sizeof(address)); add_assoc_string(&zaddr, "address", address); add_assoc_long(&zaddr, "port", ntohs(packet->socket_addr.addr.inet_v4.sin_port)); } else if (packet->socket_type == SW_SOCK_UDP6) { inet_ntop(AF_INET6, &packet->socket_addr.addr.inet_v6.sin6_addr, address, sizeof(address)); add_assoc_string(&zaddr, "address", address); add_assoc_long(&zaddr, "port", ntohs(packet->socket_addr.addr.inet_v6.sin6_port)); } else if (packet->socket_type == SW_SOCK_UNIX_DGRAM) { add_assoc_string(&zaddr, "address", packet->socket_addr.addr.un.sun_path); } ZVAL_STRINGL(&args[1], packet->data, packet->length); args[2] = zaddr; argc = 3; } auto fci_cache = php_swoole_server_get_fci_cache(serv, req->info.server_fd, SW_SERVER_CB_onPacket); if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onPipeMessage handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } zval_ptr_dtor(&args[1]); if (!serv->event_object) { zval_ptr_dtor(&args[2]); } return SW_OK; } static sw_inline void php_swoole_create_task_object(zval *ztask, Server *serv, EventData *req, zval *zdata) { object_init_ex(ztask, swoole_server_task_ce); php_swoole_server_task_set_server(ztask, serv); php_swoole_server_task_set_info(ztask, &req->info); zend_update_property_long( swoole_server_task_ce, SW_Z8_OBJ_P(ztask), ZEND_STRL("worker_id"), (zend_long) req->info.reactor_id); zend_update_property_long(swoole_server_task_ce, SW_Z8_OBJ_P(ztask), ZEND_STRL("id"), (zend_long) req->info.fd); zend_update_property(swoole_server_task_ce, SW_Z8_OBJ_P(ztask), ZEND_STRL("data"), zdata); zend_update_property_double(swoole_server_task_ce, SW_Z8_OBJ_P(ztask), ZEND_STRL("dispatch_time"), req->info.time); zend_update_property_long( swoole_server_task_ce, SW_Z8_OBJ_P(ztask), ZEND_STRL("flags"), (zend_long) swTask_type(req)); } static int php_swoole_server_onTask(Server *serv, EventData *req) { sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); zval *zdata = php_swoole_task_unpack(req); if (zdata == nullptr) { return SW_ERR; } zval retval; uint32_t argc; zval argv[4]; if (serv->task_enable_coroutine || serv->task_object) { argc = 2; argv[0] = *zserv; php_swoole_create_task_object(&argv[1], serv, req, zdata); } else { argc = 4; argv[0] = *zserv; ZVAL_LONG(&argv[1], (zend_long) req->info.fd); ZVAL_LONG(&argv[2], (zend_long) req->info.reactor_id); argv[3] = *zdata; } if (UNEXPECTED(!zend::function::call(server_object->property->callbacks[SW_SERVER_CB_onTask], argc, argv, &retval, serv->task_enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onTask handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (argc == 2) { zval_ptr_dtor(&argv[1]); } sw_zval_free(zdata); if (!ZVAL_IS_NULL(&retval)) { php_swoole_task_finish(serv, &retval, req); zval_ptr_dtor(&retval); } return SW_OK; } static int php_swoole_server_onFinish(Server *serv, EventData *req) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); zval *zdata = php_swoole_task_unpack(req); if (zdata == nullptr) { return SW_ERR; } if (swTask_type(req) & SW_TASK_COROUTINE) { TaskId task_id = req->info.fd; auto task_co_iterator = server_object->property->task_coroutine_map.find(task_id); if (task_co_iterator == server_object->property->task_coroutine_map.end()) { swoole_error_log(SW_LOG_WARNING, SW_ERROR_TASK_TIMEOUT, "task[%ld] has expired", task_id); _fail: sw_zval_free(zdata); return SW_OK; } TaskCo *task_co = task_co_iterator->second; // Server->taskwait if (task_co->list == nullptr) { if (task_co->timer) { swoole_timer_del(task_co->timer); } FutureTask *context = &task_co->context; PHPCoroutine::resume_m(context, zdata); efree(task_co); sw_zval_free(zdata); server_object->property->task_coroutine_map.erase(task_id); return SW_OK; } // Server->taskCo uint32_t i; int task_index = -1; zval *result = task_co->result; for (i = 0; i < task_co->count; i++) { if (task_co->list[i] == task_id) { task_index = i; break; } } if (task_index < 0) { php_swoole_fatal_error(E_WARNING, "task[%ld] is invalid", task_id); goto _fail; } (void) add_index_zval(result, task_index, zdata); efree(zdata); server_object->property->task_coroutine_map.erase(task_id); if (php_swoole_array_length(result) == task_co->count) { if (task_co->timer) { swoole_timer_del(task_co->timer); task_co->timer = nullptr; } FutureTask *context = &task_co->context; PHPCoroutine::resume_m(context, result); sw_zval_free(result); efree(task_co); } return SW_OK; } zend_fcall_info_cache *fci_cache = nullptr; if (swTask_type(req) & SW_TASK_CALLBACK) { auto callback_iterator = server_object->property->task_callbacks.find(req->info.fd); if (callback_iterator == server_object->property->task_callbacks.end()) { swTask_type(req) = swTask_type(req) & (~SW_TASK_CALLBACK); } else { fci_cache = &callback_iterator->second; } } else { fci_cache = server_object->property->callbacks[SW_SERVER_CB_onFinish]; } if (UNEXPECTED(fci_cache == nullptr)) { sw_zval_free(zdata); php_swoole_fatal_error(E_WARNING, "require onFinish callback"); return SW_ERR; } zval args[3]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; object_init_ex(object, swoole_server_task_result_ce); zend_update_property_long( swoole_server_task_result_ce, SW_Z8_OBJ_P(object), ZEND_STRL("task_id"), (zend_long) req->info.fd); zend_update_property_long(swoole_server_task_result_ce, SW_Z8_OBJ_P(object), ZEND_STRL("task_worker_id"), (zend_long) req->info.reactor_id); zend_update_property_double( swoole_server_task_result_ce, SW_Z8_OBJ_P(object), ZEND_STRL("dispatch_time"), req->info.time); zend_update_property(swoole_server_task_result_ce, SW_Z8_OBJ_P(object), ZEND_STRL("data"), zdata); argc = 2; } else { ZVAL_LONG(&args[1], req->info.fd); args[2] = *zdata; argc = 3; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onFinish handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (swTask_type(req) & SW_TASK_CALLBACK) { sw_zend_fci_cache_discard(fci_cache); server_object->property->task_callbacks.erase(req->info.fd); } sw_zval_free(zdata); if (serv->event_object) { zval_ptr_dtor(&args[1]); } return SW_OK; } static void php_swoole_onStart(Server *serv) { serv->lock(); zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onStart]; zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("master_pid"), serv->gs->master_pid); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("manager_pid"), serv->gs->manager_pid); if (UNEXPECTED(!zend::function::call(fci_cache, 1, zserv, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onStart handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } serv->unlock(); } static void php_swoole_server_onManagerStart(Server *serv) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onManagerStart]; zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("master_pid"), serv->gs->master_pid); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("manager_pid"), serv->gs->manager_pid); if (UNEXPECTED(!zend::function::call(fci_cache, 1, zserv, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onManagerStart handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } static void php_swoole_server_onManagerStop(Server *serv) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onManagerStop]; if (UNEXPECTED(!zend::function::call(fci_cache, 1, zserv, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onManagerStop handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } static void php_swoole_onShutdown(Server *serv) { serv->lock(); zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onShutdown]; if (fci_cache != nullptr) { if (UNEXPECTED(!zend::function::call(fci_cache, 1, zserv, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onShutdown handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } serv->unlock(); } static void php_swoole_server_onWorkerStart(Server *serv, int worker_id) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onWorkerStart]; zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("master_pid"), serv->gs->master_pid); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("manager_pid"), serv->gs->manager_pid); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("worker_id"), worker_id); zend_update_property_bool(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("taskworker"), serv->is_task_worker()); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("worker_pid"), getpid()); if (serv->is_task_worker() && !serv->task_enable_coroutine) { PHPCoroutine::disable_hook(); } zval args[2]; args[0] = *zserv; ZVAL_LONG(&args[1], worker_id); if (SWOOLE_G(enable_library)) { zend::function::call("\\Swoole\\Server\\Helper::onWorkerStart", 2, args); } if (fci_cache) { if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, serv->is_enable_coroutine()))) { php_swoole_error(E_WARNING, "%s->onWorkerStart handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void php_swoole_server_onBeforeReload(Server *serv) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onBeforeReload]; if (fci_cache) { zval args[1]; args[0] = *zserv; if (UNEXPECTED(!zend::function::call(fci_cache, 1, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onBeforeReload handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void php_swoole_server_onAfterReload(Server *serv) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onAfterReload]; if (fci_cache) { zval args[1]; args[0] = *zserv; if (UNEXPECTED(!zend::function::call(fci_cache, 1, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onAfterReload handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void php_swoole_server_onWorkerStop(Server *serv, int worker_id) { if (SwooleWG.shutdown) { return; } SwooleWG.shutdown = true; zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onWorkerStop]; zval args[2]; args[0] = *zserv; ZVAL_LONG(&args[1], worker_id); if (SWOOLE_G(enable_library)) { zend::function::call("\\Swoole\\Server\\Helper::onWorkerStop", 2, args); } if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onWorkerStop handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } static void php_swoole_server_onWorkerExit(Server *serv, int worker_id) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onWorkerExit]; zval args[2]; args[0] = *zserv; ZVAL_LONG(&args[1], worker_id); if (SWOOLE_G(enable_library)) { zend::function::call("\\Swoole\\Server\\Helper::onWorkerExit", 2, args); } if (fci_cache) { if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onWorkerExit handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void php_swoole_onUserWorkerStart(Server *serv, Worker *worker) { zval *object = (zval *) worker->ptr; zend_update_property_long(swoole_process_ce, SW_Z8_OBJ_P(object), ZEND_STRL("id"), SwooleG.process_id); zval *zserv = (zval *) serv->private_data_2; zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("master_pid"), serv->gs->master_pid); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("manager_pid"), serv->gs->manager_pid); php_swoole_process_start(worker, object); } static void php_swoole_server_onWorkerError(Server *serv, int worker_id, const ExitStatus &exit_status) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); auto fci_cache = server_object->property->callbacks[SW_SERVER_CB_onWorkerError]; zval args[5]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; object_init_ex(object, swoole_server_status_info_ce); zend_update_property_long(swoole_server_status_info_ce, SW_Z8_OBJ_P(object), ZEND_STRL("worker_id"), worker_id); zend_update_property_long( swoole_server_status_info_ce, SW_Z8_OBJ_P(object), ZEND_STRL("worker_pid"), exit_status.get_pid()); zend_update_property_long( swoole_server_status_info_ce, SW_Z8_OBJ_P(object), ZEND_STRL("status"), exit_status.get_status()); zend_update_property_long( swoole_server_status_info_ce, SW_Z8_OBJ_P(object), ZEND_STRL("exit_code"), exit_status.get_code()); zend_update_property_long( swoole_server_status_info_ce, SW_Z8_OBJ_P(object), ZEND_STRL("signal"), exit_status.get_signal()); argc = 2; } else { ZVAL_LONG(&args[1], worker_id); ZVAL_LONG(&args[2], exit_status.get_pid()); ZVAL_LONG(&args[3], exit_status.get_code()); ZVAL_LONG(&args[4], exit_status.get_signal()); argc = 5; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onWorkerError handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (serv->event_object) { zval_ptr_dtor(&args[1]); } } void php_swoole_server_onConnect(Server *serv, DataHead *info) { auto fci_cache = php_swoole_server_get_fci_cache(serv, info->server_fd, SW_SERVER_CB_onConnect); if (fci_cache) { zval *zserv = (zval *) serv->private_data_2; zval args[3]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; object_init_ex(object, swoole_server_event_ce); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("fd"), (zend_long) info->fd); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("reactor_id"), (zend_long) info->reactor_id); zend_update_property_double( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("dispatch_time"), info->time); argc = 2; } else { ZVAL_LONG(&args[1], info->fd); ZVAL_LONG(&args[2], info->reactor_id); argc = 3; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onConnect handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (serv->event_object) { zval_ptr_dtor(&args[1]); } } } void php_swoole_server_onClose(Server *serv, DataHead *info) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); if (serv->enable_coroutine && serv->send_yield) { auto _i_coros_list = server_object->property->send_coroutine_map.find(info->fd); if (_i_coros_list != server_object->property->send_coroutine_map.end()) { auto coros_list = _i_coros_list->second; server_object->property->send_coroutine_map.erase(info->fd); while (!coros_list->empty()) { FutureTask *context = coros_list->front(); coros_list->pop_front(); swoole_set_last_error(ECONNRESET); zval_ptr_dtor(&context->coro_params); ZVAL_NULL(&context->coro_params); php_swoole_server_send_resume(serv, context, info->fd); } delete coros_list; } } auto fci_cache = php_swoole_server_get_fci_cache(serv, info->server_fd, SW_SERVER_CB_onClose); if (fci_cache) { zval *zserv = (zval *) serv->private_data_2; zval args[3]; int argc; args[0] = *zserv; if (serv->event_object) { zval *object = &args[1]; object_init_ex(object, swoole_server_event_ce); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("fd"), (zend_long) info->fd); zend_update_property_long( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("reactor_id"), (zend_long) info->reactor_id); zend_update_property_double( swoole_server_event_ce, SW_Z8_OBJ_P(object), ZEND_STRL("dispatch_time"), info->time); argc = 2; } else { ZVAL_LONG(&args[1], info->fd); ZVAL_LONG(&args[2], info->reactor_id); argc = 3; } if (UNEXPECTED(!zend::function::call(fci_cache, argc, args, nullptr, serv->enable_coroutine))) { php_swoole_error(E_WARNING, "%s->onClose handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } if (serv->event_object) { zval_ptr_dtor(&args[1]); } } } void php_swoole_server_onBufferFull(Server *serv, DataHead *info) { zval *zserv = (zval *) serv->private_data_2; auto fci_cache = php_swoole_server_get_fci_cache(serv, info->server_fd, SW_SERVER_CB_onBufferFull); if (fci_cache) { zval args[2]; args[0] = *zserv; ZVAL_LONG(&args[1], info->fd); if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onBufferFull handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void php_swoole_server_onSendTimeout(Timer *timer, TimerNode *tnode) { FutureTask *context = (FutureTask *) tnode->data; zval *zdata = &context->coro_params; zval result; Server *serv = sw_server(); ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); swoole_set_last_error(ETIMEDOUT); ZVAL_FALSE(&result); SessionId session_id = (long) context->private_data; auto _i_coros_list = server_object->property->send_coroutine_map.find(session_id); if (_i_coros_list != server_object->property->send_coroutine_map.end()) { auto coros_list = _i_coros_list->second; coros_list->remove(context); // free memory if (coros_list->size() == 0) { delete coros_list; server_object->property->send_coroutine_map.erase(session_id); } } else { swWarn("send coroutine[session#%ld] not exists", session_id); return; } context->private_data = nullptr; PHPCoroutine::resume_m(context, &result); zval_ptr_dtor(zdata); efree(context); } static enum swReturn_code php_swoole_server_send_resume(Server *serv, FutureTask *context, SessionId fd) { char *data; zval *zdata = &context->coro_params; zval result; if (ZVAL_IS_NULL(zdata)) { _fail: ZVAL_FALSE(&result); } else { size_t length = php_swoole_get_send_data(zdata, &data); if (length == 0) { goto _fail; } bool ret = serv->send(fd, data, length); if (!ret && swoole_get_last_error() == SW_ERROR_OUTPUT_SEND_YIELD && serv->send_yield) { return SW_CONTINUE; } ZVAL_BOOL(&result, ret); } if (context->timer) { swoole_timer_del((TimerNode *) context->timer); context->timer = nullptr; } PHPCoroutine::resume_m(context, &result); zval_ptr_dtor(zdata); efree(context); return SW_READY; } void php_swoole_server_send_yield(Server *serv, SessionId session_id, zval *zdata, zval *return_value) { ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); std::list<FutureTask *> *coros_list; auto coroutine_iterator = server_object->property->send_coroutine_map.find(session_id); if (coroutine_iterator == server_object->property->send_coroutine_map.end()) { coros_list = new std::list<FutureTask *>; server_object->property->send_coroutine_map[session_id] = coros_list; } else { coros_list = coroutine_iterator->second; } FutureTask *context = (FutureTask *) emalloc(sizeof(FutureTask)); coros_list->push_back(context); context->private_data = (void *) session_id; if (serv->send_timeout > 0) { context->timer = swoole_timer_add((long) (serv->send_timeout * 1000), false, php_swoole_server_onSendTimeout, context); } else { context->timer = nullptr; } context->coro_params = *zdata; PHPCoroutine::yield_m(return_value, context); } static int php_swoole_server_dispatch_func(Server *serv, Connection *conn, SendData *data) { serv->lock(); auto fci_cache = (zend_fcall_info_cache *) serv->private_data_3; zval args[4]; zval *zserv = &args[0], *zfd = &args[1], *ztype = &args[2], *zdata = nullptr; zval retval; zend_long worker_id = -1; *zserv = *((zval *) serv->private_data_2); ZVAL_LONG(zfd, conn ? conn->session_id : data->info.fd); ZVAL_LONG(ztype, (zend_long)(data ? data->info.type : (int) SW_SERVER_EVENT_CLOSE)); if (data && sw_zend_function_max_num_args(fci_cache->function_handler) > 3) { // TODO: reduce memory copy zdata = &args[3]; ZVAL_STRINGL(zdata, data->data, data->info.len > SW_IPC_BUFFER_SIZE ? SW_IPC_BUFFER_SIZE : data->info.len); } if (UNEXPECTED(sw_zend_call_function_ex(nullptr, fci_cache, zdata ? 4 : 3, args, &retval) != SUCCESS)) { php_swoole_error(E_WARNING, "%s->onDispatch handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } else if (!ZVAL_IS_NULL(&retval)) { worker_id = zval_get_long(&retval); if (worker_id >= (zend_long) serv->worker_num) { php_swoole_fatal_error(E_WARNING, "invalid target worker-id[" ZEND_LONG_FMT "]", worker_id); worker_id = -1; } zval_ptr_dtor(&retval); } if (zdata) { zval_ptr_dtor(zdata); } serv->unlock(); /* the exception should only be thrown after unlocked */ if (UNEXPECTED(EG(exception))) { zend_exception_error(EG(exception), E_ERROR); } return worker_id; } void php_swoole_server_onBufferEmpty(Server *serv, DataHead *info) { zval *zserv = (zval *) serv->private_data_2; ServerObject *server_object = server_fetch_object(Z_OBJ_P(zserv)); zend_fcall_info_cache *fci_cache; if (serv->send_yield) { auto _i_coros_list = server_object->property->send_coroutine_map.find(info->fd); if (_i_coros_list != server_object->property->send_coroutine_map.end()) { auto coros_list = _i_coros_list->second; server_object->property->send_coroutine_map.erase(info->fd); while (!coros_list->empty()) { FutureTask *context = coros_list->front(); coros_list->pop_front(); if (php_swoole_server_send_resume(serv, context, info->fd) == SW_CONTINUE) { coros_list->push_back(context); return; } } delete coros_list; } } fci_cache = php_swoole_server_get_fci_cache(serv, info->server_fd, SW_SERVER_CB_onBufferEmpty); if (fci_cache) { zval args[2]; args[0] = *zserv; ZVAL_LONG(&args[1], info->fd); if (UNEXPECTED(!zend::function::call(fci_cache, 2, args, nullptr, false))) { php_swoole_error(E_WARNING, "%s->onBufferEmpty handler error", SW_Z_OBJCE_NAME_VAL_P(zserv)); } } } static void **php_swoole_server_worker_create_buffers(Server *serv, uint buffer_num) { zend_string **buffers = (zend_string **) sw_calloc(buffer_num, sizeof(zend_string *)); if (buffers == nullptr) { swError("malloc for worker input_buffers failed"); } return (void **) buffers; } static void php_swoole_server_worker_free_buffers(Server *serv, uint buffer_num, void **buffers) { sw_free(buffers); } static sw_inline zend_string *php_swoole_server_worker_get_input_buffer(Server *serv, int reactor_id) { zend_string **buffers = (zend_string **) serv->worker_input_buffers; if (serv->is_base_mode()) { return buffers[0]; } else { return buffers[reactor_id]; } } static sw_inline void php_swoole_server_worker_set_buffer(Server *serv, DataHead *info, zend_string *addr) { zend_string **buffers = (zend_string **) serv->worker_input_buffers; buffers[info->reactor_id] = addr; } static void *php_swoole_server_worker_get_buffer(Server *serv, DataHead *info) { zend_string *worker_buffer = php_swoole_server_worker_get_input_buffer(serv, info->reactor_id); if (worker_buffer == nullptr) { worker_buffer = zend_string_alloc(info->len, 0); worker_buffer->len = 0; php_swoole_server_worker_set_buffer(serv, info, worker_buffer); } return worker_buffer->val + worker_buffer->len; } static size_t php_swoole_server_worker_get_buffer_len(Server *serv, DataHead *info) { zend_string *worker_buffer = php_swoole_server_worker_get_input_buffer(serv, info->reactor_id); return worker_buffer == nullptr ? 0 : worker_buffer->len; } static void php_swoole_server_worker_add_buffer_len(Server *serv, DataHead *info, size_t len) { zend_string *worker_buffer = php_swoole_server_worker_get_input_buffer(serv, info->reactor_id); worker_buffer->len += len; } static void php_swoole_server_worker_move_buffer(Server *serv, PipeBuffer *buffer) { zend_string *worker_buffer = php_swoole_server_worker_get_input_buffer(serv, buffer->info.reactor_id); memcpy(buffer->data, &worker_buffer, sizeof(worker_buffer)); worker_buffer->val[worker_buffer->len] = '\0'; php_swoole_server_worker_set_buffer(serv, &buffer->info, nullptr); } static size_t php_swoole_server_worker_get_packet(Server *serv, EventData *req, char **data_ptr) { size_t length; if (req->info.flags & SW_EVENT_DATA_PTR) { PacketPtr *task = (PacketPtr *) req; *data_ptr = task->data.str; length = task->data.length; } else if (req->info.flags & SW_EVENT_DATA_OBJ_PTR) { zend_string *worker_buffer; memcpy(&worker_buffer, req->data, sizeof(worker_buffer)); *data_ptr = worker_buffer->val; length = worker_buffer->len; } else { *data_ptr = req->data; length = req->info.len; } return length; } static PHP_METHOD(swoole_server, __construct) { ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); Server *serv = server_object->serv; if (serv) { php_swoole_fatal_error(E_ERROR, "Constructor of %s can only be called once", SW_Z_OBJCE_NAME_VAL_P(ZEND_THIS)); } zval *zserv = ZEND_THIS; char *host; size_t host_len = 0; zend_long sock_type = SW_SOCK_TCP; zend_long serv_port = 0; zend_long serv_mode = Server::MODE_PROCESS; // only cli env if (!SWOOLE_G(cli)) { zend_throw_exception_ex( swoole_exception_ce, -1, "%s can only be used in CLI mode", SW_Z_OBJCE_NAME_VAL_P(zserv)); RETURN_FALSE; } if (sw_server() != nullptr) { zend_throw_exception_ex( swoole_exception_ce, -3, "server is running. unable to create %s", SW_Z_OBJCE_NAME_VAL_P(zserv)); RETURN_FALSE; } ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 4) Z_PARAM_STRING(host, host_len) Z_PARAM_OPTIONAL Z_PARAM_LONG(serv_port) Z_PARAM_LONG(serv_mode) Z_PARAM_LONG(sock_type) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); if (serv_mode != Server::MODE_BASE && serv_mode != Server::MODE_PROCESS) { php_swoole_fatal_error(E_ERROR, "invalid $mode parameters %d", (int) serv_mode); RETURN_FALSE; } serv = new Server((enum Server::Mode) serv_mode); serv->private_data_2 = sw_zval_dup(zserv); server_set_ptr(zserv, serv); if (serv_mode == Server::MODE_BASE) { serv->reactor_num = 1; serv->worker_num = 1; } /* primary port */ do { if (serv_port == 0 && strcasecmp(host, "SYSTEMD") == 0) { if (serv->add_systemd_socket() <= 0) { php_swoole_fatal_error(E_ERROR, "failed to add systemd socket"); RETURN_FALSE; } } else { ListenPort *port = serv->add_port((enum swSocket_type) sock_type, host, serv_port); if (!port) { zend_throw_exception_ex(swoole_exception_ce, errno, "failed to listen server port[%s:" ZEND_LONG_FMT "], Error: %s[%d]", host, serv_port, strerror(errno), errno); RETURN_FALSE; } } for (auto ls : serv->ports) { php_swoole_server_add_port(server_object, ls); } server_object->property->primary_port = (ServerPortProperty *) serv->get_primary_port()->ptr; } while (0); /* iterator */ do { zval connection_iterator; object_init_ex(&connection_iterator, swoole_connection_iterator_ce); ConnectionIterator *iterator = php_swoole_connection_iterator_get_ptr(&connection_iterator); iterator->serv = serv; zend_update_property(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("connections"), &connection_iterator); zval_ptr_dtor(&connection_iterator); } while (0); /* info */ zend_update_property_stringl(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("host"), host, host_len); zend_update_property_long( swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("port"), (zend_long) serv->get_primary_port()->port); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("mode"), serv_mode); zend_update_property_long(swoole_server_ce, SW_Z8_OBJ_P(zserv), ZEND_STRL("type"), sock_type); } static PHP_METHOD(swoole_server, __destruct) {} static PHP_METHOD(swoole_server, set) { ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (serv->is_started()) { php_swoole_fatal_error( E_WARNING, "server is running, unable to execute %s->set", SW_Z_OBJCE_NAME_VAL_P(ZEND_THIS)); RETURN_FALSE; } zval *zset = nullptr, *ztmp; HashTable *vht; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ARRAY(zset) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); vht = Z_ARRVAL_P(zset); php_swoole_set_global_option(vht); php_swoole_set_coroutine_option(vht); php_swoole_set_aio_option(vht); if (php_swoole_array_get_value(vht, "chroot", ztmp)) { serv->chroot_ = zend::String(ztmp).to_std_string(); } if (php_swoole_array_get_value(vht, "user", ztmp)) { serv->user_ = zend::String(ztmp).to_std_string(); } if (php_swoole_array_get_value(vht, "group", ztmp)) { serv->group_ = zend::String(ztmp).to_std_string(); } if (php_swoole_array_get_value(vht, "daemonize", ztmp)) { serv->daemonize = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "pid_file", ztmp)) { serv->pid_file = zend::String(ztmp).to_std_string(); } if (php_swoole_array_get_value(vht, "reactor_num", ztmp)) { zend_long v = zval_get_long(ztmp); serv->reactor_num = SW_MAX(0, SW_MIN(v, UINT16_MAX)); if (serv->reactor_num == 0) { serv->reactor_num = SW_CPU_NUM; } } if (php_swoole_array_get_value(vht, "single_thread", ztmp)) { serv->single_thread = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "worker_num", ztmp)) { zend_long v = zval_get_long(ztmp); serv->worker_num = SW_MAX(0, SW_MIN(v, UINT32_MAX)); if (serv->worker_num == 0) { serv->worker_num = SW_CPU_NUM; } } if (php_swoole_array_get_value(vht, "max_wait_time", ztmp)) { zend_long v = zval_get_long(ztmp); serv->max_wait_time = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } if (php_swoole_array_get_value(vht, "max_queued_bytes", ztmp)) { zend_long v = zval_get_long(ztmp); serv->max_queued_bytes = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } if (php_swoole_array_get_value(vht, "enable_coroutine", ztmp)) { serv->enable_coroutine = zval_is_true(ztmp); } else { serv->enable_coroutine = SWOOLE_G(enable_coroutine); } if (php_swoole_array_get_value(vht, "send_timeout", ztmp)) { serv->send_timeout = zval_get_double(ztmp); } if (php_swoole_array_get_value(vht, "dispatch_mode", ztmp)) { zend_long v = zval_get_long(ztmp); serv->dispatch_mode = SW_MAX(0, SW_MIN(v, UINT8_MAX)); } if (php_swoole_array_get_value(vht, "send_yield", ztmp)) { serv->send_yield = zval_is_true(ztmp); if (serv->send_yield && !(serv->dispatch_mode == SW_DISPATCH_FDMOD || serv->dispatch_mode == SW_DISPATCH_IPMOD)) { php_swoole_error(E_WARNING, "'send_yield' option can only be set when using dispatch_mode=2/4"); serv->send_yield = 0; } } if (php_swoole_array_get_value(vht, "dispatch_func", ztmp)) { Server::DispatchFunction c_dispatch_func = nullptr; while (1) { if (Z_TYPE_P(ztmp) == IS_STRING) { c_dispatch_func = (Server::DispatchFunction) swoole_get_function(Z_STRVAL_P(ztmp), Z_STRLEN_P(ztmp)); if (c_dispatch_func) { break; } } #ifdef ZTS if (serv->is_process_mode() && !serv->single_thread) { php_swoole_fatal_error(E_ERROR, "option [dispatch_func] does not support with ZTS"); } #endif char *func_name = nullptr; zend_fcall_info_cache *fci_cache = (zend_fcall_info_cache *) emalloc(sizeof(zend_fcall_info_cache)); if (!sw_zend_is_callable_ex(ztmp, nullptr, 0, &func_name, nullptr, fci_cache, nullptr)) { php_swoole_fatal_error(E_ERROR, "function '%s' is not callable", func_name); return; } efree(func_name); sw_zend_fci_cache_persist(fci_cache); if (serv->private_data_3) { sw_zend_fci_cache_discard((zend_fcall_info_cache *) serv->private_data_3); efree(serv->private_data_3); } serv->private_data_3 = (void *) fci_cache; c_dispatch_func = php_swoole_server_dispatch_func; break; } serv->dispatch_func = c_dispatch_func; } /** * for dispatch_mode = 1/3 */ if (php_swoole_array_get_value(vht, "discard_timeout_request", ztmp)) { serv->discard_timeout_request = zval_is_true(ztmp); } // onConnect/onClose event if (php_swoole_array_get_value(vht, "enable_unsafe_event", ztmp)) { serv->enable_unsafe_event = zval_is_true(ztmp); } // delay receive if (php_swoole_array_get_value(vht, "enable_delay_receive", ztmp)) { serv->enable_delay_receive = zval_is_true(ztmp); } #if defined(__linux__) and defined(HAVE_REUSEPORT) if (php_swoole_array_get_value(vht, "enable_reuse_port", ztmp)) { serv->enable_reuse_port = zval_is_true(ztmp); } #endif // task use object if (php_swoole_array_get_value(vht, "task_use_object", ztmp) || php_swoole_array_get_value(vht, "task_object", ztmp)) { serv->task_object = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "event_object", ztmp)) { serv->event_object = zval_is_true(ztmp); if (serv->event_object) { serv->task_object = true; } } // task coroutine if (php_swoole_array_get_value(vht, "task_enable_coroutine", ztmp)) { serv->task_enable_coroutine = zval_is_true(ztmp); } // task_worker_num if (php_swoole_array_get_value(vht, "task_worker_num", ztmp)) { zend_long v = zval_get_long(ztmp); serv->task_worker_num = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } // task ipc mode, 1,2,3 if (php_swoole_array_get_value(vht, "task_ipc_mode", ztmp)) { zend_long v = zval_get_long(ztmp); serv->task_ipc_mode = SW_MAX(0, SW_MIN(v, UINT8_MAX)); } /** * Temporary file directory for task_worker */ if (php_swoole_array_get_value(vht, "task_tmpdir", ztmp)) { zend::String str_v(ztmp); swoole_set_task_tmpdir(str_v.to_std_string()); } // task_max_request if (php_swoole_array_get_value(vht, "task_max_request", ztmp)) { zend_long v = zval_get_long(ztmp); serv->task_max_request = SW_MAX(0, SW_MIN(v, UINT32_MAX)); // task_max_request_grace if (php_swoole_array_get_value(vht, "task_max_request_grace", ztmp)) { zend_long v = zval_get_long(ztmp); serv->task_max_request_grace = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } else if (serv->task_max_request > SW_WORKER_MIN_REQUEST) { serv->task_max_request_grace = serv->task_max_request / 2; } } // max_connection if (php_swoole_array_get_value(vht, "max_connection", ztmp) || php_swoole_array_get_value(vht, "max_conn", ztmp)) { zend_long v = zval_get_long(ztmp); serv->set_max_connection(SW_MAX(0, SW_MIN(v, UINT32_MAX))); } if (php_swoole_array_get_value(vht, "start_session_id", ztmp)) { serv->set_start_session_id(zval_get_long(ztmp)); } // heartbeat_check_interval if (php_swoole_array_get_value(vht, "heartbeat_check_interval", ztmp)) { zend_long v = zval_get_long(ztmp); serv->heartbeat_check_interval = SW_MAX(0, SW_MIN(v, UINT16_MAX)); } // heartbeat idle time if (php_swoole_array_get_value(vht, "heartbeat_idle_time", ztmp)) { zend_long v = zval_get_long(ztmp); serv->heartbeat_idle_time = SW_MAX(0, SW_MIN(v, UINT16_MAX)); if (serv->heartbeat_check_interval > serv->heartbeat_idle_time) { php_swoole_fatal_error(E_WARNING, "heartbeat_idle_time must be greater than heartbeat_check_interval"); serv->heartbeat_check_interval = serv->heartbeat_idle_time / 2; } } else if (serv->heartbeat_check_interval > 0) { serv->heartbeat_idle_time = serv->heartbeat_check_interval * 2; } // max_request if (php_swoole_array_get_value(vht, "max_request", ztmp)) { zend_long v = zval_get_long(ztmp); serv->max_request = SW_MAX(0, SW_MIN(v, UINT32_MAX)); // max_request_grace if (php_swoole_array_get_value(vht, "max_request_grace", ztmp)) { zend_long v = zval_get_long(ztmp); serv->max_request_grace = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } else if (serv->max_request > SW_WORKER_MIN_REQUEST) { serv->max_request_grace = serv->max_request / 2; } } // reload async if (php_swoole_array_get_value(vht, "reload_async", ztmp)) { serv->reload_async = zval_is_true(ztmp); } // cpu affinity if (php_swoole_array_get_value(vht, "open_cpu_affinity", ztmp)) { serv->open_cpu_affinity = zval_is_true(ztmp); } // cpu affinity set if (php_swoole_array_get_value(vht, "cpu_affinity_ignore", ztmp)) { int ignore_num = zend_hash_num_elements(Z_ARRVAL_P(ztmp)); if (ignore_num >= SW_CPU_NUM) { php_swoole_fatal_error(E_ERROR, "cpu_affinity_ignore num must be less than cpu num (%d)", SW_CPU_NUM); RETURN_FALSE; } int available_num = SW_CPU_NUM - ignore_num; int *available_cpu = (int *) sw_malloc(sizeof(int) * available_num); if (!available_cpu) { php_swoole_fatal_error(E_WARNING, "malloc() failed"); RETURN_FALSE; } int flag, i, available_i = 0; zval *zval_core = nullptr; for (i = 0; i < SW_CPU_NUM; i++) { flag = 1; SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(ztmp), zval_core) if (i == zval_get_long(zval_core)) { flag = 0; break; } SW_HASHTABLE_FOREACH_END(); if (flag) { available_cpu[available_i] = i; available_i++; } } serv->cpu_affinity_available_num = available_num; if (serv->cpu_affinity_available) { sw_free(serv->cpu_affinity_available); } serv->cpu_affinity_available = available_cpu; } // parse cookie header if (php_swoole_array_get_value(vht, "http_parse_cookie", ztmp)) { serv->http_parse_cookie = zval_is_true(ztmp); } // parse x-www-form-urlencoded form data if (php_swoole_array_get_value(vht, "http_parse_post", ztmp)) { serv->http_parse_post = zval_is_true(ztmp); } // parse multipart/form-data file uploads if (php_swoole_array_get_value(vht, "http_parse_files", ztmp)) { serv->http_parse_files = zval_is_true(ztmp); } #ifdef SW_HAVE_COMPRESSION // http content compression if (php_swoole_array_get_value(vht, "http_compression", ztmp)) { serv->http_compression = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "http_compression_level", ztmp) || php_swoole_array_get_value(vht, "http_gzip_level", ztmp)) { zend_long level = zval_get_long(ztmp); if (level > UINT8_MAX) { level = UINT8_MAX; } else if (level < 0) { level = 0; } serv->http_compression_level = level; } if (php_swoole_array_get_value(vht, "compression_min_length", ztmp)) { serv->compression_min_length = zval_get_long(ztmp); } #endif #ifdef SW_HAVE_ZLIB if (php_swoole_array_get_value(vht, "websocket_compression", ztmp)) { serv->websocket_compression = zval_is_true(ztmp); } #endif // temporary directory for HTTP uploaded file. if (php_swoole_array_get_value(vht, "upload_tmp_dir", ztmp)) { zend::String str_v(ztmp); if (php_swoole_create_dir(str_v.val(), str_v.len()) < 0) { php_swoole_fatal_error(E_ERROR, "Unable to create upload_tmp_dir[%s]", str_v.val()); return; } serv->upload_tmp_dir = str_v.to_std_string(); } /** * http static file handler */ if (php_swoole_array_get_value(vht, "enable_static_handler", ztmp)) { serv->enable_static_handler = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "document_root", ztmp)) { zend::String str_v(ztmp); if (str_v.len() >= PATH_MAX) { php_swoole_fatal_error(E_ERROR, "The length of document_root must be less than %d", PATH_MAX); return; } serv->set_document_root(std::string(str_v.val(), str_v.len())); } if (php_swoole_array_get_value(vht, "http_autoindex", ztmp)) { serv->http_autoindex = zval_is_true(ztmp); } if (php_swoole_array_get_value(vht, "http_index_files", ztmp)) { if (ZVAL_IS_ARRAY(ztmp)) { zval *_http_index_files; SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(ztmp), _http_index_files) zend::String __http_index_files(_http_index_files); if (__http_index_files.len() > 0) { serv->add_static_handler_index_files(__http_index_files.to_std_string()); } SW_HASHTABLE_FOREACH_END(); } else { php_swoole_fatal_error(E_ERROR, "http_index_files must be array"); RETURN_FALSE; } } /** * [static_handler] locations */ if (php_swoole_array_get_value(vht, "static_handler_locations", ztmp)) { if (ZVAL_IS_ARRAY(ztmp)) { zval *_location; SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(ztmp), _location) zend::String __location(_location); if (__location.len() > 0 && __location.val()[0] == '/') { serv->add_static_handler_location(__location.to_std_string()); } SW_HASHTABLE_FOREACH_END(); } else { php_swoole_fatal_error(E_ERROR, "static_handler_locations num must be array"); RETURN_FALSE; } } /** * buffer input size */ if (php_swoole_array_get_value(vht, "input_buffer_size", ztmp) || php_swoole_array_get_value(vht, "buffer_input_size", ztmp)) { zend_long v = zval_get_long(ztmp); serv->input_buffer_size = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } /** * buffer output size */ if (php_swoole_array_get_value(vht, "output_buffer_size", ztmp) || php_swoole_array_get_value(vht, "buffer_output_size", ztmp)) { zend_long v = zval_get_long(ztmp); serv->output_buffer_size = SW_MAX(0, SW_MIN(v, UINT32_MAX)); } // message queue key if (php_swoole_array_get_value(vht, "message_queue_key", ztmp)) { zend_long v = zval_get_long(ztmp); serv->message_queue_key = SW_MAX(0, SW_MIN(v, INT64_MAX)); } if (serv->task_enable_coroutine && (serv->task_ipc_mode == SW_TASK_IPC_MSGQUEUE || serv->task_ipc_mode == SW_TASK_IPC_PREEMPTIVE)) { php_swoole_fatal_error(E_ERROR, "cannot use msgqueue when task_enable_coroutine is enable"); RETURN_FALSE; } sw_zend_call_method_with_1_params( server_object->property->ports.at(0), swoole_server_port_ce, nullptr, "set", nullptr, zset); zval *zsetting = sw_zend_read_and_convert_property_array(swoole_server_ce, ZEND_THIS, ZEND_STRL("setting"), 0); php_array_merge(Z_ARRVAL_P(zsetting), Z_ARRVAL_P(zset)); RETURN_TRUE; } static PHP_METHOD(swoole_server, on) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (serv->is_started()) { php_swoole_fatal_error(E_WARNING, "server is running, unable to register event callback function"); RETURN_FALSE; } zval *name; zval *cb; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &name, &cb) == FAILURE) { RETURN_FALSE; } char *func_name = nullptr; zend_fcall_info_cache *fci_cache = (zend_fcall_info_cache *) emalloc(sizeof(zend_fcall_info_cache)); if (!sw_zend_is_callable_ex(cb, nullptr, 0, &func_name, nullptr, fci_cache, nullptr)) { php_swoole_fatal_error(E_ERROR, "function '%s' is not callable", func_name); return; } efree(func_name); zend::String _event_name_ori(name); zend::String _event_name_tolower(zend_string_tolower(_event_name_ori.get()), false); ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); auto i = server_event_map.find(_event_name_tolower.to_std_string()); if (i == server_event_map.end()) { zval *port_object = server_object->property->ports.at(0); zval retval; efree(fci_cache); sw_zend_call_method_with_2_params(port_object, swoole_server_port_ce, nullptr, "on", &retval, name, cb); RETURN_BOOL(Z_BVAL_P(&retval)); } else { int event_type = i->second.type; std::string property_name = "on" + i->second.name; zend_update_property( swoole_server_ce, SW_Z8_OBJ_P(ZEND_THIS), property_name.c_str(), property_name.length(), cb); if (server_object->property->callbacks[event_type]) { efree(server_object->property->callbacks[event_type]); } server_object->property->callbacks[event_type] = fci_cache; RETURN_TRUE; } } static PHP_METHOD(swoole_server, getCallback) { zval *name; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ZVAL(name) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); zend::String _event_name_ori(name); zend::String _event_name_tolower(zend_string_tolower(_event_name_ori.get()), false); auto i = server_event_map.find(_event_name_tolower.to_std_string()); if (i != server_event_map.end()) { std::string property_name = "on" + i->second.name; // Notice: we should use Z_OBJCE_P instead of swoole_server_ce, because we need to consider the subclasses. zval rv, *property = zend_read_property( Z_OBJCE_P(ZEND_THIS), SW_Z8_OBJ_P(ZEND_THIS), property_name.c_str(), property_name.length(), 1, &rv); if (!ZVAL_IS_NULL(property)) { RETURN_ZVAL(property, 1, 0); } } ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); sw_zend_call_method_with_1_params( server_object->property->ports.at(0), swoole_server_port_ce, nullptr, "getcallback", return_value, name); } static PHP_METHOD(swoole_server, listen) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (serv->is_started()) { php_swoole_fatal_error(E_WARNING, "server is running, can't add listener"); RETURN_FALSE; } char *host; size_t host_len; long sock_type; long port; if (zend_parse_parameters(ZEND_NUM_ARGS(), "sll", &host, &host_len, &port, &sock_type) == FAILURE) { RETURN_FALSE; } ListenPort *ls = serv->add_port((enum swSocket_type) sock_type, host, (int) port); if (!ls) { RETURN_FALSE; } ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); zval *port_object = php_swoole_server_add_port(server_object, ls); RETURN_ZVAL(port_object, 1, 0); } extern Worker *php_swoole_process_get_and_check_worker(zval *zobject); static PHP_METHOD(swoole_server, addProcess) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (serv->is_started()) { php_swoole_fatal_error(E_WARNING, "server is running, can't add process"); RETURN_FALSE; } zval *process = nullptr; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &process) == FAILURE) { RETURN_FALSE; } if (ZVAL_IS_NULL(process)) { php_swoole_fatal_error(E_WARNING, "the first parameter can't be empty"); RETURN_FALSE; } if (!instanceof_function(Z_OBJCE_P(process), swoole_process_ce)) { php_swoole_fatal_error(E_ERROR, "object is not instanceof swoole_process"); RETURN_FALSE; } if (serv->onUserWorkerStart == nullptr) { serv->onUserWorkerStart = php_swoole_onUserWorkerStart; } zval *tmp_process = (zval *) emalloc(sizeof(zval)); memcpy(tmp_process, process, sizeof(zval)); process = tmp_process; ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); server_object->property->user_processes.push_back(process); Z_TRY_ADDREF_P(process); Worker *worker = php_swoole_process_get_and_check_worker(process); worker->ptr = process; int id = serv->add_worker(worker); if (id < 0) { php_swoole_fatal_error(E_WARNING, "Server::add_worker() failed"); RETURN_FALSE; } zend_update_property_long(swoole_process_ce, SW_Z8_OBJ_P(process), ZEND_STRL("id"), id); RETURN_LONG(id); } static PHP_METHOD(swoole_server, start) { zval *zserv = ZEND_THIS; Server *serv = php_swoole_server_get_and_check_server(zserv); if (serv->is_started()) { php_swoole_fatal_error( E_WARNING, "server is running, unable to execute %s->start()", SW_Z_OBJCE_NAME_VAL_P(zserv)); RETURN_FALSE; } if (serv->is_shutdown()) { php_swoole_fatal_error( E_WARNING, "server have been shutdown, unable to execute %s->start()", SW_Z_OBJCE_NAME_VAL_P(zserv)); RETURN_FALSE; } if (SwooleTG.reactor) { php_swoole_fatal_error( E_WARNING, "eventLoop has already been created, unable to start %s", SW_Z_OBJCE_NAME_VAL_P(zserv)); RETURN_FALSE; } ServerObject *server_object = server_fetch_object(Z_OBJ_P((zval *) serv->private_data_2)); server_object->register_callback(); server_object->on_before_start(); if (serv->start() < 0) { php_swoole_fatal_error(E_ERROR, "failed to start server. Error: %s", sw_error); } RETURN_TRUE; } static PHP_METHOD(swoole_server, send) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; zval *zfd; zval *zdata; zend_long server_socket = -1; ZEND_PARSE_PARAMETERS_START(2, 3) Z_PARAM_ZVAL(zfd) Z_PARAM_ZVAL(zdata) Z_PARAM_OPTIONAL Z_PARAM_LONG(server_socket) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); if (UNEXPECTED(ZVAL_IS_NULL(zfd))) { php_swoole_fatal_error(E_WARNING, "fd can not be null"); RETURN_FALSE; } char *data; size_t length = php_swoole_get_send_data(zdata, &data); if (length == 0) { php_swoole_fatal_error(E_WARNING, "data is empty"); RETURN_FALSE; } // UNIX DGRAM SOCKET if (serv->have_dgram_sock && Z_TYPE_P(zfd) == IS_STRING && Z_STRVAL_P(zfd)[0] == '/') { network::Socket *sock = server_socket == -1 ? serv->dgram_socket : serv->get_server_socket(server_socket); if (sock == nullptr) { RETURN_FALSE; } RETURN_BOOL(sock->sendto(Z_STRVAL_P(zfd), 0, data, length) > 0); } fd = zval_get_long(zfd); if (UNEXPECTED(fd <= 0)) { php_swoole_fatal_error(E_WARNING, "invalid fd[" ZEND_LONG_FMT "]", fd); RETURN_FALSE; } bool ret = serv->send(fd, data, length); if (!ret && swoole_get_last_error() == SW_ERROR_OUTPUT_SEND_YIELD) { zval_add_ref(zdata); php_swoole_server_send_yield(serv, fd, zdata, return_value); } else { RETURN_BOOL(ret); } } static PHP_METHOD(swoole_server, sendto) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } char *addr; size_t addr_len; zend_long port; char *data; size_t len; zend_long server_socket_fd = -1; enum swSocket_type type; ZEND_PARSE_PARAMETERS_START(3, 4) Z_PARAM_STRING(addr, addr_len) Z_PARAM_LONG(port) Z_PARAM_STRING(data, len) Z_PARAM_OPTIONAL Z_PARAM_LONG(server_socket_fd) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); if (len == 0) { php_swoole_fatal_error(E_WARNING, "data is empty"); RETURN_FALSE; } if (addr[0] == '/') { type = SW_SOCK_UNIX_DGRAM; } else if (strchr(addr, ':')) { type = SW_SOCK_UDP6; } else { type = SW_SOCK_UDP; } network::Socket *server_socket = nullptr; switch (type) { case SW_SOCK_UDP: if (!serv->udp_socket_ipv4) { php_swoole_fatal_error(E_WARNING, "UDP listener has to be added before executing sendto"); RETURN_FALSE; } else { server_socket = server_socket_fd < 0 ? serv->udp_socket_ipv4 : serv->get_server_socket(server_socket_fd); } break; case SW_SOCK_UDP6: if (!serv->udp_socket_ipv6) { php_swoole_fatal_error(E_WARNING, "UDP6 listener has to be added before executing sendto"); RETURN_FALSE; } else { server_socket = server_socket_fd < 0 ? serv->udp_socket_ipv6 : serv->get_server_socket(server_socket_fd); } break; case SW_SOCK_UNIX_DGRAM: if (!serv->dgram_socket) { php_swoole_fatal_error(E_WARNING, "UnixDgram listener has to be added before executing sendto"); RETURN_FALSE; } else { server_socket = server_socket_fd < 0 ? serv->dgram_socket : serv->get_server_socket(server_socket_fd); } break; default: abort(); break; } SW_CHECK_RETURN(server_socket->sendto(addr, port, data, len)); } static PHP_METHOD(swoole_server, sendfile) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; char *filename; size_t len; zend_long offset = 0; zend_long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls|ll", &fd, &filename, &len, &offset, &length) == FAILURE) { RETURN_FALSE; } if (serv->is_master()) { php_swoole_fatal_error(E_WARNING, "can't sendfile[%s] to the connections in master process", filename); RETURN_FALSE; } RETURN_BOOL(serv->sendfile(fd, filename, len, offset, length)); } static PHP_METHOD(swoole_server, close) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; zend_bool reset = false; ZEND_PARSE_PARAMETERS_START(1, 2) Z_PARAM_LONG(fd) Z_PARAM_OPTIONAL Z_PARAM_BOOL(reset) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); RETURN_BOOL(serv->close(fd, reset)); } static PHP_METHOD(swoole_server, pause) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &fd) == FAILURE) { RETURN_FALSE; } Connection *conn = serv->get_connection_verify(fd); if (!conn) { swoole_set_last_error(SW_ERROR_SESSION_NOT_EXIST); RETURN_FALSE; } RETURN_BOOL(serv->feedback(conn, SW_SERVER_EVENT_PAUSE_RECV)); } static PHP_METHOD(swoole_server, resume) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &fd) == FAILURE) { RETURN_FALSE; } Connection *conn = serv->get_connection_verify(fd); if (!conn) { swoole_set_last_error(SW_ERROR_SESSION_NOT_EXIST); RETURN_FALSE; } RETURN_BOOL(serv->feedback(conn, SW_SERVER_EVENT_RESUME_RECV)); } static PHP_METHOD(swoole_server, stats) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } array_init(return_value); add_assoc_long_ex(return_value, ZEND_STRL("start_time"), serv->gs->start_time); add_assoc_long_ex(return_value, ZEND_STRL("connection_num"), serv->gs->connection_num); add_assoc_long_ex(return_value, ZEND_STRL("accept_count"), serv->gs->accept_count); add_assoc_long_ex(return_value, ZEND_STRL("close_count"), serv->gs->close_count); /** * reset */ int tasking_num = serv->gs->tasking_num; if (tasking_num < 0) { tasking_num = serv->gs->tasking_num = 0; } uint32_t idle_worker_num = 0; uint32_t worker_num = serv->worker_num; uint32_t task_worker_num = serv->task_worker_num; add_assoc_long_ex(return_value, ZEND_STRL("worker_num"), worker_num); idle_worker_num = serv->get_idle_worker_num(); add_assoc_long_ex(return_value, ZEND_STRL("idle_worker_num"), idle_worker_num); add_assoc_long_ex(return_value, ZEND_STRL("task_worker_num"), task_worker_num); add_assoc_long_ex(return_value, ZEND_STRL("tasking_num"), tasking_num); add_assoc_long_ex(return_value, ZEND_STRL("request_count"), serv->gs->request_count); add_assoc_long_ex(return_value, ZEND_STRL("dispatch_count"), serv->gs->dispatch_count); if (SwooleWG.worker) { add_assoc_long_ex(return_value, ZEND_STRL("worker_request_count"), SwooleWG.worker->request_count); add_assoc_long_ex(return_value, ZEND_STRL("worker_dispatch_count"), SwooleWG.worker->dispatch_count); } if (serv->task_ipc_mode > SW_TASK_IPC_UNIXSOCK && serv->gs->task_workers.queue) { size_t queue_num = -1; size_t queue_bytes = -1; if (serv->gs->task_workers.queue->stat(&queue_num, &queue_bytes)) { add_assoc_long_ex(return_value, ZEND_STRL("task_queue_num"), queue_num); add_assoc_long_ex(return_value, ZEND_STRL("task_queue_bytes"), queue_bytes); } } if (task_worker_num > 0) { idle_worker_num = serv->get_idle_task_worker_num(); add_assoc_long_ex(return_value, ZEND_STRL("task_idle_worker_num"), idle_worker_num); } add_assoc_long_ex(return_value, ZEND_STRL("coroutine_num"), Coroutine::count()); } static PHP_METHOD(swoole_server, reload) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_bool only_reload_taskworker = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &only_reload_taskworker) == FAILURE) { RETURN_FALSE; } int sig = only_reload_taskworker ? SIGUSR2 : SIGUSR1; if (swoole_kill(serv->gs->manager_pid, sig) < 0) { php_swoole_sys_error(E_WARNING, "failed to send the reload signal"); RETURN_FALSE; } RETURN_TRUE; } static PHP_METHOD(swoole_server, heartbeat) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_bool close_connection = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &close_connection) == FAILURE) { RETURN_FALSE; } if (serv->heartbeat_idle_time < 1) { RETURN_FALSE; } array_init(return_value); double checktime = microtime() - serv->heartbeat_idle_time; serv->foreach_connection([serv, checktime, close_connection, return_value](Connection *conn) { swTrace("heartbeat check fd=%d", conn->fd); if (conn->protect || conn->last_recv_time == 0 || conn->last_recv_time > checktime) { return; } if (close_connection) { conn->close_force = 1; serv->close(conn->fd, false); } add_next_index_long(return_value, conn->session_id); }); } static PHP_METHOD(swoole_server, taskwait) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (!serv->is_worker()) { php_swoole_fatal_error(E_WARNING, "taskwait method can only be used in the worker process"); RETURN_FALSE; } EventData buf; memset(&buf.info, 0, sizeof(buf.info)); zval *zdata; double timeout = SW_TASKWAIT_TIMEOUT; zend_long dst_worker_id = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|dl", &zdata, &timeout, &dst_worker_id) == FAILURE) { RETURN_FALSE; } if (php_swoole_check_task_param(serv, dst_worker_id) < 0) { RETURN_FALSE; } if (php_swoole_task_pack(&buf, zdata) < 0) { RETURN_FALSE; } int _dst_worker_id = (int) dst_worker_id; // coroutine if (PHPCoroutine::get_cid() >= 0) { php_swoole_task_wait_co(serv, &buf, timeout, _dst_worker_id, INTERNAL_FUNCTION_PARAM_PASSTHRU); return; } TaskId task_id = buf.info.fd; uint64_t notify; EventData *task_result = &(serv->task_result[SwooleG.process_id]); sw_memset_zero(task_result, sizeof(*task_result)); Pipe *pipe = serv->task_notify_pipes.at(SwooleG.process_id).get(); network::Socket *task_notify_socket = pipe->get_socket(false); // clear history task while (task_notify_socket->wait_event(0, SW_EVENT_READ) == SW_OK) { if (task_notify_socket->read(&notify, sizeof(notify)) <= 0) { break; } } sw_atomic_fetch_add(&serv->gs->tasking_num, 1); if (serv->gs->task_workers.dispatch_blocking(&buf, &_dst_worker_id) >= 0) { while (1) { if (task_notify_socket->wait_event((int) (timeout * 1000), SW_EVENT_READ) != SW_OK) { break; } if (pipe->read(&notify, sizeof(notify)) > 0) { if (task_result->info.fd != task_id) { continue; } zval *task_notify_data = php_swoole_task_unpack(task_result); if (task_notify_data == nullptr) { RETURN_FALSE; } else { RETVAL_ZVAL(task_notify_data, 0, 0); efree(task_notify_data); return; } break; } else { php_swoole_sys_error(E_WARNING, "taskwait failed"); break; } } } else { sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); } RETURN_FALSE; } static PHP_METHOD(swoole_server, taskWaitMulti) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (!serv->is_worker()) { php_swoole_fatal_error(E_WARNING, "taskWaitMulti method can only be used in the worker process"); RETURN_FALSE; } EventData buf; memset(&buf.info, 0, sizeof(buf.info)); zval *ztasks; zval *ztask; double timeout = SW_TASKWAIT_TIMEOUT; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|d", &ztasks, &timeout) == FAILURE) { RETURN_FALSE; } array_init(return_value); int dst_worker_id; int i = 0; int n_task = php_swoole_array_length(ztasks); if (n_task >= SW_MAX_CONCURRENT_TASK) { php_swoole_fatal_error(E_WARNING, "too many concurrent tasks"); RETURN_FALSE; } int list_of_id[SW_MAX_CONCURRENT_TASK] = {}; uint64_t notify; EventData *task_result = &(serv->task_result[SwooleG.process_id]); sw_memset_zero(task_result, sizeof(*task_result)); Pipe *pipe = serv->task_notify_pipes.at(SwooleG.process_id).get(); Worker *worker = serv->get_worker(SwooleG.process_id); File fp = swoole::make_tmpfile(); if (!fp.ready()) { RETURN_FALSE; } std::string file_path = fp.get_path(); fp.close(); int *finish_count = (int *) task_result->data; worker->lock->lock(); *finish_count = 0; swoole_strlcpy(task_result->data + 4, file_path.c_str(), SW_TASK_TMP_PATH_SIZE); worker->lock->unlock(); // clear history task network::Socket *task_notify_socket = pipe->get_socket(false); task_notify_socket->set_nonblock(); while (task_notify_socket->read(&notify, sizeof(notify)) > 0) { } task_notify_socket->set_block(); SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(ztasks), ztask) TaskId task_id = php_swoole_task_pack(&buf, ztask); if (task_id < 0) { php_swoole_fatal_error(E_WARNING, "task pack failed"); goto _fail; } swTask_type(&buf) |= SW_TASK_WAITALL; dst_worker_id = -1; sw_atomic_fetch_add(&serv->gs->tasking_num, 1); if (serv->gs->task_workers.dispatch_blocking(&buf, &dst_worker_id) < 0) { php_swoole_sys_error(E_WARNING, "taskwait failed"); task_id = -1; _fail: add_index_bool(return_value, i, 0); n_task--; } else { sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); } list_of_id[i] = task_id; i++; SW_HASHTABLE_FOREACH_END(); if (n_task == 0) { swoole_set_last_error(SW_ERROR_TASK_DISPATCH_FAIL); RETURN_FALSE; } pipe->set_timeout(timeout); double _now = microtime(); while (n_task > 0) { int ret = pipe->read(&notify, sizeof(notify)); if (ret > 0 && *finish_count < n_task) { if (microtime() - _now < timeout) { continue; } } break; } worker->lock->lock(); auto content = swoole::file_get_contents(file_path); worker->lock->unlock(); if (content.get() == nullptr) { RETURN_FALSE; } EventData *result; zval *zdata; uint32_t j; do { result = (EventData *) (content->str + content->offset); TaskId task_id = result->info.fd; zdata = php_swoole_task_unpack(result); if (zdata == nullptr) { goto _next; } for (j = 0; j < php_swoole_array_length(ztasks); j++) { if (list_of_id[j] == task_id) { break; } } (void) add_index_zval(return_value, j, zdata); efree(zdata); _next: content->offset += sizeof(DataHead) + result->info.len; } while (content->offset < 0 || (size_t) content->offset < content->length); // delete tmp file unlink(file_path.c_str()); } static PHP_METHOD(swoole_server, taskCo) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (!serv->is_worker()) { php_swoole_fatal_error(E_WARNING, "taskCo method can only be used in the worker process"); RETURN_FALSE; } ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); zval *ztasks; zval *ztask; double timeout = SW_TASKWAIT_TIMEOUT; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|d", &ztasks, &timeout) == FAILURE) { RETURN_FALSE; } int dst_worker_id = -1; TaskId task_id; int i = 0; uint32_t n_task = php_swoole_array_length(ztasks); EventData buf; memset(&buf.info, 0, sizeof(buf.info)); if (n_task >= SW_MAX_CONCURRENT_TASK) { php_swoole_fatal_error(E_WARNING, "too many concurrent tasks"); RETURN_FALSE; } if (php_swoole_check_task_param(serv, dst_worker_id) < 0) { RETURN_FALSE; } int *list = (int *) ecalloc(n_task, sizeof(int)); if (list == nullptr) { RETURN_FALSE; } TaskCo *task_co = (TaskCo *) emalloc(sizeof(TaskCo)); if (task_co == nullptr) { efree(list); RETURN_FALSE; } task_co->server_object = server_object; zval *result = sw_malloc_zval(); array_init(result); SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(ztasks), ztask) task_id = php_swoole_task_pack(&buf, ztask); if (task_id < 0) { php_swoole_fatal_error(E_WARNING, "failed to pack task"); goto _fail; } swTask_type(&buf) |= (SW_TASK_NONBLOCK | SW_TASK_COROUTINE); dst_worker_id = -1; sw_atomic_fetch_add(&serv->gs->tasking_num, 1); if (serv->gs->task_workers.dispatch(&buf, &dst_worker_id) < 0) { task_id = -1; _fail: add_index_bool(result, i, 0); n_task--; sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); } else { server_object->property->task_coroutine_map[task_id] = task_co; } list[i] = task_id; i++; SW_HASHTABLE_FOREACH_END(); if (n_task == 0) { swoole_set_last_error(SW_ERROR_TASK_DISPATCH_FAIL); RETURN_FALSE; } long ms = (long) (timeout * 1000); task_co->result = result; task_co->list = list; task_co->count = n_task; TimerNode *timer = swoole_timer_add(ms, false, php_swoole_task_onTimeout, task_co); if (timer) { task_co->timer = timer; } PHPCoroutine::yield_m(return_value, &task_co->context); } static PHP_METHOD(swoole_server, task) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } ServerObject *server_object = server_fetch_object(Z_OBJ_P(ZEND_THIS)); zval *zdata; zend_long dst_worker_id = -1; zend_fcall_info fci = empty_fcall_info; zend_fcall_info_cache fci_cache = empty_fcall_info_cache; ZEND_PARSE_PARAMETERS_START(1, 3) Z_PARAM_ZVAL(zdata) Z_PARAM_OPTIONAL Z_PARAM_LONG(dst_worker_id) Z_PARAM_FUNC_EX(fci, fci_cache, 1, 0) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); if (php_swoole_check_task_param(serv, dst_worker_id) < 0) { RETURN_FALSE; } EventData buf; memset(&buf.info, 0, sizeof(buf.info)); if (php_swoole_task_pack(&buf, zdata) < 0) { RETURN_FALSE; } if (!serv->is_worker()) { swTask_type(&buf) |= SW_TASK_NOREPLY; } else if (fci.size) { swTask_type(&buf) |= SW_TASK_CALLBACK; sw_zend_fci_cache_persist(&fci_cache); server_object->property->task_callbacks[buf.info.fd] = fci_cache; } swTask_type(&buf) |= SW_TASK_NONBLOCK; int _dst_worker_id = (int) dst_worker_id; sw_atomic_fetch_add(&serv->gs->tasking_num, 1); if (serv->gs->task_workers.dispatch(&buf, &_dst_worker_id) >= 0) { RETURN_LONG(buf.info.fd); } sw_atomic_fetch_sub(&serv->gs->tasking_num, 1); RETURN_FALSE; } static PHP_METHOD(swoole_server, sendMessage) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (!serv->onPipeMessage) { php_swoole_fatal_error(E_WARNING, "onPipeMessage is null, can't use sendMessage"); RETURN_FALSE; } zval *zmessage; zend_long worker_id = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "zl", &zmessage, &worker_id) == FAILURE) { RETURN_FALSE; } if (worker_id == SwooleG.process_id) { php_swoole_fatal_error(E_WARNING, "can't send messages to self"); RETURN_FALSE; } if (worker_id >= serv->worker_num + serv->task_worker_num) { php_swoole_fatal_error(E_WARNING, "worker_id[%d] is invalid", (int) worker_id); RETURN_FALSE; } EventData buf; memset(&buf.info, 0, sizeof(buf.info)); if (php_swoole_task_pack(&buf, zmessage) < 0) { RETURN_FALSE; } buf.info.type = SW_SERVER_EVENT_PIPE_MESSAGE; Worker *to_worker = serv->get_worker(worker_id); SW_CHECK_RETURN(serv->send_to_worker_from_worker( to_worker, &buf, sizeof(buf.info) + buf.info.len, SW_PIPE_MASTER | SW_PIPE_NONBLOCK)); } static PHP_METHOD(swoole_server, finish) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (sw_unlikely(serv->task_enable_coroutine)) { php_swoole_fatal_error(E_ERROR, "please use %s->finish instead when task_enable_coroutine is enable", ZSTR_VAL(swoole_server_task_ce->name)); RETURN_FALSE; } zval *zdata; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ZVAL(zdata) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); SW_CHECK_RETURN(php_swoole_task_finish(serv, zdata, nullptr)); } static PHP_METHOD(swoole_server_task, finish) { Server *serv = php_swoole_server_task_get_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zval *zdata; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ZVAL(zdata) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); DataHead *info = php_swoole_server_task_get_info(ZEND_THIS); SW_CHECK_RETURN(php_swoole_task_finish(serv, zdata, (EventData *) info)); } static PHP_METHOD(swoole_server_task, pack) { EventData buf; memset(&buf.info, 0, sizeof(buf.info)); zval *zdata; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_ZVAL(zdata) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); if (php_swoole_task_pack(&buf, zdata) < 0) { RETURN_FALSE; } swTask_type(&buf) |= (SW_TASK_NONBLOCK | SW_TASK_NOREPLY); RETURN_STRINGL((char *) &buf, sizeof(buf.info) + buf.info.len); } static PHP_METHOD(swoole_server, bind) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd = 0; zend_long uid = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll", &fd, &uid) == FAILURE) { RETURN_FALSE; } if (uid > UINT32_MAX || uid < INT32_MIN) { php_swoole_fatal_error(E_WARNING, "uid can not be greater than %u or less than %d", UINT32_MAX, INT32_MIN); RETURN_FALSE; } Connection *conn = serv->get_connection_verify(fd); if (conn == nullptr) { RETURN_FALSE; } sw_spinlock(&conn->lock); if (conn->uid != 0) { RETVAL_FALSE; } else { conn->uid = (uint32_t) uid; RETVAL_TRUE; } sw_spinlock_release(&conn->lock); } #ifdef SWOOLE_SOCKETS_SUPPORT static PHP_METHOD(swoole_server, getSocket) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); zend_long port = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &port) == FAILURE) { RETURN_FALSE; } ListenPort *lp = serv->get_port(port); php_socket *socket_object = php_swoole_convert_to_socket(lp->get_fd()); if (!socket_object) { RETURN_FALSE; } SW_ZVAL_SOCKET(return_value, socket_object); zval *zsocket = sw_zval_dup(return_value); Z_TRY_ADDREF_P(zsocket); } #endif static PHP_METHOD(swoole_server, getClientInfo) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; zend_long reactor_id = -1; zend_bool dont_check_connection = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|lb", &fd, &reactor_id, &dont_check_connection) == FAILURE) { RETURN_FALSE; } Connection *conn = serv->get_connection_verify(fd); if (!conn) { RETURN_FALSE; } // connection is closed if (conn->active == 0 && !dont_check_connection) { RETURN_FALSE; } else { array_init(return_value); if (conn->uid > 0 || serv->dispatch_mode == SW_DISPATCH_UIDMOD) { add_assoc_long(return_value, "uid", conn->uid); } ListenPort *port = serv->get_port_by_fd(conn->fd); if (port && port->open_websocket_protocol) { add_assoc_long(return_value, "websocket_status", conn->websocket_status); } #ifdef SW_USE_OPENSSL if (conn->ssl_client_cert && conn->ssl_client_cert_pid == SwooleG.pid) { add_assoc_stringl( return_value, "ssl_client_cert", conn->ssl_client_cert->str, conn->ssl_client_cert->length); } #endif // server socket Connection *from_sock = serv->get_connection(conn->server_fd); if (from_sock) { add_assoc_long(return_value, "server_port", from_sock->info.get_port()); } add_assoc_long(return_value, "server_fd", conn->server_fd); add_assoc_long(return_value, "socket_fd", conn->fd); add_assoc_long(return_value, "socket_type", conn->socket_type); add_assoc_long(return_value, "remote_port", conn->info.get_port()); add_assoc_string(return_value, "remote_ip", (char *) conn->info.get_ip()); add_assoc_long(return_value, "reactor_id", conn->reactor_id); add_assoc_long(return_value, "connect_time", conn->connect_time); add_assoc_long(return_value, "last_time", (int) conn->last_recv_time); add_assoc_double(return_value, "last_recv_time", conn->last_recv_time); add_assoc_double(return_value, "last_send_time", conn->last_send_time); add_assoc_double(return_value, "last_dispatch_time", conn->last_dispatch_time); add_assoc_long(return_value, "close_errno", conn->close_errno); add_assoc_long(return_value, "recv_queued_bytes", conn->recv_queued_bytes); add_assoc_long(return_value, "send_queued_bytes", conn->send_queued_bytes); } } static PHP_METHOD(swoole_server, getClientList) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long start_session_id = 0; zend_long find_count = 10; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|ll", &start_session_id, &find_count) == FAILURE) { RETURN_FALSE; } // exceeded the maximum number of searches if (find_count > SW_MAX_FIND_COUNT) { php_swoole_fatal_error(E_WARNING, "swoole connection list max_find_count=%d", SW_MAX_FIND_COUNT); RETURN_FALSE; } // copy it out to avoid being overwritten by other processes int serv_max_fd = serv->get_maxfd(); int start_fd; if (start_session_id == 0) { start_fd = serv->get_minfd(); } else { Connection *conn = serv->get_connection_verify(start_session_id); if (!conn) { RETURN_FALSE; } start_fd = conn->fd; } if ((int) start_fd >= serv_max_fd) { RETURN_FALSE; } array_init(return_value); int fd = start_fd + 1; for (; fd <= serv_max_fd; fd++) { swTrace("maxfd=%d, fd=%d, find_count=%ld, start_fd=%ld", serv_max_fd, fd, find_count, start_session_id); Connection *conn = serv->get_connection_for_iterator(fd); if (conn) { add_next_index_long(return_value, conn->session_id); find_count--; } // finish fetch if (find_count <= 0) { break; } } } static PHP_METHOD(swoole_server, sendwait) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long fd; zval *zdata; if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz", &fd, &zdata) == FAILURE) { RETURN_FALSE; } char *data; size_t length = php_swoole_get_send_data(zdata, &data); if (length == 0) { php_swoole_fatal_error(E_WARNING, "data is empty"); RETURN_FALSE; } if (serv->is_process_mode() || serv->is_task_worker()) { php_swoole_fatal_error(E_WARNING, "can't sendwait"); RETURN_FALSE; } RETURN_BOOL(serv->sendwait(fd, data, length)); } static PHP_METHOD(swoole_server, exists) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long session_id; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(session_id) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); Connection *conn = serv->get_connection_verify(session_id); if (!conn || conn->closed) { RETURN_FALSE; } else { RETURN_TRUE; } } static PHP_METHOD(swoole_server, protect) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long session_id; zend_bool value = 1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|b", &session_id, &value) == FAILURE) { RETURN_FALSE; } Connection *conn = serv->get_connection_verify(session_id); if (!conn || conn->closed) { RETURN_FALSE; } else { conn->protect = value; RETURN_TRUE; } } static PHP_METHOD(swoole_server, getWorkerId) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (!serv->is_worker()) { RETURN_FALSE; } else { RETURN_LONG(SwooleG.process_id); } } static PHP_METHOD(swoole_server, getWorkerStatus) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_long worker_id = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &worker_id) == FAILURE) { RETURN_FALSE; } Worker *worker; if (worker_id == -1) { worker = SwooleWG.worker; } else { worker = serv->get_worker(worker_id); } if (!worker) { RETURN_FALSE; } else { RETURN_LONG(worker->status); } } static PHP_METHOD(swoole_server, getWorkerPid) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (!serv->is_worker()) { zend_long worker_id = -1; if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &worker_id) == FAILURE) { RETURN_FALSE; } if (worker_id < 0) { RETURN_FALSE; } RETURN_LONG(serv->get_worker(worker_id)->pid); } else { RETURN_LONG(SwooleG.pid); } } static PHP_METHOD(swoole_server, getManagerPid) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); RETURN_LONG(serv->gs->manager_pid); } static PHP_METHOD(swoole_server, getMasterPid) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); RETURN_LONG(serv->gs->master_pid); } static PHP_METHOD(swoole_server, shutdown) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } if (swoole_kill(serv->gs->master_pid, SIGTERM) < 0) { php_swoole_sys_error(E_WARNING, "failed to shutdown. swKill(%d, SIGTERM) failed", serv->gs->master_pid); RETURN_FALSE; } else { RETURN_TRUE; } } static PHP_METHOD(swoole_server, stop) { Server *serv = php_swoole_server_get_and_check_server(ZEND_THIS); if (sw_unlikely(!serv->is_started())) { php_swoole_fatal_error(E_WARNING, "server is not running"); RETURN_FALSE; } zend_bool wait_reactor = 0; long worker_id = SwooleG.process_id; if (zend_parse_parameters(ZEND_NUM_ARGS(), "|lb", &worker_id, &wait_reactor) == FAILURE) { RETURN_FALSE; } if (worker_id == SwooleG.process_id && wait_reactor == 0) { if (SwooleTG.reactor != nullptr) { SwooleTG.reactor->defer( [](void *data) { Reactor *reactor = (Reactor *) data; reactor->running = false; }, SwooleTG.reactor); } serv->running = false; } else { Worker *worker = serv->get_worker(worker_id); if (worker == nullptr) { RETURN_FALSE; } else if (swoole_kill(worker->pid, SIGTERM) < 0) { php_swoole_sys_error(E_WARNING, "swKill(%d, SIGTERM) failed", worker->pid); RETURN_FALSE; } } RETURN_TRUE; } // swoole_connection_iterator static PHP_METHOD(swoole_connection_iterator, __construct) { php_swoole_fatal_error(E_ERROR, "please use the Swoole\\Server->connections"); return; } static PHP_METHOD(swoole_connection_iterator, rewind) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); iterator->index = 0; iterator->current_fd = iterator->serv->get_minfd(); } static PHP_METHOD(swoole_connection_iterator, valid) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); int fd = iterator->current_fd; int max_fd = iterator->serv->get_maxfd(); for (; fd <= max_fd; fd++) { Connection *conn = iterator->serv->get_connection_for_iterator(fd); if (!conn) { continue; } if (iterator->port && (iterator->port->get_fd() < 0 || conn->server_fd != iterator->port->get_fd())) { continue; } iterator->session_id = conn->session_id; iterator->current_fd = fd; iterator->index++; RETURN_TRUE; } RETURN_FALSE; } static PHP_METHOD(swoole_connection_iterator, current) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); RETURN_LONG(iterator->session_id); } static PHP_METHOD(swoole_connection_iterator, next) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); iterator->current_fd++; } static PHP_METHOD(swoole_connection_iterator, key) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); RETURN_LONG(iterator->index); } static PHP_METHOD(swoole_connection_iterator, count) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); if (iterator->port) { RETURN_LONG(*iterator->port->connection_num); } else { RETURN_LONG(iterator->serv->gs->connection_num); } } static PHP_METHOD(swoole_connection_iterator, offsetExists) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); zval *zserv = (zval *) iterator->serv->private_data_2; zval *zfd; zval retval; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zfd) == FAILURE) { RETURN_FALSE; } sw_zend_call_method_with_1_params(zserv, swoole_server_ce, nullptr, "exists", &retval, zfd); RETVAL_BOOL(Z_BVAL_P(&retval)); } static PHP_METHOD(swoole_connection_iterator, offsetGet) { ConnectionIterator *iterator = php_swoole_connection_iterator_get_and_check_ptr(ZEND_THIS); zval *zserv = (zval *) iterator->serv->private_data_2; zval *zfd; zval retval; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &zfd) == FAILURE) { RETURN_FALSE; } sw_zend_call_method_with_1_params(zserv, swoole_server_ce, nullptr, "getClientInfo", &retval, zfd); RETVAL_ZVAL(&retval, 0, 0); } static PHP_METHOD(swoole_connection_iterator, offsetSet) {} static PHP_METHOD(swoole_connection_iterator, offsetUnset) {} static PHP_METHOD(swoole_connection_iterator, __destruct) {}
; A319452: Numbers that are congruent to {0, 3, 6, 10} mod 12. ; 0,3,6,10,12,15,18,22,24,27,30,34,36,39,42,46,48,51,54,58,60,63,66,70,72,75,78,82,84,87,90,94,96,99,102,106,108,111,114,118,120,123,126,130,132,135,138,142,144,147,150,154,156,159,162,166,168,171,174,178,180,183,186,190,192,195,198,202,204,207,210,214,216,219,222,226,228,231,234,238,240,243,246,250,252,255,258,262,264,267,270,274,276,279,282,286,288,291,294,298,300,303,306,310,312,315,318,322,324,327,330,334,336,339,342,346,348,351,354,358,360,363,366,370,372,375,378,382,384,387,390,394,396,399,402,406,408,411,414,418,420,423,426,430,432,435,438,442,444,447,450,454,456,459,462,466,468,471,474,478,480,483,486,490,492,495,498,502,504,507,510,514,516,519,522,526,528,531,534,538,540,543,546,550,552,555,558,562,564,567,570,574,576,579,582,586,588,591,594,598,600,603,606,610,612,615,618,622,624,627,630,634,636,639,642,646,648,651,654,658,660,663,666,670,672,675,678,682,684,687,690,694,696,699,702,706,708,711,714,718,720,723,726,730,732,735,738,742,744,747 mov $1,$0 mod $0,4 mul $1,6 add $1,$0 div $1,3 mul $1,6 div $1,4
; A157736: a(n) = 388962*n^2 - 347508*n + 77617. ; 119071,938449,2535751,4910977,8064127,11995201,16704199,22191121,28455967,35498737,43319431,51918049,61294591,71449057,82381447,94091761,106579999,119846161,133890247,148712257,164312191,180690049,197845831,215779537,234491167,253980721,274248199,295293601,317116927,339718177,363097351,387254449,412189471,437902417,464393287,491662081,519708799,548533441,578136007,608516497,639674911,671611249,704325511,737817697,772087807,807135841,842961799,879565681,916947487,955107217,994044871,1033760449,1074253951,1115525377,1157574727,1200402001,1244007199,1288390321,1333551367,1379490337,1426207231,1473702049,1521974791,1571025457,1620854047,1671460561,1722844999,1775007361,1827947647,1881665857,1936161991,1991436049,2047488031,2104317937,2161925767,2220311521,2279475199,2339416801,2400136327,2461633777,2523909151,2586962449,2650793671,2715402817,2780789887,2846954881,2913897799,2981618641,3050117407,3119394097,3189448711,3260281249,3331891711,3404280097,3477446407,3551390641,3626112799,3701612881,3777890887,3854946817,3932780671,4011392449,4090782151,4170949777,4251895327,4333618801,4416120199,4499399521,4583456767,4668291937,4753905031,4840296049,4927464991,5015411857,5104136647,5193639361,5283919999,5374978561,5466815047,5559429457,5652821791,5746992049,5841940231,5937666337,6034170367,6131452321,6229512199,6328350001,6427965727,6528359377,6629530951,6731480449,6834207871,6937713217,7041996487,7147057681,7252896799,7359513841,7466908807,7575081697,7684032511,7793761249,7904267911,8015552497,8127615007,8240455441,8354073799,8468470081,8583644287,8699596417,8816326471,8933834449,9052120351,9171184177,9291025927,9411645601,9533043199,9655218721,9778172167,9901903537,10026412831,10151700049,10277765191,10404608257,10532229247,10660628161,10789804999,10919759761,11050492447,11182003057,11314291591,11447358049,11581202431,11715824737,11851224967,11987403121,12124359199,12262093201,12400605127,12539894977,12679962751,12820808449,12962432071,13104833617,13248013087,13391970481,13536705799,13682219041,13828510207,13975579297,14123426311,14272051249,14421454111,14571634897,14722593607,14874330241,15026844799,15180137281,15334207687,15489056017,15644682271,15801086449,15958268551,16116228577,16274966527,16434482401,16594776199,16755847921,16917697567,17080325137,17243730631,17407914049,17572875391,17738614657,17905131847,18072426961,18240499999,18409350961,18578979847,18749386657,18920571391,19092534049,19265274631,19438793137,19613089567,19788163921,19964016199,20140646401,20318054527,20496240577,20675204551,20854946449,21035466271,21216764017,21398839687,21581693281,21765324799,21949734241,22134921607,22320886897,22507630111,22695151249,22883450311,23072527297,23262382207,23453015041,23644425799,23836614481,24029581087,24223325617 cal $0,157734 ; a(n) = 441*n^2 - 394*n + 88. mov $1,$0 sub $1,135 mul $1,882 add $1,119071
COMMENT @----------------------------------------------------------------------- Copyright (c) Geoworks 1991 -- All Rights Reserved PROJECT: PC GEOS MODULE: FILE: bootLog.asm AUTHOR: Cheng, 3/91 ROUTINES: Name Description ---- ----------- LogInit INTERNAL - Intialize log file LogWriteInitEntry GLOBAL - write an entry to the log file preceeded by the word "Initializing " LogWriteEntry GLOBAL - write an entry to the log file LogTerminateEntry INTERNAL - terminate an entry with a CR, LF and commits the file as well LogWriteString INTERNAL REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial revision Doug 8/91 Moved from UI to kernel DESCRIPTION: Allows the system to write stuff out to a log file. Belongs logically to the file module in the kernel but there's no need for this stuff to be in fixed memory. $Id: bootLog.asm,v 1.1 97/04/05 01:10:54 newdeal Exp $ -------------------------------------------------------------------------------@ COMMENT @----------------------------------------------------------------------- FUNCTION: LogInit DESCRIPTION: Called to initialize the log file. CALLED BY: INTERNAL BootInit PASS: ds - dgroup RETURN: DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial version -------------------------------------------------------------------------------@ LocalDefNLString logFilename <"GEOS.LOG", 0 > logBeginString char "Logging On", 0 LogInit proc near uses ax, cx, dx, si .enter call LogTestIfLogging ; make sure logging jc done call FilePushDir push ds segmov ds, cs, si mov ax, SP_PRIVATE_DATA call FileSetStandardPath ; change to system dir mov ax, ((FILE_CREATE_TRUNCATE or mask FCF_NATIVE) shl 8) or \ (FILE_DENY_W or FILE_ACCESS_RW) clr cx ; no special file attrs mov dx, offset cs:logFilename ; ; Unless there is a dos present, there is no point ; in creating a log file, as no one can look ; at it... call FileCreate ; ax <- file handle jnc storeHan clr ax storeHan: pop ds ; ds <- dgroup mov ds:logFileHan, ax call FilePopDir push ds mov ds, si mov si, offset logBeginString call LogWriteEntry pop ds clc done: .leave ret LogInit endp COMMENT @----------------------------------------------------------------------- FUNCTION: LogWriteInitEntry DESCRIPTION: Writes a string to the log preceeded by the word "Initializing ". CALLED BY: GLOBAL PASS: ds:si - string to write to the log There is no need for a preceeding space. RETURN: carry set if error DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial version -------------------------------------------------------------------------------@ ; strings logInitStr char "Initializing ", 0 SBCS <logCRLFStr char VC_ENTER, VC_LF, 0 > DBCS <logCRLFStr char C_ENTER, C_LINEFEED, 0 > if DBCS_PCGEOS LogWriteDBCSEntry proc far uses ds, si, es, di, ax .enter sub sp, 256 segmov es, ss mov di, sp ;es:di <- ptr to dest buffer charLoop: lodsw ;ax <- get DBCS char stosb ;<- store SBCS char tst ax ;NULL? jnz charLoop ;loop until reached NULL segmov ds, ss mov si, sp ;ds:si <- ptr to SBCS string call LogWriteInitEntry add sp, 256 .leave ret LogWriteDBCSEntry endp endif if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LogWriteInitEntry proc far mov ss:[TPD_dataBX], handle LogWriteInitEntryReal mov ss:[TPD_dataAX], offset LogWriteInitEntryReal GOTO SysCallMovableXIPWithDSSI LogWriteInitEntry endp CopyStackCodeXIP ends else LogWriteInitEntry proc far FALL_THRU LogWriteInitEntryReal LogWriteInitEntry endp endif LogWriteInitEntryReal proc far uses ax, bx,cx,dx,ds .enter call LogTestIfLogging ; make sure logging jc done mov bx, ds mov cx, si ; save ds:si mov dx, dgroup ; dx <- dgroup mov ds, dx PSem ds, logFileSem ; grab semaphore segmov ds, cs, si mov si, offset logInitStr call LogWriteString ; write "Initializing " mov ds, bx ; restore ds:si mov si, cx jc exit call LogWriteString jc exit call LogTerminateEntry exit: mov ds, dx ; ds <- dgroup VSem ds, logFileSem ; release semaphore done: .leave ret LogWriteInitEntryReal endp COMMENT @----------------------------------------------------------------------- FUNCTION: LogWriteEntry DESCRIPTION: Writes a string out to the log file with a trailing CR, LF. We ensure that the info in the file is current by always commiting all output. CALLED BY: GLOBAL PASS: ds:si - offset to string RETURN: carry set if error DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial version -------------------------------------------------------------------------------@ if FULL_EXECUTE_IN_PLACE CopyStackCodeXIP segment resource LogWriteEntry proc far mov ss:[TPD_dataBX], handle LogWriteEntryReal mov ss:[TPD_dataAX], offset LogWriteEntryReal GOTO SysCallMovableXIPWithDSSI LogWriteEntry endp CopyStackCodeXIP ends else LogWriteEntry proc far FALL_THRU LogWriteEntryReal LogWriteEntry endp endif LogWriteEntryReal proc far uses ax, dx, ds .enter call LogTestIfLogging ; make sure logging jc done push ds mov dx, dgroup mov ds, dx PSem ds, logFileSem ; grab semaphore pop ds call LogWriteString jc exit call LogTerminateEntry exit: mov ds, dx VSem ds, logFileSem ; release semaphore done: .leave ret LogWriteEntryReal endp COMMENT @----------------------------------------------------------------------- FUNCTION: LogTerminateEntry DESCRIPTION: Terminates the current entry with a Carraige Return, Line Feed. The log file is also commited. CALLED BY: INTERNAL LogWriteInitEntry LogWriteEntry PASS: logFileSem grabbed RETURN: carry set if error DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial version -------------------------------------------------------------------------------@ LogTerminateEntry proc near uses ax,bx,ds,si .enter segmov ds, cs, si mov si, offset logCRLFStr call LogWriteString jc done mov bx, dgroup mov ds, bx mov bx, ds:logFileHan ; bx <- file handle tst bx jz done clr al call FileCommit done: .leave ret LogTerminateEntry endp COMMENT @----------------------------------------------------------------------- FUNCTION: LogWriteString DESCRIPTION: Writes a string out to the log file WITHOUT a trailing CR, LF. A FileCommit is not done. Use LogTerminateEntry when termination and commiting are desired. We ensure that the info in the file is current by always commiting all output. CALLED BY: INTERNAL LogWriteInitEntry LogWriteEntry PASS: ds:si - offset to string logFileSem grabbed RETURN: carry set if error DESTROYED: nothing REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Cheng 3/91 Initial version -------------------------------------------------------------------------------@ LogWriteString proc near uses ax, bx, cx, dx, ds, es, di, si .enter mov bx, dgroup mov es, bx ; es <- dgroup mov bx, es:logFileHan ; bx <- file handle tst bx jz writeThroughBIOS segmov es, ds, dx mov dx, si ; ds:dx <- string mov di, dx ; es:di <- string clr al ; locate null mov cx, 0ffffh repne scasb not cx ; cx <- length of string dec cx clr al call FileWriteFar ; write string out done: .leave ret writeThroughBIOS: lodsb tst al jz done mov ah, 0xe ; output a single character int 10h jmp writeThroughBIOS LogWriteString endp COMMENT @---------------------------------------------------------------------- FUNCTION: LogTestIfLogging DESCRIPTION: Check to see if logging is turned on or not CALLED BY: INTERNAL LogInit LogWriteInitEntry LogWriteEntry PASS: nothing RETURN: carry - clear if logging, set if logging turned off DESTROYED: al, dx REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 8/91 Initial version ------------------------------------------------------------------------------@ LogTestIfLogging proc near call SysGetConfig ; al <- config flags, dx destroyed test al, mask SCF_LOGGING clc ; yes, go ahead... jne done stc ; NO! we're not logging -- exit w/err done: ret LogTestIfLogging endp
; A194986: a(n) = 1 + floor(n/sqrt(6)). ; Submitted by Jon Maiga ; 1,1,2,2,3,3,3,4,4,5,5,5,6,6,7,7,7,8,8,9,9,9,10,10,11,11,12,12,12,13,13,14,14,14,15,15,16,16,16,17,17,18,18,18,19,19,20,20,21,21,21,22,22,23,23,23,24,24,25,25,25,26,26,27,27,27,28,28,29,29,29,30,30,31,31,32,32,32,33,33,34,34,34,35,35,36,36,36,37,37,38,38,38,39,39,40,40,41,41,41 add $0,1 pow $0,2 lpb $0 sub $0,$1 add $1,6 sub $0,$1 lpe mov $0,$1 div $0,6 add $0,1
; A111333: Number of odd numbers <= n-th prime. ; Submitted by Jamie Morken(s3) ; 1,2,3,4,6,7,9,10,12,15,16,19,21,22,24,27,30,31,34,36,37,40,42,45,49,51,52,54,55,57,64,66,69,70,75,76,79,82,84,87,90,91,96,97,99,100,106,112,114,115,117,120,121,126,129,132,135,136,139,141,142,147,154,156,157,159,166,169,174,175,177,180,184,187,190,192,195,199,201,205,210,211,216,217,220,222,225,229,231,232,234,240,244,246,250,252,255,261,262,271 mul $0,2 seq $0,173919 ; Numbers that are prime or one less than a prime. div $0,2 add $0,1
; ****************************************************************************** ; ****************************************************************************** ; ; Name : tokeniser.asm ; Purpose : Tokeniser for RPL/65 ; Author : Paul Robson (paul@robsons.org.uk) ; Created : 14th November 2019 ; ; ****************************************************************************** ; ****************************************************************************** ; ****************************************************************************** ; ; Tokenises the string in the input buffer, to the output buffer. ; After removing trailing spaces (because of comment) ; ; In order :- ; 1) If it begins with 0-9 or $ it is a decimal/hexadecimal ; constant (note Postfix -) ; 2) If it begins with : it is a definition ; 3) If it begins with " or ' it is a string or a comment. ; 4) If it starts with a token, then it is that token. ; 5) If it is an identifier (A-Z or :) see if it is a definition ; if so compile a call to it, otherwise compile the identifier. ; 6) An error occurs. ; ; ****************************************************************************** TokeniseInputBuffer: pha phx phy stz TokenOffset ; reset index into TokenBuffer stz TokenBuffer ; empty that buffer lda #0 ; create faux line by writing 3 bytes out. jsr TokWriteToken jsr TokWriteToken jsr TokWriteToken ; ; Remove any trailing spaces ; ldx #255 ; find the end. _TIBForward: inx lda InputBuffer,x bne _TIBForward _TIBBackward: dex ; back one. cpx #255 ; gone too far. beq _TIBExit ; return empty buffer lda InputBuffer,x cmp #" " beq _TIBBackward stz InputBuffer+1,x ; truncate at last non space. ldx #0 ; start of the input bufferr. ; ; Main Tokenising Loop. ; _TIBMainLoop: lda InputBuffer,x ; next character beq _TIBExit ; done the buffer if zero. inx cmp #" " ; skip over spaces beq _TIBMainLoop dex ; undo the last inx. ; ; Check for hexadecimal/decimal constant. ; cmp #"$" ; is it $ ? beq _TIBConstant cmp #"0" ; check 0-9 bcc _TIBNotConstant cmp #"9"+1 bcs _TIBNotConstant _TIBConstant: jsr TOKConvertConstant bra _TIBMainLoop ; ; Check for definition ; _TIBNotConstant: cmp #":" ; definition bne _TIBNotDefinition jsr TOKConvertDefinition bra _TIBMainLoop ; ; Check for comment and string. ; _TIBNotDefinition: cmp #"'" beq _TIBIsCommentString cmp #'"' bne _TIBNotCommentString _TIBIsCommentString: jsr TOKConvertCommentString bra _TIBMainLoop ; ; Check for a token here. ; _TIBNotCommentString: jsr TOKCheckIsToken ; check if a token. bcs _TIBMainLoop ; ; Finally output an identifier (same code as definition) ; Then check to see if it is a call, if so, replace it. ; lda TokenOffset ; save token offset. pha jsr TOKCopyIdentifier ; copy identifier. pla jsr TOKCheckIdentifierIsCall ; convert if call. bra _TIBMainLoop _TIBExit: ply plx pla rts ; ****************************************************************************** ; ; Write a byte to the token buffer ; ; ****************************************************************************** TOKWriteToken: phx ldx TokenOffset sta TokenBuffer,x stz TokenBuffer+1,x inc TokenOffset plx rts ; ****************************************************************************** ; ; Marks the last identifier written - doesn't check this - as last. ; ; ****************************************************************************** TOKFixUpLast: phx ldx TokenOffset lda TokenBuffer-1,x ora #$E0 sta TokenBuffer-1,x plx rts ; ****************************************************************************** ; ; Convert A (ASCII) to tokenised (C1-DA = A-Z DB = .) CS Okay CC Fail ; ; ****************************************************************************** TOKConvertIdentifier: cmp #"." ; dot is special case. beq _TKCIDot sec ; A-Z -> 1-27 sbc #64 beq _TKCIFail cmp #27 bcs _TKCIFail ora #$C0 ; fix up sec rts ; _TKCIFail: clc rts _TKCIDot: ; return . lda #$C0+27 sec rts
// Copyright (c) YugaByte, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. // #include "yb/docdb/in_mem_docdb.h" #include <sstream> #include "yb/common/hybrid_time.h" #include "yb/docdb/doc_key.h" #include "yb/docdb/doc_reader.h" #include "yb/docdb/docdb.h" #include "yb/docdb/docdb_rocksdb_util.h" #include "yb/docdb/docdb_test_util.h" #include "yb/gutil/strings/substitute.h" #include "yb/rocksdb/db.h" #include "yb/util/status_format.h" #include "yb/util/status_log.h" #include "yb/util/test_macros.h" using std::endl; using std::string; using std::stringstream; using strings::Substitute; namespace yb { namespace docdb { Status InMemDocDbState::SetPrimitive(const DocPath& doc_path, const PrimitiveValue& value) { VLOG(2) << __func__ << ": doc_path=" << doc_path.ToString() << ", value=" << value.ToString(); const PrimitiveValue encoded_doc_key_as_primitive(doc_path.encoded_doc_key().AsSlice()); const bool is_deletion = value.value_type() == ValueType::kTombstone; if (doc_path.num_subkeys() == 0) { if (is_deletion) { root_.DeleteChild(encoded_doc_key_as_primitive); } else { root_.SetChildPrimitive(encoded_doc_key_as_primitive, value); } return Status::OK(); } SubDocument* current_subdoc = nullptr; if (is_deletion) { current_subdoc = root_.GetChild(encoded_doc_key_as_primitive); if (current_subdoc == nullptr) { // The subdocument we're trying to delete does not exist, nothing to do. return Status::OK(); } } else { current_subdoc = root_.GetOrAddChild(encoded_doc_key_as_primitive).first; } const auto num_subkeys = doc_path.num_subkeys(); for (size_t subkey_index = 0; subkey_index < num_subkeys - 1; ++subkey_index) { const PrimitiveValue& subkey = doc_path.subkey(subkey_index); if (subkey.value_type() == ValueType::kArrayIndex) { return STATUS(NotSupported, "Setting values at a given array index is not supported yet."); } if (current_subdoc->value_type() != ValueType::kObject) { return STATUS_FORMAT(IllegalState, "Cannot set or delete values inside a subdocument of type $0", current_subdoc->value_type()); } if (is_deletion) { current_subdoc = current_subdoc->GetChild(subkey); if (current_subdoc == nullptr) { // Document does not exist, nothing to do. return Status::OK(); } } else { current_subdoc = current_subdoc->GetOrAddChild(subkey).first; } } if (is_deletion) { current_subdoc->DeleteChild(doc_path.last_subkey()); } else { current_subdoc->SetChildPrimitive(doc_path.last_subkey(), value); } return Status::OK(); } Status InMemDocDbState::DeleteSubDoc(const DocPath &doc_path) { return SetPrimitive(doc_path, PrimitiveValue::kTombstone); } void InMemDocDbState::SetDocument(const KeyBytes& encoded_doc_key, SubDocument&& doc) { root_.SetChild(PrimitiveValue(encoded_doc_key.AsSlice()), std::move(doc)); } const SubDocument* InMemDocDbState::GetSubDocument(const SubDocKey& subdoc_key) const { const SubDocument* current = root_.GetChild(PrimitiveValue(subdoc_key.doc_key().Encode().AsSlice())); for (const auto& subkey : subdoc_key.subkeys()) { if (current == nullptr) { return nullptr; } current = current->GetChild(subkey); } return current; } void InMemDocDbState::CaptureAt(const DocDB& doc_db, HybridTime hybrid_time, rocksdb::QueryId query_id) { // Clear the internal state. root_ = SubDocument(); auto rocksdb_iter = CreateRocksDBIterator( doc_db.regular, doc_db.key_bounds, BloomFilterMode::DONT_USE_BLOOM_FILTER, boost::none /* user_key_for_filter */, query_id); rocksdb_iter.SeekToFirst(); KeyBytes prev_key; while (rocksdb_iter.Valid()) { const auto key = rocksdb_iter.key(); CHECK_NE(0, prev_key.CompareTo(key)) << "Infinite loop detected on key " << prev_key.ToString(); prev_key = KeyBytes(key); SubDocKey subdoc_key; CHECK_OK(subdoc_key.FullyDecodeFrom(key)); CHECK_EQ(0, subdoc_key.num_subkeys()) << "Expected to be positioned at the first key of a new document with no subkeys, " << "but found " << subdoc_key.num_subkeys() << " subkeys: " << subdoc_key.ToString(); subdoc_key.remove_hybrid_time(); // TODO: It would be good to be able to refer to a slice of the original key whenever we need // to extract document key out of a subdocument key. auto encoded_doc_key = subdoc_key.doc_key().Encode(); // TODO(dtxn) Pass real TransactionOperationContext when we need to support cross-shard // transactions write intents resolution during DocDbState capturing. // For now passing kNonTransactionalOperationContext in order to fail if there are any intents, // since this is not supported. auto encoded_subdoc_key = subdoc_key.EncodeWithoutHt(); auto doc_from_rocksdb_opt = ASSERT_RESULT(yb::docdb::TEST_GetSubDocument( encoded_subdoc_key, doc_db, query_id, kNonTransactionalOperationContext, CoarseTimePoint::max() /* deadline */, ReadHybridTime::SingleTime(hybrid_time))); // doc_found can be false for deleted documents, and that is perfectly valid. if (doc_from_rocksdb_opt) { SetDocument(encoded_doc_key, std::move(*doc_from_rocksdb_opt)); } // Go to the next top-level document key. ROCKSDB_SEEK(&rocksdb_iter, subdoc_key.AdvanceOutOfSubDoc().AsSlice()); VLOG(4) << "After performing a seek: IsValid=" << rocksdb_iter.Valid(); if (VLOG_IS_ON(4) && rocksdb_iter.Valid()) { VLOG(4) << "Next key: " << FormatSliceAsStr(rocksdb_iter.key()); SubDocKey tmp_subdoc_key; CHECK_OK(tmp_subdoc_key.FullyDecodeFrom(rocksdb_iter.key())); VLOG(4) << "Parsed as SubDocKey: " << tmp_subdoc_key.ToString(); } } // Initialize the "captured at" hybrid_time now, even though we expect it to be overwritten in // many cases. One common usage pattern is that this will be called with HybridTime::kMax, but // we'll later call SetCaptureHybridTime and set the hybrid_time to the last known hybrid_time of // an operation performed on DocDB. captured_at_ = hybrid_time; // Ensure we don't get any funny value types in the root node (had a test failure like this). CHECK_EQ(root_.value_type(), ValueType::kObject); } void InMemDocDbState::SetCaptureHybridTime(HybridTime hybrid_time) { CHECK(hybrid_time.is_valid()); captured_at_ = hybrid_time; } bool InMemDocDbState::EqualsAndLogDiff(const InMemDocDbState &expected, bool log_diff) { bool matches = true; if (num_docs() != expected.num_docs()) { if (log_diff) { LOG(WARNING) << "Found " << num_docs() << " documents but expected to find " << expected.num_docs(); } matches = false; } // As an optimization, a SubDocument won't even maintain a map if it is an empty object that no // operations have been performed on. As we are using a SubDocument to represent the top-level // mapping of encoded document keys to SubDocuments here, we need to check for that situation. if (expected.root_.has_valid_object_container()) { for (const auto& expected_kv : expected.root_.object_container()) { const KeyBytes encoded_doc_key(expected_kv.first.GetString()); const SubDocument& expected_doc = expected_kv.second; DocKey doc_key; CHECK_OK(doc_key.FullyDecodeFrom(encoded_doc_key.AsSlice())); const SubDocument* child_from_this = GetDocument(doc_key); if (child_from_this == nullptr) { if (log_diff) { LOG(WARNING) << "Document with key " << doc_key.ToString() << " is missing but is " << "expected to be " << expected_doc.ToString(); } matches = false; continue; } if (*child_from_this != expected_kv.second) { if (log_diff) { LOG(WARNING) << "Expected document with key " << doc_key.ToString() << " to be " << expected_doc.ToString() << " but found " << *child_from_this; } matches = false; } } } // Also report all document keys that are present in this ("actual") database but are absent from // the other ("expected") database. if (root_.has_valid_object_container()) { for (const auto& actual_kv : root_.object_container()) { const KeyBytes encoded_doc_key(actual_kv.first.GetString()); DocKey doc_key; CHECK_OK(doc_key.FullyDecodeFrom(encoded_doc_key.AsSlice())); const SubDocument* child_from_expected = GetDocument(doc_key); if (child_from_expected == nullptr) { DocKey doc_key; CHECK_OK(doc_key.FullyDecodeFrom(encoded_doc_key.AsSlice())); if (log_diff) { LOG(WARNING) << "Unexpected document found with key " << doc_key.ToString() << ":" << actual_kv.second.ToString(); } matches = false; } } } // A brute-force way to check that the comparison logic above is correct. // TODO: disable this if it makes tests much slower. CHECK_EQ(matches, ToDebugString() == expected.ToDebugString()); return matches; } string InMemDocDbState::ToDebugString() const { stringstream ss; if (root_.has_valid_object_container()) { int i = 1; for (const auto& kv : root_.object_container()) { DocKey doc_key; CHECK_OK(doc_key.FullyDecodeFrom(rocksdb::Slice(kv.first.GetString()))); ss << i << ". " << doc_key.ToString() << " => " << kv.second.ToString() << endl; ++i; } } string dump_str = ss.str(); return dump_str.empty() ? "<Empty>" : dump_str; } HybridTime InMemDocDbState::captured_at() const { CHECK(captured_at_.is_valid()); return captured_at_; } void InMemDocDbState::SanityCheck() const { CHECK_EQ(root_.value_type(), ValueType::kObject); } const SubDocument* InMemDocDbState::GetDocument(const DocKey& doc_key) const { return GetSubDocument(SubDocKey(doc_key)); } } // namespace docdb } // namespace yb
; ; Small C z88 Character functions ; Written by Dominic Morris <djm@jb.man.ac.uk> ; 22 August 1998 ; ; 17/2/99 djm Rewritten to remove the jp and thus be shorter ; ; $Id: islower.asm,v 1.7 2016-03-06 21:41:15 dom Exp $ ; SECTION code_clib PUBLIC _islower PUBLIC islower EXTERN asm_islower ; FASTCALL ._islower .islower ld a,l call asm_islower ld hl,0 ret c inc l ret
; A051336: Number of arithmetic progressions in {1,2,3,...,n}, including trivial arithmetic progressions of lengths 1 and 2. ; 1,3,7,13,22,33,48,65,86,110,138,168,204,242,284,330,381,434,493,554,621,692,767,844,929,1017,1109,1205,1307,1411,1523,1637,1757,1881,2009,2141,2282,2425,2572,2723,2882,3043,3212,3383,3560,3743,3930,4119,4318,4520,4728,4940,5158,5378,5606,5838,6078,6322,6570,6820,7082,7346,7614,7888,8169,8454,8747,9042,9343,9648,9961,10276,10603,10932,11265,11604,11949,12298,12655,13014,13383,13757,14135,14515,14907,15303,15703,16107,16519,16933,17359,17789,18225,18665,19109,19557,20017,20479,20947,21421,21904,22389,22882,23377,23880,24391,24906,25423,25952,26483,27022,27565,28118,28673,29236,29803,30376,30955,31538,32125,32728,33334,33944,34558,35178,35802,36438,37076,37722,38372,39030,39690,40362,41038,41718,42406,43102,43800,44506,45214,45934,46658,47386,48118,48865,49616,50371,51132,51899,52668,53449,54232,55023,55820,56625,57434,58255,59078,59905,60736,61579,62426,63283,64142,65007,65880,66757,67636,68531,69429,70335,71247,72165,73085,74013,74947,75891,76839,77791,78745,79717,80691,81673,82659,83653,84651,85657,86667,87683,88707,89739,90773,91821,92871,93925,94987,96058,97131,98216,99303,100402,101505,102612,103723,104846,105973,107104,108241,109388,110539,111706,112875,114050,115229,116412,117599,118802,120009,121220,122435,123662,124893,126132,127373,128626,129888,131154,132422,133702,134984,136274,137572,138878,140186,141506,142830,144160,145494,146836,148180,149544,150910,152282,153660,155044,156434,157832,159234,160644,162058 mov $1,1 mov $2,$0 lpb $2,1 add $3,1 mov $4,$2 lpb $4,1 add $1,$4 trn $4,$3 lpe add $1,1 sub $2,1 lpe
; A315653: Coordination sequence Gal.5.305.5 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. ; Submitted by Jon Maiga ; 1,6,12,16,22,28,34,38,44,50,56,62,66,72,78,84,88,94,100,106,112,116,122,128,134,138,144,150,156,162,166,172,178,184,188,194,200,206,212,216,222,228,234,238,244,250,256,262,266,272 mov $3,$0 mul $0,2 mov $1,$0 add $0,1 add $0,$1 add $1,5 lpb $1 trn $0,2 mov $2,$1 sub $2,8 mov $1,$2 trn $1,1 lpe lpb $3 add $0,2 sub $3,1 lpe add $0,1
; A013636: n*nextprime(n). ; 0,2,6,15,20,35,42,77,88,99,110,143,156,221,238,255,272,323,342,437,460,483,506,667,696,725,754,783,812,899,930,1147,1184,1221,1258,1295,1332,1517,1558,1599,1640,1763 mov $2,$0 cal $0,151800 ; Least prime > n (version 2 of the "next prime" function). mov $1,$2 mov $2,$0 mul $2,$1 mul $1,$0 add $1,$2 div $1,2
.global s_prepare_buffers s_prepare_buffers: push %r10 push %rcx push %rdx lea addresses_WC_ht+0xe3a2, %r10 nop nop nop and $7484, %rdx and $0xffffffffffffffc0, %r10 vmovaps (%r10), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $1, %xmm3, %rcx add %rdx, %rdx pop %rdx pop %rcx pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r9 push %rbx push %rcx push %rdi push %rsi // Store lea addresses_US+0xe064, %rsi xor $13139, %rcx mov $0x5152535455565758, %r9 movq %r9, %xmm0 movntdq %xmm0, (%rsi) // Exception!!! nop nop nop nop nop mov (0), %rsi nop nop nop nop nop dec %rdi // Store lea addresses_WT+0x18aa2, %rdi nop nop nop nop nop add $41807, %r13 movl $0x51525354, (%rdi) nop nop nop xor $990, %r10 // Faulty Load lea addresses_RW+0x60a2, %r9 nop nop nop cmp %rdi, %rdi movb (%r9), %r10b lea oracles, %r13 and $0xff, %r10 shlq $12, %r10 mov (%r13,%r10,1), %r10 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_RW', 'congruent': 0}} {'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 16, 'type': 'addresses_US', 'congruent': 1}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT', 'congruent': 7}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_RW', 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': True, 'size': 32, 'type': 'addresses_WC_ht', 'congruent': 7}} {'32': 10} 32 32 32 32 32 32 32 32 32 32 */
; ================================================================== ; The Mike Operating System bootloader ; Copyright (C) 2006 - 2014 MikeOS Developers -- see doc/LICENSE.TXT ; ; Based on a free boot loader by E Dehling. It scans the FAT12 ; floppy for KERNEL.BIN (the MikeOS kernel), loads it and executes it. ; This must grow no larger than 512 bytes (one sector), with the final ; two bytes being the boot signature (AA55h). Note that in FAT12, ; a cluster is the same as a sector: 512 bytes. ; ================================================================== BITS 16 jmp short bootloader_start ; Jump past disk description section nop ; Pad out before disk description ; ------------------------------------------------------------------ ; Disk description table, to make it a valid floppy ; Note: some of these values are hard-coded in the source! ; Values are those used by IBM for 1.44 MB, 3.5" diskette OEMLabel db "MIKEBOOT" ; Disk label BytesPerSector dw 512 ; Bytes per sector SectorsPerCluster db 1 ; Sectors per cluster ReservedForBoot dw 1 ; Reserved sectors for boot record NumberOfFats db 2 ; Number of copies of the FAT RootDirEntries dw 224 ; Number of entries in root dir ; (224 * 32 = 7168 = 14 sectors to read) LogicalSectors dw 2880 ; Number of logical sectors MediumByte db 0F0h ; Medium descriptor byte SectorsPerFat dw 9 ; Sectors per FAT SectorsPerTrack dw 18 ; Sectors per track (36/cylinder) Sides dw 2 ; Number of sides/heads HiddenSectors dd 0 ; Number of hidden sectors LargeSectors dd 0 ; Number of LBA sectors DriveNo dw 0 ; Drive No: 0 Signature db 41 ; Drive signature: 41 for floppy VolumeID dd 00000000h ; Volume ID: any number VolumeLabel db "MIKEOS "; Volume Label: any 11 chars FileSystem db "FAT12 " ; File system type: don't change! ; ------------------------------------------------------------------ ; Main bootloader code bootloader_start: mov ax, 07C0h ; Set up 4K of stack space above buffer add ax, 544 ; 8k buffer = 512 paragraphs + 32 paragraphs (loader) cli ; Disable interrupts while changing stack mov ss, ax mov sp, 4096 sti ; Restore interrupts mov ax, 07C0h ; Set data segment to where we're loaded mov ds, ax ; NOTE: A few early BIOSes are reported to improperly set DL cmp dl, 0 je no_change mov [bootdev], dl ; Save boot device number mov ah, 8 ; Get drive parameters int 13h jc fatal_disk_error and cx, 3Fh ; Maximum sector number mov [SectorsPerTrack], cx ; Sector numbers start at 1 movzx dx, dh ; Maximum head number add dx, 1 ; Head numbers start at 0 - add 1 for total mov [Sides], dx no_change: mov eax, 0 ; Needed for some older BIOSes ; First, we need to load the root directory from the disk. Technical details: ; Start of root = ReservedForBoot + NumberOfFats * SectorsPerFat = logical 19 ; Number of root = RootDirEntries * 32 bytes/entry / 512 bytes/sector = 14 ; Start of user data = (start of root) + (number of root) = logical 33 floppy_ok: ; Ready to read first block of data mov ax, 19 ; Root dir starts at logical sector 19 call l2hts mov si, buffer ; Set ES:BX to point to our buffer (see end of code) mov bx, ds mov es, bx mov bx, si mov ah, 2 ; Params for int 13h: read floppy sectors mov al, 14 ; And read 14 of them pusha ; Prepare to enter loop read_root_dir: popa ; In case registers are altered by int 13h pusha stc ; A few BIOSes do not set properly on error int 13h ; Read sectors using BIOS jnc search_dir ; If read went OK, skip ahead call reset_floppy ; Otherwise, reset floppy controller and try again jnc read_root_dir ; Floppy reset OK? jmp reboot ; If not, fatal double error search_dir: popa mov ax, ds ; Root dir is now in [buffer] mov es, ax ; Set DI to this info mov di, buffer mov cx, word [RootDirEntries] ; Search all (224) entries mov ax, 0 ; Searching at offset 0 next_root_entry: xchg cx, dx ; We use CX in the inner loop... mov si, kern_filename ; Start searching for kernel filename mov cx, 11 rep cmpsb je found_file_to_load ; Pointer DI will be at offset 11 add ax, 32 ; Bump searched entries by 1 (32 bytes per entry) mov di, buffer ; Point to next entry add di, ax xchg dx, cx ; Get the original CX back loop next_root_entry mov si, file_not_found ; If kernel is not found, bail out call print_string jmp reboot found_file_to_load: ; Fetch cluster and load FAT into RAM mov ax, word [es:di+0Fh] ; Offset 11 + 15 = 26, contains 1st cluster mov word [cluster], ax mov ax, 1 ; Sector 1 = first sector of first FAT call l2hts mov di, buffer ; ES:BX points to our buffer mov bx, di mov ah, 2 ; int 13h params: read (FAT) sectors mov al, 9 ; All 9 sectors of 1st FAT pusha ; Prepare to enter loop read_fat: popa ; In case registers are altered by int 13h pusha stc int 13h ; Read sectors using the BIOS jnc read_fat_ok ; If read went OK, skip ahead call reset_floppy ; Otherwise, reset floppy controller and try again jnc read_fat ; Floppy reset OK? ; ****************************************************************** fatal_disk_error: ; ****************************************************************** mov si, disk_error ; If not, print error message and reboot call print_string jmp reboot ; Fatal double error read_fat_ok: popa mov ax, 2000h ; Segment where we'll load the kernel mov es, ax mov bx, 0 mov ah, 2 ; int 13h floppy read params mov al, 1 push ax ; Save in case we (or int calls) lose it ; Now we must load the FAT from the disk. Here's how we find out where it starts: ; FAT cluster 0 = media descriptor = 0F0h ; FAT cluster 1 = filler cluster = 0FFh ; Cluster start = ((cluster number) - 2) * SectorsPerCluster + (start of user) ; = (cluster number) + 31 load_file_sector: mov ax, word [cluster] ; Convert sector to logical add ax, 31 call l2hts ; Make appropriate params for int 13h mov ax, 2000h ; Set buffer past what we've already read mov es, ax mov bx, word [pointer] pop ax ; Save in case we (or int calls) lose it push ax stc int 13h jnc calculate_next_cluster ; If there's no error... call reset_floppy ; Otherwise, reset floppy and retry jmp load_file_sector ; In the FAT, cluster values are stored in 12 bits, so we have to ; do a bit of maths to work out whether we're dealing with a byte ; and 4 bits of the next byte -- or the last 4 bits of one byte ; and then the subsequent byte! calculate_next_cluster: mov ax, [cluster] mov dx, 0 mov bx, 3 mul bx mov bx, 2 div bx ; DX = [cluster] mod 2 mov si, buffer add si, ax ; AX = word in FAT for the 12 bit entry mov ax, word [ds:si] or dx, dx ; If DX = 0 [cluster] is even; if DX = 1 then it's odd jz even ; If [cluster] is even, drop last 4 bits of word ; with next cluster; if odd, drop first 4 bits odd: shr ax, 4 ; Shift out first 4 bits (they belong to another entry) jmp short next_cluster_cont even: and ax, 0FFFh ; Mask out final 4 bits next_cluster_cont: mov word [cluster], ax ; Store cluster cmp ax, 0FF8h ; FF8h = end of file marker in FAT12 jae end add word [pointer], 512 ; Increase buffer pointer 1 sector length jmp load_file_sector end: ; We've got the file to load! pop ax ; Clean up the stack (AX was pushed earlier) mov dl, byte [bootdev] ; Provide kernel with boot device info jmp 2000h:0000h ; Jump to entry point of loaded kernel! ; ------------------------------------------------------------------ ; BOOTLOADER SUBROUTINES reboot: mov ax, 0 int 16h ; Wait for keystroke mov ax, 0 int 19h ; Reboot the system print_string: ; Output string in SI to screen pusha mov ah, 0Eh ; int 10h teletype function .repeat: lodsb ; Get char from string cmp al, 0 je .done ; If char is zero, end of string int 10h ; Otherwise, print it jmp short .repeat .done: popa ret reset_floppy: ; IN: [bootdev] = boot device; OUT: carry set on error push ax push dx mov ax, 0 mov dl, byte [bootdev] stc int 13h pop dx pop ax ret l2hts: ; Calculate head, track and sector settings for int 13h ; IN: logical sector in AX, OUT: correct registers for int 13h push bx push ax mov bx, ax ; Save logical sector mov dx, 0 ; First the sector div word [SectorsPerTrack] add dl, 01h ; Physical sectors start at 1 mov cl, dl ; Sectors belong in CL for int 13h mov ax, bx mov dx, 0 ; Now calculate the head div word [SectorsPerTrack] mov dx, 0 div word [Sides] mov dh, dl ; Head/side mov ch, al ; Track pop ax pop bx mov dl, byte [bootdev] ; Set correct device ret ; ------------------------------------------------------------------ ; STRINGS AND VARIABLES kern_filename db "KERNEL BIN" ; MikeOS kernel filename disk_error db "Floppy error! Press any key...", 0 file_not_found db "KERNEL.BIN not found!", 0 bootdev db 0 ; Boot device number cluster dw 0 ; Cluster of the file we want to load pointer dw 0 ; Pointer into Buffer, for loading kernel ; ------------------------------------------------------------------ ; END OF BOOT SECTOR AND BUFFER START times 510-($-$$) db 0 ; Pad remainder of boot sector with zeros dw 0AA55h ; Boot signature (DO NOT CHANGE!) buffer: ; Disk buffer begins (8k after this, stack starts) ; ==================================================================
; A035276: One seventh of deca-factorial numbers. ; 1,17,459,16983,798201,45497457,3048329619,234721380663,20420760117681,1980813731415057,211947069261411099,24797807103585098583,3149321502155307520041,431457045795277130245617,63424185731905738146105699,9957597159909200888938594743,1662918725704836548452745322081,294336614449756069076135922008337,55040946902104384917237417415559019,10843066539714563828695771230865126743,2244514773720914712540024644789081235801,487059705897438492621185347919230628168817 mov $1,1 mov $2,7 lpb $0 sub $0,1 add $2,10 mul $1,$2 lpe mov $0,$1
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS=FLAG_FPU_PE ;TEST_FILE_META_END FLD1 FLDZ ;TEST_BEGIN_RECORDING FYL2XP1 ;st1 = 1.0 * log2(0 + 1.0) ;TEST_END_RECORDING
INCLUDE "defines.asm" SECTION "Rst $00", ROM0[$00] NULL:: ; This traps jumps to $0000, which is a common "default" pointer ; $FFFF is another one, but reads rIE as the instruction byte ; Thus, we put two `nop`s that may serve as operands, before soft-crashing ; The operand will always be 0, so even jumps will work fine. Nice! nop nop rst Crash SECTION "Rst $08", ROM0[$08] ; Waits for the next VBlank beginning ; Requires the VBlank handler to be able to trigger, otherwise will loop infinitely ; This means IME should be set, the VBlank interrupt should be selected in IE, ; and the LCD should be turned on. ; WARNING: Be careful if calling this with IME reset (`di`), if this was compiled ; with the `-h` flag, then a hardware bug is very likely to cause this routine to ; go horribly wrong. ; Note: the VBlank handler recognizes being called from this function (through `hVBlankFlag`), ; and does not try to save registers if so. To be safe, consider all registers to be destroyed. ; @destroy Possibly every register. The VBlank handler stops preserving anything when executed from this function WaitVBlank:: ld a, 1 ldh [hVBlankFlag], a .wait halt jr .wait SECTION "Rst $10", ROM0[$10 - 1] MemsetLoop: ld a, d assert @ == $10 ; You probably don't want to use this for writing to VRAM while the LCD is on. See LCDMemset. Memset:: ld [hli], a ld d, a dec bc ld a, b or c jr nz, MemsetLoop ret SECTION "Rst $18", ROM0[$18] MemcpySmall:: ld a, [de] ld [hli], a inc de dec c jr nz, MemcpySmall ret SECTION "Rst $20", ROM0[$20] MemsetSmall:: ld [hli], a dec c jr nz, MemsetSmall ret SECTION "Rst $28", ROM0[$28 - 3] ; Dereferences `hl` and jumps there ; All other registers are passed to the called code intact, except Z is reset ; Soft-crashes if the jump target is in RAM ; @param hl Pointer to an address to jump to JumpToPtr:: ld a, [hli] ld h, [hl] ld l, a assert @ == $28 ; Jump to some address ; All registers are passed to the called code intact, except Z is reset ; (`jp CallHL` is equivalent to `jp hl`, but with the extra error checking on top) ; Soft-crashes if attempting to jump to RAM ; @param hl The address of the code to jump to CallHL:: bit 7, h error nz jp hl SECTION "Rst $30", ROM0[$30] ; Jumps to some address ; All registers are passed to the target code intact, except Z is reset ; (`jp CallDE` would be equivalent to `jp de` if that instruction existed) ; Soft-crashes if attempting to jump to RAM ; @param de The address of the code to jump to CallDE:: bit 7, d push de ret z ; No jumping to RAM, boy! rst Crash SECTION "Rst $38", ROM0[$38] ; Perform a soft-crash. Prints debug info on-screen Crash:: di ; Doing this as soon as possible to avoid interrupts messing up jp HandleCrash SECTION "Handlers", ROM0[$40] ; VBlank handler push af ldh a, [hLCDC] ldh [rLCDC], a jp VBlankHandler ds $48 - @ ; STAT handler rst $38 ds $50 - @ ; Timer handler rst $38 ds $58 - @ ; Serial handler rst $38 ds $60 - @ ; Joypad handler (useless) rst $38 SECTION "VBlank handler", ROM0 VBlankHandler: ldh a, [hSCY] ldh [rSCY], a ldh a, [hSCX] ldh [rSCX], a ;ldh a, [hBGP] ;ldh [rBGP], a ;ldh a, [hOBP0] ;ldh [rOBP0], a ;ldh a, [hOBP1] ;ldh [rOBP1], a ; OAM DMA can occur late in the handler, because it will still work even ; outside of VBlank. Sprites just will not appear on the scanline(s) ; during which it's running. ldh a, [hOAMHigh] and a jr z, .noOAMTransfer call hOAMDMA xor a ldh [hOAMHigh], a .noOAMTransfer ; Put all operations that cannot be interrupted above this line ; For example, OAM DMA (can't jump to ROM in the middle of it), ; VRAM accesses (can't screw up timing), etc ei ldh a, [hVBlankFlag] and a jr z, .lagFrame xor a ldh [hVBlankFlag], a ld c, LOW(rP1) ld a, $20 ; Select D-pad ldh [c], a REPT 6 ldh a, [c] ENDR or $F0 ; Set 4 upper bits (give them consistency) ld b, a ; Filter impossible D-pad combinations and $0C ; Filter only Down and Up ld a, b jr nz, .notUpAndDown or $0C ; If both are pressed, "unpress" them ld b, a .notUpAndDown and $03 ; Filter only Left and Right jr nz, .notLeftAndRight ; If both are pressed, "unpress" them inc b inc b inc b .notLeftAndRight swap b ; Put D-pad buttons in upper nibble ld a, $10 ; Select buttons ldh [c], a REPT 6 ldh a, [c] ENDR ; On SsAB held, soft-reset and $0F jr z, .perhapsReset .dontReset or $F0 ; Set 4 upper bits xor b ; Mix with D-pad bits, and invert all bits (such that pressed=1) thanks to "or $F0" ld b, a ; Release joypad ld a, $30 ldh [c], a ldh a, [hHeldKeys] cpl and b ldh [hPressedKeys], a ld a, b ldh [hHeldKeys], a pop af ; Pop off return address as well to exit infinite loop .lagFrame pop af ret .perhapsReset ldh a, [hCanSoftReset] and a jr z, .dontReset jp Reset SECTION "VBlank HRAM", HRAM ; DO NOT TOUCH THIS ; When this flag is set, the VBlank handler will assume the caller is `WaitVBlank`, ; and attempt to exit it. You don't want that to happen outside of that function. hVBlankFlag:: db ; High byte of the address of the OAM buffer to use. ; When this is non-zero, the VBlank handler will write that value to rDMA, and ; reset it. hOAMHigh:: db ; Shadow registers for a bunch of hardware regs. ; Writing to these causes them to take effect more or less immediately, so these ; are copied to the hardware regs by the VBlank handler, taking effect between frames. ; They also come in handy for "resetting" them if modifying them mid-frame for raster FX. hLCDC:: db hSCY:: db hSCX:: db hBGP:: db hOBP0:: db hOBP1:: db ; Keys that are currently being held, and that became held just this frame, respectively. ; Each bit represents a button, with that bit set == button pressed ; Button order: Down, Up, Left, Right, Start, select, B, A ; U+D and L+R are filtered out by software, so they will never happen hHeldKeys:: db hPressedKeys:: db ; If this is 0, pressing SsAB at the same time will not reset the game hCanSoftReset:: db
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r13 push %r14 push %r15 push %r9 push %rbx push %rdi lea addresses_WC_ht+0x56ba, %r13 nop nop xor %r10, %r10 mov $0x6162636465666768, %r15 movq %r15, (%r13) inc %rbx lea addresses_normal_ht+0x1c63a, %r14 nop nop nop sub $23956, %r9 movb $0x61, (%r14) sub %rdi, %rdi lea addresses_A_ht+0x19eba, %r9 cmp %rdi, %rdi movl $0x61626364, (%r9) and $43633, %r15 pop %rdi pop %rbx pop %r9 pop %r15 pop %r14 pop %r13 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %rbp push %rcx // Faulty Load lea addresses_UC+0x1e6ba, %rbp nop nop nop sub $65110, %r12 mov (%rbp), %r14w lea oracles, %r12 and $0xff, %r14 shlq $12, %r14 mov (%r12,%r14,1), %r14 pop %rcx pop %rbp pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': True, 'same': False, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 4}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_UC', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 9, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 7, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 8, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A308570: a(n) = sigma_{2*n}(n). ; 1,17,730,65793,9765626,2177317874,678223072850,281479271743489,150094635684419611,100000095367432689202,81402749386839761113322,79496851942053939878082786,91733330193268616658399616010,123476696151234472370970011268514,191751059232885017991271870136000900,340282367000166625996085689103316680705,684326450885775034048946719925754910487330,1548139828450288992388859497883708742551977331,3914144333903073791808962606796280957916632792442,10995116277770000000000009096155943548898107836724578 add $0,1 mov $2,$0 lpb $0 mov $3,$2 dif $3,$0 cmp $3,$2 cmp $3,0 mul $3,$0 sub $0,1 pow $3,$2 pow $3,2 add $1,$3 lpe add $1,1 mov $0,$1
// stdafx.cpp : source file that includes just the standard includes // CornUnitTest.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
#include "ofApp.h" // we need to include the RegularExpression // header file and say that we are using that // name space #include "Poco/RegularExpression.h" using Poco::RegularExpression; // Some explanation on regular expressions // http://gnosis.cx/publish/programming/regular_expressions.html // more info // http://www.regular-expressions.info/reference.html //-------------------------------------------------------------- void ofApp::setup() { ofBackground(0); page = 0; searchGoogleImages(); } //-------------------------------------------------------------- void ofApp::searchGoogleImages() { // clear old imges images.clear(); urls.clear(); // create the google url string string term = "openframeworks"; string googleImgURL = "http://www.google.com/search?q="+term+"&tbm=isch&sout=1&tbs=isz&&start="+ofToString(page); cout << "seraching for " << googleImgURL << endl; ofHttpResponse res = ofLoadURL(googleImgURL); if(res.status > 0) { // copy over the response date fromt the url load rawData = res.data.getText(); // first we want to get the search contents tag // in the webpage there is a table for all the images. we // want to get the content in the table using // the <table> (.*?) </table> expression RegularExpression regEx("<table width=\"100%\" class=\"images_table\" style=\"table-layout:fixed\">(.*?)</table>"); RegularExpression::Match match; int found = regEx.match(rawData, match); // did we find the table tag with all the images // if so lets now start pulling out all the img tags if(found != 0) { // this is just the table content string contents = rawData.substr(match.offset, match.length); // setup the regex for img tags RegularExpression regEx("<img[^>]*src=\"([^\"]*)"); RegularExpression::Match imgMatch; // now lets search for img tags in the content // we keep search till we run out of img tags while(regEx.match(contents, imgMatch) != 0) { // we get the sub string from the content // and then trim the content so that we // can continue to search string foundStr = contents.substr(imgMatch.offset, imgMatch.length); contents = contents.substr(imgMatch.offset + imgMatch.length); // setup the regex for src attribute in the img tag RegularExpression regImgEx("src=\"(.*?).$"); RegularExpression::Match srcMatch; // if we found the src tag lets grab just // the url from the src attribute if (regImgEx.match(foundStr, srcMatch)!=0) { // save the img url string url = foundStr.substr(srcMatch.offset+5, srcMatch.length); urls.push_back(url); } } // end while } } // load all the images for (unsigned int i=0; i<urls.size(); i++) { images.push_back(URLImage()); images.back().url = urls[i]; images.back().bDoneLoading = false; } // just clean up for rendering to screen ofStringReplace(rawData, "\n", ""); ofStringReplace(rawData, " ", ""); ofStringReplace(rawData, "\t", ""); string str; for (unsigned int i=0; i<rawData.size(); i++) { str += rawData[i]; if(i%40==39) str+="\n"; } rawData = str.substr(0, 2000)+"..."; } //-------------------------------------------------------------- void ofApp::update(){ for(unsigned int i=0; i<images.size(); i++) { if(!images[i].bDoneLoading) { images[i].loadImage(images[i].url); images[i].bDoneLoading = true; break; } } } //-------------------------------------------------------------- void ofApp::draw() { // draw the raw data from google ofSetColor(255); ofDrawBitmapString(rawData, 20, 20); // draw the urls for(unsigned int i=0; i<urls.size(); i++) { ofSetColor(255); ofDrawBitmapString(urls[i].substr(0, 30)+"...", 360, 20+(i*20)); } // draw the urls for(unsigned int i=0; i<urls.size(); i++) { ofSetColor(255); ofDrawBitmapString(urls[i].substr(0, 30)+"...", 360, 20+(i*20)); } // draw the images float x = 0; float y = 0; for(unsigned int i=0; i<images.size(); i++) { ofSetColor(255); images[i].draw(640+x, 20+y); y += images[i].getHeight()+2; if(y > ofGetHeight()-100) { y = 0; x += 200; } } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ page += 22; searchGoogleImages(); } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
; uint8_t z180_inp(uint16_t port) SECTION code_clib SECTION code_z180 PUBLIC _z180_inp_fastcall EXTERN asm_z180_inp defc _z180_inp_fastcall = asm_z180_inp
/*========================================================================= Program: Visualization Toolkit Module: TestNumberToString.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkSmartPointer.h" #include "vtkNumberToString.h" #include "vtkTypeTraits.h" #include <limits> #include <sstream> #include <vtkMinimalStandardRandomSequence.h> namespace { template <typename T> int TestConvert(unsigned int samples); template <typename T> int ConvertNumericLimitsValue(const char* t, T); } int TestNumberToString(int, char*[]) { int status = EXIT_SUCCESS; ; std::cout << "Testing <numeric_limits>..." << std::endl; if (ConvertNumericLimitsValue("unsigned short", static_cast<unsigned short>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("short", static_cast<short>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("unsigned int", static_cast<unsigned int>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("int", static_cast<int>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("unsigned long", static_cast<unsigned long>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("long", static_cast<int>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("float", static_cast<float>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (ConvertNumericLimitsValue("double", static_cast<double>(0)) == EXIT_FAILURE) { status = EXIT_FAILURE; } if (status == EXIT_FAILURE) { return status; } unsigned int samples = 10000; if (TestConvert<float>(samples) || TestConvert<double>(samples)) { return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } namespace { template <typename T> int TestConvert(unsigned int samples) { std::cout << "Testing type: " << typeid(T).name() << std::endl; for (int p = 5; p < 20; ++p) { unsigned int matches = 0; unsigned int mismatches = 0; // Now convert numbers to strings. Read the strings as floats and doubles // and compare the results with the original values. vtkNumberToString convert; { vtkSmartPointer<vtkMinimalStandardRandomSequence> randomSequence = vtkSmartPointer<vtkMinimalStandardRandomSequence>::New(); for (unsigned int i = 0; i < samples; ++i) { randomSequence->Next(); T value = randomSequence->GetRangeValue(-1.0, 1.0); std::stringstream convertedStr; convertedStr << convert(value); std::stringstream rawStr; rawStr << std::setprecision(p) << value; T convertedValue; std::istringstream convertedStream(convertedStr.str()); convertedStream >> convertedValue; if (convertedValue != value) { std::cout << "ERROR: " << value << " != " << convertedValue << std::endl; ++mismatches; } T rawValue; std::istringstream rawStream(rawStr.str()); rawStream >> rawValue; if (rawValue == value) { ++matches; } } } std::cout << "For precision " << p << " Matches without conversion: " << matches << std::endl; std::cout << " MisMatches with conversion: " << mismatches << std::endl; if (mismatches) { return EXIT_FAILURE; } if (matches == samples) { std::cout << "The minimum precision for type " << typeid(T).name() << " is " << p << std::endl; break; } } return EXIT_SUCCESS; } template <typename T> int ConvertNumericLimitsValue(const char* t, T) { vtkNumberToString convert; int status = EXIT_SUCCESS; { T value = std::numeric_limits<T>::max(); std::stringstream convertedStr; convertedStr << convert(value); std::istringstream convertedStream(convertedStr.str()); std::cout << t << "(max) " << "raw: " << value << " converted: " << convertedStream.str() << std::endl; T convertedValue; convertedStream >> convertedValue; if (value != convertedValue) { std::cout << "ERROR: Bad conversion of std::max" << std::endl; status = EXIT_FAILURE; } } { T value = std::numeric_limits<T>::min(); std::stringstream convertedStr; convertedStr << convert(value); std::istringstream convertedStream(convertedStr.str()); std::cout << t << "(min) " << "raw: " << value << " converted: " << convertedStream.str() << std::endl; T convertedValue; convertedStream >> convertedValue; if (value != convertedValue) { std::cout << "ERROR: Bad conversion of std::min" << std::endl; status = EXIT_FAILURE; } } { T value = std::numeric_limits<T>::lowest(); std::stringstream convertedStr; convertedStr << convert(value); std::istringstream convertedStream(convertedStr.str()); std::cout << t << "(lowest) " << "raw: " << value << " converted: " << convertedStream.str() << std::endl; T convertedValue; convertedStream >> convertedValue; if (value != convertedValue) { std::cout << "ERROR: Bad conversion of std::lowest" << std::endl; status = EXIT_FAILURE; } } { T value = std::numeric_limits<T>::epsilon(); std::stringstream convertedStr; convertedStr << convert(value); std::istringstream convertedStream(convertedStr.str()); std::cout << t << "(epsilon) " << "raw: " << value << " converted: " << convertedStream.str() << std::endl; T convertedValue; convertedStream >> convertedValue; if (value != convertedValue) { std::cout << "ERROR: Bad conversion of std::epsilon" << std::endl; status = EXIT_FAILURE; } } return status; } }
; A308741: Decimal expansion of BesselI(1/4,1/2)/BesselI(-3/4,1/2). ; Submitted by Jon Maiga ; 8,3,6,3,3,8,5,3,1,2,0,1,2,9,6,6,0,0,7,6,3,6,7,2,7,9,9,1,1,7,4,6,7,8,2,9,4,3,5,8,5,0,2,9,8,9,5,4,6,6,1,6,1,3,1,7,8,1,1,6,6,3,3,2,1,6,6,4,7,5,3,5,3,9,3,5,8,5,4,2,4,6,2,9,7,5,3,4,3,0,2,4,2,0,4,9,3,9,5,6 add $0,1 mov $2,5 mov $3,$0 mul $3,4 lpb $3 add $5,$2 add $1,$5 add $2,$1 sub $3,2 mul $5,2 mul $5,$3 lpe mov $4,10 pow $4,$0 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
object_const_def ; object_event constants const ROUTE38ECRUTEAKGATE_OFFICER Route38EcruteakGate_MapScripts: db 0 ; scene scripts db 0 ; callbacks Route38EcruteakGateOfficerScript: jumptextfaceplayer Route38EcruteakGateOfficerText Route38EcruteakGateOfficerText: text "Where did you say" line "you're from?" para "NEW BARK TOWN?" para "PROF.ELM lives" line "over there, right?" para "You've come a long" line "way to get here." done Route38EcruteakGate_MapEvents: db 0, 0 ; filler db 4 ; warp events warp_event 0, 4, ROUTE_38, 1 warp_event 0, 5, ROUTE_38, 2 warp_event 9, 4, ECRUTEAK_CITY, 14 warp_event 9, 5, ECRUTEAK_CITY, 15 db 0 ; coord events db 0 ; bg events db 1 ; object events object_event 5, 2, SPRITE_OFFICER, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, Route38EcruteakGateOfficerScript, -1
; A very simple printing routine for use in 32 bit protected mode since ; we won't be able to use the BIOS once we make the switch into 32 bit protected mode ; This function doesn't scroll, all prints start at the upper left corner. ; The address of the first character of the string to be printed should be passed ; in EBX. [bits 32] ; Useful constants. VIDEO_MEMORY equ 0xb8000 ; Address of the 1st pair of bytes (ASCII code + ; character attributes) for the screen device in text mode. WHITE_ON_BLACK equ 0x0f ; Character attributes - fore/back-ground color. ; print a null terminated string point to by EBX print_string_pm: pusha mov edx, VIDEO_MEMORY ; Point EDX to start of video memory for text mode. print_string_pm_loop: mov al, [ebx] ; Store the character at EBX in AL. mov ah, WHITE_ON_BLACK ; Store the character attributes in AH cmp al, 0 ; Check if this is the end of the string. je print_string_pm_done mov [edx], ax ; Store the character and its attributes at the current character ; cell. add ebx, 1 ; Advance to the next character of the string. add edx, 2 ; Advance to the next pair of bytes in video memory text mode. jmp print_string_pm_loop ; Repeat. print_string_pm_done: popa ret
#ifndef ROSUNIT_RESETSRV_HPP #define ROSUNIT_RESETSRV_HPP #include <ros/ros.h> #include <std_srvs/Empty.h> #include <string> #include "HEAR_core/ExternalTrigger.hpp" namespace HEAR{ class ROSUnit_ResetServer { private: ros::NodeHandle nh_; ResetTrigger* ext_trig; ros::ServiceServer m_server; bool srv_callback(std_srvs::EmptyRequest&, std_srvs::EmptyResponse&); public: ROSUnit_ResetServer(ros::NodeHandle&); ResetTrigger* registerServer(const std::string&); }; } #endif
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld a, 30 ldff(00), a ld a, 01 ldff(4d), a stop, 00 ld b, 98 call lwaitly_b ld a, 01 ldff(45), a ld a, 40 ldff(41), a ld a, 00 ld(8000), a ld a, 01 ld(c000), a ld a, c0 ldff(51), a xor a, a ldff(52), a ldff(54), a ld a, 80 ldff(53), a xor a, a ldff(0f), a ld a, 02 ldff(ff), a ei ld hl, 8000 ld a, 05 ldff(43), a halt .text@1000 lstatint: ld a, 80 ldff(55), a ld b, 03 .text@1146 ldff a, (41) and a, b jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f
// // Copyright © 2020 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include "IFrameReader.hpp" #include <opencv2/opencv.hpp> namespace od { class CvVideoFrameReader : public IFrameReader<cv::Mat> { public: /** * @brief Default constructor. * * Underlying open cv video capture object will be instantiated. */ CvVideoFrameReader() = default; ~CvVideoFrameReader() override = default; /** *@brief Initialises reader to capture frames from video file. * * @param source path to the video file or image sequence. * * @throws std::runtime_error if init failed */ void Init(const std::string& source); std::shared_ptr <cv::Mat> ReadFrame() override; bool IsExhausted(const std::shared_ptr <cv::Mat>& frame) const override; /** * Returns effective video frame width supported by the source/set by the user. * Must be called after Init method. * @return frame width */ int GetSourceWidth() const; /** * Returns effective video frame height supported by the source/set by the user. * Must be called after Init method. * @return frame height */ int GetSourceHeight() const; /** * Returns effective fps value supported by the source/set by the user. * @return fps value */ double GetSourceFps() const; /** * Will query OpenCV to convert images to RGB * Copy is actually default behaviour, but the set function needs to be called * in order to know whether OpenCV supports conversion from our source format. * @return boolean, * true: OpenCV returns RGB * false: OpenCV returns the fourcc format from GetSourceEncoding */ bool ConvertToRGB(); /** * Returns 4-character code of codec. * @return codec name */ std::string GetSourceEncoding() const; /** * Get the fourcc int from its string name. * @return codec int */ int GetSourceEncodingInt() const; int GetFrameCount() const; private: cv::VideoCapture m_capture; void CheckIsOpen(const std::string& source); }; class CvVideoFrameReaderRgbWrapper : public IFrameReader<cv::Mat> { public: CvVideoFrameReaderRgbWrapper() = delete; CvVideoFrameReaderRgbWrapper(const CvVideoFrameReaderRgbWrapper& o) = delete; CvVideoFrameReaderRgbWrapper(CvVideoFrameReaderRgbWrapper&& o) = delete; CvVideoFrameReaderRgbWrapper(std::unique_ptr<od::CvVideoFrameReader> reader); std::shared_ptr<cv::Mat> ReadFrame() override; bool IsExhausted(const std::shared_ptr<cv::Mat>& frame) const override; private: std::unique_ptr<od::CvVideoFrameReader> m_reader; }; }// namespace od
; A100451: a(n) = 0 for n <= 2; for n >= 3, a(n) = (n-2)*floor((n^2-2)/(n-2)). ; 0,0,7,14,21,32,45,60,77,96,117,140,165,192,221,252,285,320,357,396,437,480,525,572,621,672,725,780,837,896,957,1020,1085,1152,1221,1292,1365,1440,1517,1596,1677,1760,1845,1932,2021,2112,2205,2300,2397,2496,2597,2700,2805,2912,3021,3132,3245,3360,3477,3596,3717,3840,3965,4092,4221,4352,4485,4620,4757,4896,5037,5180,5325,5472,5621,5772,5925,6080,6237,6396,6557,6720,6885,7052,7221,7392,7565,7740,7917,8096,8277,8460,8645,8832,9021,9212,9405,9600,9797,9996,10197,10400,10605,10812,11021,11232,11445,11660,11877,12096,12317,12540,12765,12992,13221,13452,13685,13920,14157,14396,14637,14880,15125,15372,15621,15872,16125,16380,16637,16896,17157,17420,17685,17952,18221,18492,18765,19040,19317,19596,19877,20160,20445,20732,21021,21312,21605,21900,22197,22496,22797,23100,23405,23712,24021,24332,24645,24960,25277,25596,25917,26240,26565,26892,27221,27552,27885,28220,28557,28896,29237,29580,29925,30272,30621,30972,31325,31680,32037,32396,32757,33120,33485,33852,34221,34592,34965,35340,35717,36096,36477,36860,37245,37632,38021,38412,38805,39200,39597,39996,40397,40800,41205,41612,42021,42432,42845,43260,43677,44096,44517,44940,45365,45792,46221,46652,47085,47520,47957,48396,48837,49280,49725,50172,50621,51072,51525,51980,52437,52896,53357,53820,54285,54752,55221,55692,56165,56640,57117,57596,58077,58560,59045,59532,60021,60512,61005,61500,61997,62496 mov $2,$0 sub $0,1 trn $2,4 add $2,3 lpb $0,1 sub $0,1 add $1,$2 add $1,4 lpe
section .text global _start ;must be declared for linker (ld) _start: ;tell linker entry point xor ebx,ebx ;ebx=0 mov ecx,msg ;address of message to write lea edx,[ebx+len] ;message length lea eax,[ebx+4] ;system call number (sys_write) inc ebx ;file descriptor (stdout) int 0x80 ;call kernel xor eax, eax ;set eax=0 inc eax ;system call number (sys_exit) int 0x80 ;call kernel section .rodata msg db 'Hello, world!',0xa ;our string len equ $ - msg ;length of our string
CopycatsHouse1FObject: db $a ; border block db $3 ; warps db $7, $2, $0, $ff db $7, $3, $0, $ff db $1, $7, $0, COPYCATS_HOUSE_2F db $0 ; signs db $3 ; objects object SPRITE_MOM_GEISHA, $2, $2, STAY, DOWN, $1 ; person object SPRITE_FAT_BALD_GUY, $5, $4, STAY, LEFT, $2 ; person object SPRITE_CHANSEY, $1, $4, STAY, NONE, $3 ; person ; warp-to EVENT_DISP COPYCATS_HOUSE_1F_WIDTH, $7, $2 EVENT_DISP COPYCATS_HOUSE_1F_WIDTH, $7, $3 EVENT_DISP COPYCATS_HOUSE_1F_WIDTH, $1, $7 ; COPYCATS_HOUSE_2F
; A161731: Expansion of (1-3*x)/(1-8*x+14*x^2). ; Submitted by Christian Krause ; 1,5,26,138,740,3988,21544,116520,630544,3413072,18476960,100032672,541583936,2932214080,15875537536,85953303168,465368899840,2519604954368,13641675037184,73858930936320,399887996969984,2165078942651392,11722199583631360,63466491471931392,343621137604612096,1860438220229857280,10072809835374288896,54536343599776309248,295271411102970429440,1598662478426895106048,8655500071973574836224,46862725877812067205120,253724806014866489933824,1373720285829562978598912,7437615002428372969717760 mov $1,1 mov $3,1 lpb $0 sub $0,1 mov $2,$3 mul $2,2 mul $3,4 add $3,$1 mul $1,4 add $1,$2 lpe mov $0,$3
; void *tshr_saddrcup(void *saddr) SECTION code_clib SECTION code_arch PUBLIC _tshr_saddrcup_fastcall EXTERN _zx_saddrcup_fastcall defc _tshr_saddrcup_fastcall = _zx_saddrcup_fastcall
;; ;; Copyright (c) 2019, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %include "include/aesni_emu.inc" %define AES128_CBC_MAC aes128_cbc_mac_x4_no_aesni %define SUBMIT_JOB_AES_CCM_AUTH submit_job_aes_ccm_auth_sse_no_aesni %define FLUSH_JOB_AES_CCM_AUTH flush_job_aes_ccm_auth_sse_no_aesni %include "sse/mb_mgr_aes_ccm_auth_submit_flush_sse.asm"
; A089255: Odd numbers n such that 2*n-5 is a prime. ; 5,9,11,17,21,23,29,33,39,47,51,53,57,59,71,77,81,89,93,99,101,117,119,123,131,137,141,143,149,159,161,171,177,179,189,197,201,203,207,213,219,227,231,233,257,263,273,281,287,291,299,303,309,311,323,329,333 mov $2,$0 add $2,2 pow $2,2 lpb $2 sub $2,1 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,4 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe sub $1,2 div $1,2 add $1,2 mov $0,$1
.model tiny .data A db 1,-2,-3,-4,-5,-6,7,-8,9,-10 .code N: push cs pop ds xor ax,ax xor bx,bx mov cx,10 M: cmp A[bx],0 jg K mov A[bx],0 K: inc bx loop M mov ax,4c00h int 21h end N
; A120140: a(1)=13; a(n)=floor((26+sum(a(1) to a(n-1)))/2). ; 13,19,29,43,65,97,146,219,328,492,738,1107,1661,2491,3737,5605,8408,12612,18918,28377,42565,63848,95772,143658,215487,323230,484845,727268,1090902,1636353,2454529,3681794,5522691,8284036,12426054,18639081 add $0,1 mov $2,2 lpb $0 sub $0,1 mov $1,$2 div $1,2 add $2,8 add $2,$1 add $2,4 lpe add $1,12
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r14 push %r9 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0xc625, %rsi clflush (%rsi) nop nop nop nop sub $2581, %r9 mov (%rsi), %bx nop nop nop nop sub $58258, %r9 lea addresses_D_ht+0xe67, %rsi lea addresses_WC_ht+0x1db47, %rdi nop nop dec %r14 mov $99, %rcx rep movsl nop nop nop xor $37734, %r9 lea addresses_A_ht+0x554b, %r14 nop nop sub $34782, %r12 mov (%r14), %ebx nop sub $2587, %r14 lea addresses_D_ht+0x1e1a7, %rsi lea addresses_D_ht+0xe891, %rdi nop nop nop nop nop xor $11275, %rdx mov $81, %rcx rep movsq nop nop sub $48511, %rdx lea addresses_normal_ht+0xe267, %rsi lea addresses_WC_ht+0x5a67, %rdi nop nop xor $20799, %r9 mov $87, %rcx rep movsb and $48269, %rdi lea addresses_WC_ht+0x1ea73, %rsi nop nop nop nop nop and %rdx, %rdx movups (%rsi), %xmm7 vpextrq $1, %xmm7, %rcx nop nop nop nop nop add %rdi, %rdi lea addresses_D_ht+0xb0a7, %rdx nop nop nop inc %r9 movw $0x6162, (%rdx) nop xor %rbx, %rbx lea addresses_WC_ht+0x3367, %r12 nop nop nop nop nop xor %r14, %r14 mov (%r12), %rdx add $29105, %rdx lea addresses_UC_ht+0x158c1, %rdx nop nop nop nop sub $3572, %r14 movw $0x6162, (%rdx) nop nop xor $52998, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r14 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %rax push %rbp push %rdi push %rsi // Store lea addresses_normal+0x1fe67, %rbp clflush (%rbp) nop nop xor $49901, %rax mov $0x5152535455565758, %r13 movq %r13, %xmm1 vmovups %ymm1, (%rbp) nop nop nop nop cmp %r11, %r11 // Store lea addresses_D+0x53e7, %rax nop nop nop nop nop xor $26183, %r15 movl $0x51525354, (%rax) nop nop nop add $30141, %rax // Load lea addresses_PSE+0x7be7, %rdi nop nop nop nop and %rsi, %rsi mov (%rdi), %r13 nop nop nop nop nop add $58475, %rax // Faulty Load lea addresses_D+0x12e67, %rsi nop nop nop nop cmp $19183, %rbp mov (%rsi), %ax lea oracles, %rsi and $0xff, %rax shlq $12, %rax mov (%rsi,%rax,1), %rax pop %rsi pop %rdi pop %rbp pop %rax pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_D_ht', 'congruent': 1, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'36': 637} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "init.h" #include "base58.h" using namespace json_spirit; using namespace std; int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); static void accountingDeprecationCheck() { if (!GetBoolArg("-enableaccounts", false)) throw runtime_error( "Accounting API is deprecated and will be removed in future.\n" "It can easily result in negative or odd balances if misused or misunderstood, which has happened in the field.\n" "If you still want to enable it, add to your config file enableaccounts=1\n"); if (GetBoolArg("-staking", true)) throw runtime_error("If you want to use accounting API, staking must be disabled, add to your config file staking=0\n"); } std::string HelpRequiringPassphrase() { return pwalletMain->IsCrypted() ? "\nrequires wallet passphrase to be set with walletpassphrase first" : ""; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); if (fWalletUnlockStakingOnly) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet is unlocked for staking only."); } void WalletTxToJSON(const CWalletTx& wtx, Object& entry) { int confirms = wtx.GetDepthInMainChain(); entry.push_back(Pair("confirmations", confirms)); if (wtx.IsCoinBase() || wtx.IsCoinStake()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", (int64_t)(mapBlockIndex[wtx.hashBlock]->nTime))); } entry.push_back(Pair("txid", wtx.GetHash().GetHex())); entry.push_back(Pair("time", (int64_t)wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } string AccountFromValue(const Value& value) { string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } Value getinfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getinfo\n" "Returns an object containing various state info."); proxyType proxy; GetProxy(NET_IPV4, proxy); Object obj, diff; obj.push_back(Pair("version", FormatFullVersion())); obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION)); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint()))); obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake()))); obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("timeoffset", (int64_t)GetTimeOffset())); obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply))); obj.push_back(Pair("connections", (int)vNodes.size())); obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string()))); obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP())); diff.push_back(Pair("proof-of-work", GetDifficulty())); diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true)))); obj.push_back(Pair("difficulty", diff)); obj.push_back(Pair("testnet", fTestNet)); obj.push_back(Pair("keypoololdest", (int64_t)pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize())); obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee))); obj.push_back(Pair("mininput", ValueFromAmount(nMinimumInputValue))); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", (int64_t)nWalletUnlockTime / 1000)); obj.push_back(Pair("errors", GetWarnings("statusbar"))); return obj; } Value getnewpubkey(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewpubkey [account]\n" "Returns new public key for coinbase generation."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); vector<unsigned char> vchPubKey = newKey.Raw(); return HexStr(vchPubKey.begin(), vchPubKey.end()); } Value getnewaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getnewaddress [account]\n" "Returns a new CryptoRevenueToken address for receiving payments. " "If [account] is specified, it is added to the address book " "so payments received with the address will be credited to [account]."); // Parse the account first so we don't generate a key if there's an error string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked()) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBookName(keyID, strAccount); return CBitcoinAddress(keyID).ToString(); } CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey; scriptPubKey.SetDestination(account.vchPubKey.GetID()); for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount); walletdb.WriteAccount(strAccount, account); } return CBitcoinAddress(account.vchPubKey.GetID()); } Value getaccountaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccountaddress <account>\n" "Returns the current CryptoRevenueToken address for receiving payments to this account."); // Parse the account first so we don't generate a key if there's an error string strAccount = AccountFromValue(params[0]); Value ret; ret = GetAccountAddress(strAccount).ToString(); return ret; } Value setaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setaccount <CryptoRevenueTokenaddress> <account>\n" "Sets the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoRevenueToken address"); string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { string strOldAccount = pwalletMain->mapAddressBook[address.Get()]; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBookName(address.Get(), strAccount); return Value::null; } Value getaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaccount <CryptoRevenueTokenaddress>\n" "Returns the account associated with the given address."); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoRevenueToken address"); string strAccount; map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty()) strAccount = (*mi).second; return strAccount; } Value getaddressesbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "getaddressesbyaccount <account>\n" "Returns the list of addresses for the given account."); string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account Array ret; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strName = item.second; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } Value sendtoaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendtoaddress <CryptoRevenueTokenaddress> <amount> [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); CBitcoinAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoRevenueToken address"); // Amount int64_t nAmount = AmountFromValue(params[1]); // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value listaddressgroupings(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listaddressgroupings\n" "Lists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions"); Array jsonGroupings; map<CTxDestination, int64_t> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { Array jsonGrouping; BOOST_FOREACH(CTxDestination address, grouping) { Array addressInfo; addressInfo.push_back(CBitcoinAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { LOCK(pwalletMain->cs_wallet); if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } Value signmessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "signmessage <CryptoRevenueTokenaddress> <message>\n" "Sign a message with the private key of an address"); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strMessage = params[1].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; vector<unsigned char> vchSig; if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } Value verifymessage(const Array& params, bool fHelp) { if (fHelp || params.size() != 3) throw runtime_error( "verifymessage <CryptoRevenueTokenaddress> <signature> <message>\n" "Verify a signed message"); string strAddress = params[0].get_str(); string strSign = params[1].get_str(); string strMessage = params[2].get_str(); CBitcoinAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); bool fInvalid = false; vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid); if (fInvalid) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding"); CDataStream ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; CKey key; if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig)) return false; return (key.GetPubKey().GetID() == keyID); } Value getreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaddress <CryptoRevenueTokenaddress> [minconf=1]\n" "Returns the total amount received by <CryptoRevenueTokenaddress> in transactions with at least [minconf] confirmations."); // Bitcoin address CBitcoinAddress address = CBitcoinAddress(params[0].get_str()); CScript scriptPubKey; if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoRevenueToken address"); scriptPubKey.SetDestination(address.Get()); if (!IsMine(*pwalletMain,scriptPubKey)) return (double)0.0; // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second; if (strName == strAccount) setAddress.insert(address); } } Value getreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getreceivedbyaccount <account> [minconf=1]\n" "Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations."); accountingDeprecationCheck(); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account string strAccount = AccountFromValue(params[0]); set<CTxDestination> setAddress; GetAccountAddresses(strAccount, setAddress); // Tally int64_t nAmount = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return (double)nAmount / (double)COIN; } int64_t GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth) { int64_t nBalance = 0; // Tally wallet transactions for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!IsFinalTx(wtx) || wtx.GetDepthInMainChain() < 0) continue; int64_t nReceived, nSent, nFee; wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee); if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) nBalance += nReceived; nBalance -= nSent + nFee; } // Tally internal accounting entries nBalance += walletdb.GetAccountCreditDebit(strAccount); return nBalance; } int64_t GetAccountBalance(const string& strAccount, int nMinDepth) { CWalletDB walletdb(pwalletMain->strWalletFile); return GetAccountBalance(walletdb, strAccount, nMinDepth); } Value getbalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getbalance [account] [minconf=1]\n" "If [account] is not specified, returns the server's total available balance.\n" "If [account] is specified, returns the balance in the account."); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and getbalance '*' 0 should return the same number. int64_t nBalance = 0; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!wtx.IsTrusted()) continue; int64_t allFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount); if (wtx.GetDepthInMainChain() >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) nBalance += r.second; } BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listSent) nBalance -= r.second; nBalance -= allFee; } return ValueFromAmount(nBalance); } accountingDeprecationCheck(); string strAccount = AccountFromValue(params[0]); int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); return ValueFromAmount(nBalance); } Value movecmd(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 5) throw runtime_error( "move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n" "Move from one account in your wallet to another."); accountingDeprecationCheck(); string strFrom = AccountFromValue(params[0]); string strTo = AccountFromValue(params[1]); int64_t nAmount = AmountFromValue(params[2]); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; walletdb.WriteAccountingEntry(debit); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; walletdb.WriteAccountingEntry(credit); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } Value sendfrom(const Array& params, bool fHelp) { if (fHelp || params.size() < 3 || params.size() > 6) throw runtime_error( "sendfrom <fromaccount> <toCryptoRevenueTokenaddress> <amount> [minconf=1] [comment] [comment-to]\n" "<amount> is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); CBitcoinAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CryptoRevenueToken address"); int64_t nAmount = AmountFromValue(params[2]); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); return wtx.GetHash().GetHex(); } Value sendmany(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 4) throw runtime_error( "sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n" "amounts are double-precision floating point numbers" + HelpRequiringPassphrase()); string strAccount = AccountFromValue(params[0]); Object sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); set<CBitcoinAddress> setAddress; vector<pair<CScript, int64_t> > vecSend; int64_t totalAmount = 0; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid CryptoRevenueToken address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64_t nAmount = AmountFromValue(s.value_); totalAmount += nAmount; vecSend.push_back(make_pair(scriptPubKey, nAmount)); } EnsureWalletIsUnlocked(); // Check funds int64_t nBalance = GetAccountBalance(strAccount, nMinDepth); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); int64_t nFeeRequired = 0; bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed"); } if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } Value addmultisigaddress(const Array& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) { string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n" "Add a nrequired-to-sign multisignature address to the wallet\"\n" "each key is a CryptoRevenueToken address or hex-encoded public key\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } int nRequired = params[0].get_int(); const Array& keys = params[1].get_array(); string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Gather public keys if (nRequired < 1) throw runtime_error("a multisignature address must require at least one key to redeem"); if ((int)keys.size() < nRequired) throw runtime_error( strprintf("not enough keys supplied " "(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired)); std::vector<CKey> pubkeys; pubkeys.resize(keys.size()); for (unsigned int i = 0; i < keys.size(); i++) { const std::string& ks = keys[i].get_str(); // Case 1: Bitcoin address and we have full public key: CBitcoinAddress address(ks); if (address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) throw runtime_error( strprintf("%s does not refer to a key",ks.c_str())); CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s",ks.c_str())); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } // Case 2: hex public key else if (IsHex(ks)) { CPubKey vchPubKey(ParseHex(ks)); if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey)) throw runtime_error(" Invalid public key: "+ks); } else { throw runtime_error(" Invalid public key: "+ks); } } // Construct using pay-to-script-hash: CScript inner; inner.SetMultisig(nRequired, pubkeys); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } Value addredeemscript(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) { string msg = "addredeemscript <redeemScript> [account]\n" "Add a P2SH address with a specified redeemScript to the wallet.\n" "If [account] is specified, assign address to [account]."; throw runtime_error(msg); } string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Construct using pay-to-script-hash: vector<unsigned char> innerData = ParseHexV(params[0], "redeemScript"); CScript inner(innerData.begin(), innerData.end()); CScriptID innerID = inner.GetID(); if (!pwalletMain->AddCScript(inner)) throw runtime_error("AddCScript() failed"); pwalletMain->SetAddressBookName(innerID, strAccount); return CBitcoinAddress(innerID).ToString(); } struct tallyitem { int64_t nAmount; int nConf; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); } }; Value ListReceived(const Array& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); // Tally map<CBitcoinAddress, tallyitem> mapTally; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || wtx.IsCoinStake() || !IsFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = min(item.nConf, nDepth); } } // Reply Array ret; map<string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook) { const CBitcoinAddress& address = item.first; const string& strAccount = item.second; map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; int64_t nAmount = 0; int nConf = std::numeric_limits<int>::max(); if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; } if (fByAccounts) { tallyitem& item = mapAccountTally[strAccount]; item.nAmount += nAmount; item.nConf = min(item.nConf, nConf); } else { Object obj; obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } if (fByAccounts) { for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { int64_t nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; Object obj; obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); ret.push_back(obj); } } return ret; } Value listreceivedbyaddress(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaddress [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include addresses that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"address\" : receiving address\n" " \"account\" : the account of the receiving address\n" " \"amount\" : total amount received by the address\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); return ListReceived(params, false); } Value listreceivedbyaccount(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "listreceivedbyaccount [minconf=1] [includeempty=false]\n" "[minconf] is the minimum number of confirmations before payments are included.\n" "[includeempty] whether to include accounts that haven't received any payments.\n" "Returns an array of objects containing:\n" " \"account\" : the account of the receiving addresses\n" " \"amount\" : total amount received by addresses with this account\n" " \"confirmations\" : number of confirmations of the most recent transaction included"); accountingDeprecationCheck(); return ListReceived(params, true); } static void MaybePushAddress(Object & entry, const CTxDestination &dest) { CBitcoinAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret) { int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); bool fAllAccounts = (strAccount == string("*")); // Sent if ((!wtx.IsCoinStake()) && (!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) { Object entry; entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.first); entry.push_back(Pair("category", "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.second))); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { bool stop = false; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) { string account; if (pwalletMain->mapAddressBook.count(r.first)) account = pwalletMain->mapAddressBook[r.first]; if (fAllAccounts || (account == strAccount)) { Object entry; entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.first); if (wtx.IsCoinBase() || wtx.IsCoinStake()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } if (!wtx.IsCoinStake()) entry.push_back(Pair("amount", ValueFromAmount(r.second))); else { entry.push_back(Pair("amount", ValueFromAmount(-nFee))); stop = true; // only one coinstake output } if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } if (stop) break; } } } void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret) { bool fAllAccounts = (strAccount == string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { Object entry; entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", (int64_t)acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } Value listtransactions(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listtransactions [account] [count=10] [from=0]\n" "Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]."); string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); Array ret; std::list<CAccountingEntry> acentries; CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount); // iterate backwards until we have nCount items to return: for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; Array::iterator first = ret.begin(); std::advance(first, nFrom); Array::iterator last = ret.begin(); std::advance(last, nFrom+nCount); if (last != ret.end()) ret.erase(last, ret.end()); if (first != ret.begin()) ret.erase(ret.begin(), first); std::reverse(ret.begin(), ret.end()); // Return oldest to newest return ret; } Value listaccounts(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "listaccounts [minconf=1]\n" "Returns Object that has account names as keys, account balances as values."); accountingDeprecationCheck(); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); map<string, int64_t> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first)) // This address belongs to me mapAccountBalances[entry.second] = 0; } for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; int64_t nFee; string strSentAccount; list<pair<CTxDestination, int64_t> > listReceived; list<pair<CTxDestination, int64_t> > listSent; int nDepth = wtx.GetDepthInMainChain(); if (nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& s, listSent) mapAccountBalances[strSentAccount] -= s.second; if (nDepth >= nMinDepth && wtx.GetBlocksToMaturity() == 0) { BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64_t)& r, listReceived) if (pwalletMain->mapAddressBook.count(r.first)) mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second; else mapAccountBalances[""] += r.second; } } list<CAccountingEntry> acentries; CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries); BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; Object ret; BOOST_FOREACH(const PAIRTYPE(string, int64_t)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } Value listsinceblock(const Array& params, bool fHelp) { if (fHelp) throw runtime_error( "listsinceblock [blockhash] [target-confirmations]\n" "Get all transactions in blocks since block [blockhash], or all transactions if omitted"); CBlockIndex *pindex = NULL; int target_confirms = 1; if (params.size() > 0) { uint256 blockId = 0; blockId.SetHex(params[0].get_str()); pindex = CBlockLocator(blockId).GetBlockIndex(); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1; Array transactions; for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain() < depth) ListTransactions(tx, "*", 0, true, transactions); } uint256 lastblock; if (target_confirms == 1) { lastblock = hashBestChain; } else { int target_height = pindexBest->nHeight + 1 - target_confirms; CBlockIndex *block; for (block = pindexBest; block && block->nHeight > target_height; block = block->pprev) { } lastblock = block ? block->GetBlockHash() : 0; } Object ret; ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } Value gettransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "gettransaction <txid>\n" "Get detailed information about <txid>"); uint256 hash; hash.SetHex(params[0].get_str()); Object entry; if (pwalletMain->mapWallet.count(hash)) { const CWalletTx& wtx = pwalletMain->mapWallet[hash]; TxToJSON(wtx, 0, entry); int64_t nCredit = wtx.GetCredit(); int64_t nDebit = wtx.GetDebit(); int64_t nNet = nCredit - nDebit; int64_t nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe()) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); Array details; ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details); entry.push_back(Pair("details", details)); } else { CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock)) { TxToJSON(tx, 0, entry); if (hashBlock == 0) entry.push_back(Pair("confirmations", 0)); else { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); else entry.push_back(Pair("confirmations", 0)); } } } else throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); } return entry; } Value backupwallet(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "backupwallet <destination>\n" "Safely copies wallet.dat to destination, which can be a directory or a path with filename."); string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return Value::null; } Value keypoolrefill(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "keypoolrefill [new-size]\n" "Fills the keypool." + HelpRequiringPassphrase()); unsigned int nSize = max(GetArg("-keypool", 100), (int64_t)0); if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size"); nSize = (unsigned int) params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(nSize); if (pwalletMain->GetKeyPoolSize() < nSize) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return Value::null; } void ThreadTopUpKeyPool(void* parg) { // Make this thread recognisable as the key-topping-up thread RenameThread("CryptoRevenueToken-key-top"); pwalletMain->TopUpKeyPool(); } void ThreadCleanWalletPassphrase(void* parg) { // Make this thread recognisable as the wallet relocking thread RenameThread("CryptoRevenueToken-lock-wa"); int64_t nMyWakeTime = GetTimeMillis() + *((int64_t*)parg) * 1000; ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); if (nWalletUnlockTime == 0) { nWalletUnlockTime = nMyWakeTime; do { if (nWalletUnlockTime==0) break; int64_t nToSleep = nWalletUnlockTime - GetTimeMillis(); if (nToSleep <= 0) break; LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); MilliSleep(nToSleep); ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime); } while(1); if (nWalletUnlockTime) { nWalletUnlockTime = 0; pwalletMain->Lock(); } } else { if (nWalletUnlockTime < nMyWakeTime) nWalletUnlockTime = nMyWakeTime; } LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime); delete (int64_t*)parg; } Value walletpassphrase(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw runtime_error( "walletpassphrase <passphrase> <timeout> [stakingonly]\n" "Stores the wallet decryption key in memory for <timeout> seconds.\n" "if [stakingonly] is true sending functions are disabled."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() > 0) { if (!pwalletMain->Unlock(strWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); } else throw runtime_error( "walletpassphrase <passphrase> <timeout>\n" "Stores the wallet decryption key in memory for <timeout> seconds."); NewThread(ThreadTopUpKeyPool, NULL); int64_t* pnSleepTime = new int64_t(params[1].get_int64()); NewThread(ThreadCleanWalletPassphrase, pnSleepTime); // ppcoin: if user OS account compromised prevent trivial sendmoney commands if (params.size() > 2) fWalletUnlockStakingOnly = params[2].get_bool(); else fWalletUnlockStakingOnly = false; return Value::null; } Value walletpassphrasechange(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return Value::null; } Value walletlock(const Array& params, bool fHelp) { if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw runtime_error( "walletlock\n" "Removes the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked."); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return Value::null; } Value encryptwallet(const Array& params, bool fHelp) { if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "wallet encrypted; CryptoRevenueToken server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup."; } class DescribeAddressVisitor : public boost::static_visitor<Object> { public: Object operator()(const CNoDestination &dest) const { return Object(); } Object operator()(const CKeyID &keyID) const { Object obj; CPubKey vchPubKey; pwalletMain->GetPubKey(keyID, vchPubKey); obj.push_back(Pair("isscript", false)); obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw()))); obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed())); return obj; } Object operator()(const CScriptID &scriptID) const { Object obj; obj.push_back(Pair("isscript", true)); CScript subscript; pwalletMain->GetCScript(scriptID, subscript); std::vector<CTxDestination> addresses; txnouttype whichType; int nRequired; ExtractDestinations(subscript, whichType, addresses, nRequired); obj.push_back(Pair("script", GetTxnOutputType(whichType))); obj.push_back(Pair("hex", HexStr(subscript.begin(), subscript.end()))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); obj.push_back(Pair("addresses", a)); if (whichType == TX_MULTISIG) obj.push_back(Pair("sigsrequired", nRequired)); return obj; } }; Value validateaddress(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "validateaddress <CryptoRevenueTokenaddress>\n" "Return information about <CryptoRevenueTokenaddress>."); CBitcoinAddress address(params[0].get_str()); bool isValid = address.IsValid(); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } Value validatepubkey(const Array& params, bool fHelp) { if (fHelp || !params.size() || params.size() > 2) throw runtime_error( "validatepubkey <CryptoRevenueTokenpubkey>\n" "Return information about <CryptoRevenueTokenpubkey>."); std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str()); CPubKey pubKey(vchPubKey); bool isValid = pubKey.IsValid(); bool isCompressed = pubKey.IsCompressed(); CKeyID keyID = pubKey.GetID(); CBitcoinAddress address; address.Set(keyID); Object ret; ret.push_back(Pair("isvalid", isValid)); if (isValid) { CTxDestination dest = address.Get(); string currentAddress = address.ToString(); ret.push_back(Pair("address", currentAddress)); bool fMine = IsMine(*pwalletMain, dest); ret.push_back(Pair("ismine", fMine)); ret.push_back(Pair("iscompressed", isCompressed)); if (fMine) { Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest); ret.insert(ret.end(), detail.begin(), detail.end()); } if (pwalletMain->mapAddressBook.count(dest)) ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest])); } return ret; } // ppcoin: reserve balance from being staked for network protection Value reservebalance(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "reservebalance [<reserve> [amount]]\n" "<reserve> is true or false to turn balance reserve on or off.\n" "<amount> is a real and rounded to cent.\n" "Set reserve amount not participating in network protection.\n" "If no parameters provided current setting is printed.\n"); if (params.size() > 0) { bool fReserve = params[0].get_bool(); if (fReserve) { if (params.size() == 1) throw runtime_error("must provide amount to reserve balance.\n"); int64_t nAmount = AmountFromValue(params[1]); nAmount = (nAmount / CENT) * CENT; // round to cent if (nAmount < 0) throw runtime_error("amount cannot be negative.\n"); nReserveBalance = nAmount; } else { if (params.size() > 1) throw runtime_error("cannot specify amount to turn off reserve.\n"); nReserveBalance = 0; } } Object result; result.push_back(Pair("reserve", (nReserveBalance > 0))); result.push_back(Pair("amount", ValueFromAmount(nReserveBalance))); return result; } // ppcoin: check wallet integrity Value checkwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "checkwallet\n" "Check wallet for integrity.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion))); } return result; } // ppcoin: repair wallet Value repairwallet(const Array& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "repairwallet\n" "Repair wallet if checkwallet reports any problem.\n"); int nMismatchSpent; int64_t nBalanceInQuestion; pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion); Object result; if (nMismatchSpent == 0) result.push_back(Pair("wallet check passed", true)); else { result.push_back(Pair("mismatched spent coins", nMismatchSpent)); result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion))); } return result; } // CryptoRevenueToken: resend unconfirmed wallet transactions Value resendtx(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "resendtx\n" "Re-send unconfirmed transactions.\n" ); ResendWalletTransactions(true); return Value::null; } // ppcoin: make a public-private key pair Value makekeypair(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; key.MakeNewKey(false); CPrivKey vchPrivKey = key.GetPrivKey(); Object result; result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw()))); return result; }
mov ah, 0x0e ; tty mode mov al, 'H' int 0x10 mov al, 'e' int 0x10 mov al, 'l' int 0x10 int 0x10 ; 'l' is still on al mov al, 'o' int 0x10 jmp $ ; jump to current address = infinite loop ; padding and magic number times 510-($-$$) db 0 dw 0xaa55
; A183918: Characteristic sequence for cos(2Pi/n) being rational. ; 1,1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mov $2,$0 div $0,4 bin $2,5 cmp $0,$2
; A038720: a(n) = (n+3)*n!/2. ; 2,5,18,84,480,3240,25200,221760,2177280,23587200,279417600,3592512000,49816166400,741015475200,11769069312000,198766503936000,3556874280960000,67224923910144000,1338096104497152000,27978373094031360000,613091306060513280000,14050009097220096000000,336076217605504696320000,8376053423398732431360000,217156940606633803776000000,5847726186335781715968000000,163333041756275282411520000000,4725769341481564837773312000000,141468191899835231272697856000000,4376672186901152467499089920000000,139788257121024687901334568960000000 add $0,1 mov $1,2 lpb $0 add $1,$0 mul $1,$0 sub $0,1 lpe sub $1,3 div $1,2 add $1,2 mov $0,$1
; A091913: Triangle read by rows: a(n,k) = C(n,k)*(2^(n-k) - 1) for k<n, a(n,k) = 0 for k>=n, where k=0...max(n-1,0). ; Submitted by Jon Maiga ; 0,1,3,2,7,9,3,15,28,18,4,31,75,70,30,5,63,186,225,140,45,6,127,441,651,525,245,63,7,255,1016,1764,1736,1050,392,84,8,511,2295,4572,5292,3906,1890,588,108,9,1023,5110,11475,15240,13230,7812,3150,840,135,10,2047 sub $0,1 lpb $0 add $1,1 sub $0,$1 lpe add $1,1 sub $2,$0 add $2,$1 bin $1,$0 mov $0,2 pow $0,$2 sub $0,1 mul $1,$0 mov $0,$1
if ~ defined VERSION_OS err 'VERSION_OS should be defined in a cmd line argument' end if if VERSION_OS <> 'L' & VERSION_OS <> 'W' & VERSION_OS <> 'X' err "unsupported VERSION_OS" end if VERSION_PRE = 'asmFish' macro SetDefault val*, sym* if ~ defined sym restore sym sym = val end if end macro SetDefault 0, DEBUG SetDefault 0, VERBOSE SetDefault 0, PROFILE SetDefault 1, USE_BOOK SetDefault 1, USE_SYZYGY SetDefault 1, USE_CMDLINEQUIT SetDefault 1, USE_HASHFULL SetDefault 1, USE_CURRMOVE SetDefault 0, USE_SPAMFILTER SetDefault 0, USE_WEAKNESS SetDefault 0, USE_VARIETY SetDefault 0, USE_MATEFINDER SetDefault 1, PEDANTIC SetDefault '<empty>', LOG_FILE ; use something other than <empty> to hardcode a starting log file into the engine SetDefault 'base', VERSION_POST SetDefault 0, CPU_HAS_TZCNT SetDefault 0, CPU_HAS_POPCNT SetDefault 0, CPU_HAS_BMI1 SetDefault 0, CPU_HAS_BMI2 SetDefault 0, CPU_HAS_AVX1 ; not implemented yet SetDefault 0, CPU_HAS_AVX2 ; not implemented yet if VERSION_POST = 'base' CPU_HAS_POPCNT = 0 CPU_HAS_BMI1 = 0 CPU_HAS_BMI2 = 0 else if VERSION_POST = 'popcnt' CPU_HAS_POPCNT = 1 CPU_HAS_TZCNT = 0 CPU_HAS_BMI1 = 0 CPU_HAS_BMI2 = 0 else if VERSION_POST = 'bmi1' CPU_HAS_POPCNT = 1 CPU_HAS_TZCNT = 1 CPU_HAS_BMI1 = 1 CPU_HAS_BMI2 = 0 else if VERSION_POST = 'bmi2' CPU_HAS_POPCNT = 1 CPU_HAS_TZCNT = 1 CPU_HAS_BMI1 = 1 CPU_HAS_BMI2 = 1 end if FASMG_INC = 'include/' include string 'format.inc' shl (8*lengthof FASMG_INC) + FASMG_INC include string 'instructions/bmi1.inc' shl (8*lengthof FASMG_INC) + FASMG_INC include string 'instructions/bmi2.inc' shl (8*lengthof FASMG_INC) + FASMG_INC include string 'instructions/avx.inc' shl (8*lengthof FASMG_INC) + FASMG_INC ; instruction and target macros if VERSION_OS = 'L' format ELF64 executable 3 entry Start else if VERSION_OS = 'W' format PE64 console stack THREAD_STACK_SIZE entry Start else if VERSION_OS = 'X' format MACHO64 entry Start end if ; assembler macros include 'fasm1macros.asm' ; os headers if VERSION_OS = 'L' include 'linux64.asm' else if VERSION_OS = 'W' include 'windows64.asm' else if VERSION_OS = 'X' include 'apple64.asm' end if ; basic macros include 'Def.asm' include 'Structs.asm' include 'AvxMacros.asm' include 'BasicMacros.asm' include 'Debug.asm' ; engine macros include 'AttackMacros.asm' include 'GenMacros.asm' include 'MovePickMacros.asm' include 'SearchMacros.asm' include 'QSearchMacros.asm' include 'HashMacros.asm' include 'PosIsDrawMacro.asm' include 'SliderBlockers.asm' include 'UpdateStats.asm' include 'Pawn.asm' ; data and bss section if VERSION_OS = 'L' segment readable writeable include 'MainData.asm' segment readable writeable include 'MainBss.asm' else if VERSION_OS = 'W' section '.data' data readable writeable include 'MainData.asm' section '.bss' data readable writeable include 'MainBss.asm' end if ; code section if VERSION_OS = 'L' segment readable executable else if VERSION_OS = 'W' section '.code' code readable executable else if VERSION_OS = 'X' segment '__TEXT' readable executable section '__text' align 64 end if if USE_SYZYGY include 'TablebaseCore.asm' include 'Tablebase.asm' end if include 'Endgame.asm' include 'Evaluate.asm' include 'Hash_Probe.asm' include 'Move_IsPseudoLegal.asm' include 'SetCheckInfo.asm' include 'Move_GivesCheck.asm' include 'Gen_Captures.asm' include 'Gen_Quiets.asm' include 'Gen_QuietChecks.asm' include 'Gen_Evasions.asm' include 'MovePick.asm' include 'Move_IsLegal.asm' include 'Move_Do.asm' include 'Move_Undo.asm' calign 16 QSearch_NonPv_NoCheck: QSearch 0, 0 calign 16 QSearch_NonPv_InCheck: QSearch 0, 1 calign 16 QSearch_Pv_InCheck: QSearch 1, 1 calign 16 QSearch_Pv_NoCheck: QSearch 1, 0 calign 64 Search_NonPv: search 0, 0 include 'SeeTest.asm' include 'Move_DoNull.asm' include 'CheckTime.asm' include 'Castling.asm' calign 16 Search_Pv: search 0, 1 calign 16 Search_Root: search 1, 1 include 'Gen_NonEvasions.asm' include 'Gen_Legal.asm' include 'Perft.asm' include 'AttackersTo.asm' ;include 'EasyMoveMng.asm' include 'Think.asm' include 'TimeMng.asm' if USE_WEAKNESS include 'Weakness.asm' end if include 'Position.asm' include 'Hash.asm' include 'RootMoves.asm' include 'Limits.asm' include 'Thread.asm' include 'ThreadPool.asm' include 'Uci.asm' include 'Search_Clear.asm' include 'PrintParse.asm' include 'Math.asm' if VERSION_OS = 'L' include 'OsLinux.asm' else if VERSION_OS = 'W' include 'OsWindows.asm' else if VERSION_OS = 'X' include 'OsMac.asm' end if if USE_BOOK include 'Book.asm' end if include 'Main.asm' ; entry point in here include 'Search_Init.asm' include 'Position_Init.asm' include 'MoveGen_Init.asm' include 'BitBoard_Init.asm' include 'BitTable_Init.asm' include 'Evaluate_Init.asm' include 'Pawn_Init.asm' include 'Endgame_Init.asm' ; for mac, data and bss cannot come before first code section (?) if VERSION_OS = 'X' segment '__DATA' readable writeable section '__data' align 16 include 'MainData.asm' section '__bss' align 4096 include 'MainBss.asm' end if if VERSION_OS = 'W' section '.idata' import data readable writeable library kernel,'KERNEL32.DLL' import kernel,\ __imp_CreateFileA,'CreateFileA',\ __imp_CloseHandle,'CloseHandle',\ __imp_CreateEventA,'CreateEventA',\ __imp_CreateFileMappingA,'CreateFileMappingA',\ __imp_CreateThread,'CreateThread',\ __imp_DeleteCriticalSection,'DeleteCriticalSection',\ __imp_EnterCriticalSection,'EnterCriticalSection',\ __imp_ExitProcess,'ExitProcess',\ __imp_ExitThread,'ExitThread',\ __imp_GetCommandLineA,'GetCommandLineA',\ __imp_GetCurrentProcess,'GetCurrentProcess',\ __imp_GetFileSize,'GetFileSize',\ __imp_GetModuleHandleA,'GetModuleHandleA',\ __imp_GetProcAddress,'GetProcAddress',\ __imp_GetProcessAffinityMask,'GetProcessAffinityMask',\ __imp_GetStdHandle,'GetStdHandle',\ __imp_InitializeCriticalSection,'InitializeCriticalSection',\ __imp_LeaveCriticalSection,'LeaveCriticalSection',\ __imp_LoadLibraryA,'LoadLibraryA',\ __imp_MapViewOfFile,'MapViewOfFile',\ __imp_QueryPerformanceCounter,'QueryPerformanceCounter',\ __imp_QueryPerformanceFrequency,'QueryPerformanceFrequency',\ __imp_ReadFile,'ReadFile',\ __imp_ResumeThread,'ResumeThread',\ __imp_SetEvent,'SetEvent',\ __imp_SetPriorityClass,'SetPriorityClass',\ __imp_SetThreadAffinityMask,'SetThreadAffinityMask',\ __imp_Sleep,'Sleep',\ __imp_UnmapViewOfFile,'UnmapViewOfFile',\ __imp_VirtualAlloc,'VirtualAlloc',\ __imp_VirtualFree,'VirtualFree',\ __imp_WaitForSingleObject,'WaitForSingleObject',\ __imp_WriteFile,'WriteFile' else if VERSION_OS = 'X' interpreter '/usr/lib/dyld' uses '/usr/lib/libSystem.B.dylib' (1.0.0, 1225.0.0) ;import _clock_gettime, '_clock_gettime' import _close, '_close' import _exit, '_exit' import _fstat, '_fstat' import _mmap, '_mmap' import _munmap, '_munmap' import _nanosleep, '_nanosleep' import _open, '_open' import _pthread_cond_destroy, '_pthread_cond_destroy' import _pthread_cond_init, '_pthread_cond_init' import _pthread_cond_signal, '_pthread_cond_signal' import _pthread_cond_wait, '_pthread_cond_wait' import _pthread_create, '_pthread_create' import _pthread_exit, '_pthread_exit' import _pthread_mutex_destroy, '_pthread_mutex_destroy' import _pthread_mutex_init, '_pthread_mutex_init' import _pthread_mutex_lock, '_pthread_mutex_lock' import _pthread_mutex_unlock, '_pthread_mutex_unlock' import _pthread_join, '_pthread_join' import _read, '_read' import _write, '_write' end if
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r15 push %r8 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_WC_ht+0xda1c, %r15 nop xor %r10, %r10 movw $0x6162, (%r15) nop add %r9, %r9 lea addresses_WT_ht+0x6d1f, %r10 nop nop nop add %rbx, %rbx mov (%r10), %r9w nop nop nop nop nop xor %rdi, %rdi lea addresses_normal_ht+0x1061c, %rsi lea addresses_UC_ht+0x1e81c, %rdi nop nop sub $48740, %r15 mov $83, %rcx rep movsw add %rdi, %rdi lea addresses_WT_ht+0xb36c, %rsi lea addresses_UC_ht+0x1821c, %rdi nop nop nop xor %r8, %r8 mov $53, %rcx rep movsq nop nop nop and $26045, %rbx lea addresses_WT_ht+0x32a0, %rsi clflush (%rsi) nop nop add $7882, %r9 mov $0x6162636465666768, %r8 movq %r8, %xmm1 vmovups %ymm1, (%rsi) nop cmp %r15, %r15 lea addresses_normal_ht+0x11a1c, %r15 nop nop nop cmp $5904, %r9 mov (%r15), %edi nop xor $42566, %rsi lea addresses_UC_ht+0x1ee7c, %rsi lea addresses_normal_ht+0xa3ac, %rdi nop nop nop nop sub $45825, %r15 mov $93, %rcx rep movsb nop nop nop xor $58633, %r10 lea addresses_A_ht+0x1361c, %r9 nop nop nop nop nop and $50988, %rbx mov $0x6162636465666768, %rcx movq %rcx, %xmm4 and $0xffffffffffffffc0, %r9 movntdq %xmm4, (%r9) sub $57873, %rsi lea addresses_D_ht+0x10a1c, %rdi sub %r9, %r9 movl $0x61626364, (%rdi) nop nop sub $392, %r15 lea addresses_WC_ht+0x1443c, %rsi lea addresses_normal_ht+0x108e4, %rdi nop nop nop cmp %rbx, %rbx mov $87, %rcx rep movsb nop nop dec %r8 lea addresses_UC_ht+0x7ce4, %rcx nop and $33082, %rbx vmovups (%rcx), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $1, %xmm0, %r9 nop nop nop nop xor $43730, %rbx lea addresses_UC_ht+0xe55c, %r9 nop nop nop nop xor $30009, %rdi mov (%r9), %r15 nop add %r9, %r9 lea addresses_WT_ht+0x8ac0, %rsi clflush (%rsi) sub $55066, %r8 movb $0x61, (%rsi) nop sub $60731, %rsi lea addresses_D_ht+0x1ad1c, %r15 nop nop lfence movl $0x61626364, (%r15) nop nop nop add %rsi, %rsi lea addresses_normal_ht+0x819c, %r9 nop nop sub $6423, %rsi movb (%r9), %r10b inc %r15 pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r8 pop %r15 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rbx push %rdi push %rdx // Faulty Load lea addresses_A+0xfa1c, %rdx nop nop nop nop nop inc %rbx vmovups (%rdx), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $1, %xmm3, %r9 lea oracles, %rbx and $0xff, %r9 shlq $12, %r9 mov (%rbx,%r9,1), %r9 pop %rdx pop %rdi pop %rbx pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 6, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 2, 'size': 32, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 11, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 4, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': True}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 2, 'size': 32, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 8, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 2, 'size': 1, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 8, 'size': 4, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 1, 'same': False, 'NT': False}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; The copyright in this software is being made available under the BSD ; License, included below. This software may be subject to other third party ; and contributor rights, including patent rights, and no such rights are ; granted under this license. ; ; ; Copyright(c) 2011 - 2014, Parabola Research Limited ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met : ; ; * Redistributions of source code must retain the above copyright notice, ; this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and / or other materials provided with the distribution. ; * Neither the name of the copyright holder nor the names of its contributors may ; be used to endorse or promote products derived from this software without ; specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ; ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS ; BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR ; CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF ; SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN ; CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ; ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF ; THE POSSIBILITY OF SUCH DAMAGE. %define private_prefix hevcasm %include "x86inc.asm" %define ORDER(a, b, c, d) ((a << 6) | (b << 4) | (c << 2) | d) SECTION_RODATA 32 ones_w: times 8 dw 1 SECTION .text ; void quantize_inverse_sse4(int16_t *dst, int16_t *src, int scale, int shift, int n); INIT_XMM sse4 cglobal quantize_inverse, 5, 5, 6 mova m0, [ones_w] movd m1, r3d ; m1 = shift add r3b, 15 bts r2d, r3d ; r2d = (0x10000 << (shift - 1)) + scale movd m2, r2d pshufd m2, m2, 0 ; m2 = 1<<(shift-1), scale, 1<<(shift-1), scale, 1<<(shift-1), scale, 1<<(shift-1), scale shr r4d, 4 ; r4 = n/16 .loop %assign offset 0 %rep 2 mova m4, [r1 + offset] ; m4 = src[7], src[6], src[5], src[4], src[3], src[2], src[1], src[0] punpcklwd m5, m4, m0 ; m5 = 1, src[3], 1, src[2], 1, src[1], 1, src[0] punpckhwd m4, m0 ; m4 = 1, src[7], 1, src[6], 1, src[5], 1, src[4] pmaddwd m4, m2 ; m4 = (1<<(shift-1)) + src[7] * scale , (1<<(shift-1)) + src[6] * scale, (1<<(shift-1)) + src[5] * scale, (1<<(shift-1)) + src[4] * scale pmaddwd m5, m2 ; m5 = (1<<(shift-1)) + src[3] * scale , (1<<(shift-1)) + src[2] * scale, (1<<(shift-1)) + src[1] * scale, (1<<(shift-1)) + src[0] * scale psrad m4, m1 ; m4 = ((1<<(shift-1)) + src[7] * scale)>>shift , ((1<<(shift-1)) + src[6] * scale)>>shift, ((1<<(shift-1)) + src[5] * scale)>>shift, ((1<<(shift-1)) + src[4] * scale)>>shift psrad m5, m1 ; m5 = ((1<<(shift-1)) + src[3] * scale)>>shift , ((1<<(shift-1)) + src[2] * scale)>>shift, ((1<<(shift-1)) + src[1] * scale)>>shift, ((1<<(shift-1)) + src[0] * scale)>>shift packssdw m5, m4 ; m5 = ((1<<(shift-1)) + src[7] * scale)>>shift , ((1<<(shift-1)) + src[6] * scale)>>shift, ((1<<(shift-1)) + src[5] * scale)>>shift, ((1<<(shift-1)) + src[4] * scale)>>shift, ((1<<(shift-1)) + src[3] * scale)>>shift , ((1<<(shift-1)) + src[2] * scale)>>shift, ((1<<(shift-1)) + src[1] * scale)>>shift, ((1<<(shift-1)) + src[0] * scale)>>shift mova [r0 + offset], m5 %assign offset offset+16 %endrep add r1, 32 add r0, 32 dec r4d jg .loop RET ; int quantize_sse4(int16_t *dst, const int16_t *src, int scale, int shift, int offset, int n); INIT_XMM sse4 cglobal quantize, 6, 7, 8 movd m1, r3d ; m1 = shift bts r2d, r3d ; r2d = (1 << shift) + scale movd m2, r2d pshufd m2, m2, 0 ; m2 = 1<<(shift-16), scale, 1<<(shift-16), scale, 1<<(shift-16), scale, 1<<(shift-16), scale movd m3, r4d pshuflw m3, m3, 0 pshufd m3, m3, 0 ; m3 = offset, offset, offset, offset, offset, offset, offset, offset pxor m0, m0 ; m3 = 0 shr r5d, 4 ; r5 = n/16 .loop %assign offset 0 %rep 2 mova m4, [r1 + offset] ; m4 = src[7], src[6], src[5], src[4], src[3], src[2], src[1], src[0] pabsw m5, m4 ; m5 = abs(src[7]), abs(src[6]), abs(src[5]), abs(src[4]), abs(src[3]), abs(src[2]), abs(src[1]), abs(src[0]) punpcklwd m6, m5, m3 ; m6 = offset, abs(src[3]), offset, abs(src[2]), offset, abs(src[1]), offset, abs(src[0]) punpckhwd m5, m3 ; m5 = offset, abs(src[7]), offset, abs(src[6]), offset, abs(src[5]), offset, abs(src[4]) pmaddwd m6, m2 ; m6 = (offset<<(shift-16))+abs(src[3])*scale, (offset<<(shift-16))+abs(src[2])*scale, (offset<<(shift-16))+abs(src[1])*scale, (offset<<(shift-16))+abs(src[0])*scale psrad m6, m1 ; m6 = (offset<<(shift-16))+abs(src[3])*scale>>shift, (offset<<(shift-16))+abs(src[2])*scale>>shift, (offset<<(shift-16))+abs(src[1])*scale>>shift, (offset<<(shift-16))+abs(src[0])*scale>>shift pmaddwd m5, m2 ; m5 = (offset<<(shift-16))+abs(src[7])*scale, (offset<<(shift-16))+abs(src[6])*scale, (offset<<(shift-16))+abs(src[5])*scale, (offset<<(shift-16))+abs(src[4])*scale, psrad m5, m1 ; m5 = (offset<<(shift-16))+abs(src[7])*scale>>shift, (offset<<(shift-16))+abs(src[6])*scale>>shift, (offset<<(shift-16))+abs(src[5])*scale>>shift, (offset<<(shift-16))+abs(src[4])*scale>>shift punpcklwd m7, m4 ; m7 = (src[3]<<16)+0x????,(src[2]<<16)+0x????,(src[1]<<16)+0x????,(src[0]<<16)+0x???? psignd m6, m7 ; m6 = ((offset<<(shift-16))+abs(src[3])*scale>>shift)*sign(src[3]), ((offset<<(shift-16))+abs(src[2])*scale>>shift)*sign(src[2]), ((offset<<(shift-16))+abs(src[1])*scale>>shift)*sign(src[1]), ((offset<<(shift-16))+abs(src[0])*scale>>shift)*sign(src[0]) ; m6 = dst[3], dst[2], dst[1], dst[0] punpckhwd m4, m4 ; m4 = (src[7]<<16)+0x????,(src[6]<<16)+0x????,(src[5]<<16)+0x????,(src[4]<<16)+0x???? psignd m5, m4 ; m5 = ((offset<<(shift-16))+abs(src[7])*scale>>shift)*sign(src[7]), ((offset<<(shift-16))+abs(src[6])*scale>>shift)*sign(src[6]), ((offset<<(shift-16))+abs(src[5])*scale>>shift)*sign(src[5]), ((offset<<(shift-16))+abs(src[4])*scale>>shift)*sign(src[4]) ; m5 = dst[7], dst[6], dst[5], dst[4] packssdw m6, m5 ; m6 = dst[7], dst[6], dst[5], dst[4], dst[3], dst[2], dst[1], dst[0] por m0, m6 ; m0 is non-zero if we have seen any non-zero quantized coefficients mova [r0 + offset], m6 %assign offset offset+16 %endrep add r1, 32 add r0, 32 dec r5d jg .loop ; return zero only if m0 is zero - no non-zero quantized coefficients seen (cbf=0) packsswb m0, m0 packsswb m0, m0 movd eax, m0 RET ; int hevcasm_quantize_reconstruct_4x4_sse4(uint8_t *recSamples, ptrdiff_t recStride, const uint8_t *predSamples, ptrdiff_t predStride, const int16_t *resSamples); INIT_XMM sse4 cglobal quantize_reconstruct_4x4, 5, 6, 4 pxor m0, m0 mov r5d, 2 .loop movd m1, [r2] movd m2, [r2+r3] lea r2, [r2+2*r3] punpckldq m1, m2 punpcklbw m1, m0 movu m3, [r4] paddw m1, m3 lea r4, [r4+16] packuswb m1, m1 movd [r0], m1 pshufd m1, m1, ORDER(0, 0, 0, 1) movd [r0+r1], m1 lea r0, [r0+2*r1] dec r5d jg .loop RET ; int quantize_reconstruct_8x8_sse4(uint8_t *recSamples, ptrdiff_t recStride, const uint8_t *predSamples, ptrdiff_t predStride, const int16_t *resSamples); INIT_XMM sse4 cglobal quantize_reconstruct_8x8, 5, 6, 2 pxor m0, m0 mov r5d, 8 .loop movq m1, [r2] lea r2, [r2+r3] punpcklbw m1, m0 ; m1 = pred[7] ... pred[0] paddw m1, [r4] lea r4, [r4+16] ; m1 = pred[7]+res[7] ... pred[0]+res[0] packuswb m1, m1 movq [r0], m1 lea r0, [r0+r1] dec r5d jg .loop RET ; int quantize_reconstruct_16x16_sse4(uint8_t *recSamples, ptrdiff_t recStride, const uint8_t *predSamples, ptrdiff_t predStride, const int16_t *resSamples); INIT_XMM sse4 cglobal quantize_reconstruct_16x16, 5, 6, 3 pxor m0, m0 mov r5d, 16 .loop mova m1, [r2] lea r2, [r2+r3] punpcklbw m2, m1, m0 ; m2 = pred[7] ... pred[0] punpckhbw m1, m0 ; m1 = pred[15] ... pred[8] paddw m2, [r4] ; m2 = pred[7]+res[7] ... pred[0]+res[0] paddw m1, [r4+16] lea r4, [r4+32] ; m1 = pred[15]+res[15] ... pred[8]+res[8] packuswb m2, m1 mova [r0], m2 lea r0, [r0+r1] dec r5d jg .loop RET ; int quantize_reconstruct_32x32_sse4(uint8_t *recSamples, ptrdiff_t recStride, const uint8_t *predSamples, ptrdiff_t predStride, const int16_t *resSamples); INIT_XMM sse4 cglobal quantize_reconstruct_32x32, 5, 6, 3 pxor m0, m0 mov r5d, 32 .loop %assign offset 0 %rep 2 mova m1, [r2 + 16 * offset] punpcklbw m2, m1, m0 ; m2 = pred[7] ... pred[0] punpckhbw m1, m0 ; m1 = pred[15] ... pred[8] paddw m2, [r4 + 32 * offset] ; m2 = pred[7]+res[7] ... pred[0]+res[0] paddw m1, [r4 + 32 * offset + 16] ; m1 = pred[15]+res[15] ... pred[8]+res[8] packuswb m2, m1 mova [r0 + 16 * offset], m2 %assign offset offset + 1 %endrep lea r2, [r2+r3] lea r0, [r0+r1] lea r4, [r4+64] dec r5d jg .loop RET
; A021498: Decimal expansion of 1/494. ; 0,0,2,0,2,4,2,9,1,4,9,7,9,7,5,7,0,8,5,0,2,0,2,4,2,9,1,4,9,7,9,7,5,7,0,8,5,0,2,0,2,4,2,9,1,4,9,7,9,7,5,7,0,8,5,0,2,0,2,4,2,9,1,4,9,7,9,7,5,7,0,8,5,0,2,0,2,4,2,9,1,4,9,7,9,7,5,7,0,8,5,0,2,0,2,4,2,9,1 add $0,1 mov $1,10 pow $1,$0 mul $1,6 div $1,2964 mod $1,10 mov $0,$1
; ; Z88dk Generic Floating Point Math Library ; ; ; ; $Id: ddiv.asm,v 1.1 2008/07/27 21:44:57 aralbrec Exp $: XLIB ddiv LIB fdiv .ddiv pop hl ;ret address pop de pop ix pop bc push hl jp fdiv
; A098210: a(n) = -1 + A093137(n)^2. ; 0,15,1155,111555,11115555,1111155555,111111555555,11111115555555,1111111155555555,111111111555555555,11111111115555555555,1111111111155555555555,111111111111555555555555,11111111111115555555555555,1111111111111155555555555555,111111111111111555555555555555,11111111111111115555555555555555,1111111111111111155555555555555555,111111111111111111555555555555555555 mov $1,10 pow $1,$0 add $1,2 pow $1,2 sub $1,9 div $1,9 mov $0,$1
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE127_Buffer_Underread__new_char_loop_01.cpp Label Definition File: CWE127_Buffer_Underread__new.label.xml Template File: sources-sink-01.tmpl.cpp */ /* * @description * CWE: 127 Buffer Under-read * BadSource: Set data pointer to before the allocated memory buffer * GoodSource: Set data pointer to the allocated memory buffer * Sink: loop * BadSink : Copy data to string using a loop * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE127_Buffer_Underread__new_char_loop_01 { #ifndef OMITBAD void bad() { char * data; data = NULL; { char * data_buf = new char[100]; memset(data_buf, 'A', 100-1); data_buf[100-1] = '\0'; /* FLAW: Set data pointer to before the allocated memory buffer */ data = data_buf - 8; } { size_t i; char dest[100]; memset(dest, 'C', 100-1); /* fill with 'C's */ dest[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = '\0'; printLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location returned by new [] so can't safely call delete [] on it */ } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { char * data; data = NULL; { char * data_buf = new char[100]; memset(data_buf, 'A', 100-1); data_buf[100-1] = '\0'; /* FIX: Set data pointer to the allocated memory buffer */ data = data_buf; } { size_t i; char dest[100]; memset(dest, 'C', 100-1); /* fill with 'C's */ dest[100-1] = '\0'; /* null terminate */ /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ for (i = 0; i < 100; i++) { dest[i] = data[i]; } /* Ensure null termination */ dest[100-1] = '\0'; printLine(dest); /* INCIDENTAL CWE-401: Memory Leak - data may not point to location returned by new [] so can't safely call delete [] on it */ } } void good() { goodG2B(); } #endif /* OMITGOOD */ } // close namespace /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE127_Buffer_Underread__new_char_loop_01; // so that we can use good and bad easily int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
dnl Intel P55 mpn_hamdist -- mpn hamming distance. dnl Copyright 2000, 2002 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 2.1 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public dnl License along with the GNU MP Library; see the file COPYING.LIB. If dnl not, write to the Free Software Foundation, Inc., 51 Franklin Street, dnl Fifth Floor, Boston, MA 02110-1301, USA. include(`../config.m4') C P55: hamdist 12.0 cycles/limb C For reference, this code runs at 11.5 cycles/limb for popcount, which is C slower than the plain integer mpn/x86/pentium/popcount.asm. include_mpn(`x86/k6/mmx/hamdist.asm')
; ; Part of OS4, busy_wait.asm ; Author: Mikael Henriksson, miklhh ; ; Function for busy waiting. Used by certaion architecture specific routines ; written in C so that GCC wont optimize certaion parts away. global busy_wait busy_wait: jmp $
/*=========================================================================== _____ _____ _____ _____ ___| _|__ __|_ |__ __|__ |__ __| __ |__ ______ | \ / | || \ || | || |/ / ||___ | | \/ | || \ || \ || \ ||___ | |__/\__/|__|_||__|\__\ __||__|\__\ __||__|\__\ __||______| |_____| |_____| |_____| |_____| --[Mark3 Realtime Platform]-------------------------------------------------- Copyright (c) 2012-2016 Funkenstein Software Consulting, all rights reserved. See license.txt for more information ===========================================================================*/ /*! \file mutex.cpp \brief Mutual-exclusion object */ #include "kerneltypes.h" #include "mark3cfg.h" #include "blocking.h" #include "mutex.h" #define _CAN_HAS_DEBUG //--[Autogenerated - Do Not Modify]------------------------------------------ #include "dbg_file_list.h" #include "buffalogger.h" #if defined(DBG_FILE) # error "Debug logging file token already defined! Bailing." #else # define DBG_FILE _DBG___KERNEL_MUTEX_CPP #endif //--[End Autogenerated content]---------------------------------------------- #include "kerneldebug.h" #if KERNEL_USE_MUTEX #if KERNEL_USE_TIMEOUTS //--------------------------------------------------------------------------- /*! * \brief TimedMutex_Calback * * This function is called from the timer-expired context to trigger a timeout * on this mutex. This results in the waking of the thread that generated * the mutex claim call that was not completed in time. * * \param pclOwner_ Pointer to the thread to wake * \param pvData_ Pointer to the mutex object that the thread is blocked on */ void TimedMutex_Calback(Thread *pclOwner_, void *pvData_) { Mutex *pclMutex = static_cast<Mutex*>(pvData_); // Indicate that the semaphore has expired on the thread pclOwner_->SetExpired(true); // Wake up the thread that was blocked on this semaphore. pclMutex->WakeMe(pclOwner_); if (pclOwner_->GetCurPriority() >= Scheduler::GetCurrentThread()->GetCurPriority()) { Thread::Yield(); } } //--------------------------------------------------------------------------- void Mutex::WakeMe(Thread *pclOwner_) { // Remove from the semaphore waitlist and back to its ready list. UnBlock(pclOwner_); } #endif //--------------------------------------------------------------------------- uint8_t Mutex::WakeNext() { Thread *pclChosenOne = NULL; // Get the highest priority waiter thread pclChosenOne = m_clBlockList.HighestWaiter(); // Unblock the thread UnBlock(pclChosenOne); // The chosen one now owns the mutex m_pclOwner = pclChosenOne; // Signal a context switch if it's a greater than or equal to the current priority if (pclChosenOne->GetCurPriority() >= Scheduler::GetCurrentThread()->GetCurPriority()) { return 1; } return 0; } //--------------------------------------------------------------------------- void Mutex::Init() { // Reset the data in the mutex m_bReady = 1; // The mutex is free. m_u8MaxPri = 0; // Set the maximum priority inheritence state m_pclOwner = NULL; // Clear the mutex owner m_u8Recurse = 0; // Reset recurse count } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS bool Mutex::Claim_i(uint32_t u32WaitTimeMS_) #else void Mutex::Claim_i(void) #endif { KERNEL_TRACE_1( "Claiming Mutex, Thread %d", (uint16_t)g_pclCurrent->GetID() ); #if KERNEL_USE_TIMEOUTS Timer clTimer; bool bUseTimer = false; #endif // Disable the scheduler while claiming the mutex - we're dealing with all // sorts of private thread data, can't have a thread switch while messing // with internal data structures. Scheduler::SetScheduler(0); // Check to see if the mutex is claimed or not if (m_bReady != 0) { // Mutex isn't claimed, claim it. m_bReady = 0; m_u8Recurse = 0; m_u8MaxPri = g_pclCurrent->GetPriority(); m_pclOwner = g_pclCurrent; Scheduler::SetScheduler(1); #if KERNEL_USE_TIMEOUTS return true; #else return; #endif } // If the mutex is already claimed, check to see if this is the owner thread, // since we allow the mutex to be claimed recursively. if (g_pclCurrent == m_pclOwner) { // Ensure that we haven't exceeded the maximum recursive-lock count KERNEL_ASSERT( (m_u8Recurse < 255) ); m_u8Recurse++; // Increment the lock count and bail Scheduler::SetScheduler(1); #if KERNEL_USE_TIMEOUTS return true; #else return; #endif } // The mutex is claimed already - we have to block now. Move the // current thread to the list of threads waiting on the mutex. #if KERNEL_USE_TIMEOUTS if (u32WaitTimeMS_) { g_pclCurrent->SetExpired(false); clTimer.Init(); clTimer.Start(0, u32WaitTimeMS_, (TimerCallback_t)TimedMutex_Calback, (void*)this); bUseTimer = true; } #endif BlockPriority(g_pclCurrent); // Check if priority inheritence is necessary. We do this in order // to ensure that we don't end up with priority inversions in case // multiple threads are waiting on the same resource. if(m_u8MaxPri <= g_pclCurrent->GetPriority()) { m_u8MaxPri = g_pclCurrent->GetPriority(); Thread *pclTemp = static_cast<Thread*>(m_clBlockList.GetHead()); while(pclTemp) { pclTemp->InheritPriority(m_u8MaxPri); if(pclTemp == static_cast<Thread*>(m_clBlockList.GetTail()) ) { break; } pclTemp = static_cast<Thread*>(pclTemp->GetNext()); } m_pclOwner->InheritPriority(m_u8MaxPri); } // Done with thread data -reenable the scheduler Scheduler::SetScheduler(1); // Switch threads if this thread acquired the mutex Thread::Yield(); #if KERNEL_USE_TIMEOUTS if (bUseTimer) { clTimer.Stop(); return (g_pclCurrent->GetExpired() == 0); } return true; #endif } //--------------------------------------------------------------------------- void Mutex::Claim(void) { #if KERNEL_USE_TIMEOUTS Claim_i(0); #else Claim_i(); #endif } //--------------------------------------------------------------------------- #if KERNEL_USE_TIMEOUTS bool Mutex::Claim(uint32_t u32WaitTimeMS_) { return Claim_i(u32WaitTimeMS_); } #endif //--------------------------------------------------------------------------- void Mutex::Release() { KERNEL_TRACE_1( "Releasing Mutex, Thread %d", (uint16_t)g_pclCurrent->GetID() ); bool bSchedule = 0; // Disable the scheduler while we deal with internal data structures. Scheduler::SetScheduler(0); // This thread had better be the one that owns the mutex currently... KERNEL_ASSERT( (g_pclCurrent == m_pclOwner) ); // If the owner had claimed the lock multiple times, decrease the lock // count and return immediately. if (m_u8Recurse) { m_u8Recurse--; Scheduler::SetScheduler(1); return; } // Restore the thread's original priority if (g_pclCurrent->GetCurPriority() != g_pclCurrent->GetPriority()) { g_pclCurrent->SetPriority(g_pclCurrent->GetPriority()); // In this case, we want to reschedule bSchedule = 1; } // No threads are waiting on this semaphore? if (m_clBlockList.GetHead() == NULL) { // Re-initialize the mutex to its default values m_bReady = 1; m_u8MaxPri = 0; m_pclOwner = NULL; } else { // Wake the highest priority Thread pending on the mutex if(WakeNext()) { // Switch threads if it's higher or equal priority than the current thread bSchedule = 1; } } // Must enable the scheduler again in order to switch threads. Scheduler::SetScheduler(1); if(bSchedule) { // Switch threads if a higher-priority thread was woken Thread::Yield(); } } #endif //KERNEL_USE_MUTEX
; ************************************************** ; PSGlib - C programming library for the SEGA PSG ; ( part of devkitSMS - github.com/sverx/devkitSMS ) ; ************************************************** INCLUDE "PSGlib_private.inc" SECTION code_clib SECTION code_PSGlib PUBLIC asm_PSGlib_SetMusicVolumeAttenuation EXTERN __PSGlib_MusicStatus, __PSGlib_Channel2SFX, __PSGlib_Channel3SFX EXTERN __PSGlib_MusicVolumeAttenuation EXTERN __PSGlib_Chan0Volume, __PSGlib_Chan1Volume, __PSGlib_Chan2Volume, __PSGlib_Chan3Volume asm_PSGlib_SetMusicVolumeAttenuation: ; void PSGSetMusicVolumeAttenutation (void) ; sets the volume attenuation for the music (0-15) ; ; enter : l = volume attenuation (0-15) ; ; uses : af ld a,l ld (__PSGlib_MusicVolumeAttenuation),a ld a,(__PSGlib_MusicStatus) or a ret z ld a,(__PSGlib_Chan0Volume) add a,l cp 16 jr c, outchan0 ld a,15 outchan0: or PSGLatch|PSGChannel0|PSGVolumeData IF HAVE16bitbus push bc ld bc,PSGDataPort out (c),a pop bc ELSE out (PSGPort),a IF PSGLatchPort in a,(PSGLatchPort) ENDIF ENDIF ld a,(__PSGlib_Chan1Volume) add a,l cp 16 jr c, outchan1 ld a,15 outchan1: or PSGLatch|PSGChannel1|PSGVolumeData IF HAVE16bitbus push bc ld bc,PSGDataPort out (c),a pop bc ELSE out (PSGPort),a IF PSGLatchPort in a,(PSGLatchPort) ENDIF ENDIF ld a,(__PSGlib_Channel2SFX) or a jr nz, skipchan2 ld a,(__PSGlib_Chan2Volume) add a,l cp 16 jr c, outchan2 ld a,15 outchan2: or PSGLatch|PSGChannel2|PSGVolumeData IF HAVE16bitbus push bc ld bc,PSGDataPort out (c),a pop bc ELSE out (PSGPort),a IF PSGLatchPort in a,(PSGLatchPort) ENDIF ENDIF skipchan2: ld a,(__PSGlib_Channel3SFX) or a ret nz ld a,(__PSGlib_Chan3Volume) add a,l cp 16 jr c, outchan3 ld a,15 outchan3: or PSGLatch|PSGChannel3|PSGVolumeData IF HAVE16bitbus push bc ld bc,PSGDataPort out (c),a pop bc ELSE out (PSGPort),a IF PSGLatchPort in a,(PSGLatchPort) ENDIF ENDIF ret
CharacteristicStrings: dw .HP0 dw .HP1 dw .HP2 dw .HP3 dw .HP4 dw .Atk0 dw .Atk1 dw .Atk2 dw .Atk3 dw .Atk4 dw .Def0 dw .Def1 dw .Def2 dw .Def3 dw .Def4 dw .Spd0 dw .Spd1 dw .Spd2 dw .Spd3 dw .Spd4 dw .Spc0 dw .Spc1 dw .Spc2 dw .Spc3 dw .Spc4 .HP0: db "Loves to eat@" .HP1: db "Often dozes off@" .HP2: db "Scatters things@" .HP3: db "Scatters around@" .HP4: db "Likes to relax@" .Atk0: db "Proud of its power@" .Atk1: db "Thrashes about@" .Atk2: db "Quick tempered@" .Atk3: db "Likes to fight@" .Atk4: db "Quick tempered@" .Def0: db "Sturdy body@" .Def1: db "Can take some hits@" .Def2: db "Highly persistent@" .Def3: db "Good endurance@" .Def4: db "Good perseverance@" .Spd0: db "Likes to run@" .Spd1: db "Alert to sounds@" .Spd2: db "Carelss and silly@" .Spd3: db "A bit of a clown@" .Spd4: db "Quick to flee@" .Spc0: db "Highly curious@" .Spc1: db "Mischievous@" .Spc2: db "Strongly defiant@" .Spc3: db "Hates to lose@" .Spc4: db "Very finicky@"
; A037674: Base-4 digits are, in order, the first n terms of the periodic sequence with initial period 1,0,2,3. ; 1,4,18,75,301,1204,4818,19275,77101,308404,1233618,4934475,19737901,78951604,315806418,1263225675,5052902701,20211610804,80846443218,323385772875,1293543091501,5174172366004,20696689464018,82786757856075 mov $1,4 pow $1,$0 mul $1,20 div $1,17
; A017473: a(n) = 11*n + 7. ; 7,18,29,40,51,62,73,84,95,106,117,128,139,150,161,172,183,194,205,216,227,238,249,260,271,282,293,304,315,326,337,348,359,370,381,392,403,414,425,436,447,458,469,480,491,502,513,524,535,546,557,568,579,590,601,612,623,634,645,656,667,678,689,700,711,722,733,744,755,766,777,788,799,810,821,832,843,854,865,876,887,898,909,920,931,942,953,964,975,986,997,1008,1019,1030,1041,1052,1063,1074,1085,1096 mul $0,11 add $0,7
ldx {m2}+1 bne {la1} cmp {m2} bcc {la1}
; A055341: Number of mobiles (circular rooted trees) with n nodes and 3 leaves. ; 1,3,8,19,37,66,110,172,257,371,518,705,939,1226,1574,1992,2487,3069,3748,4533,5435,6466,7636,8958,10445,12109,13964,16025,18305,20820,23586,26618,29933,33549,37482,41751,46375,51372,56762,62566,68803 mov $4,$0 add $4,1 mov $15,$0 lpb $4 mov $0,$15 sub $4,1 sub $0,$4 mov $12,$0 mov $13,0 mov $14,$0 add $14,1 lpb $14 mov $0,$12 mov $10,0 sub $14,1 sub $0,$14 mov $9,$0 mov $11,$0 add $11,1 lpb $11 mov $0,$9 sub $11,1 sub $0,$11 mov $6,$0 add $6,7 mov $2,$6 div $2,2 mov $3,$2 sub $3,$2 mov $5,1 mov $16,$6 mov $6,3 mov $7,$16 sub $7,2 gcd $6,$7 add $5,$6 mov $8,$2 sub $8,$5 mul $8,6 add $3,$8 mov $16,$3 div $16,6 add $10,$16 lpe add $13,$10 lpe add $1,$13 lpe mov $0,$1
; A016744: a(n) = (2*n)^4. ; 0,16,256,1296,4096,10000,20736,38416,65536,104976,160000,234256,331776,456976,614656,810000,1048576,1336336,1679616,2085136,2560000,3111696,3748096,4477456,5308416,6250000,7311616,8503056,9834496,11316496,12960000,14776336,16777216,18974736,21381376,24010000,26873856,29986576,33362176,37015056,40960000,45212176,49787136,54700816,59969536,65610000,71639296,78074896,84934656,92236816,100000000,108243216,116985856,126247696,136048896,146410000,157351936,168896016,181063936,193877776,207360000 mul $0,2 pow $0,4
;Write an 8051 ASM program to add the first 15 natural numbers. ORG 0000H MOV R1,#01H MOV R2,#15 CLR A BEGIN: ADD A,R1 INC R1 DJNZ R2,BEGIN END; Deeptimaan Banerjee
; void *zx_saddrcup(void *saddr) SECTION code_arch PUBLIC zx_saddrcup zx_saddrcup: INCLUDE "arch/zx/display/z80/asm_zx_saddrcup.asm"
#include "tiroteleguiado.h" #include "3dsloader.h" static Vetor temp(0.f, 0.f, 1.f); Textura TiroTeleguiado::tMT("Texturas/Municao/m2.bmp",false); TiroTeleguiado :: TiroTeleguiado (Ponto *centro, Vetor *direcao, Vetor *lateral, float dn, float dv, float du) : Objeto3D (centro, direcao, lateral, dn, dv, du){ velocidade = 0.4f; atirada = false; tMT.carregarBMP(); gamb = 0; } TiroTeleguiado :: ~TiroTeleguiado () { //n serva pra nada } void TiroTeleguiado :: draw () { static bool gamb = false; static obj_type object; if (this->atirada) { int l_index; glPushMatrix(); glEnable(GL_TEXTURE_2D); if(!gamb){ Load3DS (&object,"Modelos/3DS/misselT.3ds"); gamb = true; } glTranslatef(this->centro->x,this->centro->y+0.2,this->centro->z); glRotatef(90.0f,1.0f,0.f,0.f); glRotatef((this->n->anguloEntre(temp)*(180/3.1416))+180,0.f,0.f,1.f); glScalef(0.004f,0.004f,0.004f); glBindTexture(GL_TEXTURE_2D, tMT.ID); glBegin(GL_TRIANGLES); for (l_index=0;l_index<object.polygons_qty;l_index++) { glTexCoord2f( object.mapcoord[ object.polygon[l_index].a ].u, object.mapcoord[ object.polygon[l_index].a ].v); glVertex3f( object.vertex[ object.polygon[l_index].a ].x, object.vertex[ object.polygon[l_index].a ].y, object.vertex[ object.polygon[l_index].a ].z); //Vertex definition glTexCoord2f( object.mapcoord[ object.polygon[l_index].b ].u, object.mapcoord[ object.polygon[l_index].b ].v); glVertex3f( object.vertex[ object.polygon[l_index].b ].x, object.vertex[ object.polygon[l_index].b ].y, object.vertex[ object.polygon[l_index].b ].z); glTexCoord2f( object.mapcoord[ object.polygon[l_index].c ].u, object.mapcoord[ object.polygon[l_index].c ].v); glVertex3f( object.vertex[ object.polygon[l_index].c ].x, object.vertex[ object.polygon[l_index].c ].y, object.vertex[ object.polygon[l_index].c ].z); } glEnd(); glFlush(); glDisable(GL_TEXTURE_2D); glPopMatrix(); } } void TiroTeleguiado :: update() { if (this->atirada) { if(this->gamb > 4){ *this->n = *this->centro2 - *this->centro; this->gamb = 0; }else{ this->gamb++; } this->n->normalizar(); *this->centro = *this->centro + *this->n * this->velocidade; this->calcularExtremidades(); } } void TiroTeleguiado :: disparar (Ponto centro, Vetor direcao) {//copias this->atirada = true; delete this->centro; delete this->n; delete this->u; this->centro = new Ponto(); this->n = new Vetor(); this->v = new Vetor(0.f,1.f,0.f); this->u = new Vetor(); *this->n = direcao; *this->centro = centro + (*this->n * this->deltaN * 4); this->centro2 = centro2; this->calcularU(); this->calcularExtremidades(); } void TiroTeleguiado :: perseguir(Ponto *destino){ this->centro2 = destino; }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r13 push %r8 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x14e3b, %rdx nop nop nop nop nop xor $2552, %r12 mov $0x6162636465666768, %r10 movq %r10, (%rdx) nop nop nop xor %r8, %r8 lea addresses_WT_ht+0x1393b, %rcx nop nop nop nop nop cmp %rax, %rax mov (%rcx), %r13d nop nop nop sub %r8, %r8 lea addresses_A_ht+0x17c43, %r13 and $5998, %rax movups (%r13), %xmm6 vpextrq $0, %xmm6, %r8 nop nop nop and %r12, %r12 lea addresses_WT_ht+0xd6bb, %r12 nop nop nop cmp $11750, %r8 mov $0x6162636465666768, %rcx movq %rcx, (%r12) nop and %r12, %r12 lea addresses_A_ht+0x193b5, %r12 nop nop dec %rdx movl $0x61626364, (%r12) nop sub %rax, %rax lea addresses_D_ht+0x14f3b, %rsi lea addresses_UC_ht+0x1976f, %rdi nop nop nop cmp %rax, %rax mov $53, %rcx rep movsq nop nop nop nop nop sub $6485, %rax lea addresses_WC_ht+0x243b, %r8 nop nop nop nop add $56240, %r12 mov $0x6162636465666768, %rdi movq %rdi, (%r8) nop nop and $47508, %r13 lea addresses_A_ht+0x19e83, %rsi lea addresses_normal_ht+0x10dfb, %rdi nop and $23334, %rdx mov $107, %rcx rep movsw nop nop nop nop nop and %r13, %r13 lea addresses_normal_ht+0x6d3b, %r10 clflush (%r10) nop nop nop sub $27408, %rsi mov $0x6162636465666768, %r13 movq %r13, %xmm3 and $0xffffffffffffffc0, %r10 vmovaps %ymm3, (%r10) nop nop nop nop nop sub %r10, %r10 lea addresses_A_ht+0xa93b, %rsi lea addresses_WT_ht+0x185fb, %rdi clflush (%rsi) nop nop nop nop mfence mov $10, %rcx rep movsb nop nop inc %r10 lea addresses_UC_ht+0xb87b, %r12 nop nop cmp $59547, %rdx movups (%r12), %xmm7 vpextrq $0, %xmm7, %r8 nop nop nop nop nop and $46404, %r8 lea addresses_D_ht+0x8eb, %rcx xor %rdi, %rdi mov (%rcx), %r12 nop nop and $40241, %r12 lea addresses_D_ht+0xa8bb, %rsi and $7707, %r12 movl $0x61626364, (%rsi) nop nop nop nop nop cmp %r12, %r12 lea addresses_D_ht+0x1953b, %r13 nop nop nop sub %r10, %r10 mov (%r13), %rsi sub %rcx, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r8 pop %r13 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r14 push %r8 push %rsi // Store lea addresses_D+0x4e3b, %r13 nop nop nop nop add $55113, %r8 movw $0x5152, (%r13) xor %r12, %r12 // Store lea addresses_D+0x176b, %r12 nop and %rsi, %rsi mov $0x5152535455565758, %r13 movq %r13, (%r12) nop nop add $10924, %r8 // Load lea addresses_D+0x14420, %rsi nop nop nop nop cmp %r12, %r12 mov (%rsi), %r14w nop nop nop sub $41422, %rsi // Faulty Load mov $0x93b, %r12 nop nop cmp %rsi, %rsi mov (%r12), %r8 lea oracles, %r12 and $0xff, %r8 shlq $12, %r8 mov (%r12,%r8,1), %r8 pop %rsi pop %r8 pop %r14 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 2}} {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_P', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 8}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 5}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4, 'NT': True, 'same': False, 'congruent': 1}} {'src': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 4}} {'src': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'size': 32, 'NT': True, 'same': False, 'congruent': 9}} {'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 2}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 10}, 'OP': 'LOAD'} {'00': 128} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A133350: Dimensions of certain Lie algebra (see reference for precise definition). ; 1,90,1274,8568,38115,130130,369460,915552,2043621,4198810,8065134,14651000,25393095,42280434,68000360,106108288,161222985,239249178,347629282,495626040,694637867,958548690,1304114076,1751385440,2324174125,3050557146,3963426390 mul $0,2 mov $1,5 lpb $0 mov $2,$0 sub $0,1 seq $2,114244 ; a(n) = (n+1)(n+2)^2*(n+3)(7n^2 + 28n + 30)/360. add $1,$2 lpe sub $1,4 mov $0,$1
;; ;; Copyright (c) 2012-2018, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation nor the names of its contributors ;; may be used to endorse or promote products derived from this software ;; without specific prior written permission. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; ; Routine to do AES key expansion %include "os.asm" %macro key_expansion_128_sse 0 ;; Assumes the xmm3 includes all zeros at this point. pshufd xmm2, xmm2, 11111111b shufps xmm3, xmm1, 00010000b pxor xmm1, xmm3 shufps xmm3, xmm1, 10001100b pxor xmm1, xmm3 pxor xmm1, xmm2 %endmacro %macro key_expansion_128_avx 0 ;; Assumes the xmm3 includes all zeros at this point. vpshufd xmm2, xmm2, 11111111b vshufps xmm3, xmm3, xmm1, 00010000b vpxor xmm1, xmm1, xmm3 vshufps xmm3, xmm3, xmm1, 10001100b vpxor xmm1, xmm1, xmm3 vpxor xmm1, xmm1, xmm2 %endmacro %ifdef LINUX %define KEY rdi %define EXP_ENC_KEYS rsi %define EXP_DEC_KEYS rdx %else %define KEY rcx %define EXP_ENC_KEYS rdx %define EXP_DEC_KEYS r8 %endif section .text ; void aes_keyexp_128(UINT128 *key, ; UINT128 *enc_exp_keys, ; UINT128 *dec_exp_keys); ; ; arg 1: rcx: pointer to key ; arg 2: rdx: pointer to expanded key array for encrypt ; arg 3: r8: pointer to expanded key array for decrypt ; MKGLOBAL(aes_keyexp_128_sse,function,) aes_keyexp_128_sse: movdqu xmm1, [KEY] ; loading the AES key movdqa [EXP_ENC_KEYS + 16*0], xmm1 movdqa [EXP_DEC_KEYS + 16*10], xmm1 ; Storing key in memory pxor xmm3, xmm3 aeskeygenassist xmm2, xmm1, 0x1 ; Generating round key 1 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*1], xmm1 aesimc xmm4, xmm1 movdqa [EXP_DEC_KEYS + 16*9], xmm4 aeskeygenassist xmm2, xmm1, 0x2 ; Generating round key 2 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*2], xmm1 aesimc xmm5, xmm1 movdqa [EXP_DEC_KEYS + 16*8], xmm5 aeskeygenassist xmm2, xmm1, 0x4 ; Generating round key 3 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*3], xmm1 aesimc xmm4, xmm1 movdqa [EXP_DEC_KEYS + 16*7], xmm4 aeskeygenassist xmm2, xmm1, 0x8 ; Generating round key 4 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*4], xmm1 aesimc xmm5, xmm1 movdqa [EXP_DEC_KEYS + 16*6], xmm5 aeskeygenassist xmm2, xmm1, 0x10 ; Generating round key 5 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*5], xmm1 aesimc xmm4, xmm1 movdqa [EXP_DEC_KEYS + 16*5], xmm4 aeskeygenassist xmm2, xmm1, 0x20 ; Generating round key 6 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*6], xmm1 aesimc xmm5, xmm1 movdqa [EXP_DEC_KEYS + 16*4], xmm5 aeskeygenassist xmm2, xmm1, 0x40 ; Generating round key 7 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*7], xmm1 aesimc xmm4, xmm1 movdqa [EXP_DEC_KEYS + 16*3], xmm4 aeskeygenassist xmm2, xmm1, 0x80 ; Generating round key 8 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*8], xmm1 aesimc xmm5, xmm1 movdqa [EXP_DEC_KEYS + 16*2], xmm5 aeskeygenassist xmm2, xmm1, 0x1b ; Generating round key 9 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*9], xmm1 aesimc xmm4, xmm1 movdqa [EXP_DEC_KEYS + 16*1], xmm4 aeskeygenassist xmm2, xmm1, 0x36 ; Generating round key 10 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*10], xmm1 movdqa [EXP_DEC_KEYS + 16*0], xmm1 ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; MKGLOBAL(aes_keyexp_128_avx,function,) aes_keyexp_128_avx: vmovdqu xmm1, [KEY] ; loading the AES key vmovdqa [EXP_ENC_KEYS + 16*0], xmm1 vmovdqa [EXP_DEC_KEYS + 16*10], xmm1 ; Storing key in memory vpxor xmm3, xmm3, xmm3 vaeskeygenassist xmm2, xmm1, 0x1 ; Generating round key 1 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*1], xmm1 vaesimc xmm4, xmm1 vmovdqa [EXP_DEC_KEYS + 16*9], xmm4 vaeskeygenassist xmm2, xmm1, 0x2 ; Generating round key 2 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*2], xmm1 vaesimc xmm5, xmm1 vmovdqa [EXP_DEC_KEYS + 16*8], xmm5 vaeskeygenassist xmm2, xmm1, 0x4 ; Generating round key 3 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*3], xmm1 vaesimc xmm4, xmm1 vmovdqa [EXP_DEC_KEYS + 16*7], xmm4 vaeskeygenassist xmm2, xmm1, 0x8 ; Generating round key 4 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*4], xmm1 vaesimc xmm5, xmm1 vmovdqa [EXP_DEC_KEYS + 16*6], xmm5 vaeskeygenassist xmm2, xmm1, 0x10 ; Generating round key 5 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*5], xmm1 vaesimc xmm4, xmm1 vmovdqa [EXP_DEC_KEYS + 16*5], xmm4 vaeskeygenassist xmm2, xmm1, 0x20 ; Generating round key 6 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*6], xmm1 vaesimc xmm5, xmm1 vmovdqa [EXP_DEC_KEYS + 16*4], xmm5 vaeskeygenassist xmm2, xmm1, 0x40 ; Generating round key 7 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*7], xmm1 vaesimc xmm4, xmm1 vmovdqa [EXP_DEC_KEYS + 16*3], xmm4 vaeskeygenassist xmm2, xmm1, 0x80 ; Generating round key 8 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*8], xmm1 vaesimc xmm5, xmm1 vmovdqa [EXP_DEC_KEYS + 16*2], xmm5 vaeskeygenassist xmm2, xmm1, 0x1b ; Generating round key 9 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*9], xmm1 vaesimc xmm4, xmm1 vmovdqa [EXP_DEC_KEYS + 16*1], xmm4 vaeskeygenassist xmm2, xmm1, 0x36 ; Generating round key 10 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*10], xmm1 vmovdqa [EXP_DEC_KEYS + 16*0], xmm1 ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; void aes_keyexp_128_enc_sse(UINT128 *key, ; UINT128 *enc_exp_keys); ; ; arg 1: rcx: pointer to key ; arg 2: rdx: pointer to expanded key array for encrypt ; MKGLOBAL(aes_keyexp_128_enc_sse,function,) aes_keyexp_128_enc_sse: movdqu xmm1, [KEY] ; loading the AES key movdqa [EXP_ENC_KEYS + 16*0], xmm1 pxor xmm3, xmm3 aeskeygenassist xmm2, xmm1, 0x1 ; Generating round key 1 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*1], xmm1 aeskeygenassist xmm2, xmm1, 0x2 ; Generating round key 2 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*2], xmm1 aeskeygenassist xmm2, xmm1, 0x4 ; Generating round key 3 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*3], xmm1 aeskeygenassist xmm2, xmm1, 0x8 ; Generating round key 4 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*4], xmm1 aeskeygenassist xmm2, xmm1, 0x10 ; Generating round key 5 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*5], xmm1 aeskeygenassist xmm2, xmm1, 0x20 ; Generating round key 6 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*6], xmm1 aeskeygenassist xmm2, xmm1, 0x40 ; Generating round key 7 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*7], xmm1 aeskeygenassist xmm2, xmm1, 0x80 ; Generating round key 8 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*8], xmm1 aeskeygenassist xmm2, xmm1, 0x1b ; Generating round key 9 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*9], xmm1 aeskeygenassist xmm2, xmm1, 0x36 ; Generating round key 10 key_expansion_128_sse movdqa [EXP_ENC_KEYS + 16*10], xmm1 ret MKGLOBAL(aes_keyexp_128_enc_avx,function,) aes_keyexp_128_enc_avx: vmovdqu xmm1, [KEY] ; loading the AES key vmovdqa [EXP_ENC_KEYS + 16*0], xmm1 vpxor xmm3, xmm3, xmm3 vaeskeygenassist xmm2, xmm1, 0x1 ; Generating round key 1 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*1], xmm1 vaeskeygenassist xmm2, xmm1, 0x2 ; Generating round key 2 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*2], xmm1 vaeskeygenassist xmm2, xmm1, 0x4 ; Generating round key 3 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*3], xmm1 vaeskeygenassist xmm2, xmm1, 0x8 ; Generating round key 4 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*4], xmm1 vaeskeygenassist xmm2, xmm1, 0x10 ; Generating round key 5 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*5], xmm1 vaeskeygenassist xmm2, xmm1, 0x20 ; Generating round key 6 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*6], xmm1 vaeskeygenassist xmm2, xmm1, 0x40 ; Generating round key 7 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*7], xmm1 vaeskeygenassist xmm2, xmm1, 0x80 ; Generating round key 8 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*8], xmm1 vaeskeygenassist xmm2, xmm1, 0x1b ; Generating round key 9 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*9], xmm1 vaeskeygenassist xmm2, xmm1, 0x36 ; Generating round key 10 key_expansion_128_avx vmovdqa [EXP_ENC_KEYS + 16*10], xmm1 ret %ifdef LINUX section .note.GNU-stack noalloc noexec nowrite progbits %endif
// Range v3 library // // Copyright Eric Niebler 2014-present // Copyright Tomislav Ivek 2015-2016 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 #include <vector> #include <sstream> #include <range/v3/core.hpp> #include <range/v3/algorithm/set_algorithm.hpp> #include <range/v3/algorithm/move.hpp> #include <range/v3/functional/identity.hpp> #include <range/v3/iterator/operations.hpp> #include <range/v3/iterator/insert_iterators.hpp> #include <range/v3/utility/common_type.hpp> #include <range/v3/utility/copy.hpp> #include <range/v3/view/all.hpp> #include <range/v3/view/const.hpp> #include <range/v3/view/drop_while.hpp> #include <range/v3/view/iota.hpp> #include <range/v3/view/move.hpp> #include <range/v3/view/reverse.hpp> #include <range/v3/view/set_algorithm.hpp> #include <range/v3/view/stride.hpp> #include <range/v3/view/take.hpp> #include <range/v3/view/transform.hpp> #include "../simple_test.hpp" #include "../test_utils.hpp" int main() { using namespace ranges; int i1_finite[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4}; int i2_finite[] = { -3, 2, 4, 4, 6, 9}; auto i1_infinite = view::ints | view::stride(3); auto i2_infinite = view::ints | view::transform([](int x) { return x * x; }); // simple identity check { ::check_equal(view::set_union(i1_infinite, i1_infinite) | view::take(100), i1_infinite | view::take(100)); } // union of two finite ranges/sets { auto res = view::set_union(i1_finite, i2_finite); models<ForwardViewConcept>(aux::copy(res)); models_not<RandomAccessViewConcept>(aux::copy(res)); models_not<CommonViewConcept>(aux::copy(res)); using R = decltype(res); CPP_assert(Same<range_value_t<R>, int>); CPP_assert(Same<range_reference_t<R>, int&>); CPP_assert(Same<decltype(iter_move(begin(res))), int&&>); static_assert(range_cardinality<R>::value == ranges::finite, "Cardinality of union of finite ranges should be finite!"); ::check_equal(res, {-3, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 9}); // check if the final result agrees with the greedy algorithm std::vector<int> greedy_union; set_union(i1_finite, i2_finite, back_inserter(greedy_union)); ::check_equal(res, greedy_union); auto it = begin(res); CHECK(&*it == &*(begin(i2_finite))); ++it; CHECK(&*it == &*(begin(i1_finite))); } // union of two infinite ranges { auto res = view::set_union(i1_infinite, i2_infinite); models<ForwardViewConcept>(aux::copy(res)); models_not<RandomAccessViewConcept>(aux::copy(res)); models_not<CommonViewConcept>(aux::copy(res)); using R = decltype(res); CPP_assert(Same<range_value_t<R>, common_type_t<range_value_t<decltype(i1_infinite)>, range_value_t<decltype(i2_infinite)>>>); CPP_assert(Same<range_reference_t<R>, common_reference_t<range_reference_t<decltype(i1_infinite)>, range_reference_t<decltype(i2_infinite)>> >); CPP_assert(Same<range_rvalue_reference_t<R>, common_reference_t<range_rvalue_reference_t<decltype(i1_infinite)>, range_rvalue_reference_t<decltype(i2_infinite)>> >); static_assert(range_cardinality<R>::value == ranges::infinite, "Cardinality of union of infinite ranges should be infinite!"); ::check_equal(res | view::take(6), {0, 1, 3, 4, 6, 9}); // check if the final result agrees with the greedy algorithm std::vector<int> greedy_union; set_union(i1_infinite | view::take(10), i2_infinite | view::take(10), back_inserter(greedy_union)); ::check_equal(res | view::take(6), greedy_union | view::take(6)); } // union of a finite and an infinite range { auto res = view::set_union(i1_finite, i2_infinite); models<ForwardViewConcept>(aux::copy(res)); models_not<RandomAccessViewConcept>(aux::copy(res)); models_not<CommonViewConcept>(aux::copy(res)); using R = decltype(res); CPP_assert(Same<range_value_t<R>, int>); CPP_assert(Same<range_reference_t<R>, int>); // our infinite range does not give out references CPP_assert(Same<range_rvalue_reference_t<R>, int>); static_assert(range_cardinality<R>::value == ranges::infinite, "Cardinality of union with an infinite range should be infinite!"); ::check_equal(res | view::take(5), {0, 1, 2, 2, 3}); } // union of an infinite and a finite range { auto res = view::set_union(i1_infinite, i2_finite); models<ForwardViewConcept>(aux::copy(res)); models_not<RandomAccessViewConcept>(aux::copy(res)); models_not<CommonViewConcept>(aux::copy(res)); using R = decltype(res); CPP_assert(Same<range_value_t<R>, int>); CPP_assert(Same<range_reference_t<R>, int>); // our infinite range does not give out references CPP_assert(Same<range_rvalue_reference_t<R>, int>); static_assert(range_cardinality<R>::value == ranges::infinite, "Cardinality of union with an infinite range should be infinite!"); ::check_equal(res | view::take(7), {-3, 0, 2, 3, 4, 4, 6}); } // unions involving unknown cardinalities { auto rng0 = view::iota(10) | view::drop_while([](int i) { return i < 25; }); static_assert(range_cardinality<decltype(rng0)>::value == ranges::unknown, ""); auto res1 = view::set_union(i2_finite, rng0); static_assert(range_cardinality<decltype(res1)>::value == ranges::unknown, "Union of a finite and unknown cardinality set should have unknown cardinality!"); auto res2 = view::set_union(rng0, i2_finite); static_assert(range_cardinality<decltype(res2)>::value == ranges::unknown, "Union of an unknown and finite cardinality set should have unknown cardinality!"); auto res3 = view::set_union(i1_infinite, rng0); static_assert(range_cardinality<decltype(res3)>::value == ranges::infinite, "Union of an infinite and unknown cardinality set should have infinite cardinality!"); auto res4 = view::set_union(rng0, i1_infinite); static_assert(range_cardinality<decltype(res4)>::value == ranges::infinite, "Union of an unknown and infinite cardinality set should have infinite cardinality!"); auto res5 = view::set_union(rng0, rng0); static_assert(range_cardinality<decltype(res5)>::value == ranges::unknown, "Union of two unknown cardinality sets should have unknown cardinality!"); ::check_equal(res5 | view::take(100), rng0 | view::take(100)); } // test const ranges { auto res1 = view::set_union(view::const_(i1_finite), view::const_(i2_finite)); using R1 = decltype(res1); CPP_assert(Same<range_value_t<R1>, int>); CPP_assert(Same<range_reference_t<R1>, const int&>); CPP_assert(Same<range_rvalue_reference_t<R1>, const int&&>); auto res2 = view::set_union(view::const_(i1_finite), i2_finite); using R2 = decltype(res2); CPP_assert(Same<range_value_t<R2>, int>); CPP_assert(Same<range_reference_t<R2>, const int&>); CPP_assert(Same<range_rvalue_reference_t<R2>, const int&&>); } // test different orderings { auto res = view::set_union(view::reverse(i1_finite), view::reverse(i2_finite), [](int a, int b) { return a > b; }); ::check_equal(res, {9, 6, 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, -3}); } struct B { int val; B(int i): val{i} {} bool operator==(const B& other) const { return val == other.val; } }; struct D: public B { D(int i): B{i} {} D(B b): B{std::move(b)} {} }; B b_finite[] = {B{-20}, B{-10}, B{1}, B{3}, B{3}, B{6}, B{8}, B{20}}; D d_finite[] = {D{0}, D{2}, D{4}, D{6}}; // sets with different element types, custom orderings { auto res = view::set_union(b_finite, d_finite, [](const B& a, const D& b){ return a.val < b.val; }); using R = decltype(res); CPP_assert(Same<range_value_t<R>, B>); CPP_assert(Same<range_reference_t<R>, B&>); CPP_assert(Same<range_rvalue_reference_t<R>, B&&>); ::check_equal(res, {B{-20}, B{-10}, B{0}, B{1}, B{2}, B{3}, B{3}, B{4}, B{6}, B{8}, B{20}}); auto it = begin(res); CHECK(&*it == &*begin(b_finite)); advance(it, 2); CHECK(&*it == &*begin(d_finite)); } // projections { auto res1 = view::set_union(b_finite, d_finite, less(), &B::val, &D::val ); using R1 = decltype(res1); CPP_assert(Same<range_value_t<R1>, B>); CPP_assert(Same<range_reference_t<R1>, B&>); CPP_assert(Same<range_rvalue_reference_t<R1>, B&&>); ::check_equal(res1, {B{-20}, B{-10}, B{0}, B{1}, B{2}, B{3}, B{3}, B{4}, B{6}, B{8}, B{20}}); auto res2 = view::set_union(view::ints(-2, 10), b_finite, less(), identity(), [](const B& x){ return x.val; } ); using R2 = decltype(res2); CPP_assert(Same<range_value_t<R2>, B>); CPP_assert(Same<range_reference_t<R2>, B>); CPP_assert(Same<range_rvalue_reference_t<R2>, B>); ::check_equal(res2, {B{-20}, B{-10}, B{-2}, B{-1}, B{0}, B{1}, B{2}, B{3}, B{3}, B{4}, B{5}, B{6}, B{7}, B{8}, B{9}, B{20}}); } // move { auto v0 = to<std::vector<MoveOnlyString>>({"a","b","c","x"}); auto v1 = to<std::vector<MoveOnlyString>>({"b","x","y","z"}); auto res = view::set_union(v0, v1, [](const MoveOnlyString& a, const MoveOnlyString& b){return a<b;}); std::vector<MoveOnlyString> expected; move(res, back_inserter(expected)); ::check_equal(expected, {"a","b","c","x","y","z"}); ::check_equal(v0, {"","","",""}); ::check_equal(v1, {"b","x","",""}); using R = decltype(res); CPP_assert(Same<range_value_t<R>, MoveOnlyString>); CPP_assert(Same<range_reference_t<R>, MoveOnlyString &>); CPP_assert(Same<range_rvalue_reference_t<R>, MoveOnlyString &&>); } // iterator (in)equality { int r1[] = {1, 2, 3}; int r2[] = { 2, 3, 4, 5}; auto res = view::set_union(r1, r2); // 1, 2, 3, 4, 5 auto it1 = ranges::next(res.begin(), 3); // *it1 == 4, member iterator into r1 points to r1.end() auto it2 = ranges::next(it1); // *it2 == 5, member iterator into r1 also points to r1.end() auto sentinel = res.end(); CHECK(*it1 == 4); CHECK(*it2 == 5); CHECK(it1 != it2); // should be different even though member iterators into r1 are the same CHECK(it1 != sentinel); CHECK(ranges::next(it1, 2) == sentinel); CHECK(it2 != sentinel); CHECK(ranges::next(it2, 1) == sentinel); } { auto rng = view::set_union( debug_input_view<int const>{i1_finite}, debug_input_view<int const>{i2_finite} ); ::check_equal(rng, {-3, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 6, 9}); } return test_result(); }
; A240876: Expansion of (1 + x)^11 / (1 - x)^12. ; Submitted by Christian Krause ; 1,23,265,2047,11969,56695,227305,795455,2485825,7059735,18474633,45046719,103274625,224298231,464387817,921406335,1759885185,3248227095,5812626185,10113604735,17152640321,28418229623,46082942185,73265596607,114375683009,175560601111,265280226953,395037809215,580301276417,841654759159,1206226549225,1709446884095,2397196917505,3328419072535,4578268733705,6241897981183,8438973867969,11319046656375,15067897531881,19915010671167,26142331229505,34094488905495,44190686315145,56938472541375 mov $1,1 mov $3,$0 mov $0,20 mov $2,1 mov $4,2 lpb $3 add $0,2 mul $1,$3 mul $1,$0 sub $0,4 sub $3,1 sub $5,1 add $5,$4 div $1,$5 add $2,$1 add $4,2 lpe mov $0,$2
{ 'abc_class': 'AbcFile' , 'minor_version': 16 , 'major_version': 46 , 'int_pool': [ undefined , '10' , '0' , '1' ] , 'uint_pool': [ undefined ] , 'double_pool': [ undefined ] , 'utf8_pool': [ undefined , '' , 'Object' , 'Array' , 'RegExp' , 'x' , 'print' ] , 'namespace_pool': [ undefined , { 'kind': 'PackageNamespace' , 'utf8': 1 } , { 'kind': 'Namespace' , 'utf8': 1 } ] , 'nsset_pool': [ undefined , [ 2 ] ] , 'name_pool': [ undefined , { 'kind': 'QName' , 'ns': 1 , 'utf8': 2 } , { 'kind': 'QName' , 'ns': 1 , 'utf8': 3 } , { 'kind': 'QName' , 'ns': 1 , 'utf8': 4 } , { 'kind': 'QName' , 'ns': 2 , 'utf8': 5 } , { 'kind': 'Multiname' , 'utf8': 5 , 'nsset': 1 } , { 'kind': 'Multiname' , 'utf8': 6 , 'nsset': 1 } ] , 'method_infos': [ { 'ret_type': 0 , 'param_types': [] , 'name': 0 , 'flags': 0 , 'optional_count': 0 , 'value_kind': [ ] , 'param_names': [ ] } , ] , 'metadata_infos': [ ] , 'instance_infos': [ ] , 'class_infos': [ ] , 'script_infos': [ { 'init': 0 , 'traits': [ { 'name': 4 , 'kind': 0 , 'attrs': 0 , 'slot_id': 0 , 'type_name': 0 , 'val_index': 0 } , ] } , ] , 'method_bodys': [ { 'method_info': 0 , 'max_stack': 3 , 'max_regs': 2 , 'scope_depth': 0 , 'max_scope': 1 , 'code': [ [ 'getlocal0' ] , [ 'pushscope' ] , [ 'findproperty', 4 ] , [ 'pushint', 1 ] , [ 'setproperty', 4 ] , [ 'pushundefined' ] , [ 'pop' ] , [ 'jump', 49 ] , [ 'label' ] , [ 'findpropstrict', 5 ] , [ 'getproperty', 5 ] , [ 'pushint', 2 ] , [ 'greaterthan' ] , [ 'iffalse', 33 ] , [ 'findpropstrict', 6 ] , [ 'getproperty', 6 ] , [ 'pushnull' ] , [ 'findpropstrict', 5 ] , [ 'getproperty', 5 ] , [ 'call', 1 ] , [ 'pop' ] , [ 'findproperty', 5 ] , [ 'findpropstrict', 5 ] , [ 'getproperty', 5 ] , [ 'pushint', 3 ] , [ 'subtract' ] , [ 'dup' ] , [ 'setlocal1' ] , [ 'setproperty', 5 ] , [ 'getlocal1' ] , [ 'kill', 1 ] , [ 'pop' ] , [ 'jump', 4 ] , [ 'jump', 5 ] , [ 'pushtrue' ] , [ 'iftrue', 16777162 ] , [ 'findpropstrict', 6 ] , [ 'getproperty', 6 ] , [ 'pushnull' ] , [ 'pushtrue' ] , [ 'call', 1 ] , [ 'pop' ] , [ 'returnvoid' ] , ] , 'exceptions': [ ] , 'fixtures': [ ] , 'traits': [ ] } , ] }
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r12 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x12b17, %r10 nop nop sub $26660, %rax mov (%r10), %r11w nop nop cmp $2888, %r12 lea addresses_WT_ht+0x1163, %r11 nop nop nop nop nop and %rax, %rax mov $0x6162636465666768, %rbx movq %rbx, (%r11) nop nop cmp $47650, %rbx lea addresses_WC_ht+0x2a07, %r10 nop nop xor $59655, %r11 mov (%r10), %r12d nop nop nop nop sub %r11, %r11 lea addresses_D_ht+0x3e93, %rcx nop nop nop cmp $4042, %rsi mov (%rcx), %r10 lfence lea addresses_WT_ht+0x6023, %r11 nop nop nop nop inc %r10 mov (%r11), %rbx nop nop xor %r10, %r10 lea addresses_WC_ht+0xfdab, %rax nop nop nop nop nop add $16318, %r10 mov (%rax), %cx and %r10, %r10 lea addresses_D_ht+0x1de77, %rsi lea addresses_D_ht+0x3ae7, %rdi nop nop nop nop and %r12, %r12 mov $10, %rcx rep movsl nop nop nop nop nop xor %rax, %rax lea addresses_D_ht+0x16023, %rcx nop nop nop nop nop and %r11, %r11 mov (%rcx), %rdi nop nop nop dec %r11 lea addresses_normal_ht+0x1ce23, %rsi nop nop nop nop cmp %r12, %r12 mov (%rsi), %r11 nop nop add $1286, %rbx lea addresses_WT_ht+0xb4a3, %r10 clflush (%r10) nop nop nop nop add %r12, %r12 mov (%r10), %bx add %r12, %r12 pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r12 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r15 push %rbp push %rcx push %rdi push %rdx push %rsi // Load lea addresses_PSE+0xc823, %r13 clflush (%r13) nop inc %r12 mov (%r13), %edi nop nop add $13998, %rdi // Store lea addresses_normal+0x9670, %r15 clflush (%r15) nop and %r10, %r10 movl $0x51525354, (%r15) nop nop nop nop add $21643, %r13 // REPMOV lea addresses_PSE+0xc823, %rsi lea addresses_PSE+0xc823, %rdi clflush (%rdi) nop nop nop nop xor $4333, %rdx mov $21, %rcx rep movsb cmp $5884, %rbp // Store lea addresses_RW+0x19063, %rdx cmp $49082, %r13 movb $0x51, (%rdx) nop cmp $5830, %rsi // Store lea addresses_WC+0xe0e3, %rdx nop add $19260, %r12 mov $0x5152535455565758, %rdi movq %rdi, %xmm3 movntdq %xmm3, (%rdx) nop nop nop sub $35222, %rdx // Faulty Load lea addresses_PSE+0xc823, %rsi nop nop nop nop nop cmp $20159, %r13 mov (%rsi), %ebp lea oracles, %r15 and $0xff, %rbp shlq $12, %rbp mov (%r15,%rbp,1), %rbp pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r15 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_PSE', 'congruent': 0, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 6, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 6, 'same': False}} {'33': 27} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */