text stringlengths 1 1.05M |
|---|
/* Copyright 2015 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/core/graph/node_builder.h"
#include <unordered_map>
#include <vector>
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/framework/versions.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/statusor.h"
#include "tensorflow/core/protobuf/error_codes.pb.h"
namespace tensorflow {
NodeBuilder::NodeOut::NodeOut(Node* n, int32_t i) // NOLINT(runtime/explicit)
: node(n),
error(false),
name(node != nullptr ? node->name() : (error = true, "")),
index(i),
dt(SafeGetOutput(node, i, &error)) {}
NodeBuilder::NodeOut::NodeOut(OutputTensor t) : NodeOut(t.node, t.index) {}
NodeBuilder::NodeOut::NodeOut(StringPiece n, int32_t i, DataType t)
: node(nullptr), error(false), name(n), index(i), dt(t) {}
NodeBuilder::NodeOut::NodeOut()
: node(nullptr), error(true), index(0), dt(DT_FLOAT) {}
NodeBuilder::NodeBuilder(StringPiece name, StringPiece op_name,
const OpRegistryInterface* op_registry,
const NodeDebugInfo* debug)
: def_builder_(name, op_name, op_registry, debug) {}
NodeBuilder::NodeBuilder(StringPiece name, const OpDef* op_def)
: def_builder_(name, op_def) {}
NodeBuilder::NodeBuilder(const NodeDefBuilder& def_builder)
: def_builder_(def_builder) {}
NodeBuilder& NodeBuilder::Input(Node* src_node, int src_index) {
inputs_.emplace_back(src_node, src_index);
DataType dt;
if (GetOutputType(src_node, src_index, &dt)) {
def_builder_.Input(src_node->name(), src_index, dt);
}
return *this;
}
NodeBuilder& NodeBuilder::Input(NodeOut src) {
if (src.error) {
AddIndexError(src.node, src.index);
} else {
inputs_.emplace_back(src.node, src.index);
def_builder_.Input(src.name, src.index, src.dt);
}
return *this;
}
NodeBuilder& NodeBuilder::Input(gtl::ArraySlice<NodeOut> src_list) {
std::vector<NodeDefBuilder::NodeOut> srcs;
srcs.reserve(src_list.size());
for (const auto& node_out : src_list) {
if (node_out.error) {
AddIndexError(node_out.node, node_out.index);
} else {
srcs.emplace_back(node_out.name, node_out.index, node_out.dt);
inputs_.emplace_back(node_out.node, node_out.index);
}
}
def_builder_.Input(gtl::ArraySlice<NodeDefBuilder::NodeOut>(srcs));
return *this;
}
NodeBuilder& NodeBuilder::ControlInput(Node* src_node) {
control_inputs_.emplace_back(src_node);
def_builder_.ControlInput(src_node->name());
return *this;
}
NodeBuilder& NodeBuilder::ControlInputs(gtl::ArraySlice<Node*> src_nodes) {
control_inputs_.insert(control_inputs_.end(), src_nodes.begin(),
src_nodes.end());
for (const Node* src_node : src_nodes) {
def_builder_.ControlInput(src_node->name());
}
return *this;
}
NodeBuilder& NodeBuilder::Device(StringPiece device_spec) {
def_builder_.Device(device_spec);
return *this;
}
NodeBuilder& NodeBuilder::AssignedDevice(StringPiece device) {
assigned_device_ = string(device);
return *this;
}
NodeBuilder& NodeBuilder::XlaCluster(StringPiece xla_cluster) {
def_builder_.Attr("_XlaCluster", xla_cluster);
return *this;
}
StatusOr<Node*> NodeBuilder::Finalize(Graph* graph, bool consume) {
Node* out;
TF_RETURN_IF_ERROR(Finalize(graph, &out, consume));
return out;
}
Status NodeBuilder::Finalize(Graph* graph, Node** created_node, bool consume) {
// In case of error, set *created_node to nullptr.
if (created_node != nullptr) {
*created_node = nullptr;
}
if (!errors_.empty()) {
return errors::InvalidArgument(absl::StrJoin(errors_, "\n"));
}
NodeDef node_def;
TF_RETURN_IF_ERROR(def_builder_.Finalize(&node_def, consume));
TF_RETURN_IF_ERROR(ValidateNodeDef(node_def, def_builder_.op_def()));
TF_RETURN_IF_ERROR(
CheckOpDeprecation(def_builder_.op_def(), graph->versions().producer()));
TF_ASSIGN_OR_RETURN(Node * node, graph->AddNode(std::move(node_def)));
node->set_assigned_device_name(assigned_device_);
for (size_t i = 0; i < inputs_.size(); ++i) {
if (inputs_[i].node != nullptr) { // Skip back edges.
graph->AddEdge(inputs_[i].node, inputs_[i].index, node, i);
}
}
for (Node* control_input : control_inputs_) {
graph->AddControlEdge(control_input, node);
}
if (created_node != nullptr) *created_node = node;
return OkStatus();
}
void NodeBuilder::AddIndexError(const Node* node, int i) {
if (node == nullptr) {
errors_.emplace_back(
strings::StrCat("Attempt to add nullptr Node to node with type ",
def_builder_.op_def().name()));
} else {
errors_.emplace_back(strings::StrCat(
"Attempt to add output ", i, " of ", node->name(), " not in range [0, ",
node->num_outputs(), ") to node with type ",
def_builder_.op_def().name(), ". Node: ", FormatNodeForError(*node)));
}
}
bool NodeBuilder::GetOutputType(const Node* node, int i, DataType* dt) {
bool error;
*dt = SafeGetOutput(node, i, &error);
if (error) AddIndexError(node, i);
return !error;
}
} // namespace tensorflow
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>linkat(fromfd, from_, tofd, to, flags) -> str
Invokes the syscall linkat.
See 'man 2 linkat' for more information.
Arguments:
fromfd(int): fromfd
from_(char*): from
tofd(int): tofd
to(char*): to
flags(int): flags
Returns:
int
</%docstring>
<%page args="fromfd=0, from_=0, tofd=0, to=0, flags=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['from', 'to']
can_pushstr_array = []
argument_names = ['fromfd', 'from', 'tofd', 'to', 'flags']
argument_values = [fromfd, from_, tofd, to, flags]
# Load all of the arguments into their destination registers / stack slots.
register_arguments = dict()
stack_arguments = collections.OrderedDict()
string_arguments = dict()
dict_arguments = dict()
array_arguments = dict()
syscall_repr = []
for name, arg in zip(argument_names, argument_values):
if arg is not None:
syscall_repr.append('%s=%s' % (name, pwnlib.shellcraft.pretty(arg, False)))
# If the argument itself (input) is a register...
if arg in allregs:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[index] = arg
# The argument is not a register. It is a string value, and we
# are expecting a string value
elif name in can_pushstr and isinstance(arg, (six.binary_type, six.text_type)):
if isinstance(arg, six.text_type):
arg = arg.encode('utf-8')
string_arguments[name] = arg
# The argument is not a register. It is a dictionary, and we are
# expecting K:V paris.
elif name in can_pushstr_array and isinstance(arg, dict):
array_arguments[name] = ['%s=%s' % (k,v) for (k,v) in arg.items()]
# The arguent is not a register. It is a list, and we are expecting
# a list of arguments.
elif name in can_pushstr_array and isinstance(arg, (list, tuple)):
array_arguments[name] = arg
# The argument is not a register, string, dict, or list.
# It could be a constant string ('O_RDONLY') for an integer argument,
# an actual integer value, or a constant.
else:
index = argument_names.index(name)
if index < len(regs):
target = regs[index]
register_arguments[target] = arg
elif arg is not None:
stack_arguments[target] = arg
# Some syscalls have different names on various architectures.
# Determine which syscall number to use for the current architecture.
for syscall in ['SYS_linkat']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* linkat(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=(b'\x00' not in arg))}
${pwnlib.shellcraft.mov(regs[argument_names.index(name)], abi.stack)}
%endfor
%for name, arg in array_arguments.items():
${pwnlib.shellcraft.pushstr_array(regs[argument_names.index(name)], arg)}
%endfor
%for name, arg in stack_arguments.items():
${pwnlib.shellcraft.push(arg)}
%endfor
${pwnlib.shellcraft.setregs(register_arguments)}
${pwnlib.shellcraft.syscall(syscall)}
|
; Raise the latch line so that we can lower it on a later line.
sbi PORTC, 5
|
; A014993: a(n) = (1 - (-11)^n)/12.
; 1,-10,111,-1220,13421,-147630,1623931,-17863240,196495641,-2161452050,23775972551,-261535698060,2876892678661,-31645819465270,348104014117971,-3829144155297680,42120585708274481,-463326442791019290,5096590870701212191,-56062499577713334100,616687495354846675101,-6783562448903313426110,74619186937936447687211,-820811056317300924559320,9028921619490310170152521,-99318137814393411871677730,1092499515958327530588455031,-12017494675541602836473005340,132192441430957631201203058741,-1454116855740533943213233646150,15995285413145873375345570107651,-175948139544604607128801271184160,1935429534990650678416813983025761,-21289724884897157462584953813283370,234186973733868732088434491946117071
add $0,1
lpb $0
sub $0,1
sub $1,11
mul $1,-11
lpe
div $1,121
mov $0,$1
|
; A157948: a(n) = 64*n^2 - n.
; 63,254,573,1020,1595,2298,3129,4088,5175,6390,7733,9204,10803,12530,14385,16368,18479,20718,23085,25580,28203,30954,33833,36840,39975,43238,46629,50148,53795,57570,61473,65504,69663,73950,78365,82908,87579,92378,97305,102360,107543,112854,118293,123860,129555,135378,141329,147408,153615,159950,166413,173004,179723,186570,193545,200648,207879,215238,222725,230340,238083,245954,253953,262080,270335,278718,287229,295868,304635,313530,322553,331704,340983,350390,359925,369588,379379,389298,399345,409520,419823,430254,440813,451500,462315,473258,484329,495528,506855,518310,529893,541604,553443,565410,577505,589728,602079,614558,627165,639900,652763,665754,678873,692120,705495,718998,732629,746388,760275,774290,788433,802704,817103,831630,846285,861068,875979,891018,906185,921480,936903,952454,968133,983940,999875,1015938,1032129,1048448,1064895,1081470,1098173,1115004,1131963,1149050,1166265,1183608,1201079,1218678,1236405,1254260,1272243,1290354,1308593,1326960,1345455,1364078,1382829,1401708,1420715,1439850,1459113,1478504,1498023,1517670,1537445,1557348,1577379,1597538,1617825,1638240,1658783,1679454,1700253,1721180,1742235,1763418,1784729,1806168,1827735,1849430,1871253,1893204,1915283,1937490,1959825,1982288,2004879,2027598,2050445,2073420,2096523,2119754,2143113,2166600,2190215,2213958,2237829,2261828,2285955,2310210,2334593,2359104,2383743,2408510,2433405,2458428,2483579,2508858,2534265,2559800,2585463,2611254,2637173,2663220,2689395,2715698,2742129,2768688,2795375,2822190,2849133,2876204,2903403,2930730,2958185,2985768,3013479,3041318,3069285,3097380,3125603,3153954,3182433,3211040,3239775,3268638,3297629,3326748,3355995,3385370,3414873,3444504,3474263,3504150,3534165,3564308,3594579,3624978,3655505,3686160,3716943,3747854,3778893,3810060,3841355,3872778,3904329,3936008,3967815,3999750
add $0,1
mul $0,64
bin $0,2
mov $1,$0
div $1,32
|
object_const_def ; object_event constants
OreburghMineB2F_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
OreburghMineB2F_MapEvents:
db 0, 0 ; filler
db 1 ; warp events
warp_event 13, 1, OREBURGH_MINE_B1F, 2
db 0 ; coord events
db 0 ; bg events
db 0 ; object events
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x9d4c, %rsi
lea addresses_D_ht+0xaccc, %rdi
nop
nop
nop
nop
inc %rax
mov $50, %rcx
rep movsq
nop
nop
nop
xor %r8, %r8
lea addresses_WC_ht+0x62cc, %r15
nop
add %rbx, %rbx
movl $0x61626364, (%r15)
nop
nop
nop
nop
nop
cmp %rdi, %rdi
lea addresses_normal_ht+0x1cbec, %rcx
nop
nop
nop
nop
inc %r8
movups (%rcx), %xmm3
vpextrq $1, %xmm3, %rax
cmp $56706, %rdi
lea addresses_WT_ht+0x138cc, %r8
sub %rdi, %rdi
mov $0x6162636465666768, %rax
movq %rax, (%r8)
nop
and $17040, %rbx
lea addresses_WC_ht+0x109c, %r15
nop
nop
nop
nop
sub %rsi, %rsi
mov $0x6162636465666768, %rbx
movq %rbx, (%r15)
nop
nop
nop
nop
cmp %rcx, %rcx
lea addresses_WT_ht+0x6bbc, %r8
nop
and %rsi, %rsi
mov $0x6162636465666768, %r15
movq %r15, %xmm4
movups %xmm4, (%r8)
nop
nop
nop
nop
nop
xor $13544, %r15
lea addresses_WC_ht+0xfd0, %rsi
dec %rax
movb (%rsi), %r15b
nop
add $56845, %rax
lea addresses_A_ht+0xc58c, %rcx
xor $1819, %rax
movb (%rcx), %r15b
nop
nop
xor %rax, %rax
lea addresses_normal_ht+0x58cc, %rsi
lea addresses_A_ht+0xe16c, %rdi
nop
nop
nop
nop
cmp $31138, %rdx
mov $90, %rcx
rep movsb
nop
inc %rbx
lea addresses_normal_ht+0x1914c, %rsi
lea addresses_normal_ht+0x100cc, %rdi
clflush (%rsi)
add $28523, %r15
mov $50, %rcx
rep movsq
add %rbx, %rbx
lea addresses_WT_ht+0x19b4c, %r15
nop
nop
nop
inc %rdi
mov (%r15), %esi
nop
nop
nop
nop
xor %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r15
push %r8
push %r9
push %rax
push %rbp
push %rdx
// Store
lea addresses_D+0x1aacc, %r9
nop
nop
nop
nop
cmp $7742, %rdx
movw $0x5152, (%r9)
and $19793, %r15
// Store
lea addresses_WT+0x25cc, %r14
nop
nop
nop
nop
nop
cmp $43204, %rax
mov $0x5152535455565758, %r9
movq %r9, (%r14)
add $45677, %rax
// Load
lea addresses_A+0x11acc, %r9
nop
nop
nop
nop
inc %rdx
movb (%r9), %r14b
nop
xor $27162, %rdx
// Store
lea addresses_normal+0x6acc, %r14
and %r8, %r8
mov $0x5152535455565758, %rdx
movq %rdx, (%r14)
nop
nop
nop
nop
nop
cmp $40854, %rbp
// Store
lea addresses_WC+0x7fcc, %r14
dec %rdx
movb $0x51, (%r14)
nop
nop
nop
nop
and %r15, %r15
// Store
lea addresses_WT+0x1815c, %rdx
dec %r14
mov $0x5152535455565758, %r8
movq %r8, (%rdx)
nop
nop
nop
nop
xor %rbp, %rbp
// Faulty Load
lea addresses_normal+0x6acc, %r14
nop
nop
and $10751, %r9
mov (%r14), %r8w
lea oracles, %rdx
and $0xff, %r8
shlq $12, %r8
mov (%rdx,%r8,1), %r8
pop %rdx
pop %rbp
pop %rax
pop %r9
pop %r8
pop %r15
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_A', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_normal', 'same': True, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 4}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_normal', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 9}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WC_ht', 'same': True, 'AVXalign': False, 'congruent': 8}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': True, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 9}, 'dst': {'same': True, 'type': 'addresses_A_ht', 'congruent': 4}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 7}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 8}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 4}}
{'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
*/
|
#define CGAL_TETRAHEDRAL_REMESHING_VERBOSE
//#define CGAL_DUMP_REMESHING_STEPS
//#define CGAL_TETRAHEDRAL_REMESHING_DEBUG
//#define CGAL_TETRAHEDRAL_REMESHING_GENERATE_INPUT_FILES
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Tetrahedral_remeshing/Remeshing_triangulation_3.h>
#include <CGAL/tetrahedral_remeshing.h>
#include <CGAL/Tetrahedral_remeshing/tetrahedral_remeshing_io.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cassert>
typedef CGAL::Exact_predicates_inexact_constructions_kernel K;
typedef CGAL::Tetrahedral_remeshing::Remeshing_triangulation_3<K> Remeshing_triangulation;
template<typename T3>
void generate_input_one_subdomain(const std::size_t nbv, T3& tr)
{
CGAL::Random rng;
typedef typename T3::Point Point;
std::vector<Point> pts;
while (pts.size() < nbv)
{
const float x = rng.uniform_real(-1.f, 1.f);
const float y = rng.uniform_real(-1.f, 1.f);
const float z = rng.uniform_real(-1.f, 1.f);
pts.push_back(Point(x, y, z));
}
tr.insert(pts.begin(), pts.end());
for (typename T3::Cell_handle c : tr.finite_cell_handles())
c->set_subdomain_index(1);
assert(tr.is_valid(true));
#ifdef CGAL_TETRAHEDRAL_REMESHING_GENERATE_INPUT_FILES
std::ofstream out("data/triangulation_one_subdomain.binary.cgal",
std::ios_base::out | std::ios_base::binary);
CGAL::save_binary_triangulation(out, tr);
out.close();
#endif
}
int main(int argc, char* argv[])
{
std::cout << "CGAL Random seed = " << CGAL::get_default_random().get_seed() << std::endl;
Remeshing_triangulation tr;
generate_input_one_subdomain(1000, tr);
const double target_edge_length = (argc > 1) ? atof(argv[1]) : 0.1;
CGAL::tetrahedral_isotropic_remeshing(tr, target_edge_length);
return EXIT_SUCCESS;
}
|
%include "include/u7bg-all-includes.asm"
%include "../u7-common/patch-eop-processSliderInput.asm"
|
;
; Spectravideo SVI specific routines
; by Stefano Bodrato
; MSX emulation layer
;
; FILVRM
;
;
; $Id: svi_filvrm.asm,v 1.2 2009/06/22 21:44:17 dom Exp $
;
XLIB FILVRM
INCLUDE "svi.def"
FILVRM:
push af
call $373C ;SETWRT
loop: pop af
out (VDP_DATA),a
push af
dec bc
ld a,b
or c
jr nz,loop
pop af
ret
|
; A134195: Antidiagonal sums of square array A126885.
; 1,3,7,15,32,72,178,494,1543,5373,20581,85653,383494,1833250,9301792,49857540,281193501,1663183383,10286884195,66365330811,445598473612,3107611606908,22470529228910,168190079241210,1301213084182483,10391369994732593,85553299734530113
lpb $0
mov $2,$0
sub $0,1
seq $2,104879 ; Row sums of a sum-of-powers triangle.
add $1,$2
lpe
add $1,1
mov $0,$1
|
; A036542: a(n) = T(n, n), array T given by A047858.
; 1,3,11,34,93,236,571,1338,3065,6904,15351,33782,73717,159732,344051,737266,1572849,3342320,7077871,14942190,31457261,66060268,138412011,289406954,603979753,1258291176,2617245671,5435817958,11274289125,23353884644,48318382051,99857989602,206158430177,425201762272,876173328351,1803886264286,3710851743709,7627861917660,15668040695771,32160715112410,65970697666521,135239930216408,277076930199511,567347999932374,1161084278931413,2374945115996116,4855443348258771
mov $1,$0
mov $2,$0
lpb $2
add $1,$0
mul $1,2
sub $2,1
lpe
div $1,2
add $1,1
|
; A057105: Triangle of numbers (when unsigned) related to congruum problem: T(n,k)=k^2+2nk-n^2 with n>k>0 and starting at T(2,1)=1.
; Submitted by Jamie Morken(s4)
; 1,-2,7,-7,4,17,-14,-1,14,31,-23,-8,9,28,49,-34,-17,2,23,46,71,-47,-28,-7,16,41,68,97,-62,-41,-18,7,34,63,94,127,-79,-56,-31,-4,25,56,89,124,161,-98,-73,-46,-17,14,47,82,119,158,199,-119,-92,-63,-32,1,36,73,112,153,196,241,-142,-113,-82,-49,-14,23,62,103
lpb $0
add $2,1
sub $0,$2
lpe
sub $2,$0
add $0,1
pow $0,2
add $2,1
pow $2,2
sub $0,$2
add $2,$0
add $2,$0
mov $0,$2
|
;==============================================================
; BIG EVIL CORPORATION .co.uk
;==============================================================
; SEGA Genesis Framework (c) Matt Phillips 2014
;==============================================================
; debugger.asm - Cross Products SNASM2 debugger setup
;==============================================================
; Setup traps/exceptions to allow SCSI debugger access
MSCSITrap equ 0x108008
MSCSIExcept equ 0x10800C
ConnectDebugger:
move.b d0, 0x108000 ; Allow write to SNASM RAM
move.l #0x02<<24+MSCSIExcept, 8+(4*0)
move.l #0x03<<24+MSCSIExcept, 8+(4*1)
move.l #0x04<<24+MSCSIExcept, 8+(4*2)
move.l #0x05<<24+MSCSIExcept, 8+(4*3)
move.l #0x06<<24+MSCSIExcept, 8+(4*4)
move.l #0x07<<24+MSCSIExcept, 8+(4*5)
move.l #0x08<<24+MSCSIExcept, 8+(4*6)
move.l #0x09<<24+MSCSIExcept, 8+(4*7)
move.l #MSCSITrap, 0x80
move.b d0, 0x10F001 ; Write protect SNASM RAM
ori #0x8000, sr ; Enable TRACE exception
rts
|
default rel
%define XMMWORD
section .text code align=64
ALIGN 16
_x86_64_AES_encrypt:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
mov r13d,DWORD[240+r15]
sub r13d,1
jmp NEAR $L$enc_loop
ALIGN 16
$L$enc_loop:
movzx esi,al
movzx edi,bl
movzx ebp,cl
mov r10d,DWORD[rsi*8+r14]
mov r11d,DWORD[rdi*8+r14]
mov r12d,DWORD[rbp*8+r14]
movzx esi,bh
movzx edi,ch
movzx ebp,dl
xor r10d,DWORD[3+rsi*8+r14]
xor r11d,DWORD[3+rdi*8+r14]
mov r8d,DWORD[rbp*8+r14]
movzx esi,dh
shr ecx,16
movzx ebp,ah
xor r12d,DWORD[3+rsi*8+r14]
shr edx,16
xor r8d,DWORD[3+rbp*8+r14]
shr ebx,16
lea r15,[16+r15]
shr eax,16
movzx esi,cl
movzx edi,dl
movzx ebp,al
xor r10d,DWORD[2+rsi*8+r14]
xor r11d,DWORD[2+rdi*8+r14]
xor r12d,DWORD[2+rbp*8+r14]
movzx esi,dh
movzx edi,ah
movzx ebp,bl
xor r10d,DWORD[1+rsi*8+r14]
xor r11d,DWORD[1+rdi*8+r14]
xor r8d,DWORD[2+rbp*8+r14]
mov edx,DWORD[12+r15]
movzx edi,bh
movzx ebp,ch
mov eax,DWORD[r15]
xor r12d,DWORD[1+rdi*8+r14]
xor r8d,DWORD[1+rbp*8+r14]
mov ebx,DWORD[4+r15]
mov ecx,DWORD[8+r15]
xor eax,r10d
xor ebx,r11d
xor ecx,r12d
xor edx,r8d
sub r13d,1
jnz NEAR $L$enc_loop
movzx esi,al
movzx edi,bl
movzx ebp,cl
movzx r10d,BYTE[2+rsi*8+r14]
movzx r11d,BYTE[2+rdi*8+r14]
movzx r12d,BYTE[2+rbp*8+r14]
movzx esi,dl
movzx edi,bh
movzx ebp,ch
movzx r8d,BYTE[2+rsi*8+r14]
mov edi,DWORD[rdi*8+r14]
mov ebp,DWORD[rbp*8+r14]
and edi,0x0000ff00
and ebp,0x0000ff00
xor r10d,edi
xor r11d,ebp
shr ecx,16
movzx esi,dh
movzx edi,ah
shr edx,16
mov esi,DWORD[rsi*8+r14]
mov edi,DWORD[rdi*8+r14]
and esi,0x0000ff00
and edi,0x0000ff00
shr ebx,16
xor r12d,esi
xor r8d,edi
shr eax,16
movzx esi,cl
movzx edi,dl
movzx ebp,al
mov esi,DWORD[rsi*8+r14]
mov edi,DWORD[rdi*8+r14]
mov ebp,DWORD[rbp*8+r14]
and esi,0x00ff0000
and edi,0x00ff0000
and ebp,0x00ff0000
xor r10d,esi
xor r11d,edi
xor r12d,ebp
movzx esi,bl
movzx edi,dh
movzx ebp,ah
mov esi,DWORD[rsi*8+r14]
mov edi,DWORD[2+rdi*8+r14]
mov ebp,DWORD[2+rbp*8+r14]
and esi,0x00ff0000
and edi,0xff000000
and ebp,0xff000000
xor r8d,esi
xor r10d,edi
xor r11d,ebp
movzx esi,bh
movzx edi,ch
mov edx,DWORD[((16+12))+r15]
mov esi,DWORD[2+rsi*8+r14]
mov edi,DWORD[2+rdi*8+r14]
mov eax,DWORD[((16+0))+r15]
and esi,0xff000000
and edi,0xff000000
xor r12d,esi
xor r8d,edi
mov ebx,DWORD[((16+4))+r15]
mov ecx,DWORD[((16+8))+r15]
xor eax,r10d
xor ebx,r11d
xor ecx,r12d
xor edx,r8d
DB 0xf3,0xc3
ALIGN 16
_x86_64_AES_encrypt_compact:
lea r8,[128+r14]
mov edi,DWORD[((0-128))+r8]
mov ebp,DWORD[((32-128))+r8]
mov r10d,DWORD[((64-128))+r8]
mov r11d,DWORD[((96-128))+r8]
mov edi,DWORD[((128-128))+r8]
mov ebp,DWORD[((160-128))+r8]
mov r10d,DWORD[((192-128))+r8]
mov r11d,DWORD[((224-128))+r8]
jmp NEAR $L$enc_loop_compact
ALIGN 16
$L$enc_loop_compact:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
lea r15,[16+r15]
movzx r10d,al
movzx r11d,bl
movzx r12d,cl
movzx r10d,BYTE[r10*1+r14]
movzx r11d,BYTE[r11*1+r14]
movzx r12d,BYTE[r12*1+r14]
movzx r8d,dl
movzx esi,bh
movzx edi,ch
movzx r8d,BYTE[r8*1+r14]
movzx r9d,BYTE[rsi*1+r14]
movzx r13d,BYTE[rdi*1+r14]
movzx ebp,dh
movzx esi,ah
shr ecx,16
movzx ebp,BYTE[rbp*1+r14]
movzx esi,BYTE[rsi*1+r14]
shr edx,16
movzx edi,cl
shl r9d,8
shl r13d,8
movzx edi,BYTE[rdi*1+r14]
xor r10d,r9d
xor r11d,r13d
movzx r9d,dl
shr eax,16
shr ebx,16
movzx r13d,al
shl ebp,8
shl esi,8
movzx r9d,BYTE[r9*1+r14]
movzx r13d,BYTE[r13*1+r14]
xor r12d,ebp
xor r8d,esi
movzx ebp,bl
movzx esi,dh
shl edi,16
movzx ebp,BYTE[rbp*1+r14]
movzx esi,BYTE[rsi*1+r14]
xor r10d,edi
movzx edi,ah
shr ecx,8
shr ebx,8
movzx edi,BYTE[rdi*1+r14]
movzx edx,BYTE[rcx*1+r14]
movzx ecx,BYTE[rbx*1+r14]
shl r9d,16
shl r13d,16
shl ebp,16
xor r11d,r9d
xor r12d,r13d
xor r8d,ebp
shl esi,24
shl edi,24
shl edx,24
xor r10d,esi
shl ecx,24
xor r11d,edi
mov eax,r10d
mov ebx,r11d
xor ecx,r12d
xor edx,r8d
cmp r15,QWORD[16+rsp]
je NEAR $L$enc_compact_done
mov esi,eax
mov edi,ebx
and esi,0x80808080
and edi,0x80808080
mov r10d,esi
mov r11d,edi
shr r10d,7
lea r8d,[rax*1+rax]
shr r11d,7
lea r9d,[rbx*1+rbx]
sub esi,r10d
sub edi,r11d
and r8d,0xfefefefe
and r9d,0xfefefefe
and esi,0x1b1b1b1b
and edi,0x1b1b1b1b
mov r10d,eax
mov r11d,ebx
xor r8d,esi
xor r9d,edi
xor eax,r8d
xor ebx,r9d
mov esi,ecx
mov edi,edx
rol eax,24
rol ebx,24
and esi,0x80808080
and edi,0x80808080
xor eax,r8d
xor ebx,r9d
mov r12d,esi
mov ebp,edi
ror r10d,16
ror r11d,16
shr r12d,7
lea r8d,[rcx*1+rcx]
xor eax,r10d
xor ebx,r11d
shr ebp,7
lea r9d,[rdx*1+rdx]
ror r10d,8
ror r11d,8
sub esi,r12d
sub edi,ebp
xor eax,r10d
xor ebx,r11d
and r8d,0xfefefefe
and r9d,0xfefefefe
and esi,0x1b1b1b1b
and edi,0x1b1b1b1b
mov r12d,ecx
mov ebp,edx
xor r8d,esi
xor r9d,edi
xor ecx,r8d
xor edx,r9d
rol ecx,24
rol edx,24
xor ecx,r8d
xor edx,r9d
mov esi,DWORD[r14]
ror r12d,16
ror ebp,16
mov edi,DWORD[64+r14]
xor ecx,r12d
xor edx,ebp
mov r8d,DWORD[128+r14]
ror r12d,8
ror ebp,8
mov r9d,DWORD[192+r14]
xor ecx,r12d
xor edx,ebp
jmp NEAR $L$enc_loop_compact
ALIGN 16
$L$enc_compact_done:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
DB 0xf3,0xc3
global fips_aes_encrypt
ALIGN 16
fips_aes_encrypt:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_AES_encrypt:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
push rbx
push rbp
push r12
push r13
push r14
push r15
mov r10,rsp
lea rcx,[((-63))+rdx]
and rsp,-64
sub rcx,rsp
neg rcx
and rcx,0x3c0
sub rsp,rcx
sub rsp,32
mov QWORD[16+rsp],rsi
mov QWORD[24+rsp],r10
$L$enc_prologue:
mov r15,rdx
mov r13d,DWORD[240+r15]
mov eax,DWORD[rdi]
mov ebx,DWORD[4+rdi]
mov ecx,DWORD[8+rdi]
mov edx,DWORD[12+rdi]
shl r13d,4
lea rbp,[r13*1+r15]
mov QWORD[rsp],r15
mov QWORD[8+rsp],rbp
lea r14,[(($L$AES_Te+2048))]
lea rbp,[768+rsp]
sub rbp,r14
and rbp,0x300
lea r14,[rbp*1+r14]
call _x86_64_AES_encrypt_compact
mov r9,QWORD[16+rsp]
mov rsi,QWORD[24+rsp]
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
mov r15,QWORD[rsi]
mov r14,QWORD[8+rsi]
mov r13,QWORD[16+rsi]
mov r12,QWORD[24+rsi]
mov rbp,QWORD[32+rsi]
mov rbx,QWORD[40+rsi]
lea rsp,[48+rsi]
$L$enc_epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_AES_encrypt:
ALIGN 16
_x86_64_AES_decrypt:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
mov r13d,DWORD[240+r15]
sub r13d,1
jmp NEAR $L$dec_loop
ALIGN 16
$L$dec_loop:
movzx esi,al
movzx edi,bl
movzx ebp,cl
mov r10d,DWORD[rsi*8+r14]
mov r11d,DWORD[rdi*8+r14]
mov r12d,DWORD[rbp*8+r14]
movzx esi,dh
movzx edi,ah
movzx ebp,dl
xor r10d,DWORD[3+rsi*8+r14]
xor r11d,DWORD[3+rdi*8+r14]
mov r8d,DWORD[rbp*8+r14]
movzx esi,bh
shr eax,16
movzx ebp,ch
xor r12d,DWORD[3+rsi*8+r14]
shr edx,16
xor r8d,DWORD[3+rbp*8+r14]
shr ebx,16
lea r15,[16+r15]
shr ecx,16
movzx esi,cl
movzx edi,dl
movzx ebp,al
xor r10d,DWORD[2+rsi*8+r14]
xor r11d,DWORD[2+rdi*8+r14]
xor r12d,DWORD[2+rbp*8+r14]
movzx esi,bh
movzx edi,ch
movzx ebp,bl
xor r10d,DWORD[1+rsi*8+r14]
xor r11d,DWORD[1+rdi*8+r14]
xor r8d,DWORD[2+rbp*8+r14]
movzx esi,dh
mov edx,DWORD[12+r15]
movzx ebp,ah
xor r12d,DWORD[1+rsi*8+r14]
mov eax,DWORD[r15]
xor r8d,DWORD[1+rbp*8+r14]
xor eax,r10d
mov ebx,DWORD[4+r15]
mov ecx,DWORD[8+r15]
xor ecx,r12d
xor ebx,r11d
xor edx,r8d
sub r13d,1
jnz NEAR $L$dec_loop
lea r14,[2048+r14]
movzx esi,al
movzx edi,bl
movzx ebp,cl
movzx r10d,BYTE[rsi*1+r14]
movzx r11d,BYTE[rdi*1+r14]
movzx r12d,BYTE[rbp*1+r14]
movzx esi,dl
movzx edi,dh
movzx ebp,ah
movzx r8d,BYTE[rsi*1+r14]
movzx edi,BYTE[rdi*1+r14]
movzx ebp,BYTE[rbp*1+r14]
shl edi,8
shl ebp,8
xor r10d,edi
xor r11d,ebp
shr edx,16
movzx esi,bh
movzx edi,ch
shr eax,16
movzx esi,BYTE[rsi*1+r14]
movzx edi,BYTE[rdi*1+r14]
shl esi,8
shl edi,8
shr ebx,16
xor r12d,esi
xor r8d,edi
shr ecx,16
movzx esi,cl
movzx edi,dl
movzx ebp,al
movzx esi,BYTE[rsi*1+r14]
movzx edi,BYTE[rdi*1+r14]
movzx ebp,BYTE[rbp*1+r14]
shl esi,16
shl edi,16
shl ebp,16
xor r10d,esi
xor r11d,edi
xor r12d,ebp
movzx esi,bl
movzx edi,bh
movzx ebp,ch
movzx esi,BYTE[rsi*1+r14]
movzx edi,BYTE[rdi*1+r14]
movzx ebp,BYTE[rbp*1+r14]
shl esi,16
shl edi,24
shl ebp,24
xor r8d,esi
xor r10d,edi
xor r11d,ebp
movzx esi,dh
movzx edi,ah
mov edx,DWORD[((16+12))+r15]
movzx esi,BYTE[rsi*1+r14]
movzx edi,BYTE[rdi*1+r14]
mov eax,DWORD[((16+0))+r15]
shl esi,24
shl edi,24
xor r12d,esi
xor r8d,edi
mov ebx,DWORD[((16+4))+r15]
mov ecx,DWORD[((16+8))+r15]
lea r14,[((-2048))+r14]
xor eax,r10d
xor ebx,r11d
xor ecx,r12d
xor edx,r8d
DB 0xf3,0xc3
ALIGN 16
_x86_64_AES_decrypt_compact:
lea r8,[128+r14]
mov edi,DWORD[((0-128))+r8]
mov ebp,DWORD[((32-128))+r8]
mov r10d,DWORD[((64-128))+r8]
mov r11d,DWORD[((96-128))+r8]
mov edi,DWORD[((128-128))+r8]
mov ebp,DWORD[((160-128))+r8]
mov r10d,DWORD[((192-128))+r8]
mov r11d,DWORD[((224-128))+r8]
jmp NEAR $L$dec_loop_compact
ALIGN 16
$L$dec_loop_compact:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
lea r15,[16+r15]
movzx r10d,al
movzx r11d,bl
movzx r12d,cl
movzx r10d,BYTE[r10*1+r14]
movzx r11d,BYTE[r11*1+r14]
movzx r12d,BYTE[r12*1+r14]
movzx r8d,dl
movzx esi,dh
movzx edi,ah
movzx r8d,BYTE[r8*1+r14]
movzx r9d,BYTE[rsi*1+r14]
movzx r13d,BYTE[rdi*1+r14]
movzx ebp,bh
movzx esi,ch
shr ecx,16
movzx ebp,BYTE[rbp*1+r14]
movzx esi,BYTE[rsi*1+r14]
shr edx,16
movzx edi,cl
shl r9d,8
shl r13d,8
movzx edi,BYTE[rdi*1+r14]
xor r10d,r9d
xor r11d,r13d
movzx r9d,dl
shr eax,16
shr ebx,16
movzx r13d,al
shl ebp,8
shl esi,8
movzx r9d,BYTE[r9*1+r14]
movzx r13d,BYTE[r13*1+r14]
xor r12d,ebp
xor r8d,esi
movzx ebp,bl
movzx esi,bh
shl edi,16
movzx ebp,BYTE[rbp*1+r14]
movzx esi,BYTE[rsi*1+r14]
xor r10d,edi
movzx edi,ch
shl r9d,16
shl r13d,16
movzx ebx,BYTE[rdi*1+r14]
xor r11d,r9d
xor r12d,r13d
movzx edi,dh
shr eax,8
shl ebp,16
movzx ecx,BYTE[rdi*1+r14]
movzx edx,BYTE[rax*1+r14]
xor r8d,ebp
shl esi,24
shl ebx,24
shl ecx,24
xor r10d,esi
shl edx,24
xor ebx,r11d
mov eax,r10d
xor ecx,r12d
xor edx,r8d
cmp r15,QWORD[16+rsp]
je NEAR $L$dec_compact_done
mov rsi,QWORD[((256+0))+r14]
shl rbx,32
shl rdx,32
mov rdi,QWORD[((256+8))+r14]
or rax,rbx
or rcx,rdx
mov rbp,QWORD[((256+16))+r14]
mov rbx,rax
mov rdx,rcx
and rbx,rsi
and rdx,rsi
mov r9,rbx
mov r12,rdx
shr r9,7
lea r8,[rax*1+rax]
shr r12,7
lea r11,[rcx*1+rcx]
sub rbx,r9
sub rdx,r12
and r8,rdi
and r11,rdi
and rbx,rbp
and rdx,rbp
xor rbx,r8
xor rdx,r11
mov r8,rbx
mov r11,rdx
and rbx,rsi
and rdx,rsi
mov r10,rbx
mov r13,rdx
shr r10,7
lea r9,[r8*1+r8]
shr r13,7
lea r12,[r11*1+r11]
sub rbx,r10
sub rdx,r13
and r9,rdi
and r12,rdi
and rbx,rbp
and rdx,rbp
xor rbx,r9
xor rdx,r12
mov r9,rbx
mov r12,rdx
and rbx,rsi
and rdx,rsi
mov r10,rbx
mov r13,rdx
shr r10,7
xor r8,rax
shr r13,7
xor r11,rcx
sub rbx,r10
sub rdx,r13
lea r10,[r9*1+r9]
lea r13,[r12*1+r12]
xor r9,rax
xor r12,rcx
and r10,rdi
and r13,rdi
and rbx,rbp
and rdx,rbp
xor r10,rbx
xor r13,rdx
xor rax,r10
xor rcx,r13
xor r8,r10
xor r11,r13
mov rbx,rax
mov rdx,rcx
xor r9,r10
xor r12,r13
shr rbx,32
shr rdx,32
xor r10,r8
xor r13,r11
rol eax,8
rol ecx,8
xor r10,r9
xor r13,r12
rol ebx,8
rol edx,8
xor eax,r10d
xor ecx,r13d
shr r10,32
shr r13,32
xor ebx,r10d
xor edx,r13d
mov r10,r8
mov r13,r11
shr r10,32
shr r13,32
rol r8d,24
rol r11d,24
rol r10d,24
rol r13d,24
xor eax,r8d
xor ecx,r11d
mov r8,r9
mov r11,r12
xor ebx,r10d
xor edx,r13d
mov rsi,QWORD[r14]
shr r8,32
shr r11,32
mov rdi,QWORD[64+r14]
rol r9d,16
rol r12d,16
mov rbp,QWORD[128+r14]
rol r8d,16
rol r11d,16
mov r10,QWORD[192+r14]
xor eax,r9d
xor ecx,r12d
mov r13,QWORD[256+r14]
xor ebx,r8d
xor edx,r11d
jmp NEAR $L$dec_loop_compact
ALIGN 16
$L$dec_compact_done:
xor eax,DWORD[r15]
xor ebx,DWORD[4+r15]
xor ecx,DWORD[8+r15]
xor edx,DWORD[12+r15]
DB 0xf3,0xc3
global fips_aes_decrypt
ALIGN 16
fips_aes_decrypt:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_AES_decrypt:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
push rbx
push rbp
push r12
push r13
push r14
push r15
mov r10,rsp
lea rcx,[((-63))+rdx]
and rsp,-64
sub rcx,rsp
neg rcx
and rcx,0x3c0
sub rsp,rcx
sub rsp,32
mov QWORD[16+rsp],rsi
mov QWORD[24+rsp],r10
$L$dec_prologue:
mov r15,rdx
mov r13d,DWORD[240+r15]
mov eax,DWORD[rdi]
mov ebx,DWORD[4+rdi]
mov ecx,DWORD[8+rdi]
mov edx,DWORD[12+rdi]
shl r13d,4
lea rbp,[r13*1+r15]
mov QWORD[rsp],r15
mov QWORD[8+rsp],rbp
lea r14,[(($L$AES_Td+2048))]
lea rbp,[768+rsp]
sub rbp,r14
and rbp,0x300
lea r14,[rbp*1+r14]
shr rbp,3
add r14,rbp
call _x86_64_AES_decrypt_compact
mov r9,QWORD[16+rsp]
mov rsi,QWORD[24+rsp]
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
mov r15,QWORD[rsi]
mov r14,QWORD[8+rsi]
mov r13,QWORD[16+rsi]
mov r12,QWORD[24+rsi]
mov rbp,QWORD[32+rsi]
mov rbx,QWORD[40+rsi]
lea rsp,[48+rsi]
$L$dec_epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_AES_decrypt:
global fips_aes_set_encrypt_key
ALIGN 16
fips_aes_set_encrypt_key:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_AES_set_encrypt_key:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
push rbx
push rbp
push r12
push r13
push r14
push r15
sub rsp,8
$L$enc_key_prologue:
call _x86_64_AES_set_encrypt_key
mov rbp,QWORD[40+rsp]
mov rbx,QWORD[48+rsp]
add rsp,56
$L$enc_key_epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_AES_set_encrypt_key:
ALIGN 16
_x86_64_AES_set_encrypt_key:
mov ecx,esi
mov rsi,rdi
mov rdi,rdx
test rsi,-1
jz NEAR $L$badpointer
test rdi,-1
jz NEAR $L$badpointer
lea rbp,[$L$AES_Te]
lea rbp,[((2048+128))+rbp]
mov eax,DWORD[((0-128))+rbp]
mov ebx,DWORD[((32-128))+rbp]
mov r8d,DWORD[((64-128))+rbp]
mov edx,DWORD[((96-128))+rbp]
mov eax,DWORD[((128-128))+rbp]
mov ebx,DWORD[((160-128))+rbp]
mov r8d,DWORD[((192-128))+rbp]
mov edx,DWORD[((224-128))+rbp]
cmp ecx,128
je NEAR $L$10rounds
cmp ecx,192
je NEAR $L$12rounds
cmp ecx,256
je NEAR $L$14rounds
mov rax,-2
jmp NEAR $L$exit
$L$10rounds:
mov rax,QWORD[rsi]
mov rdx,QWORD[8+rsi]
mov QWORD[rdi],rax
mov QWORD[8+rdi],rdx
shr rdx,32
xor ecx,ecx
jmp NEAR $L$10shortcut
ALIGN 4
$L$10loop:
mov eax,DWORD[rdi]
mov edx,DWORD[12+rdi]
$L$10shortcut:
movzx esi,dl
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,24
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shr edx,16
movzx esi,dl
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,8
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shl ebx,16
xor eax,ebx
xor eax,DWORD[((1024-128))+rcx*4+rbp]
mov DWORD[16+rdi],eax
xor eax,DWORD[4+rdi]
mov DWORD[20+rdi],eax
xor eax,DWORD[8+rdi]
mov DWORD[24+rdi],eax
xor eax,DWORD[12+rdi]
mov DWORD[28+rdi],eax
add ecx,1
lea rdi,[16+rdi]
cmp ecx,10
jl NEAR $L$10loop
mov DWORD[80+rdi],10
xor rax,rax
jmp NEAR $L$exit
$L$12rounds:
mov rax,QWORD[rsi]
mov rbx,QWORD[8+rsi]
mov rdx,QWORD[16+rsi]
mov QWORD[rdi],rax
mov QWORD[8+rdi],rbx
mov QWORD[16+rdi],rdx
shr rdx,32
xor ecx,ecx
jmp NEAR $L$12shortcut
ALIGN 4
$L$12loop:
mov eax,DWORD[rdi]
mov edx,DWORD[20+rdi]
$L$12shortcut:
movzx esi,dl
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,24
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shr edx,16
movzx esi,dl
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,8
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shl ebx,16
xor eax,ebx
xor eax,DWORD[((1024-128))+rcx*4+rbp]
mov DWORD[24+rdi],eax
xor eax,DWORD[4+rdi]
mov DWORD[28+rdi],eax
xor eax,DWORD[8+rdi]
mov DWORD[32+rdi],eax
xor eax,DWORD[12+rdi]
mov DWORD[36+rdi],eax
cmp ecx,7
je NEAR $L$12break
add ecx,1
xor eax,DWORD[16+rdi]
mov DWORD[40+rdi],eax
xor eax,DWORD[20+rdi]
mov DWORD[44+rdi],eax
lea rdi,[24+rdi]
jmp NEAR $L$12loop
$L$12break:
mov DWORD[72+rdi],12
xor rax,rax
jmp NEAR $L$exit
$L$14rounds:
mov rax,QWORD[rsi]
mov rbx,QWORD[8+rsi]
mov rcx,QWORD[16+rsi]
mov rdx,QWORD[24+rsi]
mov QWORD[rdi],rax
mov QWORD[8+rdi],rbx
mov QWORD[16+rdi],rcx
mov QWORD[24+rdi],rdx
shr rdx,32
xor ecx,ecx
jmp NEAR $L$14shortcut
ALIGN 4
$L$14loop:
mov eax,DWORD[rdi]
mov edx,DWORD[28+rdi]
$L$14shortcut:
movzx esi,dl
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,24
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shr edx,16
movzx esi,dl
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,8
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shl ebx,16
xor eax,ebx
xor eax,DWORD[((1024-128))+rcx*4+rbp]
mov DWORD[32+rdi],eax
xor eax,DWORD[4+rdi]
mov DWORD[36+rdi],eax
xor eax,DWORD[8+rdi]
mov DWORD[40+rdi],eax
xor eax,DWORD[12+rdi]
mov DWORD[44+rdi],eax
cmp ecx,6
je NEAR $L$14break
add ecx,1
mov edx,eax
mov eax,DWORD[16+rdi]
movzx esi,dl
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shr edx,16
shl ebx,8
movzx esi,dl
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
movzx esi,dh
shl ebx,16
xor eax,ebx
movzx ebx,BYTE[((-128))+rsi*1+rbp]
shl ebx,24
xor eax,ebx
mov DWORD[48+rdi],eax
xor eax,DWORD[20+rdi]
mov DWORD[52+rdi],eax
xor eax,DWORD[24+rdi]
mov DWORD[56+rdi],eax
xor eax,DWORD[28+rdi]
mov DWORD[60+rdi],eax
lea rdi,[32+rdi]
jmp NEAR $L$14loop
$L$14break:
mov DWORD[48+rdi],14
xor rax,rax
jmp NEAR $L$exit
$L$badpointer:
mov rax,-1
$L$exit:
DB 0xf3,0xc3
global fips_aes_set_decrypt_key
ALIGN 16
fips_aes_set_decrypt_key:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_AES_set_decrypt_key:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
push rbx
push rbp
push r12
push r13
push r14
push r15
push rdx
$L$dec_key_prologue:
call _x86_64_AES_set_encrypt_key
mov r8,QWORD[rsp]
cmp eax,0
jne NEAR $L$abort
mov r14d,DWORD[240+r8]
xor rdi,rdi
lea rcx,[r14*4+rdi]
mov rsi,r8
lea rdi,[rcx*4+r8]
ALIGN 4
$L$invert:
mov rax,QWORD[rsi]
mov rbx,QWORD[8+rsi]
mov rcx,QWORD[rdi]
mov rdx,QWORD[8+rdi]
mov QWORD[rdi],rax
mov QWORD[8+rdi],rbx
mov QWORD[rsi],rcx
mov QWORD[8+rsi],rdx
lea rsi,[16+rsi]
lea rdi,[((-16))+rdi]
cmp rdi,rsi
jne NEAR $L$invert
lea rax,[(($L$AES_Te+2048+1024))]
mov rsi,QWORD[40+rax]
mov rdi,QWORD[48+rax]
mov rbp,QWORD[56+rax]
mov r15,r8
sub r14d,1
ALIGN 4
$L$permute:
lea r15,[16+r15]
mov rax,QWORD[r15]
mov rcx,QWORD[8+r15]
mov rbx,rax
mov rdx,rcx
and rbx,rsi
and rdx,rsi
mov r9,rbx
mov r12,rdx
shr r9,7
lea r8,[rax*1+rax]
shr r12,7
lea r11,[rcx*1+rcx]
sub rbx,r9
sub rdx,r12
and r8,rdi
and r11,rdi
and rbx,rbp
and rdx,rbp
xor rbx,r8
xor rdx,r11
mov r8,rbx
mov r11,rdx
and rbx,rsi
and rdx,rsi
mov r10,rbx
mov r13,rdx
shr r10,7
lea r9,[r8*1+r8]
shr r13,7
lea r12,[r11*1+r11]
sub rbx,r10
sub rdx,r13
and r9,rdi
and r12,rdi
and rbx,rbp
and rdx,rbp
xor rbx,r9
xor rdx,r12
mov r9,rbx
mov r12,rdx
and rbx,rsi
and rdx,rsi
mov r10,rbx
mov r13,rdx
shr r10,7
xor r8,rax
shr r13,7
xor r11,rcx
sub rbx,r10
sub rdx,r13
lea r10,[r9*1+r9]
lea r13,[r12*1+r12]
xor r9,rax
xor r12,rcx
and r10,rdi
and r13,rdi
and rbx,rbp
and rdx,rbp
xor r10,rbx
xor r13,rdx
xor rax,r10
xor rcx,r13
xor r8,r10
xor r11,r13
mov rbx,rax
mov rdx,rcx
xor r9,r10
xor r12,r13
shr rbx,32
shr rdx,32
xor r10,r8
xor r13,r11
rol eax,8
rol ecx,8
xor r10,r9
xor r13,r12
rol ebx,8
rol edx,8
xor eax,r10d
xor ecx,r13d
shr r10,32
shr r13,32
xor ebx,r10d
xor edx,r13d
mov r10,r8
mov r13,r11
shr r10,32
shr r13,32
rol r8d,24
rol r11d,24
rol r10d,24
rol r13d,24
xor eax,r8d
xor ecx,r11d
mov r8,r9
mov r11,r12
xor ebx,r10d
xor edx,r13d
shr r8,32
shr r11,32
rol r9d,16
rol r12d,16
rol r8d,16
rol r11d,16
xor eax,r9d
xor ecx,r12d
xor ebx,r8d
xor edx,r11d
mov DWORD[r15],eax
mov DWORD[4+r15],ebx
mov DWORD[8+r15],ecx
mov DWORD[12+r15],edx
sub r14d,1
jnz NEAR $L$permute
xor rax,rax
$L$abort:
mov r15,QWORD[8+rsp]
mov r14,QWORD[16+rsp]
mov r13,QWORD[24+rsp]
mov r12,QWORD[32+rsp]
mov rbp,QWORD[40+rsp]
mov rbx,QWORD[48+rsp]
add rsp,56
$L$dec_key_epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_AES_set_decrypt_key:
global fips_aes_cbc_encrypt
ALIGN 16
EXTERN fips_openssl_ia32cap_p
fips_aes_cbc_encrypt:
mov QWORD[8+rsp],rdi ;WIN64 prologue
mov QWORD[16+rsp],rsi
mov rax,rsp
$L$SEH_begin_AES_cbc_encrypt:
mov rdi,rcx
mov rsi,rdx
mov rdx,r8
mov rcx,r9
mov r8,QWORD[40+rsp]
mov r9,QWORD[48+rsp]
cmp rdx,0
je NEAR $L$cbc_epilogue
pushfq
push rbx
push rbp
push r12
push r13
push r14
push r15
$L$cbc_prologue:
cld
mov r9d,r9d
lea r14,[$L$AES_Te]
cmp r9,0
jne NEAR $L$cbc_picked_te
lea r14,[$L$AES_Td]
$L$cbc_picked_te:
mov r10d,DWORD[fips_openssl_ia32cap_p]
cmp rdx,512
jb NEAR $L$cbc_slow_prologue
test rdx,15
jnz NEAR $L$cbc_slow_prologue
bt r10d,28
jc NEAR $L$cbc_slow_prologue
lea r15,[((-88-248))+rsp]
and r15,-64
mov r10,r14
lea r11,[2304+r14]
mov r12,r15
and r10,0xFFF
and r11,0xFFF
and r12,0xFFF
cmp r12,r11
jb NEAR $L$cbc_te_break_out
sub r12,r11
sub r15,r12
jmp NEAR $L$cbc_te_ok
$L$cbc_te_break_out:
sub r12,r10
and r12,0xFFF
add r12,320
sub r15,r12
ALIGN 4
$L$cbc_te_ok:
xchg r15,rsp
mov QWORD[16+rsp],r15
$L$cbc_fast_body:
mov QWORD[24+rsp],rdi
mov QWORD[32+rsp],rsi
mov QWORD[40+rsp],rdx
mov QWORD[48+rsp],rcx
mov QWORD[56+rsp],r8
mov DWORD[((80+240))+rsp],0
mov rbp,r8
mov rbx,r9
mov r9,rsi
mov r8,rdi
mov r15,rcx
mov eax,DWORD[240+r15]
mov r10,r15
sub r10,r14
and r10,0xfff
cmp r10,2304
jb NEAR $L$cbc_do_ecopy
cmp r10,4096-248
jb NEAR $L$cbc_skip_ecopy
ALIGN 4
$L$cbc_do_ecopy:
mov rsi,r15
lea rdi,[80+rsp]
lea r15,[80+rsp]
mov ecx,240/8
DD 0x90A548F3
mov DWORD[rdi],eax
$L$cbc_skip_ecopy:
mov QWORD[rsp],r15
mov ecx,18
ALIGN 4
$L$cbc_prefetch_te:
mov r10,QWORD[r14]
mov r11,QWORD[32+r14]
mov r12,QWORD[64+r14]
mov r13,QWORD[96+r14]
lea r14,[128+r14]
sub ecx,1
jnz NEAR $L$cbc_prefetch_te
lea r14,[((-2304))+r14]
cmp rbx,0
je NEAR $L$FAST_DECRYPT
mov eax,DWORD[rbp]
mov ebx,DWORD[4+rbp]
mov ecx,DWORD[8+rbp]
mov edx,DWORD[12+rbp]
ALIGN 4
$L$cbc_fast_enc_loop:
xor eax,DWORD[r8]
xor ebx,DWORD[4+r8]
xor ecx,DWORD[8+r8]
xor edx,DWORD[12+r8]
mov r15,QWORD[rsp]
mov QWORD[24+rsp],r8
call _x86_64_AES_encrypt
mov r8,QWORD[24+rsp]
mov r10,QWORD[40+rsp]
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
lea r8,[16+r8]
lea r9,[16+r9]
sub r10,16
test r10,-16
mov QWORD[40+rsp],r10
jnz NEAR $L$cbc_fast_enc_loop
mov rbp,QWORD[56+rsp]
mov DWORD[rbp],eax
mov DWORD[4+rbp],ebx
mov DWORD[8+rbp],ecx
mov DWORD[12+rbp],edx
jmp NEAR $L$cbc_fast_cleanup
ALIGN 16
$L$FAST_DECRYPT:
cmp r9,r8
je NEAR $L$cbc_fast_dec_in_place
mov QWORD[64+rsp],rbp
ALIGN 4
$L$cbc_fast_dec_loop:
mov eax,DWORD[r8]
mov ebx,DWORD[4+r8]
mov ecx,DWORD[8+r8]
mov edx,DWORD[12+r8]
mov r15,QWORD[rsp]
mov QWORD[24+rsp],r8
call _x86_64_AES_decrypt
mov rbp,QWORD[64+rsp]
mov r8,QWORD[24+rsp]
mov r10,QWORD[40+rsp]
xor eax,DWORD[rbp]
xor ebx,DWORD[4+rbp]
xor ecx,DWORD[8+rbp]
xor edx,DWORD[12+rbp]
mov rbp,r8
sub r10,16
mov QWORD[40+rsp],r10
mov QWORD[64+rsp],rbp
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
lea r8,[16+r8]
lea r9,[16+r9]
jnz NEAR $L$cbc_fast_dec_loop
mov r12,QWORD[56+rsp]
mov r10,QWORD[rbp]
mov r11,QWORD[8+rbp]
mov QWORD[r12],r10
mov QWORD[8+r12],r11
jmp NEAR $L$cbc_fast_cleanup
ALIGN 16
$L$cbc_fast_dec_in_place:
mov r10,QWORD[rbp]
mov r11,QWORD[8+rbp]
mov QWORD[((0+64))+rsp],r10
mov QWORD[((8+64))+rsp],r11
ALIGN 4
$L$cbc_fast_dec_in_place_loop:
mov eax,DWORD[r8]
mov ebx,DWORD[4+r8]
mov ecx,DWORD[8+r8]
mov edx,DWORD[12+r8]
mov r15,QWORD[rsp]
mov QWORD[24+rsp],r8
call _x86_64_AES_decrypt
mov r8,QWORD[24+rsp]
mov r10,QWORD[40+rsp]
xor eax,DWORD[((0+64))+rsp]
xor ebx,DWORD[((4+64))+rsp]
xor ecx,DWORD[((8+64))+rsp]
xor edx,DWORD[((12+64))+rsp]
mov r11,QWORD[r8]
mov r12,QWORD[8+r8]
sub r10,16
jz NEAR $L$cbc_fast_dec_in_place_done
mov QWORD[((0+64))+rsp],r11
mov QWORD[((8+64))+rsp],r12
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
lea r8,[16+r8]
lea r9,[16+r9]
mov QWORD[40+rsp],r10
jmp NEAR $L$cbc_fast_dec_in_place_loop
$L$cbc_fast_dec_in_place_done:
mov rdi,QWORD[56+rsp]
mov QWORD[rdi],r11
mov QWORD[8+rdi],r12
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
ALIGN 4
$L$cbc_fast_cleanup:
cmp DWORD[((80+240))+rsp],0
lea rdi,[80+rsp]
je NEAR $L$cbc_exit
mov ecx,240/8
xor rax,rax
DD 0x90AB48F3
jmp NEAR $L$cbc_exit
ALIGN 16
$L$cbc_slow_prologue:
lea rbp,[((-88))+rsp]
and rbp,-64
lea r10,[((-88-63))+rcx]
sub r10,rbp
neg r10
and r10,0x3c0
sub rbp,r10
xchg rbp,rsp
mov QWORD[16+rsp],rbp
$L$cbc_slow_body:
mov QWORD[56+rsp],r8
mov rbp,r8
mov rbx,r9
mov r9,rsi
mov r8,rdi
mov r15,rcx
mov r10,rdx
mov eax,DWORD[240+r15]
mov QWORD[rsp],r15
shl eax,4
lea rax,[rax*1+r15]
mov QWORD[8+rsp],rax
lea r14,[2048+r14]
lea rax,[((768-8))+rsp]
sub rax,r14
and rax,0x300
lea r14,[rax*1+r14]
cmp rbx,0
je NEAR $L$SLOW_DECRYPT
test r10,-16
mov eax,DWORD[rbp]
mov ebx,DWORD[4+rbp]
mov ecx,DWORD[8+rbp]
mov edx,DWORD[12+rbp]
jz NEAR $L$cbc_slow_enc_tail
ALIGN 4
$L$cbc_slow_enc_loop:
xor eax,DWORD[r8]
xor ebx,DWORD[4+r8]
xor ecx,DWORD[8+r8]
xor edx,DWORD[12+r8]
mov r15,QWORD[rsp]
mov QWORD[24+rsp],r8
mov QWORD[32+rsp],r9
mov QWORD[40+rsp],r10
call _x86_64_AES_encrypt_compact
mov r8,QWORD[24+rsp]
mov r9,QWORD[32+rsp]
mov r10,QWORD[40+rsp]
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
lea r8,[16+r8]
lea r9,[16+r9]
sub r10,16
test r10,-16
jnz NEAR $L$cbc_slow_enc_loop
test r10,15
jnz NEAR $L$cbc_slow_enc_tail
mov rbp,QWORD[56+rsp]
mov DWORD[rbp],eax
mov DWORD[4+rbp],ebx
mov DWORD[8+rbp],ecx
mov DWORD[12+rbp],edx
jmp NEAR $L$cbc_exit
ALIGN 4
$L$cbc_slow_enc_tail:
mov r11,rax
mov r12,rcx
mov rcx,r10
mov rsi,r8
mov rdi,r9
DD 0x9066A4F3
mov rcx,16
sub rcx,r10
xor rax,rax
DD 0x9066AAF3
mov r8,r9
mov r10,16
mov rax,r11
mov rcx,r12
jmp NEAR $L$cbc_slow_enc_loop
ALIGN 16
$L$SLOW_DECRYPT:
shr rax,3
add r14,rax
mov r11,QWORD[rbp]
mov r12,QWORD[8+rbp]
mov QWORD[((0+64))+rsp],r11
mov QWORD[((8+64))+rsp],r12
ALIGN 4
$L$cbc_slow_dec_loop:
mov eax,DWORD[r8]
mov ebx,DWORD[4+r8]
mov ecx,DWORD[8+r8]
mov edx,DWORD[12+r8]
mov r15,QWORD[rsp]
mov QWORD[24+rsp],r8
mov QWORD[32+rsp],r9
mov QWORD[40+rsp],r10
call _x86_64_AES_decrypt_compact
mov r8,QWORD[24+rsp]
mov r9,QWORD[32+rsp]
mov r10,QWORD[40+rsp]
xor eax,DWORD[((0+64))+rsp]
xor ebx,DWORD[((4+64))+rsp]
xor ecx,DWORD[((8+64))+rsp]
xor edx,DWORD[((12+64))+rsp]
mov r11,QWORD[r8]
mov r12,QWORD[8+r8]
sub r10,16
jc NEAR $L$cbc_slow_dec_partial
jz NEAR $L$cbc_slow_dec_done
mov QWORD[((0+64))+rsp],r11
mov QWORD[((8+64))+rsp],r12
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
lea r8,[16+r8]
lea r9,[16+r9]
jmp NEAR $L$cbc_slow_dec_loop
$L$cbc_slow_dec_done:
mov rdi,QWORD[56+rsp]
mov QWORD[rdi],r11
mov QWORD[8+rdi],r12
mov DWORD[r9],eax
mov DWORD[4+r9],ebx
mov DWORD[8+r9],ecx
mov DWORD[12+r9],edx
jmp NEAR $L$cbc_exit
ALIGN 4
$L$cbc_slow_dec_partial:
mov rdi,QWORD[56+rsp]
mov QWORD[rdi],r11
mov QWORD[8+rdi],r12
mov DWORD[((0+64))+rsp],eax
mov DWORD[((4+64))+rsp],ebx
mov DWORD[((8+64))+rsp],ecx
mov DWORD[((12+64))+rsp],edx
mov rdi,r9
lea rsi,[64+rsp]
lea rcx,[16+r10]
DD 0x9066A4F3
jmp NEAR $L$cbc_exit
ALIGN 16
$L$cbc_exit:
mov rsi,QWORD[16+rsp]
mov r15,QWORD[rsi]
mov r14,QWORD[8+rsi]
mov r13,QWORD[16+rsi]
mov r12,QWORD[24+rsi]
mov rbp,QWORD[32+rsi]
mov rbx,QWORD[40+rsi]
lea rsp,[48+rsi]
$L$cbc_popfq:
popfq
$L$cbc_epilogue:
mov rdi,QWORD[8+rsp] ;WIN64 epilogue
mov rsi,QWORD[16+rsp]
DB 0F3h,0C3h ;repret
$L$SEH_end_AES_cbc_encrypt:
ALIGN 64
$L$AES_Te:
DD 0xa56363c6,0xa56363c6
DD 0x847c7cf8,0x847c7cf8
DD 0x997777ee,0x997777ee
DD 0x8d7b7bf6,0x8d7b7bf6
DD 0x0df2f2ff,0x0df2f2ff
DD 0xbd6b6bd6,0xbd6b6bd6
DD 0xb16f6fde,0xb16f6fde
DD 0x54c5c591,0x54c5c591
DD 0x50303060,0x50303060
DD 0x03010102,0x03010102
DD 0xa96767ce,0xa96767ce
DD 0x7d2b2b56,0x7d2b2b56
DD 0x19fefee7,0x19fefee7
DD 0x62d7d7b5,0x62d7d7b5
DD 0xe6abab4d,0xe6abab4d
DD 0x9a7676ec,0x9a7676ec
DD 0x45caca8f,0x45caca8f
DD 0x9d82821f,0x9d82821f
DD 0x40c9c989,0x40c9c989
DD 0x877d7dfa,0x877d7dfa
DD 0x15fafaef,0x15fafaef
DD 0xeb5959b2,0xeb5959b2
DD 0xc947478e,0xc947478e
DD 0x0bf0f0fb,0x0bf0f0fb
DD 0xecadad41,0xecadad41
DD 0x67d4d4b3,0x67d4d4b3
DD 0xfda2a25f,0xfda2a25f
DD 0xeaafaf45,0xeaafaf45
DD 0xbf9c9c23,0xbf9c9c23
DD 0xf7a4a453,0xf7a4a453
DD 0x967272e4,0x967272e4
DD 0x5bc0c09b,0x5bc0c09b
DD 0xc2b7b775,0xc2b7b775
DD 0x1cfdfde1,0x1cfdfde1
DD 0xae93933d,0xae93933d
DD 0x6a26264c,0x6a26264c
DD 0x5a36366c,0x5a36366c
DD 0x413f3f7e,0x413f3f7e
DD 0x02f7f7f5,0x02f7f7f5
DD 0x4fcccc83,0x4fcccc83
DD 0x5c343468,0x5c343468
DD 0xf4a5a551,0xf4a5a551
DD 0x34e5e5d1,0x34e5e5d1
DD 0x08f1f1f9,0x08f1f1f9
DD 0x937171e2,0x937171e2
DD 0x73d8d8ab,0x73d8d8ab
DD 0x53313162,0x53313162
DD 0x3f15152a,0x3f15152a
DD 0x0c040408,0x0c040408
DD 0x52c7c795,0x52c7c795
DD 0x65232346,0x65232346
DD 0x5ec3c39d,0x5ec3c39d
DD 0x28181830,0x28181830
DD 0xa1969637,0xa1969637
DD 0x0f05050a,0x0f05050a
DD 0xb59a9a2f,0xb59a9a2f
DD 0x0907070e,0x0907070e
DD 0x36121224,0x36121224
DD 0x9b80801b,0x9b80801b
DD 0x3de2e2df,0x3de2e2df
DD 0x26ebebcd,0x26ebebcd
DD 0x6927274e,0x6927274e
DD 0xcdb2b27f,0xcdb2b27f
DD 0x9f7575ea,0x9f7575ea
DD 0x1b090912,0x1b090912
DD 0x9e83831d,0x9e83831d
DD 0x742c2c58,0x742c2c58
DD 0x2e1a1a34,0x2e1a1a34
DD 0x2d1b1b36,0x2d1b1b36
DD 0xb26e6edc,0xb26e6edc
DD 0xee5a5ab4,0xee5a5ab4
DD 0xfba0a05b,0xfba0a05b
DD 0xf65252a4,0xf65252a4
DD 0x4d3b3b76,0x4d3b3b76
DD 0x61d6d6b7,0x61d6d6b7
DD 0xceb3b37d,0xceb3b37d
DD 0x7b292952,0x7b292952
DD 0x3ee3e3dd,0x3ee3e3dd
DD 0x712f2f5e,0x712f2f5e
DD 0x97848413,0x97848413
DD 0xf55353a6,0xf55353a6
DD 0x68d1d1b9,0x68d1d1b9
DD 0x00000000,0x00000000
DD 0x2cededc1,0x2cededc1
DD 0x60202040,0x60202040
DD 0x1ffcfce3,0x1ffcfce3
DD 0xc8b1b179,0xc8b1b179
DD 0xed5b5bb6,0xed5b5bb6
DD 0xbe6a6ad4,0xbe6a6ad4
DD 0x46cbcb8d,0x46cbcb8d
DD 0xd9bebe67,0xd9bebe67
DD 0x4b393972,0x4b393972
DD 0xde4a4a94,0xde4a4a94
DD 0xd44c4c98,0xd44c4c98
DD 0xe85858b0,0xe85858b0
DD 0x4acfcf85,0x4acfcf85
DD 0x6bd0d0bb,0x6bd0d0bb
DD 0x2aefefc5,0x2aefefc5
DD 0xe5aaaa4f,0xe5aaaa4f
DD 0x16fbfbed,0x16fbfbed
DD 0xc5434386,0xc5434386
DD 0xd74d4d9a,0xd74d4d9a
DD 0x55333366,0x55333366
DD 0x94858511,0x94858511
DD 0xcf45458a,0xcf45458a
DD 0x10f9f9e9,0x10f9f9e9
DD 0x06020204,0x06020204
DD 0x817f7ffe,0x817f7ffe
DD 0xf05050a0,0xf05050a0
DD 0x443c3c78,0x443c3c78
DD 0xba9f9f25,0xba9f9f25
DD 0xe3a8a84b,0xe3a8a84b
DD 0xf35151a2,0xf35151a2
DD 0xfea3a35d,0xfea3a35d
DD 0xc0404080,0xc0404080
DD 0x8a8f8f05,0x8a8f8f05
DD 0xad92923f,0xad92923f
DD 0xbc9d9d21,0xbc9d9d21
DD 0x48383870,0x48383870
DD 0x04f5f5f1,0x04f5f5f1
DD 0xdfbcbc63,0xdfbcbc63
DD 0xc1b6b677,0xc1b6b677
DD 0x75dadaaf,0x75dadaaf
DD 0x63212142,0x63212142
DD 0x30101020,0x30101020
DD 0x1affffe5,0x1affffe5
DD 0x0ef3f3fd,0x0ef3f3fd
DD 0x6dd2d2bf,0x6dd2d2bf
DD 0x4ccdcd81,0x4ccdcd81
DD 0x140c0c18,0x140c0c18
DD 0x35131326,0x35131326
DD 0x2fececc3,0x2fececc3
DD 0xe15f5fbe,0xe15f5fbe
DD 0xa2979735,0xa2979735
DD 0xcc444488,0xcc444488
DD 0x3917172e,0x3917172e
DD 0x57c4c493,0x57c4c493
DD 0xf2a7a755,0xf2a7a755
DD 0x827e7efc,0x827e7efc
DD 0x473d3d7a,0x473d3d7a
DD 0xac6464c8,0xac6464c8
DD 0xe75d5dba,0xe75d5dba
DD 0x2b191932,0x2b191932
DD 0x957373e6,0x957373e6
DD 0xa06060c0,0xa06060c0
DD 0x98818119,0x98818119
DD 0xd14f4f9e,0xd14f4f9e
DD 0x7fdcdca3,0x7fdcdca3
DD 0x66222244,0x66222244
DD 0x7e2a2a54,0x7e2a2a54
DD 0xab90903b,0xab90903b
DD 0x8388880b,0x8388880b
DD 0xca46468c,0xca46468c
DD 0x29eeeec7,0x29eeeec7
DD 0xd3b8b86b,0xd3b8b86b
DD 0x3c141428,0x3c141428
DD 0x79dedea7,0x79dedea7
DD 0xe25e5ebc,0xe25e5ebc
DD 0x1d0b0b16,0x1d0b0b16
DD 0x76dbdbad,0x76dbdbad
DD 0x3be0e0db,0x3be0e0db
DD 0x56323264,0x56323264
DD 0x4e3a3a74,0x4e3a3a74
DD 0x1e0a0a14,0x1e0a0a14
DD 0xdb494992,0xdb494992
DD 0x0a06060c,0x0a06060c
DD 0x6c242448,0x6c242448
DD 0xe45c5cb8,0xe45c5cb8
DD 0x5dc2c29f,0x5dc2c29f
DD 0x6ed3d3bd,0x6ed3d3bd
DD 0xefacac43,0xefacac43
DD 0xa66262c4,0xa66262c4
DD 0xa8919139,0xa8919139
DD 0xa4959531,0xa4959531
DD 0x37e4e4d3,0x37e4e4d3
DD 0x8b7979f2,0x8b7979f2
DD 0x32e7e7d5,0x32e7e7d5
DD 0x43c8c88b,0x43c8c88b
DD 0x5937376e,0x5937376e
DD 0xb76d6dda,0xb76d6dda
DD 0x8c8d8d01,0x8c8d8d01
DD 0x64d5d5b1,0x64d5d5b1
DD 0xd24e4e9c,0xd24e4e9c
DD 0xe0a9a949,0xe0a9a949
DD 0xb46c6cd8,0xb46c6cd8
DD 0xfa5656ac,0xfa5656ac
DD 0x07f4f4f3,0x07f4f4f3
DD 0x25eaeacf,0x25eaeacf
DD 0xaf6565ca,0xaf6565ca
DD 0x8e7a7af4,0x8e7a7af4
DD 0xe9aeae47,0xe9aeae47
DD 0x18080810,0x18080810
DD 0xd5baba6f,0xd5baba6f
DD 0x887878f0,0x887878f0
DD 0x6f25254a,0x6f25254a
DD 0x722e2e5c,0x722e2e5c
DD 0x241c1c38,0x241c1c38
DD 0xf1a6a657,0xf1a6a657
DD 0xc7b4b473,0xc7b4b473
DD 0x51c6c697,0x51c6c697
DD 0x23e8e8cb,0x23e8e8cb
DD 0x7cdddda1,0x7cdddda1
DD 0x9c7474e8,0x9c7474e8
DD 0x211f1f3e,0x211f1f3e
DD 0xdd4b4b96,0xdd4b4b96
DD 0xdcbdbd61,0xdcbdbd61
DD 0x868b8b0d,0x868b8b0d
DD 0x858a8a0f,0x858a8a0f
DD 0x907070e0,0x907070e0
DD 0x423e3e7c,0x423e3e7c
DD 0xc4b5b571,0xc4b5b571
DD 0xaa6666cc,0xaa6666cc
DD 0xd8484890,0xd8484890
DD 0x05030306,0x05030306
DD 0x01f6f6f7,0x01f6f6f7
DD 0x120e0e1c,0x120e0e1c
DD 0xa36161c2,0xa36161c2
DD 0x5f35356a,0x5f35356a
DD 0xf95757ae,0xf95757ae
DD 0xd0b9b969,0xd0b9b969
DD 0x91868617,0x91868617
DD 0x58c1c199,0x58c1c199
DD 0x271d1d3a,0x271d1d3a
DD 0xb99e9e27,0xb99e9e27
DD 0x38e1e1d9,0x38e1e1d9
DD 0x13f8f8eb,0x13f8f8eb
DD 0xb398982b,0xb398982b
DD 0x33111122,0x33111122
DD 0xbb6969d2,0xbb6969d2
DD 0x70d9d9a9,0x70d9d9a9
DD 0x898e8e07,0x898e8e07
DD 0xa7949433,0xa7949433
DD 0xb69b9b2d,0xb69b9b2d
DD 0x221e1e3c,0x221e1e3c
DD 0x92878715,0x92878715
DD 0x20e9e9c9,0x20e9e9c9
DD 0x49cece87,0x49cece87
DD 0xff5555aa,0xff5555aa
DD 0x78282850,0x78282850
DD 0x7adfdfa5,0x7adfdfa5
DD 0x8f8c8c03,0x8f8c8c03
DD 0xf8a1a159,0xf8a1a159
DD 0x80898909,0x80898909
DD 0x170d0d1a,0x170d0d1a
DD 0xdabfbf65,0xdabfbf65
DD 0x31e6e6d7,0x31e6e6d7
DD 0xc6424284,0xc6424284
DD 0xb86868d0,0xb86868d0
DD 0xc3414182,0xc3414182
DD 0xb0999929,0xb0999929
DD 0x772d2d5a,0x772d2d5a
DD 0x110f0f1e,0x110f0f1e
DD 0xcbb0b07b,0xcbb0b07b
DD 0xfc5454a8,0xfc5454a8
DD 0xd6bbbb6d,0xd6bbbb6d
DD 0x3a16162c,0x3a16162c
DB 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5
DB 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76
DB 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0
DB 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0
DB 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc
DB 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15
DB 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a
DB 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75
DB 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0
DB 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84
DB 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b
DB 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf
DB 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85
DB 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8
DB 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5
DB 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2
DB 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17
DB 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73
DB 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88
DB 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb
DB 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c
DB 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79
DB 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9
DB 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08
DB 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6
DB 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a
DB 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e
DB 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e
DB 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94
DB 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf
DB 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68
DB 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
DB 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5
DB 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76
DB 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0
DB 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0
DB 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc
DB 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15
DB 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a
DB 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75
DB 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0
DB 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84
DB 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b
DB 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf
DB 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85
DB 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8
DB 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5
DB 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2
DB 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17
DB 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73
DB 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88
DB 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb
DB 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c
DB 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79
DB 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9
DB 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08
DB 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6
DB 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a
DB 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e
DB 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e
DB 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94
DB 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf
DB 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68
DB 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
DB 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5
DB 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76
DB 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0
DB 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0
DB 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc
DB 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15
DB 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a
DB 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75
DB 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0
DB 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84
DB 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b
DB 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf
DB 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85
DB 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8
DB 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5
DB 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2
DB 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17
DB 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73
DB 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88
DB 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb
DB 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c
DB 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79
DB 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9
DB 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08
DB 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6
DB 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a
DB 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e
DB 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e
DB 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94
DB 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf
DB 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68
DB 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
DB 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5
DB 0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76
DB 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0
DB 0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0
DB 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc
DB 0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15
DB 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a
DB 0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75
DB 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0
DB 0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84
DB 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b
DB 0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf
DB 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85
DB 0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8
DB 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5
DB 0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2
DB 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17
DB 0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73
DB 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88
DB 0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb
DB 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c
DB 0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79
DB 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9
DB 0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08
DB 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6
DB 0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a
DB 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e
DB 0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e
DB 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94
DB 0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf
DB 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68
DB 0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
DD 0x00000001,0x00000002,0x00000004,0x00000008
DD 0x00000010,0x00000020,0x00000040,0x00000080
DD 0x0000001b,0x00000036,0x80808080,0x80808080
DD 0xfefefefe,0xfefefefe,0x1b1b1b1b,0x1b1b1b1b
ALIGN 64
$L$AES_Td:
DD 0x50a7f451,0x50a7f451
DD 0x5365417e,0x5365417e
DD 0xc3a4171a,0xc3a4171a
DD 0x965e273a,0x965e273a
DD 0xcb6bab3b,0xcb6bab3b
DD 0xf1459d1f,0xf1459d1f
DD 0xab58faac,0xab58faac
DD 0x9303e34b,0x9303e34b
DD 0x55fa3020,0x55fa3020
DD 0xf66d76ad,0xf66d76ad
DD 0x9176cc88,0x9176cc88
DD 0x254c02f5,0x254c02f5
DD 0xfcd7e54f,0xfcd7e54f
DD 0xd7cb2ac5,0xd7cb2ac5
DD 0x80443526,0x80443526
DD 0x8fa362b5,0x8fa362b5
DD 0x495ab1de,0x495ab1de
DD 0x671bba25,0x671bba25
DD 0x980eea45,0x980eea45
DD 0xe1c0fe5d,0xe1c0fe5d
DD 0x02752fc3,0x02752fc3
DD 0x12f04c81,0x12f04c81
DD 0xa397468d,0xa397468d
DD 0xc6f9d36b,0xc6f9d36b
DD 0xe75f8f03,0xe75f8f03
DD 0x959c9215,0x959c9215
DD 0xeb7a6dbf,0xeb7a6dbf
DD 0xda595295,0xda595295
DD 0x2d83bed4,0x2d83bed4
DD 0xd3217458,0xd3217458
DD 0x2969e049,0x2969e049
DD 0x44c8c98e,0x44c8c98e
DD 0x6a89c275,0x6a89c275
DD 0x78798ef4,0x78798ef4
DD 0x6b3e5899,0x6b3e5899
DD 0xdd71b927,0xdd71b927
DD 0xb64fe1be,0xb64fe1be
DD 0x17ad88f0,0x17ad88f0
DD 0x66ac20c9,0x66ac20c9
DD 0xb43ace7d,0xb43ace7d
DD 0x184adf63,0x184adf63
DD 0x82311ae5,0x82311ae5
DD 0x60335197,0x60335197
DD 0x457f5362,0x457f5362
DD 0xe07764b1,0xe07764b1
DD 0x84ae6bbb,0x84ae6bbb
DD 0x1ca081fe,0x1ca081fe
DD 0x942b08f9,0x942b08f9
DD 0x58684870,0x58684870
DD 0x19fd458f,0x19fd458f
DD 0x876cde94,0x876cde94
DD 0xb7f87b52,0xb7f87b52
DD 0x23d373ab,0x23d373ab
DD 0xe2024b72,0xe2024b72
DD 0x578f1fe3,0x578f1fe3
DD 0x2aab5566,0x2aab5566
DD 0x0728ebb2,0x0728ebb2
DD 0x03c2b52f,0x03c2b52f
DD 0x9a7bc586,0x9a7bc586
DD 0xa50837d3,0xa50837d3
DD 0xf2872830,0xf2872830
DD 0xb2a5bf23,0xb2a5bf23
DD 0xba6a0302,0xba6a0302
DD 0x5c8216ed,0x5c8216ed
DD 0x2b1ccf8a,0x2b1ccf8a
DD 0x92b479a7,0x92b479a7
DD 0xf0f207f3,0xf0f207f3
DD 0xa1e2694e,0xa1e2694e
DD 0xcdf4da65,0xcdf4da65
DD 0xd5be0506,0xd5be0506
DD 0x1f6234d1,0x1f6234d1
DD 0x8afea6c4,0x8afea6c4
DD 0x9d532e34,0x9d532e34
DD 0xa055f3a2,0xa055f3a2
DD 0x32e18a05,0x32e18a05
DD 0x75ebf6a4,0x75ebf6a4
DD 0x39ec830b,0x39ec830b
DD 0xaaef6040,0xaaef6040
DD 0x069f715e,0x069f715e
DD 0x51106ebd,0x51106ebd
DD 0xf98a213e,0xf98a213e
DD 0x3d06dd96,0x3d06dd96
DD 0xae053edd,0xae053edd
DD 0x46bde64d,0x46bde64d
DD 0xb58d5491,0xb58d5491
DD 0x055dc471,0x055dc471
DD 0x6fd40604,0x6fd40604
DD 0xff155060,0xff155060
DD 0x24fb9819,0x24fb9819
DD 0x97e9bdd6,0x97e9bdd6
DD 0xcc434089,0xcc434089
DD 0x779ed967,0x779ed967
DD 0xbd42e8b0,0xbd42e8b0
DD 0x888b8907,0x888b8907
DD 0x385b19e7,0x385b19e7
DD 0xdbeec879,0xdbeec879
DD 0x470a7ca1,0x470a7ca1
DD 0xe90f427c,0xe90f427c
DD 0xc91e84f8,0xc91e84f8
DD 0x00000000,0x00000000
DD 0x83868009,0x83868009
DD 0x48ed2b32,0x48ed2b32
DD 0xac70111e,0xac70111e
DD 0x4e725a6c,0x4e725a6c
DD 0xfbff0efd,0xfbff0efd
DD 0x5638850f,0x5638850f
DD 0x1ed5ae3d,0x1ed5ae3d
DD 0x27392d36,0x27392d36
DD 0x64d90f0a,0x64d90f0a
DD 0x21a65c68,0x21a65c68
DD 0xd1545b9b,0xd1545b9b
DD 0x3a2e3624,0x3a2e3624
DD 0xb1670a0c,0xb1670a0c
DD 0x0fe75793,0x0fe75793
DD 0xd296eeb4,0xd296eeb4
DD 0x9e919b1b,0x9e919b1b
DD 0x4fc5c080,0x4fc5c080
DD 0xa220dc61,0xa220dc61
DD 0x694b775a,0x694b775a
DD 0x161a121c,0x161a121c
DD 0x0aba93e2,0x0aba93e2
DD 0xe52aa0c0,0xe52aa0c0
DD 0x43e0223c,0x43e0223c
DD 0x1d171b12,0x1d171b12
DD 0x0b0d090e,0x0b0d090e
DD 0xadc78bf2,0xadc78bf2
DD 0xb9a8b62d,0xb9a8b62d
DD 0xc8a91e14,0xc8a91e14
DD 0x8519f157,0x8519f157
DD 0x4c0775af,0x4c0775af
DD 0xbbdd99ee,0xbbdd99ee
DD 0xfd607fa3,0xfd607fa3
DD 0x9f2601f7,0x9f2601f7
DD 0xbcf5725c,0xbcf5725c
DD 0xc53b6644,0xc53b6644
DD 0x347efb5b,0x347efb5b
DD 0x7629438b,0x7629438b
DD 0xdcc623cb,0xdcc623cb
DD 0x68fcedb6,0x68fcedb6
DD 0x63f1e4b8,0x63f1e4b8
DD 0xcadc31d7,0xcadc31d7
DD 0x10856342,0x10856342
DD 0x40229713,0x40229713
DD 0x2011c684,0x2011c684
DD 0x7d244a85,0x7d244a85
DD 0xf83dbbd2,0xf83dbbd2
DD 0x1132f9ae,0x1132f9ae
DD 0x6da129c7,0x6da129c7
DD 0x4b2f9e1d,0x4b2f9e1d
DD 0xf330b2dc,0xf330b2dc
DD 0xec52860d,0xec52860d
DD 0xd0e3c177,0xd0e3c177
DD 0x6c16b32b,0x6c16b32b
DD 0x99b970a9,0x99b970a9
DD 0xfa489411,0xfa489411
DD 0x2264e947,0x2264e947
DD 0xc48cfca8,0xc48cfca8
DD 0x1a3ff0a0,0x1a3ff0a0
DD 0xd82c7d56,0xd82c7d56
DD 0xef903322,0xef903322
DD 0xc74e4987,0xc74e4987
DD 0xc1d138d9,0xc1d138d9
DD 0xfea2ca8c,0xfea2ca8c
DD 0x360bd498,0x360bd498
DD 0xcf81f5a6,0xcf81f5a6
DD 0x28de7aa5,0x28de7aa5
DD 0x268eb7da,0x268eb7da
DD 0xa4bfad3f,0xa4bfad3f
DD 0xe49d3a2c,0xe49d3a2c
DD 0x0d927850,0x0d927850
DD 0x9bcc5f6a,0x9bcc5f6a
DD 0x62467e54,0x62467e54
DD 0xc2138df6,0xc2138df6
DD 0xe8b8d890,0xe8b8d890
DD 0x5ef7392e,0x5ef7392e
DD 0xf5afc382,0xf5afc382
DD 0xbe805d9f,0xbe805d9f
DD 0x7c93d069,0x7c93d069
DD 0xa92dd56f,0xa92dd56f
DD 0xb31225cf,0xb31225cf
DD 0x3b99acc8,0x3b99acc8
DD 0xa77d1810,0xa77d1810
DD 0x6e639ce8,0x6e639ce8
DD 0x7bbb3bdb,0x7bbb3bdb
DD 0x097826cd,0x097826cd
DD 0xf418596e,0xf418596e
DD 0x01b79aec,0x01b79aec
DD 0xa89a4f83,0xa89a4f83
DD 0x656e95e6,0x656e95e6
DD 0x7ee6ffaa,0x7ee6ffaa
DD 0x08cfbc21,0x08cfbc21
DD 0xe6e815ef,0xe6e815ef
DD 0xd99be7ba,0xd99be7ba
DD 0xce366f4a,0xce366f4a
DD 0xd4099fea,0xd4099fea
DD 0xd67cb029,0xd67cb029
DD 0xafb2a431,0xafb2a431
DD 0x31233f2a,0x31233f2a
DD 0x3094a5c6,0x3094a5c6
DD 0xc066a235,0xc066a235
DD 0x37bc4e74,0x37bc4e74
DD 0xa6ca82fc,0xa6ca82fc
DD 0xb0d090e0,0xb0d090e0
DD 0x15d8a733,0x15d8a733
DD 0x4a9804f1,0x4a9804f1
DD 0xf7daec41,0xf7daec41
DD 0x0e50cd7f,0x0e50cd7f
DD 0x2ff69117,0x2ff69117
DD 0x8dd64d76,0x8dd64d76
DD 0x4db0ef43,0x4db0ef43
DD 0x544daacc,0x544daacc
DD 0xdf0496e4,0xdf0496e4
DD 0xe3b5d19e,0xe3b5d19e
DD 0x1b886a4c,0x1b886a4c
DD 0xb81f2cc1,0xb81f2cc1
DD 0x7f516546,0x7f516546
DD 0x04ea5e9d,0x04ea5e9d
DD 0x5d358c01,0x5d358c01
DD 0x737487fa,0x737487fa
DD 0x2e410bfb,0x2e410bfb
DD 0x5a1d67b3,0x5a1d67b3
DD 0x52d2db92,0x52d2db92
DD 0x335610e9,0x335610e9
DD 0x1347d66d,0x1347d66d
DD 0x8c61d79a,0x8c61d79a
DD 0x7a0ca137,0x7a0ca137
DD 0x8e14f859,0x8e14f859
DD 0x893c13eb,0x893c13eb
DD 0xee27a9ce,0xee27a9ce
DD 0x35c961b7,0x35c961b7
DD 0xede51ce1,0xede51ce1
DD 0x3cb1477a,0x3cb1477a
DD 0x59dfd29c,0x59dfd29c
DD 0x3f73f255,0x3f73f255
DD 0x79ce1418,0x79ce1418
DD 0xbf37c773,0xbf37c773
DD 0xeacdf753,0xeacdf753
DD 0x5baafd5f,0x5baafd5f
DD 0x146f3ddf,0x146f3ddf
DD 0x86db4478,0x86db4478
DD 0x81f3afca,0x81f3afca
DD 0x3ec468b9,0x3ec468b9
DD 0x2c342438,0x2c342438
DD 0x5f40a3c2,0x5f40a3c2
DD 0x72c31d16,0x72c31d16
DD 0x0c25e2bc,0x0c25e2bc
DD 0x8b493c28,0x8b493c28
DD 0x41950dff,0x41950dff
DD 0x7101a839,0x7101a839
DD 0xdeb30c08,0xdeb30c08
DD 0x9ce4b4d8,0x9ce4b4d8
DD 0x90c15664,0x90c15664
DD 0x6184cb7b,0x6184cb7b
DD 0x70b632d5,0x70b632d5
DD 0x745c6c48,0x745c6c48
DD 0x4257b8d0,0x4257b8d0
DB 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38
DB 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb
DB 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87
DB 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb
DB 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d
DB 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e
DB 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2
DB 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25
DB 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16
DB 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92
DB 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda
DB 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84
DB 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a
DB 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06
DB 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02
DB 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b
DB 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea
DB 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73
DB 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85
DB 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e
DB 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89
DB 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b
DB 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20
DB 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4
DB 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31
DB 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f
DB 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d
DB 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef
DB 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0
DB 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61
DB 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26
DB 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
DD 0x80808080,0x80808080,0xfefefefe,0xfefefefe
DD 0x1b1b1b1b,0x1b1b1b1b,0,0
DB 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38
DB 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb
DB 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87
DB 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb
DB 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d
DB 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e
DB 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2
DB 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25
DB 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16
DB 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92
DB 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda
DB 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84
DB 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a
DB 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06
DB 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02
DB 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b
DB 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea
DB 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73
DB 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85
DB 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e
DB 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89
DB 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b
DB 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20
DB 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4
DB 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31
DB 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f
DB 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d
DB 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef
DB 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0
DB 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61
DB 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26
DB 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
DD 0x80808080,0x80808080,0xfefefefe,0xfefefefe
DD 0x1b1b1b1b,0x1b1b1b1b,0,0
DB 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38
DB 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb
DB 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87
DB 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb
DB 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d
DB 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e
DB 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2
DB 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25
DB 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16
DB 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92
DB 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda
DB 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84
DB 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a
DB 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06
DB 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02
DB 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b
DB 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea
DB 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73
DB 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85
DB 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e
DB 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89
DB 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b
DB 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20
DB 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4
DB 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31
DB 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f
DB 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d
DB 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef
DB 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0
DB 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61
DB 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26
DB 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
DD 0x80808080,0x80808080,0xfefefefe,0xfefefefe
DD 0x1b1b1b1b,0x1b1b1b1b,0,0
DB 0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38
DB 0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb
DB 0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87
DB 0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb
DB 0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d
DB 0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e
DB 0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2
DB 0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25
DB 0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16
DB 0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92
DB 0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda
DB 0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84
DB 0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a
DB 0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06
DB 0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02
DB 0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b
DB 0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea
DB 0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73
DB 0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85
DB 0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e
DB 0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89
DB 0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b
DB 0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20
DB 0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4
DB 0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31
DB 0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f
DB 0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d
DB 0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef
DB 0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0
DB 0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61
DB 0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26
DB 0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
DD 0x80808080,0x80808080,0xfefefefe,0xfefefefe
DD 0x1b1b1b1b,0x1b1b1b1b,0,0
DB 65,69,83,32,102,111,114,32,120,56,54,95,54,52,44,32
DB 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97
DB 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103
DB 62,0
ALIGN 64
EXTERN __imp_RtlVirtualUnwind
ALIGN 16
block_se_handler:
push rsi
push rdi
push rbx
push rbp
push r12
push r13
push r14
push r15
pushfq
sub rsp,64
mov rax,QWORD[120+r8]
mov rbx,QWORD[248+r8]
mov rsi,QWORD[8+r9]
mov r11,QWORD[56+r9]
mov r10d,DWORD[r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jb NEAR $L$in_block_prologue
mov rax,QWORD[152+r8]
mov r10d,DWORD[4+r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jae NEAR $L$in_block_prologue
mov rax,QWORD[24+rax]
lea rax,[48+rax]
mov rbx,QWORD[((-8))+rax]
mov rbp,QWORD[((-16))+rax]
mov r12,QWORD[((-24))+rax]
mov r13,QWORD[((-32))+rax]
mov r14,QWORD[((-40))+rax]
mov r15,QWORD[((-48))+rax]
mov QWORD[144+r8],rbx
mov QWORD[160+r8],rbp
mov QWORD[216+r8],r12
mov QWORD[224+r8],r13
mov QWORD[232+r8],r14
mov QWORD[240+r8],r15
$L$in_block_prologue:
mov rdi,QWORD[8+rax]
mov rsi,QWORD[16+rax]
mov QWORD[152+r8],rax
mov QWORD[168+r8],rsi
mov QWORD[176+r8],rdi
jmp NEAR $L$common_seh_exit
ALIGN 16
key_se_handler:
push rsi
push rdi
push rbx
push rbp
push r12
push r13
push r14
push r15
pushfq
sub rsp,64
mov rax,QWORD[120+r8]
mov rbx,QWORD[248+r8]
mov rsi,QWORD[8+r9]
mov r11,QWORD[56+r9]
mov r10d,DWORD[r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jb NEAR $L$in_key_prologue
mov rax,QWORD[152+r8]
mov r10d,DWORD[4+r11]
lea r10,[r10*1+rsi]
cmp rbx,r10
jae NEAR $L$in_key_prologue
lea rax,[56+rax]
mov rbx,QWORD[((-8))+rax]
mov rbp,QWORD[((-16))+rax]
mov r12,QWORD[((-24))+rax]
mov r13,QWORD[((-32))+rax]
mov r14,QWORD[((-40))+rax]
mov r15,QWORD[((-48))+rax]
mov QWORD[144+r8],rbx
mov QWORD[160+r8],rbp
mov QWORD[216+r8],r12
mov QWORD[224+r8],r13
mov QWORD[232+r8],r14
mov QWORD[240+r8],r15
$L$in_key_prologue:
mov rdi,QWORD[8+rax]
mov rsi,QWORD[16+rax]
mov QWORD[152+r8],rax
mov QWORD[168+r8],rsi
mov QWORD[176+r8],rdi
jmp NEAR $L$common_seh_exit
ALIGN 16
cbc_se_handler:
push rsi
push rdi
push rbx
push rbp
push r12
push r13
push r14
push r15
pushfq
sub rsp,64
mov rax,QWORD[120+r8]
mov rbx,QWORD[248+r8]
lea r10,[$L$cbc_prologue]
cmp rbx,r10
jb NEAR $L$in_cbc_prologue
lea r10,[$L$cbc_fast_body]
cmp rbx,r10
jb NEAR $L$in_cbc_frame_setup
lea r10,[$L$cbc_slow_prologue]
cmp rbx,r10
jb NEAR $L$in_cbc_body
lea r10,[$L$cbc_slow_body]
cmp rbx,r10
jb NEAR $L$in_cbc_frame_setup
$L$in_cbc_body:
mov rax,QWORD[152+r8]
lea r10,[$L$cbc_epilogue]
cmp rbx,r10
jae NEAR $L$in_cbc_prologue
lea rax,[8+rax]
lea r10,[$L$cbc_popfq]
cmp rbx,r10
jae NEAR $L$in_cbc_prologue
mov rax,QWORD[8+rax]
lea rax,[56+rax]
$L$in_cbc_frame_setup:
mov rbx,QWORD[((-16))+rax]
mov rbp,QWORD[((-24))+rax]
mov r12,QWORD[((-32))+rax]
mov r13,QWORD[((-40))+rax]
mov r14,QWORD[((-48))+rax]
mov r15,QWORD[((-56))+rax]
mov QWORD[144+r8],rbx
mov QWORD[160+r8],rbp
mov QWORD[216+r8],r12
mov QWORD[224+r8],r13
mov QWORD[232+r8],r14
mov QWORD[240+r8],r15
$L$in_cbc_prologue:
mov rdi,QWORD[8+rax]
mov rsi,QWORD[16+rax]
mov QWORD[152+r8],rax
mov QWORD[168+r8],rsi
mov QWORD[176+r8],rdi
$L$common_seh_exit:
mov rdi,QWORD[40+r9]
mov rsi,r8
mov ecx,154
DD 0xa548f3fc
mov rsi,r9
xor rcx,rcx
mov rdx,QWORD[8+rsi]
mov r8,QWORD[rsi]
mov r9,QWORD[16+rsi]
mov r10,QWORD[40+rsi]
lea r11,[56+rsi]
lea r12,[24+rsi]
mov QWORD[32+rsp],r10
mov QWORD[40+rsp],r11
mov QWORD[48+rsp],r12
mov QWORD[56+rsp],rcx
call QWORD[__imp_RtlVirtualUnwind]
mov eax,1
add rsp,64
popfq
pop r15
pop r14
pop r13
pop r12
pop rbp
pop rbx
pop rdi
pop rsi
DB 0F3h,0C3h ;repret
section .pdata rdata align=4
ALIGN 4
DD $L$SEH_begin_AES_encrypt wrt ..imagebase
DD $L$SEH_end_AES_encrypt wrt ..imagebase
DD $L$SEH_info_AES_encrypt wrt ..imagebase
DD $L$SEH_begin_AES_decrypt wrt ..imagebase
DD $L$SEH_end_AES_decrypt wrt ..imagebase
DD $L$SEH_info_AES_decrypt wrt ..imagebase
DD $L$SEH_begin_AES_set_encrypt_key wrt ..imagebase
DD $L$SEH_end_AES_set_encrypt_key wrt ..imagebase
DD $L$SEH_info_AES_set_encrypt_key wrt ..imagebase
DD $L$SEH_begin_AES_set_decrypt_key wrt ..imagebase
DD $L$SEH_end_AES_set_decrypt_key wrt ..imagebase
DD $L$SEH_info_AES_set_decrypt_key wrt ..imagebase
DD $L$SEH_begin_AES_cbc_encrypt wrt ..imagebase
DD $L$SEH_end_AES_cbc_encrypt wrt ..imagebase
DD $L$SEH_info_AES_cbc_encrypt wrt ..imagebase
section .xdata rdata align=8
ALIGN 8
$L$SEH_info_AES_encrypt:
DB 9,0,0,0
DD block_se_handler wrt ..imagebase
DD $L$enc_prologue wrt ..imagebase,$L$enc_epilogue wrt ..imagebase
$L$SEH_info_AES_decrypt:
DB 9,0,0,0
DD block_se_handler wrt ..imagebase
DD $L$dec_prologue wrt ..imagebase,$L$dec_epilogue wrt ..imagebase
$L$SEH_info_AES_set_encrypt_key:
DB 9,0,0,0
DD key_se_handler wrt ..imagebase
DD $L$enc_key_prologue wrt ..imagebase,$L$enc_key_epilogue wrt ..imagebase
$L$SEH_info_AES_set_decrypt_key:
DB 9,0,0,0
DD key_se_handler wrt ..imagebase
DD $L$dec_key_prologue wrt ..imagebase,$L$dec_key_epilogue wrt ..imagebase
$L$SEH_info_AES_cbc_encrypt:
DB 9,0,0,0
DD cbc_se_handler wrt ..imagebase
|
; A014480: Expansion of (1+2*x)/(1-2*x)^2.
; 1,6,20,56,144,352,832,1920,4352,9728,21504,47104,102400,221184,475136,1015808,2162688,4587520,9699328,20447232,42991616,90177536,188743680,394264576,822083584,1711276032,3556769792,7381975040,15300820992,31675383808,65498251264,135291469824,279172874240,575525617664,1185410973696,2439541424128,5016521801728,10307921510400,21165598834688,43430709297152,89060441849856,182518930210816,373833953443840,765260092932096,1565704557953024,3201777860083712,6544293208522752
mov $1,$0
mul $1,2
add $1,1
mov $2,2
pow $2,$0
mul $1,$2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1b598, %rbp
nop
nop
nop
xor %r13, %r13
movb $0x61, (%rbp)
nop
nop
nop
nop
cmp $4985, %rcx
lea addresses_WT_ht+0x9d89, %r13
nop
and %r15, %r15
vmovups (%r13), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $1, %xmm2, %r10
nop
xor $52878, %r15
lea addresses_normal_ht+0x1ae68, %rdi
nop
nop
nop
nop
cmp $29684, %rbx
mov (%rdi), %rbp
nop
nop
nop
nop
and $6620, %rbx
lea addresses_normal_ht+0x1798, %rdi
sub %rbx, %rbx
movups (%rdi), %xmm7
vpextrq $1, %xmm7, %r15
nop
nop
nop
nop
sub %r15, %r15
lea addresses_WC_ht+0x7798, %rsi
lea addresses_WC_ht+0x12718, %rdi
nop
nop
nop
nop
xor $40828, %r13
mov $72, %rcx
rep movsw
nop
nop
nop
add %rbp, %rbp
lea addresses_UC_ht+0x18ac7, %rbx
cmp %rcx, %rcx
mov (%rbx), %r13w
add $54723, %r13
lea addresses_UC_ht+0x17bf8, %r15
nop
nop
and %rsi, %rsi
mov (%r15), %rbp
nop
nop
sub %rdi, %rdi
lea addresses_D_ht+0x1ab58, %r10
inc %rdi
movl $0x61626364, (%r10)
nop
nop
nop
nop
nop
dec %r10
lea addresses_D_ht+0x130b8, %rsi
lea addresses_WC_ht+0x19198, %rdi
nop
nop
dec %r15
mov $24, %rcx
rep movsl
nop
nop
nop
sub %rbx, %rbx
lea addresses_WT_ht+0x8c68, %rbp
nop
nop
cmp $54588, %r10
movb (%rbp), %bl
nop
nop
nop
inc %rbp
lea addresses_D_ht+0xed8, %rcx
nop
nop
nop
cmp %rdi, %rdi
mov (%rcx), %r15w
and %r10, %r10
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %r8
push %rbp
push %rdi
push %rsi
// Store
lea addresses_WC+0x8798, %rsi
nop
nop
nop
cmp %r8, %r8
mov $0x5152535455565758, %rbp
movq %rbp, %xmm7
movups %xmm7, (%rsi)
nop
nop
nop
nop
inc %rbp
// Faulty Load
lea addresses_WC+0x8798, %r14
nop
nop
nop
nop
and %r10, %r10
vmovups (%r14), %ymm4
vextracti128 $1, %ymm4, %xmm4
vpextrq $0, %xmm4, %rdi
lea oracles, %rbp
and $0xff, %rdi
shlq $12, %rdi
mov (%rbp,%rdi,1), %rdi
pop %rsi
pop %rdi
pop %rbp
pop %r8
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': True, 'size': 16}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 16}}
[Faulty Load]
{'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_WC', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 9, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}}
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 1, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': True, 'congruent': 11, 'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'}
{'src': {'same': True, 'congruent': 5, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WC_ht'}}
{'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': True, 'congruent': 4, 'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'NT': False, 'same': True, 'congruent': 5, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 4}}
{'src': {'same': False, 'congruent': 3, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}}
{'src': {'NT': False, 'same': True, 'congruent': 4, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1}, 'OP': 'LOAD'}
{'src': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'}
{'7f': 1, 'eb': 3, '3b': 2, 'ef': 2, '0b': 1001, 'a6': 14, '87': 1, '48': 27, '5b': 3, '9f': 2, '00': 620, '03': 1983, '6e': 2433, '43': 728, 'b3': 2, '8b': 3, 'bf': 164, '72': 4022, '6d': 4790, '27': 1, 'ff': 1, '4f': 1, '46': 1, '1f': 1, '0f': 1, '33': 4, '06': 4, 'be': 4127, '83': 5, '5f': 1, '23': 1, 'a7': 1765, 'e3': 7, '2b': 3, '6f': 5, '37': 1, '77': 5, 'c3': 4, '57': 6, 'bb': 4, '7b': 1, 'd3': 54, '3f': 1, 'db': 2, '93': 2, 'af': 4, 'a3': 1, '73': 2, 'd7': 1, '9b': 2, '2f': 1, '97': 2, 'e7': 1, '6b': 6}
06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 00 00 00 06 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 33 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 00 2b 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 2b 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 a6 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 be 43 43 43 43 43 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 00 03 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 0b 00 be 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 6d 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 43 00 03 0b 0b 0b 0b 0b
*/
|
;
; Copyright (c) 2013 - 2016, Linaro Limited
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; * Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
; * Neither the name of the Linaro nor the
; names of its contributors may be used to endorse or promote products
; derived from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
; HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;
; Parameters and result.
#define src1 r0
#define src2 r1
#define limit r2
#define result r0
; Internal variables.
#define data1 r3
#define data2 r4
#define limit_wd r5
#define diff r6
#define tmp1 r7
#define tmp2 r12
#define pos r8
#define mask r14
EXPORT InternalMemCompareMem
THUMB
AREA CompareMem, CODE, READONLY
InternalMemCompareMem
push {r4-r8, lr}
eor tmp1, src1, src2
tst tmp1, #3
bne Lmisaligned4
ands tmp1, src1, #3
bne Lmutual_align
add limit_wd, limit, #3
nop.w
lsr limit_wd, limit_wd, #2
; Start of performance-critical section -- one 32B cache line.
Lloop_aligned
ldr data1, [src1], #4
ldr data2, [src2], #4
Lstart_realigned
subs limit_wd, limit_wd, #1
eor diff, data1, data2 ; Non-zero if differences found.
cbnz diff, L0
bne Lloop_aligned
; End of performance-critical section -- one 32B cache line.
; Not reached the limit, must have found a diff.
L0
cbnz limit_wd, Lnot_limit
// Limit % 4 == 0 => all bytes significant.
ands limit, limit, #3
beq Lnot_limit
lsl limit, limit, #3 // Bits -> bytes.
mov mask, #~0
lsl mask, mask, limit
bic data1, data1, mask
bic data2, data2, mask
orr diff, diff, mask
Lnot_limit
rev diff, diff
rev data1, data1
rev data2, data2
; The MS-non-zero bit of DIFF marks either the first bit
; that is different, or the end of the significant data.
; Shifting left now will bring the critical information into the
; top bits.
clz pos, diff
lsl data1, data1, pos
lsl data2, data2, pos
; But we need to zero-extend (char is unsigned) the value and then
; perform a signed 32-bit subtraction.
lsr data1, data1, #28
sub result, data1, data2, lsr #28
pop {r4-r8, pc}
Lmutual_align
; Sources are mutually aligned, but are not currently at an
; alignment boundary. Round down the addresses and then mask off
; the bytes that precede the start point.
bic src1, src1, #3
bic src2, src2, #3
add limit, limit, tmp1 ; Adjust the limit for the extra.
lsl tmp1, tmp1, #2 ; Bytes beyond alignment -> bits.
ldr data1, [src1], #4
neg tmp1, tmp1 ; Bits to alignment -32.
ldr data2, [src2], #4
mov tmp2, #~0
; Little-endian. Early bytes are at LSB.
lsr tmp2, tmp2, tmp1 ; Shift (tmp1 & 31).
add limit_wd, limit, #3
orr data1, data1, tmp2
orr data2, data2, tmp2
lsr limit_wd, limit_wd, #2
b Lstart_realigned
Lmisaligned4
sub limit, limit, #1
L1
// Perhaps we can do better than this.
ldrb data1, [src1], #1
ldrb data2, [src2], #1
subs limit, limit, #1
it cs
cmpcs data1, data2
beq L1
sub result, data1, data2
pop {r4-r8, pc}
END
|
#include "ncurses_display.h"
#include <curses.h>
#include <chrono>
#include <string>
#include <thread>
#include <vector>
#include "format.h"
#include "system.h"
using std::string;
using std::to_string;
// 50 bars uniformly displayed from 0 - 100 %
// 2% is one bar(|)
std::string NCursesDisplay::ProgressBar(float percent) {
std::string result{"0%"};
int size{50};
float bars{percent * size};
for (int i{0}; i < size; ++i) {
result += i <= bars ? '|' : ' ';
}
string display{to_string(percent * 100).substr(0, 4)};
if (percent < 0.1 || percent == 1.0)
display = " " + to_string(percent * 100).substr(0, 3);
return result + " " + display + "/100%";
}
void NCursesDisplay::DisplaySystem(System& system, WINDOW* window) {
int row{0};
mvwprintw(window, ++row, 2, ("OS: " + system.OperatingSystem()).c_str());
mvwprintw(window, ++row, 2, ("Kernel: " + system.Kernel()).c_str());
mvwprintw(window, ++row, 2, "CPU: ");
wattron(window, COLOR_PAIR(1));
mvwprintw(window, row, 10, "");
wprintw(window, ProgressBar(system.Cpu().Utilization()).c_str());
wattroff(window, COLOR_PAIR(1));
mvwprintw(window, ++row, 2, "Memory: ");
wattron(window, COLOR_PAIR(1));
mvwprintw(window, row, 10, "");
wprintw(window, ProgressBar(system.MemoryUtilization()).c_str());
wattroff(window, COLOR_PAIR(1));
mvwprintw(window, ++row, 2,
("Total Processes: " + to_string(system.TotalProcesses())).c_str());
mvwprintw(
window, ++row, 2,
("Running Processes: " + to_string(system.RunningProcesses())).c_str());
mvwprintw(window, ++row, 2,
("Up Time: " + Format::ElapsedTime(system.UpTime())).c_str());
wrefresh(window);
}
void NCursesDisplay::DisplayProcesses(std::vector<Process>& processes,
WINDOW* window, int n) {
int row{0};
int const pid_column{2};
int const user_column{9};
int const cpu_column{18};
int const ram_column{26};
int const time_column{35};
int const command_column{46};
wattron(window, COLOR_PAIR(2));
mvwprintw(window, ++row, pid_column, "PID");
mvwprintw(window, row, user_column, "USER");
mvwprintw(window, row, cpu_column, "CPU[%%]");
mvwprintw(window, row, ram_column, "RAM[MB]");
mvwprintw(window, row, time_column, "TIME+");
mvwprintw(window, row, command_column, "COMMAND");
wattroff(window, COLOR_PAIR(2));
for (int i = 0; i < n; ++i) {
mvwprintw(window, ++row, pid_column, to_string(processes[i].Pid()).c_str());
mvwprintw(window, row, user_column, processes[i].User().c_str());
float cpu = processes[i].CpuUtilization() * 100;
mvwprintw(window, row, cpu_column, to_string(cpu).substr(0, 4).c_str());
mvwprintw(window, row, ram_column, processes[i].Ram().c_str());
mvwprintw(window, row, time_column,
Format::ElapsedTime(processes[i].UpTime()).c_str());
mvwprintw(window, row, command_column,
processes[i].Command().substr(0, window->_maxx - 46).c_str());
}
}
void NCursesDisplay::Display(System& system, int n) {
initscr(); // start ncurses
noecho(); // do not print input values
cbreak(); // terminate ncurses on ctrl + c
start_color(); // enable color
int x_max{getmaxx(stdscr)};
WINDOW* system_window = newwin(9, x_max - 1, 0, 0);
WINDOW* process_window =
newwin(3 + n, x_max - 1, system_window->_maxy + 1, 0);
while (1) {
init_pair(1, COLOR_BLUE, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
box(system_window, 0, 0);
box(process_window, 0, 0);
DisplaySystem(system, system_window);
DisplayProcesses(system.Processes(), process_window, n);
wrefresh(system_window);
wrefresh(process_window);
refresh();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
endwin();
} |
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x7337, %rbp
nop
nop
nop
xor %rax, %rax
movw $0x6162, (%rbp)
cmp $20579, %r12
lea addresses_WC_ht+0x1da97, %r11
clflush (%r11)
dec %rcx
movb $0x61, (%r11)
nop
nop
nop
xor %r11, %r11
lea addresses_WC_ht+0x7310, %rsi
lea addresses_normal_ht+0xb007, %rdi
add $39575, %rbp
mov $1, %rcx
rep movsq
nop
nop
nop
nop
sub $53297, %r10
lea addresses_WT_ht+0x17a97, %rsi
lea addresses_D_ht+0x101f7, %rdi
nop
nop
nop
nop
mfence
mov $115, %rcx
rep movsw
nop
nop
nop
nop
nop
sub $27020, %rbp
lea addresses_WC_ht+0x66f7, %rsi
lea addresses_A_ht+0x11297, %rdi
nop
nop
nop
nop
nop
sub $26143, %r11
mov $127, %rcx
rep movsw
nop
inc %r10
lea addresses_UC_ht+0xa297, %rbp
nop
nop
nop
sub $47259, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm5
and $0xffffffffffffffc0, %rbp
vmovntdq %ymm5, (%rbp)
nop
nop
nop
nop
nop
dec %rbp
lea addresses_D_ht+0xd417, %rsi
nop
and $64601, %r12
movw $0x6162, (%rsi)
nop
nop
nop
nop
sub %r10, %r10
lea addresses_D_ht+0xe5b, %rsi
lea addresses_UC_ht+0x8bdb, %rdi
nop
nop
nop
inc %r11
mov $28, %rcx
rep movsq
nop
nop
nop
nop
inc %rcx
lea addresses_normal_ht+0x13967, %rax
clflush (%rax)
nop
add %rcx, %rcx
mov (%rax), %edi
nop
nop
nop
nop
nop
and $23847, %r12
lea addresses_D_ht+0xae97, %r12
add $45787, %r11
movw $0x6162, (%r12)
xor %r12, %r12
lea addresses_A_ht+0xf797, %rsi
lea addresses_normal_ht+0x4797, %rdi
clflush (%rsi)
nop
sub $50494, %r12
mov $50, %rcx
rep movsl
nop
nop
nop
nop
nop
and %r10, %r10
lea addresses_normal_ht+0x1aa97, %rcx
nop
nop
nop
nop
add %rdi, %rdi
mov $0x6162636465666768, %r10
movq %r10, %xmm5
vmovups %ymm5, (%rcx)
nop
add $40942, %r11
lea addresses_D_ht+0x46a7, %rsi
lea addresses_UC_ht+0x16297, %rdi
nop
nop
and %rax, %rax
mov $66, %rcx
rep movsw
nop
nop
nop
nop
nop
and %rax, %rax
lea addresses_D_ht+0x1776d, %r12
nop
nop
nop
nop
inc %rcx
mov $0x6162636465666768, %rax
movq %rax, %xmm7
vmovups %ymm7, (%r12)
nop
and %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r8
push %r9
push %rsi
// Faulty Load
lea addresses_PSE+0x1e297, %rsi
nop
nop
nop
nop
xor %r15, %r15
mov (%rsi), %r8d
lea oracles, %rsi
and $0xff, %r8
shlq $12, %r8
mov (%rsi,%r8,1), %r8
pop %rsi
pop %r9
pop %r8
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_PSE', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_PSE', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 5}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WC_ht', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 4, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_WC_ht'}}
{'dst': {'same': False, 'congruent': 5, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}}
{'dst': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 5, 'type': 'addresses_WC_ht'}}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC_ht', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': True, 'AVXalign': False, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 7}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 2, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 3}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 7, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_normal_ht', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 11, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 1}, 'OP': 'STOR'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A130820: Decimal expansion of number whose Engel expansion is given by the sequence: 1,1,2,2,3,3,4,4,...Ceiling[n/2],...
; 2,8,7,0,2,2,2,1,5,6,9,7,3,3,9,6,3,3,0,8,1,9,4,5,8,8,6,5,8,1,1,1,9,9,6,0,1,2,4,0,3,1,9,2,6,2,2,8,0,9,9,5,7,0,1,2,0,3,1,2,7,7,3,6,2,7,2,8,5,0,3,8,0,7,6,8,0,3,7,5,2,7,8,4,5,6,3,9,2,3,6,1,5,0,7,1,4,8,2,4
mov $1,1
mov $2,1
mov $3,$0
mul $3,5
lpb $3
mul $2,$3
add $1,$2
cmp $4,0
mov $5,$0
div $5,3
add $5,$4
div $1,$5
div $2,$5
sub $3,1
mov $4,$3
cmp $4,0
add $3,$4
div $1,$3
add $1,$2
lpe
mov $6,10
pow $6,$0
div $2,$6
div $1,$2
add $1,$6
mod $1,10
mov $0,$1
|
*= $0801
.byte $4c,$16,$08,$00,$97,$32
.byte $2c,$30,$3a,$9e,$32,$30
.byte $37,$30,$00,$00,$00,$a9
.byte $01,$85,$02
jsr print
.byte 13
.text "(up)laxa"
.byte 0
lda #%00011011
sta db
lda #%11000110
sta ab
lda #%10110001
sta xb
lda #%01101100
sta yb
lda #0
sta pb
tsx
stx sb
lda #0
sta db
next lda db
sta da
sta dr
sta ar
sta xr
lda yb
sta yr
lda pb
ora #%00110000
and #%01111101
ldx db
bne nozero
ora #%00000010
nozero
ldx db
bpl nominus
ora #%10000000
nominus
sta pr
lda sb
sta sr
ldx sb
txs
lda pb
pha
lda ab
ldx xb
ldy yb
plp
cmd .byte $af
.word da
php
cld
sta aa
stx xa
sty ya
pla
sta pa
tsx
stx sa
jsr check
inc db
bne jmpnext
inc pb
beq nonext
jmpnext jmp next
nonext
jsr print
.text " - ok"
.byte 13,0
lda 2
beq load
wait jsr $ffe4
beq wait
jmp $8000
load jsr print
name .text "laxay"
namelen = *-name
.byte 0
lda #0
sta $0a
sta $b9
lda #namelen
sta $b7
lda #<name
sta $bb
lda #>name
sta $bc
pla
pla
jmp $e16f
db .byte 0
ab .byte 0
xb .byte 0
yb .byte 0
pb .byte 0
sb .byte 0
da .byte 0
aa .byte 0
xa .byte 0
ya .byte 0
pa .byte 0
sa .byte 0
dr .byte 0
ar .byte 0
xr .byte 0
yr .byte 0
pr .byte 0
sr .byte 0
check
.block
lda da
cmp dr
bne error
lda aa
cmp ar
bne error
lda xa
cmp xr
bne error
lda ya
cmp yr
bne error
lda pa
cmp pr
bne error
lda sa
cmp sr
bne error
rts
error jsr print
.byte 13
.null "before "
ldx #<db
ldy #>db
jsr showregs
jsr print
.byte 13
.null "after "
ldx #<da
ldy #>da
jsr showregs
jsr print
.byte 13
.null "right "
ldx #<dr
ldy #>dr
jsr showregs
lda #13
jsr $ffd2
wait jsr $ffe4
beq wait
cmp #3
beq stop
rts
stop lda 2
beq basic
jmp $8000
basic jmp ($a002)
showregs stx 172
sty 173
ldy #0
lda (172),y
jsr hexb
lda #32
jsr $ffd2
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
jsr hexb
lda #32
jsr $ffd2
iny
lda (172),y
ldx #"n"
asl a
bcc ok7
ldx #"N"
ok7 pha
txa
jsr $ffd2
pla
ldx #"v"
asl a
bcc ok6
ldx #"V"
ok6 pha
txa
jsr $ffd2
pla
ldx #"0"
asl a
bcc ok5
ldx #"1"
ok5 pha
txa
jsr $ffd2
pla
ldx #"b"
asl a
bcc ok4
ldx #"B"
ok4 pha
txa
jsr $ffd2
pla
ldx #"d"
asl a
bcc ok3
ldx #"D"
ok3 pha
txa
jsr $ffd2
pla
ldx #"i"
asl a
bcc ok2
ldx #"I"
ok2 pha
txa
jsr $ffd2
pla
ldx #"z"
asl a
bcc ok1
ldx #"Z"
ok1 pha
txa
jsr $ffd2
pla
ldx #"c"
asl a
bcc ok0
ldx #"C"
ok0 pha
txa
jsr $ffd2
pla
lda #32
jsr $ffd2
iny
lda (172),y
.bend
hexb pha
lsr a
lsr a
lsr a
lsr a
jsr hexn
pla
and #$0f
hexn ora #$30
cmp #$3a
bcc hexn0
adc #6
hexn0 jmp $ffd2
print pla
.block
sta print0+1
pla
sta print0+2
ldx #1
print0 lda !*,x
beq print1
jsr $ffd2
inx
bne print0
print1 sec
txa
adc print0+1
sta print2+1
lda #0
adc print0+2
sta print2+2
print2 jmp !*
.bend
|
; A021291: Decimal expansion of 1/287.
; 0,0,3,4,8,4,3,2,0,5,5,7,4,9,1,2,8,9,1,9,8,6,0,6,2,7,1,7,7,7,0,0,3,4,8,4,3,2,0,5,5,7,4,9,1,2,8,9,1,9,8,6,0,6,2,7,1,7,7,7,0,0,3,4,8,4,3,2,0,5,5,7,4,9,1,2,8,9,1,9,8,6,0,6,2,7,1,7,7,7,0,0,3,4,8,4,3,2,0
add $0,1
mov $1,10
pow $1,$0
sub $1,6
mul $1,8
div $1,14
add $1,4
div $1,164
mod $1,10
mov $0,$1
|
; A204255: Symmetric matrix given by f(i,j)=1+[(i+j) mod 4].
; 3,4,4,1,1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4
mov $1,1
lpb $0
sub $0,$1
trn $0,1
add $1,1
lpe
add $1,1
mod $1,4
add $1,1
|
/* Copyright (c) 2014-2018, NVIDIA CORPORATION. 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 NVIDIA CORPORATION nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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.
*/
/* Contact ckubisch@nvidia.com (Christoph Kubisch) for feedback */
#include "cadscene.hpp"
#include <fileformats/cadscenefile.h>
#include <algorithm>
#include <assert.h>
#define USE_CACHECOMBINE 1
nvmath::vec4f randomVector(float from, float to)
{
nvmath::vec4f vec;
float width = to - from;
for(int i = 0; i < 4; i++)
{
vec.get_value()[i] = from + (float(rand()) / float(RAND_MAX)) * width;
}
return vec;
}
// all oct functions derived from "A Survey of Efficient Representations for Independent Unit Vectors"
// http://jcgt.org/published/0003/02/01/paper.pdf
// Returns +/- 1
inline nvmath::vec3f oct_signNotZero(nvmath::vec3f v) {
// leaves z as is
return nvmath::vec3f((v.x >= 0.0f) ? +1.0f : -1.0f, (v.y >= 0.0f) ? +1.0f : -1.0f, 1.0f);
}
// Assume normalized input. Output is on [-1, 1] for each component.
inline nvmath::vec3f float32x3_to_oct(nvmath::vec3f v) {
// Project the sphere onto the octahedron, and then onto the xy plane
nvmath::vec3f p = nvmath::vec3f(v.x, v.y, 0) * (1.0f / (fabsf(v.x) + fabsf(v.y) + fabsf(v.z)));
// Reflect the folds of the lower hemisphere over the diagonals
return (v.z <= 0.0f) ? nvmath::vec3f(1.0f - fabsf(p.y), 1.0f - fabsf(p.x), 0.0f) * oct_signNotZero(p) : p;
}
inline nvmath::vec3f oct_to_float32x3(nvmath::vec3f e) {
nvmath::vec3f v = nvmath::vec3f(e.x, e.y, 1.0f - fabsf(e.x) - fabsf(e.y));
if (v.z < 0.0f) {
v = nvmath::vec3f(1.0f - fabs(v.y), 1.0f - fabs(v.x), v.z) * oct_signNotZero(v);
}
return nvmath::normalize(v);
}
inline nvmath::vec3f float32x3_to_octn_precise(nvmath::vec3f v, const int n) {
nvmath::vec3f s = float32x3_to_oct(v); // Remap to the square
// Each snorm's max value interpreted as an integer,
// e.g., 127.0 for snorm8
float M = float(1 << ((n / 2) - 1)) - 1.0;
// Remap components to snorm(n/2) precision...with floor instead
// of round (see equation 1)
s = nvmath::nv_floor(nvmath::nv_clamp(s, -1.0f, +1.0f) * M) * (1.0f / M);
nvmath::vec3f bestRepresentation = s;
float highestCosine = nvmath::dot(oct_to_float32x3(s), v);
// Test all combinations of floor and ceil and keep the best.
// Note that at +/- 1, this will exit the square... but that
// will be a worse encoding and never win.
for(int i = 0; i <= 1; ++i)
{
for(int j = 0; j <= 1; ++j)
{
// This branch will be evaluated at compile time
if((i != 0) || (j != 0))
{
// Offset the bit pattern (which is stored in floating
// point!) to effectively change the rounding mode
// (when i or j is 0: floor, when it is one: ceiling)
nvmath::vec3f candidate = nvmath::vec3f(i, j, 0) * (1 / M) + s;
float cosine = nvmath::dot(oct_to_float32x3(candidate), v);
if(cosine > highestCosine)
{
bestRepresentation = candidate;
highestCosine = cosine;
}
}
}
}
return bestRepresentation;
}
bool CadScene::loadCSF(const char* filename, int clones, int cloneaxis)
{
CSFile* csf;
CSFileMemoryPTR mem = CSFileMemory_new();
if(CSFile_loadExt(&csf, filename, mem) != CADSCENEFILE_NOERROR || !(csf->fileFlags & CADSCENEFILE_FLAG_UNIQUENODES))
{
CSFileMemory_delete(mem);
return false;
}
int copies = clones + 1;
CSFile_transform(csf);
srand(234525);
// materials
m_materials.resize(csf->numMaterials);
for(int n = 0; n < csf->numMaterials; n++)
{
CSFMaterial* csfmaterial = &csf->materials[n];
Material& material = m_materials[n];
for(int i = 0; i < 2; i++)
{
material.sides[i].ambient = randomVector(0.0f, 0.1f);
material.sides[i].diffuse = nvmath::vec4f(csf->materials[n].color) + randomVector(0.0f, 0.07f);
material.sides[i].specular = randomVector(0.25f, 0.55f);
material.sides[i].emissive = randomVector(0.0f, 0.05f);
}
}
// geometry
int numGeoms = csf->numGeometries;
m_geometry.resize(csf->numGeometries * copies);
m_geometryBboxes.resize(csf->numGeometries * copies);
for(int n = 0; n < csf->numGeometries; n++)
{
CSFGeometry* csfgeom = &csf->geometries[n];
Geometry& geom = m_geometry[n];
geom.cloneIdx = -1;
geom.numVertices = csfgeom->numVertices;
geom.numIndexSolid = csfgeom->numIndexSolid;
geom.numIndexWire = csfgeom->numIndexWire;
Vertex* vertices = new Vertex[csfgeom->numVertices];
for(uint32_t i = 0; i < csfgeom->numVertices; i++)
{
vertices[i].position[0] = csfgeom->vertex[3 * i + 0];
vertices[i].position[1] = csfgeom->vertex[3 * i + 1];
vertices[i].position[2] = csfgeom->vertex[3 * i + 2];
vertices[i].position[3] = 1.0f;
nvmath::vec3f normal;
if(csfgeom->normal)
{
normal.x = csfgeom->normal[3 * i + 0];
normal.y = csfgeom->normal[3 * i + 1];
normal.z = csfgeom->normal[3 * i + 2];
}
else
{
normal = normalize(nvmath::vec3f(vertices[i].position));
}
nvmath::vec3f packed = float32x3_to_octn_precise(normal, 16);
vertices[i].normalOctX = std::min(32767, std::max(-32767, int32_t(packed.x * 32767.0f)));
vertices[i].normalOctY = std::min(32767, std::max(-32767, int32_t(packed.y * 32767.0f)));
m_geometryBboxes[n].merge(vertices[i].position);
}
geom.vboData = vertices;
geom.vboSize = sizeof(Vertex) * csfgeom->numVertices;
unsigned int* indices = new unsigned int[csfgeom->numIndexSolid + csfgeom->numIndexWire];
memcpy(&indices[0], csfgeom->indexSolid, sizeof(unsigned int) * csfgeom->numIndexSolid);
if(csfgeom->indexWire)
{
memcpy(&indices[csfgeom->numIndexSolid], csfgeom->indexWire, sizeof(unsigned int) * csfgeom->numIndexWire);
}
geom.iboData = indices;
geom.iboSize = sizeof(unsigned int) * (csfgeom->numIndexSolid + csfgeom->numIndexWire);
geom.parts.resize(csfgeom->numParts);
size_t offsetSolid = 0;
size_t offsetWire = csfgeom->numIndexSolid * sizeof(unsigned int);
for(uint32_t i = 0; i < csfgeom->numParts; i++)
{
geom.parts[i].indexWire.count = csfgeom->parts[i].numIndexWire;
geom.parts[i].indexSolid.count = csfgeom->parts[i].numIndexSolid;
geom.parts[i].indexWire.offset = offsetWire;
geom.parts[i].indexSolid.offset = offsetSolid;
offsetWire += csfgeom->parts[i].numIndexWire * sizeof(unsigned int);
offsetSolid += csfgeom->parts[i].numIndexSolid * sizeof(unsigned int);
}
}
for(int c = 1; c <= clones; c++)
{
for(int n = 0; n < numGeoms; n++)
{
m_geometryBboxes[n + numGeoms * c] = m_geometryBboxes[n];
const Geometry& geomorig = m_geometry[n];
Geometry& geom = m_geometry[n + numGeoms * c];
geom = geomorig;
geom.cloneIdx = n;
}
}
// nodes
int numObjects = 0;
m_matrices.resize(csf->numNodes * copies);
for(int n = 0; n < csf->numNodes; n++)
{
CSFNode* csfnode = &csf->nodes[n];
memcpy(m_matrices[n].objectMatrix.get_value(), csfnode->objectTM, sizeof(float) * 16);
memcpy(m_matrices[n].worldMatrix.get_value(), csfnode->worldTM, sizeof(float) * 16);
m_matrices[n].objectMatrixIT = nvmath::transpose(nvmath::invert(m_matrices[n].objectMatrix));
m_matrices[n].worldMatrixIT = nvmath::transpose(nvmath::invert(m_matrices[n].worldMatrix));
if(csfnode->geometryIDX < 0)
continue;
numObjects++;
}
// objects
m_objects.resize(numObjects * copies);
m_objectAssigns.resize(numObjects * copies);
numObjects = 0;
for(int n = 0; n < csf->numNodes; n++)
{
CSFNode* csfnode = &csf->nodes[n];
if(csfnode->geometryIDX < 0)
continue;
Object& object = m_objects[numObjects];
object.matrixIndex = n;
object.geometryIndex = csfnode->geometryIDX;
m_objectAssigns[numObjects] = nvmath::vec2i(object.matrixIndex, object.geometryIndex);
object.parts.resize(csfnode->numParts);
for(uint32_t i = 0; i < csfnode->numParts; i++)
{
object.parts[i].active = 1;
object.parts[i].matrixIndex = csfnode->parts[i].nodeIDX < 0 ? object.matrixIndex : csfnode->parts[i].nodeIDX;
object.parts[i].materialIndex = csfnode->parts[i].materialIDX;
#if 1
if(csf->materials[csfnode->parts[i].materialIDX].color[3] < 0.9f)
{
object.parts[i].active = 0;
}
#endif
}
BBox bbox = m_geometryBboxes[object.geometryIndex].transformed(m_matrices[n].worldMatrix);
m_bbox.merge(bbox);
updateObjectDrawCache(object);
numObjects++;
}
// compute clone move delta based on m_bbox;
nvmath::vec4f dim = m_bbox.max - m_bbox.min;
int sq = 1;
int numAxis = 0;
for(int i = 0; i < 3; i++)
{
numAxis += (cloneaxis & (1 << i)) ? 1 : 0;
}
assert(numAxis);
switch(numAxis)
{
case 1:
sq = copies;
break;
case 2:
while(sq * sq < copies)
{
sq++;
}
break;
case 3:
while(sq * sq * sq < copies)
{
sq++;
}
break;
}
for(int c = 1; c <= clones; c++)
{
int numNodes = csf->numNodes;
nvmath::vec4f shift = dim * 1.05f;
float u = 0;
float v = 0;
float w = 0;
switch(numAxis)
{
case 1:
u = float(c);
break;
case 2:
u = float(c % sq);
v = float(c / sq);
break;
case 3:
u = float(c % sq);
v = float((c / sq) % sq);
w = float(c / (sq * sq));
break;
}
float use = u;
if(cloneaxis & (1 << 0))
{
shift.x *= -use;
if(numAxis > 1)
use = v;
}
else
{
shift.x = 0;
}
if(cloneaxis & (1 << 1))
{
shift.y *= use;
if(numAxis > 2)
use = w;
else if(numAxis > 1)
use = v;
}
else
{
shift.y = 0;
}
if(cloneaxis & (1 << 2))
{
shift.z *= -use;
}
else
{
shift.z = 0;
}
shift.w = 0;
// move all world matrices
for(int n = 0; n < numNodes; n++)
{
MatrixNode& node = m_matrices[n + numNodes * c];
MatrixNode& nodeOrig = m_matrices[n];
node = nodeOrig;
node.worldMatrix.set_col(3, node.worldMatrix.col(3) + shift);
node.worldMatrixIT = nvmath::transpose(nvmath::invert(node.worldMatrix));
}
{
// patch object matrix of root
MatrixNode& node = m_matrices[csf->rootIDX + numNodes * c];
node.objectMatrix.set_col(3, node.objectMatrix.col(3) + shift);
node.objectMatrixIT = nvmath::transpose(nvmath::invert(node.objectMatrix));
}
// clone objects
for(int n = 0; n < numObjects; n++)
{
const Object& objectorig = m_objects[n];
Object& object = m_objects[n + numObjects * c];
object = objectorig;
object.geometryIndex += c * numGeoms;
object.matrixIndex += c * numNodes;
for(size_t i = 0; i < object.parts.size(); i++)
{
object.parts[i].matrixIndex += c * numNodes;
}
for(size_t i = 0; i < object.cacheSolid.state.size(); i++)
{
object.cacheSolid.state[i].matrixIndex += c * numNodes;
}
for(size_t i = 0; i < object.cacheWire.state.size(); i++)
{
object.cacheWire.state[i].matrixIndex += c * numNodes;
}
m_objectAssigns[n + numObjects * c] = nvmath::vec2i(object.matrixIndex, object.geometryIndex);
}
}
CSFileMemory_delete(mem);
return true;
}
struct ListItem
{
CadScene::DrawStateInfo state;
CadScene::DrawRange range;
};
static bool ListItem_compare(const ListItem& a, const ListItem& b)
{
int diff = 0;
diff = diff != 0 ? diff : (a.state.materialIndex - b.state.materialIndex);
diff = diff != 0 ? diff : (a.state.matrixIndex - b.state.matrixIndex);
diff = diff != 0 ? diff : int(a.range.offset - b.range.offset);
return diff < 0;
}
static void fillCache(CadScene::DrawRangeCache& cache, const std::vector<ListItem>& list)
{
cache = CadScene::DrawRangeCache();
if(!list.size())
return;
CadScene::DrawStateInfo state = list[0].state;
CadScene::DrawRange range = list[0].range;
int stateCount = 0;
for(size_t i = 1; i < list.size() + 1; i++)
{
bool newrange = false;
if(i == list.size() || list[i].state != state)
{
// push range
if(range.count)
{
stateCount++;
cache.offsets.push_back(range.offset);
cache.counts.push_back(range.count);
}
// emit
if(stateCount)
{
cache.state.push_back(state);
cache.stateCount.push_back(stateCount);
}
stateCount = 0;
if(i == list.size())
{
break;
}
else
{
state = list[i].state;
range.offset = list[i].range.offset;
range.count = 0;
newrange = true;
}
}
const CadScene::DrawRange& currange = list[i].range;
if(newrange || (USE_CACHECOMBINE && currange.offset == (range.offset + sizeof(unsigned int) * range.count)))
{
// merge
range.count += currange.count;
}
else
{
// push
if(range.count)
{
stateCount++;
cache.offsets.push_back(range.offset);
cache.counts.push_back(range.count);
}
range = currange;
}
}
}
void CadScene::updateObjectDrawCache(Object& object)
{
Geometry& geom = m_geometry[object.geometryIndex];
std::vector<ListItem> listSolid;
std::vector<ListItem> listWire;
listSolid.reserve(geom.parts.size());
listWire.reserve(geom.parts.size());
for(size_t i = 0; i < geom.parts.size(); i++)
{
if(!object.parts[i].active)
continue;
ListItem item;
item.state.materialIndex = object.parts[i].materialIndex;
item.range = geom.parts[i].indexSolid;
item.state.matrixIndex = object.parts[i].matrixIndex;
listSolid.push_back(item);
item.range = geom.parts[i].indexWire;
item.state.matrixIndex = object.parts[i].matrixIndex;
listWire.push_back(item);
}
std::sort(listSolid.begin(), listSolid.end(), ListItem_compare);
std::sort(listWire.begin(), listWire.end(), ListItem_compare);
fillCache(object.cacheSolid, listSolid);
fillCache(object.cacheWire, listWire);
}
void CadScene::unload()
{
if(m_geometry.empty())
return;
for(size_t i = 0; i < m_geometry.size(); i++)
{
if(m_geometry[i].cloneIdx >= 0)
continue;
delete[] m_geometry[i].vboData;
delete[] m_geometry[i].iboData;
}
m_matrices.clear();
m_geometryBboxes.clear();
m_geometry.clear();
m_objectAssigns.clear();
m_objects.clear();
m_geometryBboxes.clear();
}
|
;=================================================================
;
; Copyright (c) 2014, Teriks
;
; All rights reserved.
;
; libasm_io is distributed under the following BSD 3-Clause License
;
; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
; documentation and/or other materials provided with the distribution.
;
; 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from
; this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
; HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
; ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;
;==================================================================
;the following is defined when the library examples are being built with the library
%ifdef _LIBASM_IO_BUILDING_
;if the library build system is building the examples, then an option to NASM specifies the directory
;to find this include, so we can include it by its name only
%include "libasm_io.inc"
%else
;otherwise if this code is compiled against the already installed library
;it's header needs to be included from its installed location
%include "/usr/local/include/libasm_io.inc"
%endif
;main gets called by the c runtime library, so it needs to be global to let the linker find it
;the cglobal macro from the library will add an underscore to the 'main' symbol name in the global statement
;and define main as _main if the platform we are on uses underscores in front of its C symbols
cglobal main
section .data
message_1: db "this",0
message_2: db "is",0
message_3: db "how",0
message_4: db "to",0
message_5: db "use",0
message_6: db "the",0
message_7: db "stack",0
message_1a: db "this : ",0
message_2a: db "is : ",0
message_3a: db "how : ",0
message_4a: db "to : ",0
message_5a: db "use : ",0
message_6a: db "the : ",0
message_7a: db "stack : ",0
example_1: db "printing output from example 1:",0
example_2: db "printing output from example 2:",0
example_3: db "printing output from the 'fun_with_lea' function:",0
section .text
print_messages_example:
;set up a new stack frame
push rbp
mov rbp, rsp
;subtract RSP by 56+8 to make room for 7x 8-byte pointer values on the stack, 7*8=56
;the +8 is to align the stack pointer to 16 bytes, 56/16 = 3.5 and (56+8)/16=4.0
;to align to 16 bytes, the value has to be divisible by 16 evenly
;64 bit windows requires the stack pointer be aligned to 16 bytes.
;it also requires that the stack contain at least 32 bytes of space in all function calls that
;call other functions. The alignment here is for portability.
sub rsp, (56+8)
;================================
;the keyword QWORD stands for QUAD WORD, a WORD is 16 bits (or two bytes).
;so a QWORD has 64 bits, which is big enough to hold the 64bit pointer
;to a message string (or any other memory)
;we need to specify the size so mov knows how many bytes of data its going to move into a memory location.
;some possible sizes are :
;BYTE -> 8 bits
;WORD -> 16 bits
;DWORD -> 32 bits
;TWORD -> 48 bits (three words)
;QWORD -> 64 bits
;we want to count by 8's in our offset, because we are moving 64 bit values which are 8 bytes long
;and they should not overlap at all.
;we need to use lea or mov to put a 64 bit label address into a register before moving the address into memory.
;this is because you cannot move the address of a 64 bit immediate label into memory directly without it being
;turnicated to 32 bits. Having the address turnicated will possibly cause the linker to complain
;or worse, cause your program to crash unexpectedly; the latter being a difficult to find bug.
;move the label address into a register first with lea, then move the register
;contents into a memory location on the stack.
lea rax, [rel message_1]
mov QWORD [rsp], rax
;mov accomplishes the same thing here.
;except we have no option of doing arithmetic on the right hand operand like lea can,
;and we need to specify the label address as being a QWORD.
mov rax, QWORD message_2
mov QWORD [rsp+8], rax
lea rax, [rel message_3]
mov QWORD [rsp+16], rax
lea rax, [rel message_4]
mov QWORD [rsp+24], rax
lea rax, [rel message_5]
mov QWORD [rsp+32], rax
lea rax, [rel message_6]
mov QWORD [rsp+40], rax
lea rax, [rel message_7]
mov QWORD [rsp+48], rax
;================================
mov rdi, [rsp]
call print_string
call print_nl
mov rdi, [rsp+8]
call print_string
call print_nl
mov rdi, [rsp+16]
call print_string
call print_nl
mov rdi, [rsp+24]
call print_string
call print_nl
mov rdi, [rsp+32]
call print_string
call print_nl
mov rdi, [rsp+40]
call print_string
call print_nl
mov rdi, [rsp+48]
call print_string
call print_nl
;restore the previous stack frame.
;we just add to rsp and equal amount to what we subtracted when we entered the function
;then restore the stack base pointer rbp by popping it.
add rsp, (56+8)
pop rbp
ret
print_messages_example_v2:
;this sets up a new stack frame
push rbp
mov rbp, rsp
;subtract RSP by (56+8) to make room for 7x 8-byte pointer values on the stack 7*8=56.
;the +8 is to align it, because 56 is not aligned to 16 bytes.
;(we need a value that divides by 16 evenly)
sub rsp, (56+8)
;================================
; you can also use RBP with a negative offset to address stack values, we use subtract because we are storing values
; in the direction in memory that moves towards RSP, (RSP resides at a lower address than RBP).
; we need to start at an offset equal in size to the data we are moving to memory
;
; otherwise, if we use [RBP] as the first address, this will happen:
;
; -- (etc..)
; -- (contains another byte of pointer)
; -- (rbp) high pointer address (contains a byte of a pointer)
; -- ..
; -- ..
; -- (rsp) low pointer address
;
;
; we would write into the calling functions stack frame and make it mad at us,
; probably crashing the program
; x86_64 is a little-endian architecture, it lays out the bytes of integers from low address to high address
; starting with the least significant byte
;=================================
lea rax, [rel message_1a]
mov QWORD [rbp-8], rax
lea rax, [rel message_2a]
mov QWORD [rbp-16], rax
lea rax, [rel message_3a]
mov QWORD [rbp-24], rax
lea rax, [rel message_4a]
mov QWORD [rbp-32], rax
lea rax, [rel message_5a]
mov QWORD [rbp-40], rax
lea rax, [rel message_6a]
mov QWORD [rbp-48], rax
lea rax, [rel message_7a]
mov QWORD [rbp-56], rax
;================================
; it's safe to address [RSP] directly
; because all register values in x86_64 are in little-endian format.
; (they are laid out from low byte to high byte in memory and in registers)
;
; right now the stack is something like this (thinking in terms of individual bytes in memory):
;
;
; -- (rbp) high address
; -- ..
; -- (etc..)
; -- (third byte of pointer to message_7)
; -- (second byte of pointer to message_7)
; -- (rsp) low address (has the first byte of pointer to message_7)
;
;
; also, when we address RSP and move it into RDI, nasm knows we need to pull a quad word from memory (64 bits);
; that is because RDI is a 64bit register.
;
; if your moving a byte of memory into a byte register like AL, it works the same.
;
; you could just do:
;
; mov AL, [rsp]
;
; and nasm will figure out that you want a byte because AL is a byte long
;
;if we start at RSP now we will be printing in reverse order.
;we aligned our stack to 16 bytes using +8 though so we need to start at [RSP+8],
;which is equal to [RBP-56] at this point.
mov rdi, [rsp+8]
call print_string
;print RSP+8 as an unsigned 64 bit integer, so we see the address of the string that was just printed
lea rdi, [(rsp+8)]
call print_uint
call print_nl
;=========READ ABOUT LEA HERE===========
;we are adding 8 to the end of our effective address to keep up with the fact that RSP was aligned to 16 bytes using +8
mov rdi, [(rsp+8) +8]
call print_string
; lea stands for LOAD EFFECTIVE ADDRESS, and it means:
; 1. take the effective address calculation on the RIGHT and compute the actual pointer value from it.
; 2. put the calculated pointer value in the register on the LEFT.
lea rdi, [(rsp+8) +8]
;print the address in RDI, which is equal to [(RSP+8) +8]
call print_uint
call print_nl
;===================================
mov rdi, [(rsp+16) +8]
call print_string
lea rdi, [(rsp+16) +8]
call print_uint
call print_nl
mov rdi, [(rsp+24) +8]
call print_string
lea rdi, [(rsp+24) +8]
call print_uint
call print_nl
mov rdi, [(rsp+32) +8]
call print_string
lea rdi, [(rsp+32) +8]
call print_uint
call print_nl
mov rdi, [(rsp+40) +8]
call print_string
lea rdi, [(rsp+40) +8]
call print_uint
call print_nl
mov rdi, [(rsp+48) +8]
call print_string
lea rdi, [(rsp+48) +8]
call print_uint
call print_nl
;restore the previous stack frame, add an equal amount to what we subtracted before
add rsp, (56+8)
pop rbp
ret
fun_with_lea:
; I am using LEA here to show you some of the fancy expressions that can be used to address memory.
; there are some constraints to memory addressing, but nasm can occasionally factor your math down
; to meet these constraints.
;
; if your affective address for memory operations do not meet processor constraints
; you will get an 'invalid effective address' error from nasm.
;
; the constraints are a bit too long to describe here,
; but you can read about effective addresses in nasm at this link:
;
; http://www.nasm.us/doc/nasmdoc3.html#section-3.3
;
push rbp
mov rbp, rsp
sub rsp, 32
;calculate a bogus address and print the result.
;lea can be used for arithmetic on values that are not actually pointers,
;but that's sort of hacky and has limited usage due to constraints on effective addressing calculations
mov rdi, 5
lea rdi, [rdi+10*2-6]
call print_int
call print_nl
;here we add together two registers and multiply by 8
mov rsi, 8
mov rdi, 5
lea rdi, [rsi+rdi*8]
call print_int
call print_nl
mov rdi, 5
lea rdi, [rdi-10*8]
call print_int
call print_nl
add rsp, 32
pop rbp
ret
main:
;create a new stack frame
;we first save the 'stack base pointer' which is the high address of the stack.
;the stack is currently like this:
;
; -- (rbp) high pointer address
; -- ..probably local variable/parameter in stack memory from the function that called this one..
; -- ..maybe another local variable/function parameter from the calling function..
; -- (rsp) low pointer address
;
;save the 'stack base pointer'
push rbp
;we effectively slide the bottom of the stack down (RBP) to RSP and make it empty
;by setting the 'stack base pointer' to the 'stack pointer'
;
;it makes the stack like this:
;
; -- (rbp) high pointer address = (rsp) low pointer address
;
;slide the base of the stack down to RSP, so its empty
mov rbp, rsp
;On windows, we need a minimum of 32 bytes of stack space before calling
;any functions, RSP also always needs to be aligned to 16 bytes.
;32/16 = 2, 2 is a whole number which means 32 is indeed aligned to 16 bytes
;this is for compatibility, Linux and Mac can run programs with or without the stack pointer being aligned,
;but on Windows if the stack is not aligned the program will crash.
sub rsp, 32
;print a message describing what the following output is from
mov rdi, QWORD example_1
call print_string
call print_nl
call print_nl
;call the first example
call print_messages_example
;make some space with a new line
call print_nl
;print a message saying the following output is from example 2
mov rdi, QWORD example_2
call print_string
call print_nl
call print_nl
;call the second example
call print_messages_example_v2
;make some space with a new line
call print_nl
;print a message saying we are going to output the results of the fun_with_lea example
mov rdi, QWORD example_3
call print_string
call print_nl
call print_nl
call fun_with_lea
call print_nl
;restore the stack to its previous state.
;first add an equal amount to RSP as what we subtracted when we entered this function.
;this includes the sum of all additional subtractions made after the first subtraction (if there are any).
;then restore the base pointer (RBP) by popping it back into itself.
add rsp, 32
;once we do the addition, the value of RBP we pushed at the beginning of the function
;should be the only thing left on the stack.
pop rbp
ret
|
; A293137: a(0) = 0, and a(n) = floor(2*sqrt(n)) - 1 for n >= 1.
; 0,1,1,2,3,3,3,4,4,5,5,5,5,6,6,6,7,7,7,7,7,8,8,8,8,9,9,9,9,9,9,10,10,10,10,10,11,11,11,11,11,11,11,12,12,12,12,12,12,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18
mul $0,4
mov $2,1
lpb $0
add $1,1
add $2,2
trn $0,$2
lpe
trn $1,1
mov $0,$1
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <activemq/wireformat/openwire/marshal/generated/ConsumerControlMarshallerTest.h>
#include <activemq/wireformat/openwire/marshal/generated/ConsumerControlMarshaller.h>
#include <activemq/commands/ConsumerControl.h>
#include <activemq/wireformat/openwire/OpenWireFormat.h>
#include <activemq/commands/DataStructure.h>
#include <activemq/commands/MessageId.h>
#include <activemq/commands/ProducerId.h>
#include <activemq/wireformat/openwire/utils/BooleanStream.h>
#include <decaf/io/DataInputStream.h>
#include <decaf/io/DataOutputStream.h>
#include <decaf/io/IOException.h>
#include <decaf/io/ByteArrayOutputStream.h>
#include <decaf/io/ByteArrayInputStream.h>
#include <decaf/util/Properties.h>
#include <decaf/lang/Pointer.h>
//
// NOTE!: This file is autogenerated - do not modify!
// if you need to make a change, please see the Java Classes in the
// activemq-core module
//
using namespace std;
using namespace activemq;
using namespace activemq::util;
using namespace activemq::exceptions;
using namespace activemq::commands;
using namespace activemq::wireformat;
using namespace activemq::wireformat::openwire;
using namespace activemq::wireformat::openwire::marshal;
using namespace activemq::wireformat::openwire::utils;
using namespace activemq::wireformat::openwire::marshal::generated;
using namespace decaf::io;
using namespace decaf::lang;
using namespace decaf::util;
///////////////////////////////////////////////////////////////////////////////
void ConsumerControlMarshallerTest::test() {
ConsumerControlMarshaller myMarshaller;
ConsumerControl myCommand;
ConsumerControl* myCommand2;
CPPUNIT_ASSERT( myMarshaller.getDataStructureType() == myCommand.getDataStructureType() );
myCommand2 = dynamic_cast<ConsumerControl*>( myMarshaller.createObject() );
CPPUNIT_ASSERT( myCommand2 != NULL );
delete myCommand2;
}
///////////////////////////////////////////////////////////////////////////////
void ConsumerControlMarshallerTest::testLooseMarshal() {
ConsumerControlMarshaller marshaller;
Properties props;
OpenWireFormat openWireFormat( props );
// Configure for this test.
openWireFormat.setVersion( 11 );
openWireFormat.setTightEncodingEnabled( false );
ConsumerControl outCommand;
ConsumerControl inCommand;
try {
// Marshal the dataStructure to a byte array.
ByteArrayOutputStream baos;
DataOutputStream dataOut( &baos );
dataOut.writeByte( outCommand.getDataStructureType() );
marshaller.looseMarshal( &openWireFormat, &outCommand, &dataOut );
// Now read it back in and make sure it's all right.
std::pair<const unsigned char*, int> array = baos.toByteArray();
ByteArrayInputStream bais( array.first, array.second, true );
DataInputStream dataIn( &bais );
unsigned char dataType = dataIn.readByte();
CPPUNIT_ASSERT( dataType == outCommand.getDataStructureType() );
marshaller.looseUnmarshal( &openWireFormat, &inCommand, &dataIn );
CPPUNIT_ASSERT( inCommand.equals( (DataStructure*) &outCommand ) == true );
} catch( ActiveMQException& e ) {
e.printStackTrace();
CPPUNIT_ASSERT( false );
} catch( ... ) {
CPPUNIT_ASSERT( false );
}
}
///////////////////////////////////////////////////////////////////////////////
void ConsumerControlMarshallerTest::testTightMarshal() {
ConsumerControlMarshaller marshaller;
Properties props;
OpenWireFormat openWireFormat( props );
// Configure for this test.
openWireFormat.setVersion( 11 );
openWireFormat.setTightEncodingEnabled( true );
ConsumerControl outCommand;
ConsumerControl inCommand;
try {
// Marshal the dataStructure to a byte array.
ByteArrayOutputStream baos;
DataOutputStream dataOut( &baos );
// Phase 1 - count the size
int size = 1;
BooleanStream bs;
size += marshaller.tightMarshal1( &openWireFormat, &outCommand, &bs );
size += bs.marshalledSize();
// Phase 2 - marshal
dataOut.writeByte( outCommand.getDataStructureType() );
bs.marshal( &dataOut );
marshaller.tightMarshal2( &openWireFormat, &outCommand, &dataOut, &bs );
// Now read it back in and make sure it's all right.
std::pair<const unsigned char*, int> array = baos.toByteArray();
ByteArrayInputStream bais( array.first, array.second, true );
DataInputStream dataIn( &bais );
unsigned char dataType = dataIn.readByte();
CPPUNIT_ASSERT( dataType == outCommand.getDataStructureType() );
bs.clear();
bs.unmarshal( &dataIn );
marshaller.tightUnmarshal( &openWireFormat, &inCommand, &dataIn, &bs );
CPPUNIT_ASSERT( inCommand.equals( (DataStructure*) &outCommand ) == true );
} catch( ActiveMQException& e ) {
e.printStackTrace();
CPPUNIT_ASSERT( false );
} catch( ... ) {
CPPUNIT_ASSERT( false );
}
}
|
CGAFractal2 label byte
word C_BLACK
Bitmap <67,41,BMC_PACKBITS,BMF_MONO>
db 0xf8, 0x00
db 0xfe, 0x00, 0x05, 0x05, 0x80, 0x00, 0xa2, 0x60,
0x00
db 0xfe, 0x00, 0x05, 0x0d, 0x53, 0x01, 0x84, 0x00,
0x00
db 0xfe, 0x00, 0x05, 0x07, 0x9b, 0xa0, 0xff, 0x00,
0x00
db 0x08, 0x00, 0x00, 0x18, 0xd8, 0x1c, 0x8c, 0x7c,
0x60, 0x00
db 0x08, 0x00, 0x00, 0x06, 0x01, 0x61, 0x04, 0x00,
0xf0, 0x00
db 0xfe, 0x00, 0x05, 0x56, 0xf7, 0x02, 0x00, 0xd0,
0x00
db 0x08, 0x00, 0x00, 0xe3, 0x5f, 0xda, 0xb5, 0x00,
0x32, 0x00
db 0x08, 0x00, 0x0b, 0x05, 0xf6, 0x7b, 0x3f, 0xc7,
0xf9, 0xc0
db 0x08, 0x00, 0x00, 0xe6, 0x79, 0x6d, 0x82, 0x5f,
0xf8, 0xc0
db 0x08, 0x00, 0x08, 0x78, 0xa0, 0x30, 0xfc, 0xf1,
0xc8, 0xc0
db 0x08, 0x00, 0xa9, 0x1a, 0x08, 0x00, 0xfe, 0x66,
0x2d, 0x40
db 0x08, 0x00, 0x1b, 0xa4, 0x00, 0x00, 0xee, 0xf0,
0x7f, 0x00
db 0x08, 0x00, 0xdf, 0xc0, 0x00, 0x00, 0x0f, 0x00,
0x38, 0x00
db 0x01, 0x02, 0xa0, 0xfe, 0x00, 0x03, 0x09, 0x80,
0x0d, 0x40
db 0x01, 0x00, 0x7a, 0xfe, 0x00, 0x03, 0x03, 0x60,
0x7c, 0x00
db 0x01, 0x06, 0x64, 0xfd, 0x00, 0x02, 0xe5, 0xf2,
0x00
db 0x08, 0x06, 0xec, 0x00, 0xe9, 0x34, 0x00, 0x2d,
0xd0, 0x00
db 0x08, 0x19, 0xbc, 0x07, 0x20, 0x69, 0x80, 0x01,
0x00, 0x00
db 0x05, 0x7b, 0xfe, 0x14, 0xbf, 0xf8, 0x20, 0xfe,
0x00
db 0x05, 0x12, 0xbf, 0xf5, 0xff, 0xfc, 0x08, 0xfe,
0x00
db 0x05, 0x1c, 0xbf, 0xd7, 0xc4, 0x7f, 0x09, 0xfe,
0x00
db 0x08, 0x3c, 0xff, 0xf7, 0x7e, 0x3f, 0xef, 0xa0,
0x00, 0x00
db 0x08, 0x02, 0x7f, 0xff, 0xdb, 0xdf, 0xfd, 0x78,
0x00, 0x00
db 0x08, 0x33, 0xff, 0xf1, 0xfb, 0xcf, 0xfa, 0xe2,
0x00, 0x00
db 0x08, 0x3d, 0x9f, 0xfe, 0x47, 0xee, 0x0e, 0xd4,
0xc2, 0x00
db 0x08, 0x08, 0x7f, 0xff, 0xff, 0xfc, 0x03, 0x07,
0x0c, 0x00
db 0x08, 0x06, 0xc6, 0xff, 0xfe, 0xd8, 0x00, 0xfc,
0x21, 0x00
db 0x08, 0x07, 0xee, 0xff, 0xfe, 0x10, 0x00, 0xb1,
0xb6, 0x40
db 0x08, 0x05, 0x18, 0x75, 0xfd, 0x70, 0x00, 0x10,
0x3b, 0x00
db 0x08, 0x00, 0x69, 0x43, 0x6e, 0xc0, 0x00, 0x13,
0xfc, 0x00
db 0x08, 0x00, 0x38, 0x77, 0x87, 0x80, 0x00, 0x1d,
0xfb, 0x40
db 0x08, 0x00, 0x71, 0x71, 0xfc, 0x00, 0x00, 0x3e,
0xdb, 0xc0
db 0x08, 0x00, 0x00, 0xb2, 0x60, 0x00, 0x00, 0x07,
0x1d, 0xc0
db 0x02, 0x00, 0x00, 0x10, 0xfe, 0x00, 0x02, 0x01,
0x61, 0x40
db 0xfb, 0x00, 0x02, 0x03, 0xba, 0xc0
db 0xfb, 0x00, 0x02, 0x01, 0x57, 0xc0
db 0xfb, 0x00, 0x02, 0x01, 0xbf, 0xc0
db 0xfb, 0x00, 0x02, 0x13, 0xdf, 0xc0
db 0xfb, 0x00, 0x02, 0x3d, 0xf7, 0xc0
db 0xf8, 0x00
|
; ===============================================================
; May 2017
; ===============================================================
;
; void *tshc_saddrpdown(void *saddr)
;
; Modify screen address to move down one pixel.
;
; ===============================================================
SECTION code_clib
SECTION code_arch
PUBLIC asm_tshc_saddrpdown
PUBLIC asm0_tshc_saddrpdown
EXTERN asm_zx_saddrpdown
EXTERN asm0_zx_saddrpdown
defc asm_tshc_saddrpdown = asm_zx_saddrpdown
defc asm0_tshc_saddrpdown = asm0_zx_saddrpdown
|
; A021411: Decimal expansion of 1/407.
; 0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2,4,5,7,0,0,2
mod $0,6
mul $0,2
mov $2,1
lpb $0
div $0,3
add $0,$2
add $0,1
mul $0,2
sub $0,1
lpe
mov $1,$0
trn $1,2
|
<% from pwnlib.shellcraft.thumb import mov %>
<%docstring>
Crash.
Example:
>>> run_assembly(shellcraft.crash()).poll(True) < 0
True
</%docstring>
pop {r0-r12,lr}
ldr sp, [sp, 64]
bx r1
|
; A327606: Expansion of e.g.f. exp(x)*(1-x)*x/(1-2*x)^2.
; 0,1,8,69,712,8705,123456,1994293,36163184,727518177,16081980760,387499155461,10108673620728,283851555270049,8536572699232592,273759055527114165,9325469762472018016,336282091434597013313,12797935594025234906664,512609204063389138693957,21555874222152774037386920,949509971834339266134653121,43721621958883528998758446048,2100581037224581993229239119029,105118438288345039320748306552272,5470449339495507148324656769557025,295618791757835641191818706998022776
lpb $0
add $1,1
add $1,$0
sub $0,1
add $2,2
mul $1,$2
lpe
mov $0,$1
lpb $0
mov $3,$0
sub $0,6
sub $0,$3
lpe
div $0,4
|
//Language: GNU C++
//
// main.cpp
// Practice
//
// Created by Neel Shah on 11/27/14.
// Copyright (c) 2014 Neel Shah. All rights reserved.
//
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <string.h>
#include <string>
#include <map>
#include<stack>
#include<map>
#include<queue>
#include <math.h>
#include<set>
#include<stdint.h>
#include <utility>
#include <cmath>
#include <iostream>
#include <iomanip>
#define MAXN 100005
#define MAXLG 17
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
using namespace std;
typedef long long int ll;
typedef pair<int, int> mp;
template<class T> void chmin(T &t, const T &f) { if (t > f) t = f; }
template<class T> void chmax(T &t, const T &f) { if (t < f) t = f; }
map<int, int> v[2*MAXN];;
vector<pair<int, int> > ans;
int n, m, deg[2*MAXN], eid = 0, self[2*MAXN]={0};
int main()
{
scanf("%d %d", &n, &m);
for(int i=0; i<m; ++i)
{
int x, y;
scanf("%d %d", &x, &y);
x--; y--;
if(x == y)
{
self[x]++;
continue;
}
deg[x]++; deg[y]++;
v[x][eid] = y;
v[y][eid] = x;
eid++;
}
vector<int> odd;
for(int i=0; i<n; ++i)
{
if(deg[i]%2)
odd.push_back(i);
if(odd.size() == 2)
{
int x = odd[0];
int y = odd[1];
v[x][eid] = y;
v[y][eid] = x;
odd.clear();
}
}
vector<int> path;
stack<int> s;
s.push(0);
while(!s.empty())
{
int node = s.top();
if(v[node].size() == 0)
{
s.pop();
path.push_back(node);
if(self[node] > 0)
{
for(int i=0; i<self[node]; ++i)
path.push_back(node);
self[node] = 0;
}
continue;
}
map<int, int>::iterator it = v[node].begin();
int id = it->first;
int next = it->second;
map<int, int>::iterator it1 = v[next].find(id);
v[next].erase(it1);
map<int, int>::iterator it2 = v[node].find(id);
v[node].erase(it2);
s.push(next);
}
// for(int i=0; i<path.size(); ++i)
// printf("%d ", path[i]+1);
// printf("\n");
path.erase(path.end()-1);
for(int i=1; i<path.size(); i+=2)
{
ans.push_back(mp(path[i-1], path[i]));
if(i+1 < path.size())
ans.push_back(mp(path[i+1], path[i]));
}
ans.push_back(mp(path[0], path[path.size()-1]));
if(path.size()%2)
ans.push_back(mp(path[path.size()-1], path[path.size()-1]));
printf("%ld\n",ans.size());
for(int i=0; i<ans.size(); ++i)
printf("%d %d\n", ans[i].first+1, ans[i].second+1);
return 0;
} |
; A038699: Smallest prime of form n*2^m-1, m >= 0, or 0 if no such prime exists.
; Submitted by Jamie Morken(s4)
; 3,3,2,3,19,5,13,7,17,19,43,11,103,13,29,31,67,17,37,19,41,43,367,23,199,103,53,223,463,29,61,31,131,67,139,71,73,37,311,79,163,41,5503,43,89,367,751,47,97,199,101,103,211,53,109,223,113,463,241663,59,487,61,251,127,1039,131,2143,67,137,139,283,71,9343,73,149,151,307,311,157,79,647,163,331,83,2719,5503,173,738197503,1423,89,181,367,743,751,379,191,193,97,197,199
mov $1,$0
sub $1,1
mov $2,$0
add $2,4
lpb $2
div $0,$2
mov $3,$1
mul $1,2
max $3,0
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,2
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,1
lpe
mov $0,$1
add $0,1
|
#include "agent.hh"
#include "search_parameters.hh"
#include "stepper.hh"
#include "technique.hh"
|
#include "DistributedObject.h"
#include <unordered_set>
#include "core/global.h"
#include "core/msgtypes.h"
#include "dclass/dcClass.h"
#include "dclass/dcField.h"
#include "dclass/dcAtomicField.h"
#include "dclass/dcMolecularField.h"
using namespace std;
DistributedObject::DistributedObject(StateServer *stateserver, doid_t do_id, doid_t parent_id,
zone_t zone_id, DCClass *dclass, DatagramIterator &dgi,
bool has_other) :
m_stateserver(stateserver), m_do_id(do_id), m_parent_id(INVALID_DO_ID), m_zone_id(0),
m_dclass(dclass), m_ai_channel(INVALID_CHANNEL), m_owner_channel(INVALID_CHANNEL),
m_ai_explicitly_set(false), m_parent_synchronized(false), m_next_context(0), m_generate_sender(INVALID_CHANNEL)
{
stringstream name;
name << dclass->get_name() << "(" << do_id << ")";
m_log = new LogCategory("object", name.str());
set_con_name(name.str());
for(int i = 0; i < m_dclass->get_num_inherited_fields(); ++i) {
DCField *field = m_dclass->get_inherited_field(i);
if(field->is_required() && !field->as_molecular_field()) {
dgi.unpack_field(field, m_required_fields[field]);
}
}
if(has_other) {
uint16_t count = dgi.read_uint16();
for(int i = 0; i < count; ++i) {
uint16_t field_id = dgi.read_uint16();
DCField *field = m_dclass->get_field_by_index(field_id);
if(!field) {
m_log->error() << "Received unknown field with ID " << field_id
<< " within an OTHER section.\n";
break;
}
if(field->is_ram()) {
dgi.unpack_field(field, m_ram_fields[field]);
} else {
m_log->error() << "Received non-RAM field " << field->get_name()
<< " within an OTHER section.\n";
dgi.skip_field(field);
}
}
}
subscribe_channel(do_id);
m_log->debug() << "Object created..." << endl;
dgi.seek_payload(); // Seek back to front of payload, to read sender
m_generate_sender = dgi.read_channel();
handle_location_change(parent_id, zone_id, m_generate_sender);
wake_children();
}
DistributedObject::DistributedObject(StateServer *stateserver, channel_t sender, doid_t do_id,
doid_t parent_id, zone_t zone_id, DCClass *dclass,
UnorderedFieldValues& required, FieldValues& ram) :
m_stateserver(stateserver), m_do_id(do_id), m_parent_id(INVALID_DO_ID), m_zone_id(0),
m_dclass(dclass), m_ai_channel(INVALID_CHANNEL), m_owner_channel(INVALID_CHANNEL),
m_ai_explicitly_set(false), m_next_context(0), m_generate_sender(sender)
{
stringstream name;
name << dclass->get_name() << "(" << do_id << ")";
m_log = new LogCategory("object", name.str());
m_required_fields = required;
m_ram_fields = ram;
subscribe_channel(do_id);
handle_location_change(parent_id, zone_id, sender);
wake_children();
}
DistributedObject::~DistributedObject()
{
if(m_log) {
delete m_log;
m_log = nullptr;
}
}
void DistributedObject::append_all_data(DatagramPtr dg)
{
dg->add_doid(m_do_id);
dg->add_location(m_parent_id, m_zone_id);
dg->add_uint16(m_dclass->get_number());
size_t field_count = m_dclass->get_num_inherited_fields();
for(size_t i = 0; i < field_count; ++i) {
DCField *field = m_dclass->get_inherited_field(i);
if(field->is_required() && !field->as_molecular_field()) {
// We only want to append all required atomic fields.
// This should also work for owned objects.
dg->add_data(m_required_fields[field]);
}
}
}
void DistributedObject::append_required_data(DatagramPtr dg, bool client_only)
{
dg->add_doid(m_do_id);
dg->add_location(m_parent_id, m_zone_id);
dg->add_uint16(m_dclass->get_number());
size_t field_count = m_dclass->get_num_inherited_fields();
for(size_t i = 0; i < field_count; ++i) {
DCField *field = m_dclass->get_inherited_field(i);
if(field->is_required() && !field->as_molecular_field() && (!client_only
|| field->is_broadcast() || field->is_clrecv())) {
dg->add_data(m_required_fields[field]);
}
}
}
void DistributedObject::append_other_data(DatagramPtr dg, bool client_only)
{
if(client_only) {
vector<DCField*> broadcast_fields;
for(auto it = m_ram_fields.begin(); it != m_ram_fields.end(); ++it) {
if(it->first->is_broadcast() || it->first->is_clrecv()) {
broadcast_fields.push_back(it->first);
}
}
dg->add_uint16(broadcast_fields.size());
for(auto it = broadcast_fields.begin(); it != broadcast_fields.end(); ++it) {
dg->add_uint16((*it)->get_number());
dg->add_data(m_ram_fields[*it]);
}
} else {
dg->add_uint16(m_ram_fields.size());
for(auto it = m_ram_fields.begin(); it != m_ram_fields.end(); ++it) {
dg->add_uint16(it->first->get_number());
dg->add_data(it->second);
}
}
}
void DistributedObject::send_interest_entry(channel_t location, uint32_t context)
{
DatagramPtr dg = Datagram::create(location, m_do_id, m_ram_fields.size() ?
STATESERVER_OBJECT_ENTER_INTEREST_WITH_REQUIRED_OTHER :
STATESERVER_OBJECT_ENTER_INTEREST_WITH_REQUIRED);
dg->add_uint32(context);
append_required_data(dg, true);
if(m_ram_fields.size()) {
append_other_data(dg, true);
}
route_datagram(dg);
}
void DistributedObject::send_location_entry(channel_t location)
{
DatagramPtr dg = Datagram::create(location, m_do_id, m_ram_fields.size() ?
STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED_OTHER :
STATESERVER_OBJECT_ENTER_LOCATION_WITH_REQUIRED);
append_required_data(dg, true);
if(m_ram_fields.size()) {
append_other_data(dg, true);
}
route_datagram(dg);
}
void DistributedObject::send_ai_entry(channel_t ai)
{
DatagramPtr dg = Datagram::create(ai, m_do_id, m_ram_fields.size() ?
STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED_OTHER :
STATESERVER_OBJECT_ENTER_AI_WITH_REQUIRED);
append_required_data(dg);
if(m_ram_fields.size()) {
append_other_data(dg);
}
route_datagram(dg);
}
void DistributedObject::send_owner_entry(channel_t owner)
{
// Owner entries are required fields trailed by other fields.
DatagramPtr dg = Datagram::create(owner, m_do_id, STATESERVER_OBJECT_ENTER_OWNER_WITH_REQUIRED_OTHER);
append_all_data(dg);
append_other_data(dg, true);
route_datagram(dg);
}
void DistributedObject::handle_location_change(doid_t new_parent, zone_t new_zone, channel_t sender)
{
doid_t old_parent = m_parent_id;
zone_t old_zone = m_zone_id;
// Set of channels that must be notified about location_change
unordered_set<channel_t> targets;
// Notify AI of changing location
if(m_ai_channel) {
targets.insert(m_ai_channel);
}
// Notify Owner of changing location
if(m_owner_channel) {
targets.insert(m_owner_channel);
}
if(new_parent == m_do_id) {
m_log->warning() << "Object cannot be parented to itself.\n";
return;
}
// Handle parent change
if(new_parent != old_parent) {
// Unsubscribe from the old parent's child-broadcast channel.
if(old_parent) { // If we have an old parent
unsubscribe_channel(parent_to_children(m_parent_id));
// Notify old parent of changing location
targets.insert(old_parent);
// Notify old location of changing location
targets.insert(location_as_channel(old_parent, old_zone));
}
m_parent_id = new_parent;
m_zone_id = new_zone;
// Subscribe to new one...
if(new_parent) { // If we have a new parent
subscribe_channel(parent_to_children(m_parent_id));
if(!m_ai_explicitly_set) {
// Ask the new parent what its AI is.
DatagramPtr dg = Datagram::create(m_parent_id, m_do_id, STATESERVER_OBJECT_GET_AI);
dg->add_uint32(m_next_context++);
route_datagram(dg);
}
targets.insert(new_parent); // Notify new parent of changing location
} else if(!m_ai_explicitly_set) {
m_ai_channel = 0;
}
} else if(new_zone != old_zone) {
m_zone_id = new_zone;
// Notify parent of changing zone
targets.insert(m_parent_id);
// Notify old location of changing location
targets.insert(location_as_channel(m_parent_id, old_zone));
} else {
return; // Not actually changing location, no need to handle.
}
// Send changing location message
DatagramPtr dg = Datagram::create(targets, sender, STATESERVER_OBJECT_CHANGING_LOCATION);
dg->add_doid(m_do_id);
dg->add_location(new_parent, new_zone);
dg->add_location(old_parent, old_zone);
route_datagram(dg);
// At this point, the new parent (which may or may not be the same as the
// old parent) is unaware of our existence in this zone.
m_parent_synchronized = false;
// Send enter location message
if(new_parent) {
send_location_entry(location_as_channel(new_parent, new_zone));
}
}
void DistributedObject::handle_ai_change(channel_t new_ai, channel_t sender,
bool channel_is_explicit)
{
channel_t old_ai = m_ai_channel;
if(new_ai == old_ai) {
return;
}
// Set of channels that must be notified about ai_change
unordered_set<channel_t> targets;
if(old_ai) {
targets.insert(old_ai);
}
if(!m_zone_objects.empty()) {
// We have at least one child, so we want to notify the children as well
targets.insert(parent_to_children(m_do_id));
}
m_ai_channel = new_ai;
m_ai_explicitly_set = channel_is_explicit;
DatagramPtr dg = Datagram::create(targets, sender, STATESERVER_OBJECT_CHANGING_AI);
dg->add_doid(m_do_id);
dg->add_channel(new_ai);
dg->add_channel(old_ai);
route_datagram(dg);
if(new_ai != m_generate_sender || old_ai) {
m_log->trace() << "Sending AI entry to " << new_ai << ".\n";
send_ai_entry(new_ai);
}
}
void DistributedObject::begin_delete(bool ai_deletion)
{
if(m_parent_id) {
// Leave parent on explicit delete ram
DatagramPtr dg = Datagram::create(m_parent_id, m_do_id, STATESERVER_OBJECT_CHANGING_LOCATION);
dg->add_doid(m_do_id);
dg->add_location(INVALID_DO_ID, 0);
dg->add_location(m_parent_id, m_zone_id);
route_datagram(dg);
}
std::unordered_set<doid_t> doids;
for(auto kv : m_zone_objects) {
for(auto it : kv.second) {
doids.insert(it);
}
}
m_deletion_count = doids.size();
if(doids.size() < 1) {
// We have no children. We can finish the deletion process now.
if(m_parent_id) {
// However, if we have a parent, we need to acknowledge
// our deletion.
DatagramPtr dg = Datagram::create(m_parent_id, m_do_id, STATESERVER_OBJECT_DELETE_RAM);
dg->add_doid(m_do_id);
dg->add_bool(ai_deletion);
route_datagram(dg);
}
finish_delete(false, ai_deletion);
return;
}
m_deletion_process = true;
delete_children(ai_deletion);
}
void DistributedObject::finish_delete(bool notify_parent, bool ai_deletion)
{
unordered_set<channel_t> targets;
if(m_parent_id) {
if(notify_parent) {
// We do have a parent and need to acknowledge our own deletion.
DatagramPtr dg = Datagram::create(m_parent_id, m_do_id, STATESERVER_OBJECT_DELETE_RAM);
dg->add_doid(m_do_id);
dg->add_bool(ai_deletion);
route_datagram(dg);
}
targets.insert(location_as_channel(m_parent_id, m_zone_id));
}
if(m_owner_channel) {
targets.insert(m_owner_channel);
}
if(m_ai_channel) {
targets.insert(m_ai_channel);
}
DatagramPtr dg = Datagram::create(targets, m_do_id, STATESERVER_OBJECT_DELETE_RAM);
dg->add_doid(m_do_id);
dg->add_bool(ai_deletion);
route_datagram(dg);
m_stateserver->m_objs.erase(m_do_id);
m_log->debug() << "Deleted.\n";
terminate();
}
void DistributedObject::delete_children(bool ai_deletion)
{
// Delete each child.
DatagramPtr dg = Datagram::create(parent_to_children(m_do_id), m_do_id,
STATESERVER_OBJECT_DELETE_CHILDREN);
dg->add_bool(ai_deletion);
route_datagram(dg);
}
void DistributedObject::wake_children()
{
DatagramPtr dg = Datagram::create(parent_to_children(m_do_id), m_do_id,
STATESERVER_OBJECT_GET_LOCATION);
dg->add_uint32(STATESERVER_CONTEXT_WAKE_CHILDREN);
route_datagram(dg);
}
void DistributedObject::save_field(DCField *field, const vector<uint8_t> &data)
{
if(field->is_required()) {
m_required_fields[field] = data;
} else if(field->is_ram()) {
m_ram_fields[field] = data;
}
}
bool DistributedObject::handle_one_update(DatagramIterator &dgi, channel_t sender)
{
vector<uint8_t> data;
uint16_t field_id = dgi.read_uint16();
DCField *field = m_dclass->get_field_by_index(field_id);
if(!field) {
m_log->error() << "Received set_field for field: " << field_id
<< ", not valid for class: " << m_dclass->get_name() << ".\n";
return false;
}
m_log->trace() << "Handling update for '" << field->get_name() << "'.\n";
dgsize_t field_start = dgi.tell();
try {
dgi.unpack_field(field, data);
} catch(const DatagramIteratorEOF&) {
m_log->error() << "Received truncated update for " << field->get_name() << ".\n";
return false;
}
DCMolecularField *molecular = field->as_molecular_field();
if(molecular) {
dgi.seek(field_start);
int n = molecular->get_num_atomics();
for(int i = 0; i < n; ++i) {
vector<uint8_t> field_data;
DCAtomicField *atomic = molecular->get_atomic(i);
dgi.unpack_field(atomic, field_data);
save_field(atomic->as_field(), field_data);
}
} else {
save_field(field, data);
}
unordered_set<channel_t> targets;
if(field->is_broadcast()) {
targets.insert(location_as_channel(m_parent_id, m_zone_id));
}
if(field->is_airecv() && m_ai_channel && m_ai_channel != sender) {
targets.insert(m_ai_channel);
}
if(field->is_ownrecv() && m_owner_channel && m_owner_channel != sender) {
targets.insert(m_owner_channel);
}
if(targets.size()) { // TODO: Review this for efficiency?
DatagramPtr dg = Datagram::create(targets, sender, STATESERVER_OBJECT_SET_FIELD);
dg->add_doid(m_do_id);
dg->add_uint16(field_id);
dg->add_data(data);
route_datagram(dg);
}
return true;
}
bool DistributedObject::handle_one_get(DatagramPtr out, uint16_t field_id,
bool succeed_if_unset, bool is_subfield)
{
DCField *field = m_dclass->get_field_by_index(field_id);
if(!field) {
m_log->error() << "Received get_field for field: " << field_id
<< ", not valid for class: " << m_dclass->get_name() << ".\n";
return false;
}
m_log->trace() << "Handling query for '" << field->get_name() << "'.\n";
DCMolecularField *molecular = field->as_molecular_field();
if(molecular) {
int n = molecular->get_num_atomics();
out->add_uint16(field_id);
for(int i = 0; i < n; ++i) {
if(!handle_one_get(out, molecular->get_atomic(i)->get_number(), succeed_if_unset, true)) {
return false;
}
}
return true;
}
if(m_required_fields.count(field)) {
if(!is_subfield) {
out->add_uint16(field_id);
}
out->add_data(m_required_fields[field]);
} else if(m_ram_fields.count(field)) {
if(!is_subfield) {
out->add_uint16(field_id);
}
out->add_data(m_ram_fields[field]);
} else {
return succeed_if_unset;
}
return true;
}
void DistributedObject::handle_datagram(DatagramHandle, DatagramIterator &dgi)
{
channel_t sender = dgi.read_channel();
uint16_t msgtype = dgi.read_uint16();
switch(msgtype) {
case STATESERVER_DELETE_AI_OBJECTS: {
if(m_ai_channel != dgi.read_channel()) {
m_log->warning() << " received reset for wrong AI channel.\n";
break; // Not my AI!
}
// Log the AI being deleted.
m_log->warning() << "AI channel " << m_ai_channel << " is now being deleted.\n";
// Begin the deletion process.
begin_delete(true);
break;
}
case STATESERVER_OBJECT_DELETE_RAM: {
if(m_do_id != dgi.read_doid()) {
if(m_deletion_process) {
// We've received this as a response from a child which is now deleted.
// Increment the amount of children that are deleted.
++m_deleted;
if(m_deleted == m_deletion_count) {
// All children are deleted. We can delete ourselves now.
finish_delete(true);
}
}
// Nothing else to do here.
break;
}
// If we received more data, assume we received a boolean.
if(dgi.get_remaining() > 0) {
// Begin the deletion process.
begin_delete(dgi.read_bool());
} else {
// Begin the deletion process.
begin_delete();
}
break;
}
case STATESERVER_OBJECT_DELETE_CHILDREN: {
begin_delete(dgi.read_bool());
break;
}
case STATESERVER_OBJECT_SET_FIELD: {
if(m_do_id != dgi.read_doid()) {
break; // Not meant for me!
}
handle_one_update(dgi, sender);
break;
}
case STATESERVER_OBJECT_SET_FIELDS: {
if(m_do_id != dgi.read_doid()) {
break; // Not meant for me!
}
uint16_t field_count = dgi.read_uint16();
for(int16_t i = 0; i < field_count; ++i) {
if(!handle_one_update(dgi, sender)) {
break;
}
}
break;
}
case STATESERVER_OBJECT_CHANGING_AI: {
doid_t r_parent_id = dgi.read_doid();
channel_t new_channel = dgi.read_channel();
m_log->trace() << "Received ChangingAI notification from " << r_parent_id << ".\n";
if(r_parent_id != m_parent_id) {
m_log->warning() << "Received AI channel from " << r_parent_id
<< " but my parent_id is " << m_parent_id << ".\n";
break;
}
if(m_ai_explicitly_set) {
break;
}
handle_ai_change(new_channel, sender, false);
break;
}
case STATESERVER_OBJECT_SET_AI: {
channel_t new_channel = dgi.read_channel();
m_log->trace() << "Updating AI to " << new_channel << ".\n";
handle_ai_change(new_channel, sender, true);
break;
}
case STATESERVER_OBJECT_GET_AI: {
m_log->trace() << "Received AI query from " << sender << ".\n";
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_AI_RESP);
dg->add_uint32(dgi.read_uint32()); // Get context
dg->add_doid(m_do_id);
dg->add_channel(m_ai_channel);
route_datagram(dg);
break;
}
case STATESERVER_OBJECT_GET_AI_RESP: {
dgi.read_uint32(); // Discard context
doid_t r_parent_id = dgi.read_doid();
m_log->trace() << "Received AI query response from " << r_parent_id << ".\n";
if(r_parent_id != m_parent_id) {
m_log->warning() << "Received AI channel from " << r_parent_id
<< " but my parent_id is " << m_parent_id << ".\n";
break;
}
channel_t new_ai = dgi.read_channel();
if(m_ai_explicitly_set) {
break;
}
handle_ai_change(new_ai, sender, false);
break;
}
case STATESERVER_OBJECT_CHANGING_LOCATION: {
doid_t child_id = dgi.read_doid();
doid_t new_parent = dgi.read_doid();
zone_t new_zone = dgi.read_zone();
doid_t r_do_id = dgi.read_doid();
zone_t r_zone = dgi.read_zone();
if(new_parent == m_do_id) {
if(m_do_id == r_do_id) {
if(new_zone == r_zone) {
break; // No change, so do nothing.
}
auto &children = m_zone_objects[r_zone];
children.erase(child_id);
if(children.empty()) {
m_zone_objects.erase(r_zone);
}
}
m_zone_objects[new_zone].insert(child_id);
DatagramPtr dg = Datagram::create(child_id, m_do_id, STATESERVER_OBJECT_LOCATION_ACK);
dg->add_doid(m_do_id);
dg->add_zone(new_zone);
route_datagram(dg);
} else if(r_do_id == m_do_id) {
auto &children = m_zone_objects[r_zone];
children.erase(child_id);
if(children.empty()) {
m_zone_objects.erase(r_zone);
}
} else {
m_log->warning() << "Received changing location from " << child_id
<< " for " << r_do_id << ", but my id is " << m_do_id << ".\n";
}
break;
}
case STATESERVER_OBJECT_LOCATION_ACK: {
doid_t r_parent_id = dgi.read_doid();
zone_t r_zone_id = dgi.read_zone();
if(r_parent_id != m_parent_id) {
m_log->trace() << "Received location acknowledgement from " << r_parent_id
<< " but my parent_id is " << m_parent_id << ".\n";
} else if(r_zone_id != m_zone_id) {
m_log->trace() << "Received location acknowledgement for zone " << r_zone_id
<< " but my zone_id is " << m_zone_id << ".\n";
} else {
m_log->trace() << "Parent acknowledged my location change.\n";
m_parent_synchronized = true;
}
break;
}
case STATESERVER_OBJECT_SET_LOCATION: {
doid_t new_parent = dgi.read_doid();
zone_t new_zone = dgi.read_zone();
m_log->trace() << "Updating location to Parent: " << new_parent
<< ", Zone: " << new_zone << ".\n";
handle_location_change(new_parent, new_zone, sender);
break;
}
case STATESERVER_OBJECT_GET_LOCATION: {
uint32_t context = dgi.read_uint32();
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_LOCATION_RESP);
dg->add_uint32(context);
dg->add_doid(m_do_id);
dg->add_location(m_parent_id, m_zone_id);
route_datagram(dg);
break;
}
case STATESERVER_OBJECT_GET_LOCATION_RESP: {
// This case occurs immediately after object creation.
// A parent expects to receive a location_resp from each
// of its pre-existing children.
if(dgi.read_uint32() != STATESERVER_CONTEXT_WAKE_CHILDREN) {
m_log->warning() << "Received unexpected GetLocationResp from "
<< dgi.read_uint32() << ".\n";
break;
}
// Get DOID of our child
doid_t doid = dgi.read_doid();
// Get location
doid_t r_parent = dgi.read_doid();
zone_t r_zone = dgi.read_zone();
// Update the child count
if(r_parent == m_do_id) {
m_zone_objects[r_zone].insert(doid);
}
break;
}
case STATESERVER_OBJECT_GET_ALL: {
uint32_t context = dgi.read_uint32();
if(dgi.read_doid() != m_do_id) {
return; // Not meant for this object!
}
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_ALL_RESP);
dg->add_uint32(context);
append_required_data(dg);
append_other_data(dg);
route_datagram(dg);
break;
}
case STATESERVER_OBJECT_GET_FIELD: {
uint32_t context = dgi.read_uint32();
if(dgi.read_doid() != m_do_id) {
return; // Not meant for this object!
}
uint16_t field_id = dgi.read_uint16();
DatagramPtr raw_field = Datagram::create();
bool success = handle_one_get(raw_field, field_id);
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_FIELD_RESP);
dg->add_uint32(context);
dg->add_bool(success);
if(success) {
dg->add_data(raw_field);
}
route_datagram(dg);
break;
}
case STATESERVER_OBJECT_GET_FIELDS: {
uint32_t context = dgi.read_uint32();
if(dgi.read_doid() != m_do_id) {
return; // Not meant for this object!
}
uint16_t field_count = dgi.read_uint16();
// Read our requested fields into a sorted set
set<uint16_t> requested_fields;
for(int i = 0; i < field_count; ++i) {
uint16_t field_id = dgi.read_uint16();
if(!requested_fields.insert(field_id).second) {
DCField* field = m_dclass->get_field_by_index(field_id);
if(field != nullptr) {
// If it is null, handle_one_get will produce a warning for us later
m_log->warning() << "Received duplicate field '"
<< field->get_name() << "' in get_fields.\n";
}
}
}
// Try to get the values for all the fields
bool success = true;
uint16_t fields_found = 0;
DatagramPtr raw_fields = Datagram::create();
for(auto it = requested_fields.begin(); it != requested_fields.end(); ++it) {
uint16_t field_id = *it;
uint16_t length = raw_fields->size();
if(!handle_one_get(raw_fields, field_id, true)) {
success = false;
break;
}
if(raw_fields->size() > length) {
fields_found++;
}
}
// Send get fields response
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_FIELDS_RESP);
dg->add_uint32(context);
dg->add_bool(success);
if(success) {
dg->add_uint16(fields_found);
dg->add_data(raw_fields);
}
route_datagram(dg);
break;
}
case STATESERVER_OBJECT_SET_OWNER: {
channel_t new_owner = dgi.read_channel();
m_log->trace() << "Updating owner to " << new_owner << "...\n";
if(new_owner == m_owner_channel) {
m_log->trace() << "... owner is the same, do nothing.\n";
return;
}
if(m_owner_channel) {
m_log->trace() << "... broadcasting changing owner...\n";
DatagramPtr dg = Datagram::create(m_owner_channel, sender, STATESERVER_OBJECT_CHANGING_OWNER);
dg->add_doid(m_do_id);
dg->add_channel(new_owner);
dg->add_channel(m_owner_channel);
route_datagram(dg);
}
m_owner_channel = new_owner;
if(new_owner) {
m_log->trace() << "... sending owner entry...\n";
send_owner_entry(new_owner);
}
m_log->trace() << "... updated owner.\n";
break;
}
case STATESERVER_OBJECT_GET_ZONE_OBJECTS:
case STATESERVER_OBJECT_GET_ZONES_OBJECTS: {
uint32_t context = dgi.read_uint32();
doid_t queried_parent = dgi.read_doid();
m_log->trace() << "Handling get_zones_objects with parent '" << queried_parent << "'"
<< ". My id is " << m_do_id << " and my parent is " << m_parent_id
<< ".\n";
uint16_t zone_count = 1;
if(msgtype == STATESERVER_OBJECT_GET_ZONES_OBJECTS) {
zone_count = dgi.read_uint16();
}
if(queried_parent == m_parent_id) {
// Query was relayed from parent! See if we match any of the zones
// and if so, reply:
for(uint16_t i = 0; i < zone_count; ++i) {
if(dgi.read_zone() == m_zone_id) {
// The parent forwarding this request down to us may or may
// not yet know about our presence (and therefore have us
// included in the count that it sent to the interested
// peer). If we are included in this count, we reply with a
// normal interest entry. If not, we reply with a standard
// location entry and allow the interested peer to resolve
// the difference itself.
if(m_parent_synchronized) {
send_interest_entry(sender, context);
} else {
send_location_entry(sender);
}
break;
}
}
} else if(queried_parent == m_do_id) {
doid_t child_count = 0;
// Start datagram to relay to children
DatagramPtr child_dg = Datagram::create(parent_to_children(m_do_id), sender,
STATESERVER_OBJECT_GET_ZONES_OBJECTS);
child_dg->add_uint32(context);
child_dg->add_doid(queried_parent);
child_dg->add_uint16(zone_count);
// Get all zones requested
for(int i = 0; i < zone_count; ++i) {
zone_t zone = dgi.read_zone();
child_count += m_zone_objects[zone].size();
child_dg->add_zone(zone);
}
// Reply to requestor with count of objects expected
DatagramPtr count_dg = Datagram::create(sender, m_do_id, STATESERVER_OBJECT_GET_ZONES_COUNT_RESP);
count_dg->add_uint32(context);
count_dg->add_doid(child_count);
route_datagram(count_dg);
// Bounce the message down to all children and have them decide
// whether or not to reply.
// TODO: Is this really that efficient?
if(child_count > 0) {
route_datagram(child_dg);
}
}
break;
}
// zones in OTP don't have meaning to the cluster itself
// as such, there is no table of zones to query in the network
// instead, a zone is said to be active if it has at least one object in it
// to get the active zones, get the keys from m_zone_objects and dump them into a std::set<zone_t>
// using an std::set ensures that no duplicate zones are sent
// TODO: evaluate efficiency on large games with many DistributedObjects
case STATESERVER_GET_ACTIVE_ZONES: {
uint32_t context = dgi.read_uint32();
std::unordered_set<zone_t> keys;
for(auto kv : m_zone_objects) {
keys.insert(kv.first);
}
DatagramPtr dg = Datagram::create(sender, m_do_id, STATESERVER_GET_ACTIVE_ZONES_RESP);
dg->add_uint32(context);
dg->add_uint16(keys.size());
std::unordered_set<zone_t>::iterator it;
for(it = keys.begin(); it != keys.end(); ++it) {
dg->add_zone(*it);
}
route_datagram(dg);
break;
}
case STATESERVER_BOUNCE_MESSAGE: {
vector<string> messages;
// Iterate over sent messages
while(dgi.get_remaining() > 0) {
messages.push_back(dgi.read_string());
}
// Dispatch each message
for(auto message : messages) {
DatagramPtr dg = Datagram::create(message);
DatagramIterator dgi(dg);
dgi.seek(1 + sizeof(channel_t)); // Ignore server header junk
handle_datagram(dg, dgi);
}
break;
}
default:
if(msgtype < STATESERVER_MSGTYPE_MIN || msgtype > STATESERVER_MSGTYPE_MAX) {
m_log->warning() << "Received unknown message of type " << msgtype << ".\n";
} else {
m_log->trace() << "Ignoring stateserver message of type " << msgtype << ".\n";
}
}
}
|
; A152725: a(n) = n*(n+1)*(n^4 + 2*n^3 - 2*n^2 - 3*n + 3)/2.
; 0,1,63,666,3430,12195,34461,83188,178956,352485,647515,1124046,1861938,2964871,4564665,6825960,9951256,14186313,19825911,27219970,36780030,48986091,64393813,83642076,107460900,136679725,172236051,215184438,266705866,328117455,400882545,486621136,587120688,704347281,840457135,997808490,1178973846,1386752563,1624183821,1894559940,2201440060,2548664181,2940367563,3380995486,3875318370,4428447255,5045849641,5733365688,6497224776,7344062425,8280937575,9315350226,10455259438,11709101691,13085809605,14594831020,16246148436,18050298813,20018393731,22162139910,24493860090,27026514271,29773721313,32749780896,35969695840,39449194785,43204755231,47253626938,51613855686,56304307395,61344692605,66755591316,72558478188,78775748101,85430742075,92547773550,100152155026,108270225063,116929375641,126158079880,135985920120,146443616361,157563055063,169377318306,181920713310,195228802315,209338432821,224287768188,240116318596,256864972365,274576027635,293293224406,313061776938,333928406511,355941374545,379150516080,403607273616,429364731313,456477649551,485002499850,514997500150,546522650451,579639768813,614412527716,650906490780,689189149845,729329962411,771400389438,815473933506,861626177335,909934822665,960479729496,1013342955688,1068608796921,1126363827015,1186696938610,1249699384206,1315464817563,1384089335461,1455671519820,1530312480180,1608115896541,1689188062563,1773637929126,1861577148250,1953120117375,2048384024001,2147488890688,2250557620416,2357716042305,2469092957695,2584820186586,2705032614438,2829868239331,2959468219485,3093976921140,3233541966796,3378314283813,3528448153371,3684101259790,3845434740210,4012613234631,4185804936313,4365181642536,4550918805720,4743195584905,4942194897591,5148103471938,5361111899326,5581414687275,5809210312725,6044701275676,6288094153188,6539599653741,6799432671955,7067812343670,7344962101386,7631109730063,7926487423281,8231331839760,8545884160240,8870390144721,9205100190063,9550269387946,9906157583190,10273029432435,10651154463181,11040807133188,11442266890236,11855818232245,12281750767755,12720359276766,13171943771938,13636809560151,14115267304425,14607633086200,15114228467976,15635380556313,16171422065191,16722691379730,17289532620270,17872295706811,18471336423813,19087016485356,19719703600660,20369771539965,21037600200771,21723575674438,22428090313146,23151542797215,23894338202785,24656888069856,25439610470688,26242930078561,27067278236895,27913093028730,28780819346566,29670908962563,30583820599101,31520019999700,32479980000300,33464180600901,34473109037563,35507259854766,36567134978130,37653243787495,38766103190361,39906237695688,41074179488056,42270468502185,43495652497815,44750287134946,46034936049438,47350170928971,48696571589365,50074726051260,51485230617156,52928689948813,54405717145011,55916933819670,57462970180330,59044465106991,60662066231313,62316430016176,64008221835600,65738116055025,67506796111951,69314954596938,71163293334966,73052523467155,74983365532845,76956549552036,78972815108188,81032911431381,83137597481835,85287642033790,87483823759746,89726931315063,92017763422921,94357128959640,96745847040360,99184747105081,101674669005063,104216463089586,106810990293070,109459122222555,112161741245541,114919740578188,117734024373876,120605507812125
mov $2,$0
mov $7,$0
pow $7,2
add $0,$7
mov $4,1
gcd $7,2
lpb $2,1
mov $1,$0
lpb $4,1
gcd $7,7
sub $1,$7
sub $4,$7
mov $5,$7
lpe
pow $1,3
lpb $5,1
add $1,1
div $2,7
mov $3,1
sub $5,$7
lpe
mov $6,$3
lpb $6,1
div $1,2
sub $6,$7
lpe
lpe
|
; Flat Assembler uses the Intel syntax.
; Effective for:
; Flat assembler version 1.64
; emu8086 integrated assembler version 4.00-Beta-20 (or above)
#fasm# ; this code is for FASM.
org 100h
name "fasmcomp"
; === [NOTE 1]
; calculate the sum of 'a' and 'b'
jmp start
a dw 5
b dw 7
start:
; this is correct syntax for emu8086 integrated assembler,
; but it is wrong for fasm:
mov ax, a
mov bx, b
add ax, bx ; AX = offset a + offset b (AX=206) (correct, but not what we expect)
; correct syntax for fasm:
mov ax, [a]
mov bx, [b]
add ax, bx ; AX = 5 + 7 (AX=000C) (correct)
;; to calculate sum of offsets for emu8086 integrated assembler
;; it is required to use the offset directive, for example:
; mov ax, offset a
; mov bx, offset b
; add ax, bx ; sum of offsets instead of values.
;; the offset directive is not supported for fasm (error: extra characters on line)
; Hello, World example in fasm:
mov dx, msg
mov ah, 9
int 21h
; for emu8086 integrated assembler:
; mov dx, offset msg
; or
; lea dx, msg
; (syntax of the integrated 8086 assembler is mostly MASM/TASM compatible)
; wait for any key...
mov ah, 0
int 16h
ret
msg db "Hello, World!", 0x0D, 0x0A, "$"
; emu8086 compatible declaration is:
; msg: db "Hello, World!", 0x0D, 0x0A, "$"
; (note: there is ":" after msg)
; === [NOTE 2]
; fasm does not support the comment directive, for example:
; comment *
; la lalala la...
; *
; === [NOTE 3]
; these precompiler directives are preparsed by the IDE:
; NAME
; #make...
; #AX=...
; etc...
; === [NOTE 4]
; for fasm it's required to use "byte" and "word" prefixes
; in places where it may be required to use "byte ptr", "word ptr"
; or "b.", "w." prefixes for the integrated 8086 assembler.
; For example:
mov byte [m1], AL
m1 dw 1234h
; ; for the integrated 8086 assembler it should be:
; mov b. m1, AL
; ; or:
; mov byte ptr m1, AL ; (MASM compatible)
; === [NOTE 5]
; uninitialised variables are not added to actual binary file
; when these variables are located in the bottom of the file
; and there is no defined data after them (MASM compatible)
; 8086 assembler always initialises variables as 0 (MASM incompatibility)
; For example:
u1 dw ?
; === [NOTE 6]
; fasm assembler is case sensitive;
; for example, the following code would cause
; "symbol redefinition" error for MASM or 8086 integrated assembler,
; but it is completely legal for fasm:
mov [d], 9
mov [D], 12
ret
d Dw 5
D dw 7
; === [NOTE 7]
; there may be other slight syntax incompatibilities,
; if you find any problem feel free to email.
|
// cpu.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#ifndef EXCEPTION_EXECUTE_HANDLER
# define EXCEPTION_EXECUTE_HANDLER 1
#endif
#ifndef CRYPTOPP_IMPORTS
#include "cpu.h"
#include "misc.h"
#include <algorithm>
#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
#include <signal.h>
#include <setjmp.h>
#endif
NAMESPACE_BEGIN(CryptoPP)
#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
extern "C" {
typedef void (*SigHandler)(int);
};
#endif // Not CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
#ifdef CRYPTOPP_CPUID_AVAILABLE
#if _MSC_VER >= 1400 && CRYPTOPP_BOOL_X64
bool CpuId(word32 input, word32 output[4])
{
__cpuid((int *)output, input);
return true;
}
#else
#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
extern "C"
{
static jmp_buf s_jmpNoCPUID;
static void SigIllHandlerCPUID(int)
{
longjmp(s_jmpNoCPUID, 1);
}
static jmp_buf s_jmpNoSSE2;
static void SigIllHandlerSSE2(int)
{
longjmp(s_jmpNoSSE2, 1);
}
}
#endif
bool CpuId(word32 input, word32 output[4])
{
#if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
__try
{
__asm
{
mov eax, input
mov ecx, 0
cpuid
mov edi, output
mov [edi], eax
mov [edi+4], ebx
mov [edi+8], ecx
mov [edi+12], edx
}
}
// GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
// function 0 returns the highest basic function understood in EAX
if(input == 0)
return !!output[0];
return true;
#else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerCPUID);
if (oldHandler == SIG_ERR)
return false;
# ifndef __MINGW32__
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
# endif
if (setjmp(s_jmpNoCPUID))
result = false;
else
{
asm volatile
(
// save ebx in case -fPIC is being used
// TODO: this might need an early clobber on EDI.
# if CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64
"pushq %%rbx; cpuid; mov %%ebx, %%edi; popq %%rbx"
# else
"push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
# endif
: "=a" (output[0]), "=D" (output[1]), "=c" (output[2]), "=d" (output[3])
: "a" (input), "c" (0)
: "cc"
);
}
# ifndef __MINGW32__
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
# endif
signal(SIGILL, oldHandler);
return result;
#endif
}
#endif
static bool TrySSE2()
{
#if CRYPTOPP_BOOL_X64
return true;
#elif defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
__try
{
#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
AS2(por xmm0, xmm0) // executing SSE2 instruction
#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE
__m128i x = _mm_setzero_si128();
return _mm_cvtsi128_si32(x) == 0;
#endif
}
// GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return true;
#else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerSSE2);
if (oldHandler == SIG_ERR)
return false;
# ifndef __MINGW32__
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
# endif
if (setjmp(s_jmpNoSSE2))
result = false;
else
{
#if CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE
__asm __volatile ("por %xmm0, %xmm0");
#elif CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE
__m128i x = _mm_setzero_si128();
result = _mm_cvtsi128_si32(x) == 0;
#endif
}
# ifndef __MINGW32__
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
# endif
signal(SIGILL, oldHandler);
return result;
#endif
}
bool CRYPTOPP_SECTION_INIT g_x86DetectionDone = false;
bool CRYPTOPP_SECTION_INIT g_hasMMX = false, CRYPTOPP_SECTION_INIT g_hasISSE = false, CRYPTOPP_SECTION_INIT g_hasSSE2 = false, CRYPTOPP_SECTION_INIT g_hasSSSE3 = false;
bool CRYPTOPP_SECTION_INIT g_hasSSE4 = false, CRYPTOPP_SECTION_INIT g_hasAESNI = false, CRYPTOPP_SECTION_INIT g_hasCLMUL = false, CRYPTOPP_SECTION_INIT g_hasSHA = false;
bool CRYPTOPP_SECTION_INIT g_hasRDRAND = false, CRYPTOPP_SECTION_INIT g_hasRDSEED = false, CRYPTOPP_SECTION_INIT g_isP4 = false;
bool CRYPTOPP_SECTION_INIT g_hasPadlockRNG = false, CRYPTOPP_SECTION_INIT g_hasPadlockACE = false, CRYPTOPP_SECTION_INIT g_hasPadlockACE2 = false;
bool CRYPTOPP_SECTION_INIT g_hasPadlockPHE = false, CRYPTOPP_SECTION_INIT g_hasPadlockPMM = false;
word32 CRYPTOPP_SECTION_INIT g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE;
static inline bool IsIntel(const word32 output[4])
{
// This is the "GenuineIntel" string
return (output[1] /*EBX*/ == 0x756e6547) &&
(output[2] /*ECX*/ == 0x6c65746e) &&
(output[3] /*EDX*/ == 0x49656e69);
}
static inline bool IsAMD(const word32 output[4])
{
// This is the "AuthenticAMD" string. Some early K5's can return "AMDisbetter!"
return (output[1] /*EBX*/ == 0x68747541) &&
(output[2] /*ECX*/ == 0x444D4163) &&
(output[3] /*EDX*/ == 0x69746E65);
}
static inline bool IsVIA(const word32 output[4])
{
// This is the "CentaurHauls" string. Some non-PadLock's can return "VIA VIA VIA "
return (output[1] /*EBX*/ == 0x746e6543) &&
(output[2] /*ECX*/ == 0x736c7561) &&
(output[3] /*EDX*/ == 0x48727561);
}
#if HAVE_GCC_CONSTRUCTOR1
void __attribute__ ((constructor (CRYPTOPP_INIT_PRIORITY + 50))) DetectX86Features()
#elif HAVE_GCC_CONSTRUCTOR0
void __attribute__ ((constructor)) DetectX86Features()
#else
void DetectX86Features()
#endif
{
word32 cpuid[4], cpuid1[4];
if (!CpuId(0, cpuid))
return;
if (!CpuId(1, cpuid1))
return;
g_hasMMX = (cpuid1[3] & (1 << 23)) != 0;
if ((cpuid1[3] & (1 << 26)) != 0)
g_hasSSE2 = TrySSE2();
g_hasSSSE3 = g_hasSSE2 && (cpuid1[2] & (1<<9));
g_hasSSE4 = g_hasSSE2 && ((cpuid1[2] & (1<<19)) && (cpuid1[2] & (1<<20)));
g_hasAESNI = g_hasSSE2 && (cpuid1[2] & (1<<25));
g_hasCLMUL = g_hasSSE2 && (cpuid1[2] & (1<<1));
if ((cpuid1[3] & (1 << 25)) != 0)
g_hasISSE = true;
else
{
word32 cpuid2[4];
CpuId(0x080000000, cpuid2);
if (cpuid2[0] >= 0x080000001)
{
CpuId(0x080000001, cpuid2);
g_hasISSE = (cpuid2[3] & (1 << 22)) != 0;
}
}
if (IsIntel(cpuid))
{
static const unsigned int RDRAND_FLAG = (1 << 30);
static const unsigned int RDSEED_FLAG = (1 << 18);
static const unsigned int SHA_FLAG = (1 << 29);
g_isP4 = ((cpuid1[0] >> 8) & 0xf) == 0xf;
g_cacheLineSize = 8 * GETBYTE(cpuid1[1], 1);
g_hasRDRAND = !!(cpuid1[2] /*ECX*/ & RDRAND_FLAG);
if (cpuid[0] /*EAX*/ >= 7)
{
word32 cpuid3[4];
if (CpuId(7, cpuid3))
{
g_hasRDSEED = !!(cpuid3[1] /*EBX*/ & RDSEED_FLAG);
g_hasSHA = !!(cpuid3[1] /*EBX*/ & SHA_FLAG);
}
}
}
else if (IsAMD(cpuid))
{
static const unsigned int RDRAND_FLAG = (1 << 30);
CpuId(0x01, cpuid);
g_hasRDRAND = !!(cpuid[2] /*ECX*/ & RDRAND_FLAG);
CpuId(0x80000005, cpuid);
g_cacheLineSize = GETBYTE(cpuid[2], 0);
}
else if (IsVIA(cpuid))
{
static const unsigned int RNG_FLAGS = (0x3 << 2);
static const unsigned int ACE_FLAGS = (0x3 << 6);
static const unsigned int ACE2_FLAGS = (0x3 << 8);
static const unsigned int PHE_FLAGS = (0x3 << 10);
static const unsigned int PMM_FLAGS = (0x3 << 12);
CpuId(0xC0000000, cpuid);
if (cpuid[0] >= 0xC0000001)
{
// Extended features available
CpuId(0xC0000001, cpuid);
g_hasPadlockRNG = !!(cpuid[3] /*EDX*/ & RNG_FLAGS);
g_hasPadlockACE = !!(cpuid[3] /*EDX*/ & ACE_FLAGS);
g_hasPadlockACE2 = !!(cpuid[3] /*EDX*/ & ACE2_FLAGS);
g_hasPadlockPHE = !!(cpuid[3] /*EDX*/ & PHE_FLAGS);
g_hasPadlockPMM = !!(cpuid[3] /*EDX*/ & PMM_FLAGS);
}
}
if (!g_cacheLineSize)
g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE;
*((volatile bool*)&g_x86DetectionDone) = true;
}
#elif (CRYPTOPP_BOOL_ARM32 || CRYPTOPP_BOOL_ARM64)
// The ARM equivalent of CPUID probing is reading a MSR. The code requires Exception Level 1 (EL1) and above, but user space runs at EL0.
// Attempting to run the code results in a SIGILL and termination.
//
// #if defined(__arm64__) || defined(__aarch64__)
// word64 caps = 0; // Read ID_AA64ISAR0_EL1
// __asm __volatile("mrs %0, " "id_aa64isar0_el1" : "=r" (caps));
// #elif defined(__arm__) || defined(__aarch32__)
// word32 caps = 0; // Read ID_ISAR5_EL1
// __asm __volatile("mrs %0, " "id_isar5_el1" : "=r" (caps));
// #endif
//
// The following does not work well either. Its appears to be missing constants, and it does not detect Aarch32 execution environments on Aarch64
// http://community.arm.com/groups/android-community/blog/2014/10/10/runtime-detection-of-cpu-features-on-an-armv8-a-cpu
//
bool CRYPTOPP_SECTION_INIT g_ArmDetectionDone = false;
bool CRYPTOPP_SECTION_INIT g_hasNEON = false, CRYPTOPP_SECTION_INIT g_hasPMULL = false, CRYPTOPP_SECTION_INIT g_hasCRC32 = false;
bool CRYPTOPP_SECTION_INIT g_hasAES = false, CRYPTOPP_SECTION_INIT g_hasSHA1 = false, CRYPTOPP_SECTION_INIT g_hasSHA2 = false;
word32 CRYPTOPP_SECTION_INIT g_cacheLineSize = CRYPTOPP_L1_CACHE_LINE_SIZE;
#ifndef CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
extern "C"
{
static jmp_buf s_jmpNoNEON;
static void SigIllHandlerNEON(int)
{
longjmp(s_jmpNoNEON, 1);
}
static jmp_buf s_jmpNoPMULL;
static void SigIllHandlerPMULL(int)
{
longjmp(s_jmpNoPMULL, 1);
}
static jmp_buf s_jmpNoCRC32;
static void SigIllHandlerCRC32(int)
{
longjmp(s_jmpNoCRC32, 1);
}
static jmp_buf s_jmpNoAES;
static void SigIllHandlerAES(int)
{
longjmp(s_jmpNoAES, 1);
}
static jmp_buf s_jmpNoSHA1;
static void SigIllHandlerSHA1(int)
{
longjmp(s_jmpNoSHA1, 1);
}
static jmp_buf s_jmpNoSHA2;
static void SigIllHandlerSHA2(int)
{
longjmp(s_jmpNoSHA2, 1);
}
};
#endif // Not CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY
static bool TryNEON()
{
#if (CRYPTOPP_BOOL_NEON_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
uint32_t v1[4] = {1,1,1,1};
uint32x4_t x1 = vld1q_u32(v1);
uint64_t v2[2] = {1,1};
uint64x2_t x2 = vld1q_u64(v2);
uint32x4_t x3 = vdupq_n_u32(2);
x3 = vsetq_lane_u32(vgetq_lane_u32(x1,0),x3,0);
x3 = vsetq_lane_u32(vgetq_lane_u32(x1,3),x3,3);
uint64x2_t x4 = vdupq_n_u64(2);
x4 = vsetq_lane_u64(vgetq_lane_u64(x2,0),x4,0);
x4 = vsetq_lane_u64(vgetq_lane_u64(x2,1),x4,1);
result = !!(vgetq_lane_u32(x3,0) | vgetq_lane_u64(x4,1));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerNEON);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoNEON))
result = false;
else
{
uint32_t v1[4] = {1,1,1,1};
uint32x4_t x1 = vld1q_u32(v1);
uint64_t v2[2] = {1,1};
uint64x2_t x2 = vld1q_u64(v2);
uint32x4_t x3 = {0,0,0,0};
x3 = vsetq_lane_u32(vgetq_lane_u32(x1,0),x3,0);
x3 = vsetq_lane_u32(vgetq_lane_u32(x1,3),x3,3);
uint64x2_t x4 = {0,0};
x4 = vsetq_lane_u64(vgetq_lane_u64(x2,0),x4,0);
x4 = vsetq_lane_u64(vgetq_lane_u64(x2,1),x4,1);
// Hack... GCC optimizes away the code and returns true
result = !!(vgetq_lane_u32(x3,0) | vgetq_lane_u64(x4,1));
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_NEON_INTRINSICS_AVAILABLE
}
static bool TryPMULL()
{
#if (CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
const poly64_t a1={2}, b1={3};
const poly64x2_t a2={4,5}, b2={6,7};
const poly64x2_t a3={0x8080808080808080,0xa0a0a0a0a0a0a0a0}, b3={0xc0c0c0c0c0c0c0c0, 0xe0e0e0e0e0e0e0e0};
const poly128_t r1 = vmull_p64(a1, b1);
const poly128_t r2 = vmull_high_p64(a2, b2);
const poly128_t r3 = vmull_high_p64(a3, b3);
// Also see https://github.com/weidai11/cryptopp/issues/233.
const uint64x2_t& t1 = vreinterpretq_u64_p128(r1); // {6,0}
const uint64x2_t& t2 = vreinterpretq_u64_p128(r2); // {24,0}
const uint64x2_t& t3 = vreinterpretq_u64_p128(r3); // {bignum,bignum}
result = !!(vgetq_lane_u64(t1,0) == 0x06 && vgetq_lane_u64(t1,1) == 0x00 && vgetq_lane_u64(t2,0) == 0x1b &&
vgetq_lane_u64(t2,1) == 0x00 && vgetq_lane_u64(t3,0) == 0x6c006c006c006c00 && vgetq_lane_u64(t3,1) == 0x6c006c006c006c00);
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerPMULL);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoPMULL))
result = false;
else
{
const poly64_t a1={2}, b1={3};
const poly64x2_t a2={4,5}, b2={6,7};
const poly64x2_t a3={0x8080808080808080,0xa0a0a0a0a0a0a0a0}, b3={0xc0c0c0c0c0c0c0c0, 0xe0e0e0e0e0e0e0e0};
const poly128_t r1 = vmull_p64(a1, b1);
const poly128_t r2 = vmull_high_p64(a2, b2);
const poly128_t r3 = vmull_high_p64(a3, b3);
// Linaro is missing vreinterpretq_u64_p128. Also see https://github.com/weidai11/cryptopp/issues/233.
const uint64x2_t& t1 = (uint64x2_t)(r1); // {6,0}
const uint64x2_t& t2 = (uint64x2_t)(r2); // {24,0}
const uint64x2_t& t3 = (uint64x2_t)(r3); // {bignum,bignum}
result = !!(vgetq_lane_u64(t1,0) == 0x06 && vgetq_lane_u64(t1,1) == 0x00 && vgetq_lane_u64(t2,0) == 0x1b &&
vgetq_lane_u64(t2,1) == 0x00 && vgetq_lane_u64(t3,0) == 0x6c006c006c006c00 && vgetq_lane_u64(t3,1) == 0x6c006c006c006c00);
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE
}
static bool TryCRC32()
{
#if (CRYPTOPP_BOOL_ARM_CRC32_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
word32 w=0, x=1; word16 y=2; byte z=3;
w = __crc32cw(w,x);
w = __crc32ch(w,y);
w = __crc32cb(w,z);
result = !!w;
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerCRC32);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoCRC32))
result = false;
else
{
word32 w=0, x=1; word16 y=2; byte z=3;
w = __crc32cw(w,x);
w = __crc32ch(w,y);
w = __crc32cb(w,z);
// Hack... GCC optimizes away the code and returns true
result = !!w;
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_ARM_CRC32_INTRINSICS_AVAILABLE
}
static bool TryAES()
{
#if (CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
// AES encrypt and decrypt
uint8x16_t data = vdupq_n_u8(0), key = vdupq_n_u8(0);
uint8x16_t r1 = vaeseq_u8(data, key);
uint8x16_t r2 = vaesdq_u8(data, key);
result = !!(vgetq_lane_u8(r1,0) | vgetq_lane_u8(r2,7));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerAES);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoAES))
result = false;
else
{
uint8x16_t data = vdupq_n_u8(0), key = vdupq_n_u8(0);
uint8x16_t r1 = vaeseq_u8(data, key);
uint8x16_t r2 = vaesdq_u8(data, key);
// Hack... GCC optimizes away the code and returns true
result = !!(vgetq_lane_u8(r1,0) | vgetq_lane_u8(r2,7));
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE
}
static bool TrySHA1()
{
#if (CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
uint32x4_t data1 = {1,2,3,4}, data2 = {5,6,7,8}, data3 = {9,10,11,12};
uint32x4_t r1 = vsha1cq_u32 (data1, 0, data2);
uint32x4_t r2 = vsha1mq_u32 (data1, 0, data2);
uint32x4_t r3 = vsha1pq_u32 (data1, 0, data2);
uint32x4_t r4 = vsha1su0q_u32 (data1, data2, data3);
uint32x4_t r5 = vsha1su1q_u32 (data1, data2);
result = !!(vgetq_lane_u32(r1,0) | vgetq_lane_u32(r2,1) | vgetq_lane_u32(r3,2) | vgetq_lane_u32(r4,3) | vgetq_lane_u32(r5,0));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerSHA1);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoSHA1))
result = false;
else
{
uint32x4_t data1 = {1,2,3,4}, data2 = {5,6,7,8}, data3 = {9,10,11,12};
uint32x4_t r1 = vsha1cq_u32 (data1, 0, data2);
uint32x4_t r2 = vsha1mq_u32 (data1, 0, data2);
uint32x4_t r3 = vsha1pq_u32 (data1, 0, data2);
uint32x4_t r4 = vsha1su0q_u32 (data1, data2, data3);
uint32x4_t r5 = vsha1su1q_u32 (data1, data2);
// Hack... GCC optimizes away the code and returns true
result = !!(vgetq_lane_u32(r1,0) | vgetq_lane_u32(r2,1) | vgetq_lane_u32(r3,2) | vgetq_lane_u32(r4,3) | vgetq_lane_u32(r5,0));
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE
}
static bool TrySHA2()
{
#if (CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE)
# if defined(CRYPTOPP_MS_STYLE_INLINE_ASSEMBLY)
volatile bool result = true;
__try
{
uint32x4_t data1 = {1,2,3,4}, data2 = {5,6,7,8}, data3 = {9,10,11,12};
uint32x4_t r1 = vsha256hq_u32 (data1, data2, data3);
uint32x4_t r2 = vsha256h2q_u32 (data1, data2, data3);
uint32x4_t r3 = vsha256su0q_u32 (data1, data2);
uint32x4_t r4 = vsha256su1q_u32 (data1, data2, data3);
result = !!(vgetq_lane_u32(r1,0) | vgetq_lane_u32(r2,1) | vgetq_lane_u32(r3,2) | vgetq_lane_u32(r4,3));
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
return false;
}
return result;
# else
// longjmp and clobber warnings. Volatile is required.
// http://github.com/weidai11/cryptopp/issues/24 and http://stackoverflow.com/q/7721854
volatile bool result = true;
volatile SigHandler oldHandler = signal(SIGILL, SigIllHandlerSHA2);
if (oldHandler == SIG_ERR)
return false;
volatile sigset_t oldMask;
if (sigprocmask(0, NULL, (sigset_t*)&oldMask))
return false;
if (setjmp(s_jmpNoSHA2))
result = false;
else
{
uint32x4_t data1 = {1,2,3,4}, data2 = {5,6,7,8}, data3 = {9,10,11,12};
uint32x4_t r1 = vsha256hq_u32 (data1, data2, data3);
uint32x4_t r2 = vsha256h2q_u32 (data1, data2, data3);
uint32x4_t r3 = vsha256su0q_u32 (data1, data2);
uint32x4_t r4 = vsha256su1q_u32 (data1, data2, data3);
// Hack... GCC optimizes away the code and returns true
result = !!(vgetq_lane_u32(r1,0) | vgetq_lane_u32(r2,1) | vgetq_lane_u32(r3,2) | vgetq_lane_u32(r4,3));
}
sigprocmask(SIG_SETMASK, (sigset_t*)&oldMask, NULL);
signal(SIGILL, oldHandler);
return result;
# endif
#else
return false;
#endif // CRYPTOPP_BOOL_ARM_CRYPTO_INTRINSICS_AVAILABLE
}
#if HAVE_GCC_CONSTRUCTOR1
void __attribute__ ((constructor (CRYPTOPP_INIT_PRIORITY + 50))) DetectArmFeatures()
#elif HAVE_GCC_CONSTRUCTOR0
void __attribute__ ((constructor)) DetectArmFeatures()
#else
void DetectArmFeatures()
#endif
{
g_hasNEON = TryNEON();
g_hasPMULL = TryPMULL();
g_hasCRC32 = TryCRC32();
g_hasAES = TryAES();
g_hasSHA1 = TrySHA1();
g_hasSHA2 = TrySHA2();
*((volatile bool*)&g_ArmDetectionDone) = true;
}
#endif
NAMESPACE_END
#endif
|
; A081006: a(n) = Fibonacci(4n) - 1, or Fibonacci(2n+1)*Lucas(2n-1).
; 2,20,143,986,6764,46367,317810,2178308,14930351,102334154,701408732,4807526975,32951280098,225851433716,1548008755919,10610209857722,72723460248140,498454011879263,3416454622906706,23416728348467684,160500643816367087,1100087778366101930,7540113804746346428,51680708854858323071,354224848179261915074,2427893228399975082452,16641027750620563662095,114059301025943970552218,781774079430987230203436,5358359254990966640871839,36726740705505779255899442,251728825683549488150424260
mul $0,2
add $0,1
lpb $0
sub $0,1
add $1,1
add $2,$1
add $1,$2
lpe
mov $0,$1
|
/*
* Reflect Library by Parra Studios
* A library for provide reflection and metadata representation.
*
* Copyright (C) 2016 - 2022 Vicente Eduardo Ferrer Garcia <vic798@gmail.com>
*
* 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 <gtest/gtest.h>
#include <reflect/reflect_value_type.h>
#include <reflect/reflect_value_type_cast.h>
class reflect_value_cast_long_test : public testing::Test
{
public:
};
TEST_F(reflect_value_cast_long_test, long_to_bool_cast)
{
value v = value_create_long(931324L);
boolean b = 1L; /* Because C compiler cast doesn't convert 931324L to 1L */
v = value_type_cast(v, TYPE_BOOL);
EXPECT_EQ((boolean)b, (boolean)value_to_bool(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_char_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_CHAR);
EXPECT_EQ((char)l, (char)value_to_char(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_short_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_SHORT);
EXPECT_EQ((short)l, (short)value_to_short(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_int_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_INT);
EXPECT_EQ((int)l, (int)value_to_int(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_long_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_LONG);
EXPECT_EQ((long)l, (long)value_to_long(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_float_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_FLOAT);
EXPECT_EQ((float)l, (float)value_to_float(v));
value_destroy(v);
}
TEST_F(reflect_value_cast_long_test, long_to_double_cast)
{
value v = value_create_long(931324L);
long l = value_to_long(v);
v = value_type_cast(v, TYPE_DOUBLE);
EXPECT_EQ((double)l, (double)value_to_double(v));
value_destroy(v);
}
|
// Copyright (C) 2014-2018 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <cc/data.h>
#include <cc/command_interpreter.h>
#include <config/command_mgr.h>
#include <dhcp/libdhcp++.h>
#include <dhcpsrv/cfgmgr.h>
#include <dhcpsrv/cfg_db_access.h>
#include <dhcp6/ctrl_dhcp6_srv.h>
#include <dhcp6/dhcp6to4_ipc.h>
#include <dhcp6/dhcp6_log.h>
#include <dhcp6/json_config_parser.h>
#include <dhcp6/parser_context.h>
#include <hooks/hooks_manager.h>
#include <stats/stats_mgr.h>
#include <cfgrpt/config_report.h>
#include <signal.h>
#include <sstream>
using namespace isc::config;
using namespace isc::db;
using namespace isc::dhcp;
using namespace isc::data;
using namespace isc::hooks;
using namespace isc::stats;
using namespace std;
namespace {
/// Structure that holds registered hook indexes.
struct CtrlDhcp6Hooks {
int hooks_index_dhcp6_srv_configured_;
/// Constructor that registers hook points for the DHCPv6 server.
CtrlDhcp6Hooks() {
hooks_index_dhcp6_srv_configured_ = HooksManager::registerHook("dhcp6_srv_configured");
}
};
// Declare a Hooks object. As this is outside any function or method, it
// will be instantiated (and the constructor run) when the module is loaded.
// As a result, the hook indexes will be defined before any method in this
// module is called.
CtrlDhcp6Hooks Hooks;
// Name of the file holding server identifier.
static const char* SERVER_DUID_FILE = "kea-dhcp6-serverid";
/// @brief Signals handler for DHCPv6 server.
///
/// This signal handler handles the following signals received by the DHCPv6
/// server process:
/// - SIGHUP - triggers server's dynamic reconfiguration.
/// - SIGTERM - triggers server's shut down.
/// - SIGINT - triggers server's shut down.
///
/// @param signo Signal number received.
void signalHandler(int signo) {
// SIGHUP signals a request to reconfigure the server.
if (signo == SIGHUP) {
ControlledDhcpv6Srv::processCommand("config-reload",
ConstElementPtr());
} else if ((signo == SIGTERM) || (signo == SIGINT)) {
ControlledDhcpv6Srv::processCommand("shutdown",
ConstElementPtr());
}
}
}
namespace isc {
namespace dhcp {
ControlledDhcpv6Srv* ControlledDhcpv6Srv::server_ = NULL;
/// @brief Configure DHCPv6 server using the configuration file specified.
///
/// This function is used to both configure the DHCP server on its startup
/// and dynamically reconfigure the server when SIGHUP signal is received.
///
/// It fetches DHCPv6 server's configuration from the 'Dhcp6' section of
/// the JSON configuration file.
///
/// @param file_name Configuration file location.
/// @return status of the command
ConstElementPtr
ControlledDhcpv6Srv::loadConfigFile(const std::string& file_name) {
// This is a configuration backend implementation that reads the
// configuration from a JSON file.
isc::data::ConstElementPtr json;
isc::data::ConstElementPtr dhcp6;
isc::data::ConstElementPtr logger;
isc::data::ConstElementPtr result;
// Basic sanity check: file name must not be empty.
try {
if (file_name.empty()) {
// Basic sanity check: file name must not be empty.
isc_throw(isc::BadValue, "JSON configuration file not specified. Please "
"use -c command line option.");
}
// Read contents of the file and parse it as JSON
Parser6Context parser;
json = parser.parseFile(file_name, Parser6Context::PARSER_DHCP6);
if (!json) {
isc_throw(isc::BadValue, "no configuration found");
}
// Let's do sanity check before we call json->get() which
// works only for map.
if (json->getType() != isc::data::Element::map) {
isc_throw(isc::BadValue, "Configuration file is expected to be "
"a map, i.e., start with { and end with } and contain "
"at least an entry called 'Dhcp6' that itself is a map. "
<< file_name
<< " is a valid JSON, but its top element is not a map."
" Did you forget to add { } around your configuration?");
}
// Use parsed JSON structures to configure the server
result = ControlledDhcpv6Srv::processCommand("config-set", json);
if (!result) {
// Undetermined status of the configuration. This should never
// happen, but as the configureDhcp6Server returns a pointer, it is
// theoretically possible that it will return NULL.
isc_throw(isc::BadValue, "undefined result of "
"processCommand(\"config-set\", json)");
}
// Now check is the returned result is successful (rcode=0) or not
// (see @ref isc::config::parseAnswer).
int rcode;
isc::data::ConstElementPtr comment =
isc::config::parseAnswer(rcode, result);
if (rcode != 0) {
string reason = comment ? comment->stringValue() :
"no details available";
isc_throw(isc::BadValue, reason);
}
} catch (const std::exception& ex) {
// If configuration failed at any stage, we drop the staging
// configuration and continue to use the previous one.
CfgMgr::instance().rollback();
LOG_ERROR(dhcp6_logger, DHCP6_CONFIG_LOAD_FAIL)
.arg(file_name).arg(ex.what());
isc_throw(isc::BadValue, "configuration error using file '"
<< file_name << "': " << ex.what());
}
return (result);
}
void
ControlledDhcpv6Srv::init(const std::string& file_name) {
// Configure the server using JSON file.
ConstElementPtr result = loadConfigFile(file_name);
int rcode;
ConstElementPtr comment = isc::config::parseAnswer(rcode, result);
if (rcode != 0) {
string reason = comment ? comment->stringValue() :
"no details available";
isc_throw(isc::BadValue, reason);
}
// We don't need to call openActiveSockets() or startD2() as these
// methods are called in processConfig() which is called by
// processCommand("config-set", ...)
// Set signal handlers. When the SIGHUP is received by the process
// the server reconfiguration will be triggered. When SIGTERM or
// SIGINT will be received, the server will start shutting down.
signal_set_.reset(new isc::util::SignalSet(SIGINT, SIGHUP, SIGTERM));
// Set the pointer to the handler function.
signal_handler_ = signalHandler;
}
void ControlledDhcpv6Srv::cleanup() {
// Nothing to do here. No need to disconnect from anything.
}
ConstElementPtr
ControlledDhcpv6Srv::commandShutdownHandler(const string&, ConstElementPtr) {
if (ControlledDhcpv6Srv::server_) {
ControlledDhcpv6Srv::server_->shutdown();
} else {
LOG_WARN(dhcp6_logger, DHCP6_NOT_RUNNING);
ConstElementPtr answer = isc::config::createAnswer(1, "Shutdown failure.");
return (answer);
}
ConstElementPtr answer = isc::config::createAnswer(0, "Shutting down.");
return (answer);
}
ConstElementPtr
ControlledDhcpv6Srv::commandLibReloadHandler(const string&, ConstElementPtr) {
/// @todo delete any stored CalloutHandles referring to the old libraries
/// Get list of currently loaded libraries and reload them.
HookLibsCollection loaded = HooksManager::getLibraryInfo();
bool status = HooksManager::loadLibraries(loaded);
if (!status) {
LOG_ERROR(dhcp6_logger, DHCP6_HOOKS_LIBS_RELOAD_FAIL);
ConstElementPtr answer = isc::config::createAnswer(1,
"Failed to reload hooks libraries.");
return (answer);
}
ConstElementPtr answer = isc::config::createAnswer(0,
"Hooks libraries successfully reloaded.");
return (answer);
}
ConstElementPtr
ControlledDhcpv6Srv::commandConfigReloadHandler(const string&,
ConstElementPtr /*args*/) {
// Get configuration file name.
std::string file = ControlledDhcpv6Srv::getInstance()->getConfigFile();
try {
LOG_INFO(dhcp6_logger, DHCP6_DYNAMIC_RECONFIGURATION).arg(file);
return (loadConfigFile(file));
} catch (const std::exception& ex) {
// Log the unsuccessful reconfiguration. The reason for failure
// should be already logged. Don't rethrow an exception so as
// the server keeps working.
LOG_ERROR(dhcp6_logger, DHCP6_DYNAMIC_RECONFIGURATION_FAIL)
.arg(file);
return (createAnswer(CONTROL_RESULT_ERROR,
"Config reload failed:" + string(ex.what())));
}
}
ConstElementPtr
ControlledDhcpv6Srv::commandConfigGetHandler(const string&,
ConstElementPtr /*args*/) {
ConstElementPtr config = CfgMgr::instance().getCurrentCfg()->toElement();
return (createAnswer(0, config));
}
ConstElementPtr
ControlledDhcpv6Srv::commandConfigWriteHandler(const string&, ConstElementPtr args) {
string filename;
if (args) {
if (args->getType() != Element::map) {
return (createAnswer(CONTROL_RESULT_ERROR, "Argument must be a map"));
}
ConstElementPtr filename_param = args->get("filename");
if (filename_param) {
if (filename_param->getType() != Element::string) {
return (createAnswer(CONTROL_RESULT_ERROR,
"passed parameter 'filename' is not a string"));
}
filename = filename_param->stringValue();
}
}
if (filename.empty()) {
// filename parameter was not specified, so let's use whatever we remember
// from the command-line
filename = getConfigFile();
}
if (filename.empty()) {
return (createAnswer(CONTROL_RESULT_ERROR, "Unable to determine filename."
"Please specify filename explicitly."));
}
// Ok, it's time to write the file.
size_t size = 0;
try {
size = writeConfigFile(filename);
} catch (const isc::Exception& ex) {
return (createAnswer(CONTROL_RESULT_ERROR, string("Error during write-config:")
+ ex.what()));
}
if (size == 0) {
return (createAnswer(CONTROL_RESULT_ERROR, "Error writing configuration to "
+ filename));
}
// Ok, it's time to return the successful response.
ElementPtr params = Element::createMap();
params->set("size", Element::create(static_cast<long long>(size)));
params->set("filename", Element::create(filename));
return (createAnswer(CONTROL_RESULT_SUCCESS, "Configuration written to "
+ filename + " successful", params));
}
ConstElementPtr
ControlledDhcpv6Srv::commandConfigSetHandler(const string&,
ConstElementPtr args) {
const int status_code = CONTROL_RESULT_ERROR;
ConstElementPtr dhcp6;
string message;
// Command arguments are expected to be:
// { "Dhcp6": { ... }, "Logging": { ... } }
// The Logging component is technically optional. If it's not supplied
// logging will revert to default logging.
if (!args) {
message = "Missing mandatory 'arguments' parameter.";
} else {
dhcp6 = args->get("Dhcp6");
if (!dhcp6) {
message = "Missing mandatory 'Dhcp6' parameter.";
} else if (dhcp6->getType() != Element::map) {
message = "'Dhcp6' parameter expected to be a map.";
}
}
if (!message.empty()) {
// Something is amiss with arguments, return a failure response.
ConstElementPtr result = isc::config::createAnswer(status_code,
message);
return (result);
}
// We are starting the configuration process so we should remove any
// staging configuration that has been created during previous
// configuration attempts.
CfgMgr::instance().rollback();
// Logging is a sibling element and must be parsed explicitly.
// The call to configureLogger parses the given Logging element if
// not null, into the staging config. Note this does not alter the
// current loggers, they remain in effect until we apply the
// logging config below. If no logging is supplied logging will
// revert to default logging.
Daemon::configureLogger(args->get("Logging"),
CfgMgr::instance().getStagingCfg());
// Let's apply the new logging. We do it early, so we'll be able to print
// out what exactly is wrong with the new socnfig in case of problems.
CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
// Now we configure the server proper.
ConstElementPtr result = processConfig(dhcp6);
// If the configuration parsed successfully, apply the new logger
// configuration and the commit the new configuration. We apply
// the logging first in case there's a configuration failure.
int rcode = 0;
isc::config::parseAnswer(rcode, result);
if (rcode == CONTROL_RESULT_SUCCESS) {
CfgMgr::instance().getStagingCfg()->applyLoggingCfg();
// Use new configuration.
CfgMgr::instance().commit();
} else {
// Ok, we applied the logging from the upcoming configuration, but
// there were problems with the config. As such, we need to back off
// and revert to the previous logging configuration.
CfgMgr::instance().getCurrentCfg()->applyLoggingCfg();
}
return (result);
}
ConstElementPtr
ControlledDhcpv6Srv::commandConfigTestHandler(const string&,
ConstElementPtr args) {
const int status_code = CONTROL_RESULT_ERROR; // 1 indicates an error
ConstElementPtr dhcp6;
string message;
// Command arguments are expected to be:
// { "Dhcp6": { ... }, "Logging": { ... } }
// The Logging component is technically optional. If it's not supplied
// logging will revert to default logging.
if (!args) {
message = "Missing mandatory 'arguments' parameter.";
} else {
dhcp6 = args->get("Dhcp6");
if (!dhcp6) {
message = "Missing mandatory 'Dhcp6' parameter.";
} else if (dhcp6->getType() != Element::map) {
message = "'Dhcp6' parameter expected to be a map.";
}
}
if (!message.empty()) {
// Something is amiss with arguments, return a failure response.
ConstElementPtr result = isc::config::createAnswer(status_code,
message);
return (result);
}
// We are starting the configuration process so we should remove any
// staging configuration that has been created during previous
// configuration attempts.
CfgMgr::instance().rollback();
// Now we check the server proper.
return (checkConfig(dhcp6));
}
ConstElementPtr
ControlledDhcpv6Srv::commandDhcpDisableHandler(const std::string&,
ConstElementPtr args) {
std::ostringstream message;
int64_t max_period = 0;
// Parse arguments to see if the 'max-period' parameter has been specified.
if (args) {
// Arguments must be a map.
if (args->getType() != Element::map) {
message << "arguments for the 'dhcp-disable' command must be a map";
} else {
ConstElementPtr max_period_element = args->get("max-period");
// max-period is optional.
if (max_period_element) {
// It must be an integer, if specified.
if (max_period_element->getType() != Element::integer) {
message << "'max-period' argument must be a number";
} else {
// It must be positive integer.
max_period = max_period_element->intValue();
if (max_period <= 0) {
message << "'max-period' must be positive integer";
}
// The user specified that the DHCP service should resume not
// later than in max-period seconds. If the 'dhcp-enable' command
// is not sent, the DHCP service will resume automatically.
network_state_->delayedEnableAll(static_cast<unsigned>(max_period));
}
}
}
}
// No error occurred, so let's disable the service.
if (message.tellp() == 0) {
network_state_->disableService();
message << "DHCPv6 service disabled";
if (max_period > 0) {
message << " for " << max_period << " seconds";
}
// Success.
return (config::createAnswer(CONTROL_RESULT_SUCCESS, message.str()));
}
// Failure.
return (config::createAnswer(CONTROL_RESULT_ERROR, message.str()));
}
ConstElementPtr
ControlledDhcpv6Srv::commandDhcpEnableHandler(const std::string&, ConstElementPtr) {
network_state_->enableService();
return (config::createAnswer(CONTROL_RESULT_SUCCESS, "DHCP service successfully enabled"));
}
ConstElementPtr
ControlledDhcpv6Srv::commandVersionGetHandler(const string&, ConstElementPtr) {
ElementPtr extended = Element::create(Dhcpv6Srv::getVersion(true));
ElementPtr arguments = Element::createMap();
arguments->set("extended", extended);
ConstElementPtr answer = isc::config::createAnswer(0,
Dhcpv6Srv::getVersion(false),
arguments);
return (answer);
}
ConstElementPtr
ControlledDhcpv6Srv::commandBuildReportHandler(const string&, ConstElementPtr) {
ConstElementPtr answer =
isc::config::createAnswer(0, isc::detail::getConfigReport());
return (answer);
}
ConstElementPtr
ControlledDhcpv6Srv::commandLeasesReclaimHandler(const string&,
ConstElementPtr args) {
int status_code = 1;
string message;
// args must be { "remove": <bool> }
if (!args) {
message = "Missing mandatory 'remove' parameter.";
} else {
ConstElementPtr remove_name = args->get("remove");
if (!remove_name) {
message = "Missing mandatory 'remove' parameter.";
} else if (remove_name->getType() != Element::boolean) {
message = "'remove' parameter expected to be a boolean.";
} else {
bool remove_lease = remove_name->boolValue();
server_->alloc_engine_->reclaimExpiredLeases6(0, 0, remove_lease);
status_code = 0;
message = "Reclamation of expired leases is complete.";
}
}
ConstElementPtr answer = isc::config::createAnswer(status_code, message);
return (answer);
}
isc::data::ConstElementPtr
ControlledDhcpv6Srv::processCommand(const std::string& command,
isc::data::ConstElementPtr args) {
string txt = args ? args->str() : "(none)";
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_COMMAND_RECEIVED)
.arg(command).arg(txt);
ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
if (!srv) {
ConstElementPtr no_srv = isc::config::createAnswer(1,
"Server object not initialized, can't process command '" +
command + "', arguments: '" + txt + "'.");
return (no_srv);
}
try {
if (command == "shutdown") {
return (srv->commandShutdownHandler(command, args));
} else if (command == "libreload") {
return (srv->commandLibReloadHandler(command, args));
} else if (command == "config-reload") {
return (srv->commandConfigReloadHandler(command, args));
} else if (command == "config-set") {
return (srv->commandConfigSetHandler(command, args));
} else if (command == "config-get") {
return (srv->commandConfigGetHandler(command, args));
} else if (command == "config-test") {
return (srv->commandConfigTestHandler(command, args));
} else if (command == "dhcp-disable") {
return (srv->commandDhcpDisableHandler(command, args));
} else if (command == "dhcp-enable") {
return (srv->commandDhcpEnableHandler(command, args));
} else if (command == "version-get") {
return (srv->commandVersionGetHandler(command, args));
} else if (command == "build-report") {
return (srv->commandBuildReportHandler(command, args));
} else if (command == "leases-reclaim") {
return (srv->commandLeasesReclaimHandler(command, args));
} else if (command == "config-write") {
return (srv->commandConfigWriteHandler(command, args));
}
return (isc::config::createAnswer(1, "Unrecognized command:"
+ command));
} catch (const Exception& ex) {
return (isc::config::createAnswer(1, "Error while processing command '"
+ command + "':" + ex.what()));
}
}
isc::data::ConstElementPtr
ControlledDhcpv6Srv::processConfig(isc::data::ConstElementPtr config) {
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_RECEIVED)
.arg(config->str());
ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
if (!srv) {
ConstElementPtr no_srv = isc::config::createAnswer(
CONTROL_RESULT_ERROR,
"Server object not initialized, can't process config.");
return (no_srv);
}
ConstElementPtr answer = configureDhcp6Server(*srv, config);
// Check that configuration was successful. If not, do not reopen sockets
// and don't bother with DDNS stuff.
try {
int rcode = 0;
isc::config::parseAnswer(rcode, answer);
if (rcode != 0) {
return (answer);
}
} catch (const std::exception& ex) {
return (isc::config::createAnswer(1, "Failed to process configuration:"
+ string(ex.what())));
}
// Re-open lease and host database with new parameters.
try {
DatabaseConnection::db_lost_callback =
boost::bind(&ControlledDhcpv6Srv::dbLostCallback, srv, _1);
CfgDbAccessPtr cfg_db = CfgMgr::instance().getStagingCfg()->getCfgDbAccess();
cfg_db->setAppendedParameters("universe=6");
cfg_db->createManagers();
} catch (const std::exception& ex) {
return (isc::config::createAnswer(1, "Unable to open database: "
+ std::string(ex.what())));
}
// Regenerate server identifier if needed.
try {
const std::string duid_file = CfgMgr::instance().getDataDir() + "/" +
std::string(SERVER_DUID_FILE);
DuidPtr duid = CfgMgr::instance().getStagingCfg()->getCfgDUID()->create(duid_file);
server_->serverid_.reset(new Option(Option::V6, D6O_SERVERID, duid->getDuid()));
if (duid) {
LOG_INFO(dhcp6_logger, DHCP6_USING_SERVERID)
.arg(duid->toText())
.arg(duid_file);
}
} catch (const std::exception& ex) {
std::ostringstream err;
err << "unable to configure server identifier: " << ex.what();
return (isc::config::createAnswer(1, err.str()));
}
// Server will start DDNS communications if its enabled.
try {
srv->startD2();
} catch (const std::exception& ex) {
std::ostringstream err;
err << "error starting DHCP_DDNS client "
" after server reconfiguration: " << ex.what();
return (isc::config::createAnswer(1, err.str()));
}
// Setup DHCPv4-over-DHCPv6 IPC
try {
Dhcp6to4Ipc::instance().open();
} catch (const std::exception& ex) {
std::ostringstream err;
err << "error starting DHCPv4-over-DHCPv6 IPC "
" after server reconfiguration: " << ex.what();
return (isc::config::createAnswer(1, err.str()));
}
// Configuration may change active interfaces. Therefore, we have to reopen
// sockets according to new configuration. It is possible that this
// operation will fail for some interfaces but the openSockets function
// guards against exceptions and invokes a callback function to
// log warnings. Since we allow that this fails for some interfaces there
// is no need to rollback configuration if socket fails to open on any
// of the interfaces.
CfgMgr::instance().getStagingCfg()->getCfgIface()->openSockets(AF_INET6, srv->getPort());
// Install the timers for handling leases reclamation.
try {
CfgMgr::instance().getStagingCfg()->getCfgExpiration()->
setupTimers(&ControlledDhcpv6Srv::reclaimExpiredLeases,
&ControlledDhcpv6Srv::deleteExpiredReclaimedLeases,
server_);
} catch (const std::exception& ex) {
std::ostringstream err;
err << "unable to setup timers for periodically running the"
" reclamation of the expired leases: "
<< ex.what() << ".";
return (isc::config::createAnswer(1, err.str()));
}
// Finally, we can commit runtime option definitions in libdhcp++. This is
// exception free.
LibDHCP::commitRuntimeOptionDefs();
// This hook point notifies hooks libraries that the configuration of the
// DHCPv6 server has completed. It provides the hook library with the pointer
// to the common IO service object, new server configuration in the JSON
// format and with the pointer to the configuration storage where the
// parsed configuration is stored.
if (HooksManager::calloutsPresent(Hooks.hooks_index_dhcp6_srv_configured_)) {
CalloutHandlePtr callout_handle = HooksManager::createCalloutHandle();
callout_handle->setArgument("io_context", srv->getIOService());
callout_handle->setArgument("network_state", srv->getNetworkState());
callout_handle->setArgument("json_config", config);
callout_handle->setArgument("server_config", CfgMgr::instance().getStagingCfg());
HooksManager::callCallouts(Hooks.hooks_index_dhcp6_srv_configured_,
*callout_handle);
// Ignore status code as none of them would have an effect on further
// operation.
}
return (answer);
}
isc::data::ConstElementPtr
ControlledDhcpv6Srv::checkConfig(isc::data::ConstElementPtr config) {
LOG_DEBUG(dhcp6_logger, DBG_DHCP6_COMMAND, DHCP6_CONFIG_RECEIVED)
.arg(config->str());
ControlledDhcpv6Srv* srv = ControlledDhcpv6Srv::getInstance();
if (!srv) {
ConstElementPtr no_srv = isc::config::createAnswer(1,
"Server object not initialized, can't process config.");
return (no_srv);
}
return (configureDhcp6Server(*srv, config, true));
}
ControlledDhcpv6Srv::ControlledDhcpv6Srv(uint16_t port)
: Dhcpv6Srv(port), io_service_(), timer_mgr_(TimerMgr::instance()) {
if (server_) {
isc_throw(InvalidOperation,
"There is another Dhcpv6Srv instance already.");
}
server_ = this; // remember this instance for use in callback
// TimerMgr uses IO service to run asynchronous timers.
TimerMgr::instance()->setIOService(getIOService());
// CommandMgr uses IO service to run asynchronous socket operations.
CommandMgr::instance().setIOService(getIOService());
// These are the commands always supported by the DHCPv6 server.
// Please keep the list in alphabetic order.
CommandMgr::instance().registerCommand("build-report",
boost::bind(&ControlledDhcpv6Srv::commandBuildReportHandler, this, _1, _2));
CommandMgr::instance().registerCommand("config-get",
boost::bind(&ControlledDhcpv6Srv::commandConfigGetHandler, this, _1, _2));
CommandMgr::instance().registerCommand("config-reload",
boost::bind(&ControlledDhcpv6Srv::commandConfigReloadHandler, this, _1, _2));
CommandMgr::instance().registerCommand("config-test",
boost::bind(&ControlledDhcpv6Srv::commandConfigTestHandler, this, _1, _2));
CommandMgr::instance().registerCommand("config-write",
boost::bind(&ControlledDhcpv6Srv::commandConfigWriteHandler, this, _1, _2));
CommandMgr::instance().registerCommand("dhcp-disable",
boost::bind(&ControlledDhcpv6Srv::commandDhcpDisableHandler, this, _1, _2));
CommandMgr::instance().registerCommand("dhcp-enable",
boost::bind(&ControlledDhcpv6Srv::commandDhcpEnableHandler, this, _1, _2));
CommandMgr::instance().registerCommand("leases-reclaim",
boost::bind(&ControlledDhcpv6Srv::commandLeasesReclaimHandler, this, _1, _2));
CommandMgr::instance().registerCommand("libreload",
boost::bind(&ControlledDhcpv6Srv::commandLibReloadHandler, this, _1, _2));
CommandMgr::instance().registerCommand("config-set",
boost::bind(&ControlledDhcpv6Srv::commandConfigSetHandler, this, _1, _2));
CommandMgr::instance().registerCommand("shutdown",
boost::bind(&ControlledDhcpv6Srv::commandShutdownHandler, this, _1, _2));
CommandMgr::instance().registerCommand("version-get",
boost::bind(&ControlledDhcpv6Srv::commandVersionGetHandler, this, _1, _2));
// Register statistic related commands
CommandMgr::instance().registerCommand("statistic-get",
boost::bind(&StatsMgr::statisticGetHandler, _1, _2));
CommandMgr::instance().registerCommand("statistic-get-all",
boost::bind(&StatsMgr::statisticGetAllHandler, _1, _2));
CommandMgr::instance().registerCommand("statistic-reset",
boost::bind(&StatsMgr::statisticResetHandler, _1, _2));
CommandMgr::instance().registerCommand("statistic-reset-all",
boost::bind(&StatsMgr::statisticResetAllHandler, _1, _2));
CommandMgr::instance().registerCommand("statistic-remove",
boost::bind(&StatsMgr::statisticRemoveHandler, _1, _2));
CommandMgr::instance().registerCommand("statistic-remove-all",
boost::bind(&StatsMgr::statisticRemoveAllHandler, _1, _2));
}
void ControlledDhcpv6Srv::shutdown() {
io_service_.stop(); // Stop ASIO transmissions
Dhcpv6Srv::shutdown(); // Initiate DHCPv6 shutdown procedure.
}
ControlledDhcpv6Srv::~ControlledDhcpv6Srv() {
try {
cleanup();
// The closure captures either a shared pointer (memory leak)
// or a raw pointer (pointing to a deleted object).
DatabaseConnection::db_lost_callback = 0;
timer_mgr_->unregisterTimers();
// Close the command socket (if it exists).
CommandMgr::instance().closeCommandSocket();
// Deregister any registered commands (please keep in alphabetic order)
CommandMgr::instance().deregisterCommand("build-report");
CommandMgr::instance().deregisterCommand("config-get");
CommandMgr::instance().deregisterCommand("config-set");
CommandMgr::instance().deregisterCommand("config-reload");
CommandMgr::instance().deregisterCommand("config-test");
CommandMgr::instance().deregisterCommand("config-write");
CommandMgr::instance().deregisterCommand("dhcp-disable");
CommandMgr::instance().deregisterCommand("dhcp-enable");
CommandMgr::instance().deregisterCommand("leases-reclaim");
CommandMgr::instance().deregisterCommand("libreload");
CommandMgr::instance().deregisterCommand("shutdown");
CommandMgr::instance().deregisterCommand("statistic-get");
CommandMgr::instance().deregisterCommand("statistic-get-all");
CommandMgr::instance().deregisterCommand("statistic-remove");
CommandMgr::instance().deregisterCommand("statistic-remove-all");
CommandMgr::instance().deregisterCommand("statistic-reset");
CommandMgr::instance().deregisterCommand("statistic-reset-all");
CommandMgr::instance().deregisterCommand("version-get");
} catch (...) {
// Don't want to throw exceptions from the destructor. The server
// is shutting down anyway.
;
}
server_ = NULL; // forget this instance. There should be no callback anymore
// at this stage anyway.
}
void ControlledDhcpv6Srv::sessionReader(void) {
// Process one asio event. If there are more events, iface_mgr will call
// this callback more than once.
if (server_) {
server_->io_service_.run_one();
}
}
void
ControlledDhcpv6Srv::reclaimExpiredLeases(const size_t max_leases,
const uint16_t timeout,
const bool remove_lease,
const uint16_t max_unwarned_cycles) {
server_->alloc_engine_->reclaimExpiredLeases6(max_leases, timeout,
remove_lease,
max_unwarned_cycles);
// We're using the ONE_SHOT timer so there is a need to re-schedule it.
TimerMgr::instance()->setup(CfgExpiration::RECLAIM_EXPIRED_TIMER_NAME);
}
void
ControlledDhcpv6Srv::deleteExpiredReclaimedLeases(const uint32_t secs) {
server_->alloc_engine_->deleteExpiredReclaimedLeases6(secs);
// We're using the ONE_SHOT timer so there is a need to re-schedule it.
TimerMgr::instance()->setup(CfgExpiration::FLUSH_RECLAIMED_TIMER_NAME);
}
void
ControlledDhcpv6Srv::dbReconnect(ReconnectCtlPtr db_reconnect_ctl) {
bool reopened = false;
// Re-open lease and host database with new parameters.
try {
CfgDbAccessPtr cfg_db = CfgMgr::instance().getCurrentCfg()->getCfgDbAccess();
cfg_db->createManagers();
reopened = true;
} catch (const std::exception& ex) {
LOG_ERROR(dhcp6_logger, DHCP6_DB_RECONNECT_ATTEMPT_FAILED).arg(ex.what());
}
if (reopened) {
// Cancel the timer.
if (TimerMgr::instance()->isTimerRegistered("Dhcp6DbReconnectTimer")) {
TimerMgr::instance()->cancel("Dhcp6DbReconnectTimer"); }
// Set network state to service enabled
network_state_->enableService();
// Toss the reconnct control, we're done with it
db_reconnect_ctl.reset();
} else {
if (!db_reconnect_ctl->checkRetries()) {
LOG_ERROR(dhcp6_logger, DHCP6_DB_RECONNECT_RETRIES_EXHAUSTED)
.arg(db_reconnect_ctl->maxRetries());
shutdown();
return;
}
LOG_INFO(dhcp6_logger, DHCP6_DB_RECONNECT_ATTEMPT_SCHEDULE)
.arg(db_reconnect_ctl->maxRetries() - db_reconnect_ctl->retriesLeft() + 1)
.arg(db_reconnect_ctl->maxRetries())
.arg(db_reconnect_ctl->retryInterval());
if (!TimerMgr::instance()->isTimerRegistered("Dhcp6DbReconnectTimer")) {
TimerMgr::instance()->registerTimer("Dhcp6DbReconnectTimer",
boost::bind(&ControlledDhcpv6Srv::dbReconnect, this,
db_reconnect_ctl),
db_reconnect_ctl->retryInterval() * 1000,
asiolink::IntervalTimer::ONE_SHOT);
}
TimerMgr::instance()->setup("Dhcp6DbReconnectTimer");
}
}
bool
ControlledDhcpv6Srv::dbLostCallback(ReconnectCtlPtr db_reconnect_ctl) {
// Disable service until we recover
network_state_->disableService();
if (!db_reconnect_ctl) {
// This shouldn't never happen
LOG_ERROR(dhcp6_logger, DHCP6_DB_RECONNECT_NO_DB_CTL);
return (false);
}
// If reconnect isn't enabled, log it and return false
if (!db_reconnect_ctl->retriesLeft() ||
!db_reconnect_ctl->retryInterval()) {
LOG_INFO(dhcp6_logger, DHCP6_DB_RECONNECT_DISABLED)
.arg(db_reconnect_ctl->retriesLeft())
.arg(db_reconnect_ctl->retryInterval());
return(false);
}
// Invoke reconnect method
dbReconnect(db_reconnect_ctl);
return(true);
}
}; // end of isc::dhcp namespace
}; // end of isc namespace
|
; A134515: Third column (k=2) of triangle A134832 (circular succession numbers).
; Submitted by Christian Krause
; 1,0,0,10,15,168,1008,8244,73125,726440,7939008,94744494,1225760627,17088219120,255365758560,4072255216296,69021889788969,1239055874931312,23484788783212480,468656477004105810,9821896865573503095
add $0,1
mov $1,1
add $1,$0
mov $3,$0
lpb $3
mul $1,$3
mul $2,2
cmp $4,0
add $5,$4
div $1,$5
div $2,-2
add $2,$1
mul $1,$5
sub $3,1
div $4,$5
lpe
mov $0,$2
div $0,2
|
; A021422: Decimal expansion of 1/418.
; 0,0,2,3,9,2,3,4,4,4,9,7,6,0,7,6,5,5,5,0,2,3,9,2,3,4,4,4,9,7,6,0,7,6,5,5,5,0,2,3,9,2,3,4,4,4,9,7,6,0,7,6,5,5,5,0,2,3,9,2,3,4,4,4,9,7,6,0,7,6,5,5,5,0,2,3,9,2,3,4,4,4,9,7,6,0,7,6,5,5,5,0,2,3,9,2,3,4,4
add $0,1
mov $1,10
pow $1,$0
mul $1,6
div $1,2508
mod $1,10
mov $0,$1
|
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setDisabled(true);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid BilluCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
return;
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
|
db DEX_ABRA ; pokedex id
db 25 ; base hp
db 20 ; base attack
db 15 ; base defense
db 90 ; base speed
db 105 ; base special
db PSYCHIC ; species type 1
db PSYCHIC ; species type 2
db 200 ; catch rate
db 73 ; base exp yield
INCBIN "pic/bmon/abra.pic",0,1 ; 55, sprite dimensions
dw AbraPicFront
dw AbraPicBack
; attacks known at lvl 0
db TELEPORT
db 0
db 0
db 0
db 3 ; growth rate
; learnset
tmlearn 1,5,6,8
tmlearn 9,10
tmlearn 17,18,19,20
tmlearn 29,30,31,32
tmlearn 33,34,35,40
tmlearn 44,45,46
tmlearn 49,50,55
db 0 ; padding
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2015 The Peercoin developers
// Copyright (c) 2014-2015 The lendcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include "kernel.h"
#include "primekeys.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
set<pair<COutPoint, unsigned int> > setStakeSeen;
uint256 hashGenesisBlock = hashGenesisBlockOfficial;
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20);
static CBigNum bnInitialHashTarget(~uint256(0) >> 28);
static CBigNum bn227HashTarget(~uint256(0) >> 32);
//static CBigNum bn227HashTarget(~uint256(0) >> 20);
//static CBigNum bnProofOfStakeLimit(~uint256(0) >> 16);
static CBigNum bnProofOfStakeLimit(~uint256(0) >> 4);
unsigned int nStakeMinAge = STAKE_MIN_AGE;
int nCoinbaseMaturity = COINBASE_MATURITY_PPC;
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainTrust = 0;
CBigNum bnBestInvalidTrust = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
set<pair<COutPoint, unsigned int> > setStakeSeenOrphan;
map<uint256, uint256> mapProofOfStake;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "lendcoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = MIN_TX_FEE;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect)
{
if (!fConnect)
{
// lendcoin: wallets need to refund inputs when disconnecting coinstake
if (tx.IsCoinStake())
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
pwallet->DisableTransaction(tx);
}
return;
}
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// 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:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, const uint256& hash, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
if (!ReadFromDisk(txdb, prevout.hash, txindexRet))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey))
return false;
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
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 the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
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))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
for (int i = 0; i < vout.size(); i++)
{
const CTxOut& txout = vout[i];
if (txout.IsEmpty() && (!IsCoinBase()) && (!IsCoinStake()))
return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction"));
// lendcoin: enforce minimum output amount
if ((!IsCoinBase() && (!IsCoinStake()) && txout.nValue < MIN_TXOUT_AMOUNT))
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue below minimum"));
if ((!txout.IsEmpty()) && txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
int64 CTransaction::GetMinFee(unsigned int nBlockSize, bool fAllowFree,
enum GetMinFee_mode mode, unsigned int nBytes) const
{
// Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE
int64 nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE;
unsigned int nNewBlockSize = nBlockSize + nBytes;
int64 nMinFee = (1 + (int64)nBytes / 1000) * nBaseFee;
if (fAllowFree)
{
if (nBlockSize == 1)
{
// Transactions under 10K are free
// (about 4500 BTC if made of 50 BTC inputs)
if (nBytes < 10000)
nMinFee = 0;
}
else
{
// Free transaction area
if (nNewBlockSize < 27000)
nMinFee = 0;
}
}
// To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01
if (nMinFee < nBaseFee)
{
BOOST_FOREACH(const CTxOut& txout, vout)
if (txout.nValue < CENT)
nMinFee = nBaseFee;
}
// Raise the price as the block approaches full
if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2)
{
if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN)
return MAX_MONEY;
nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize);
}
if (!MoneyRange(nMinFee))
nMinFee = MAX_MONEY;
return nMinFee;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// lendcoin: coinstake is also only valid in a block, not as a loose transaction
if (tx.IsCoinStake())
return tx.DoS(100, error("CTxMemPool::accept() : coinstake as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return error("CTxMemPool::accept() : FetchInputs failed %s", hash.ToString().substr(0,10).c_str());
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, false, GMF_RELAY, nSize);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make other's transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// 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", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s\n", hash.ToString().substr(0,10).c_str());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(CTransaction &tx)
{
printf("addUnchecked(): size %lu\n", mapTx.size());
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
LOCK(cs);
uint256 hash = tx.GetHash();
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!(IsCoinBase() || IsCoinStake()))
return 0;
return max(0, (nCoinbaseMaturity+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, hash, txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
// look for transaction in disconnected blocks to find orphaned CoinBase and CoinStake transactions
BOOST_FOREACH(PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
if (pindex == pindexBest || pindex->pnext != 0)
continue;
CBlock block;
if (!block.ReadFromDisk(pindex))
continue;
BOOST_FOREACH(const CTransaction& txOrphan, block.vtx)
{
if (txOrphan.GetHash() == hash)
{
tx = txOrphan;
return true;
}
}
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
static CBlockIndex* pblockindexFBBHLast;
CBlockIndex* FindBlockByHeight(int nHeight)
{
CBlockIndex *pblockindex;
if (nHeight < nBestHeight / 2)
pblockindex = pindexGenesisBlock;
else
pblockindex = pindexBest;
if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight))
pblockindex = pblockindexFBBHLast;
while (pblockindex->nHeight > nHeight)
pblockindex = pblockindex->pprev;
while (pblockindex->nHeight < nHeight)
pblockindex = pblockindex->pnext;
pblockindexFBBHLast = pblockindex;
return pblockindex;
}
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
// lendcoin: find block wanted by given orphan block
uint256 WantedByOrphan(const CBlock* pblockOrphan)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock))
pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock];
return pblockOrphan->hashPrevBlock;
}
int64 GetProofOfWorkReward(int nHeight, unsigned int nTime)
{
int64 nSubsidy = 0;
if(nHeight == 1){
nSubsidy = 1000000 * COIN;
}else if(nHeight < 1002){
nSubsidy = 1000 * COIN;
}
if(nHeight > 1002 ){
nSubsidy = 0 * COIN;
}
return nSubsidy;
}
// lendcoin: miner's coin stake is rewarded based on coin age spent (coin-days)
int64 GetProofOfStakeReward(int64 nCoinAge, unsigned int nTime, int primeNodeRate)
{
int64 nSubsidy = 0;
int64 nRewardCoinYear = 0; // creation amount pe+_ coin-year
if (primeNodeRate == 1)
nRewardCoinYear = 1 * CENT;
else if (primeNodeRate == 5)
nRewardCoinYear = 3 * CENT;
else if (primeNodeRate == 15)
nRewardCoinYear = 11 * CENT;
else if (primeNodeRate == 25)
nRewardCoinYear = 17 * CENT;
else if (primeNodeRate == 25)
nRewardCoinYear = 17 * CENT;
else if (primeNodeRate == 350)
nRewardCoinYear = 17 * CENT;
else if (primeNodeRate == 100)
nRewardCoinYear = 17 * CENT;
nSubsidy = nCoinAge * nRewardCoinYear * 33 / (365 * 33 + 8);
if (primeNodeRate == 1){nSubsidy = nSubsidy / 16;}
if (fDebug && GetBoolArg("-printcreationjclnc"))
printf("GetProofOfStakeReward(): primeNodeRate=%d create=%s nCoinAge=%"PRI64d"\n", primeNodeRate, FormatMoney(nSubsidy).c_str(), nCoinAge);
return nSubsidy;
}
/*static const int64 nTargetTimespan = 7 * 24 * 60 * 60; // one week
static const int64 nTargetSpacingWorkMax = 12 * STAKE_TARGET_SPACING; // 2-hour*/
static const int64 nTargetTimespan = 2 * 60; // one week
static const int64 nTargetSpacingWorkMax = STAKE_TARGET_SPACING; // 2-hour
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime, bool fProofOfStake)
{
CBigNum bnResult, bnLimit;
bnLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit;
bnResult.SetCompact(nBase);
bnResult *= 2;
while (nTime > 0 && bnResult < bnLimit)
{
// Maximum 25600% adjustment per day...
bnResult *= 256;
nTime -= nTargetTimespan * 4;
}
if (bnResult > bnLimit)
bnResult = bnLimit;
return bnResult.GetCompact();
}
// lendcoin: find last block index up to pindex
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake)
{
while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake))
pindex = pindex->pprev;
return pindex;
}
unsigned int static GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake)
{
if (pindexLast == NULL)
return bnProofOfWorkLimit.GetCompact(); // genesis block
const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake);
if (pindexPrev->pprev == NULL)
return fProofOfStake ? bnProofOfStakeLimit.GetCompact() : bnInitialHashTarget.GetCompact(); // first block
const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake);
if (pindexPrevPrev->pprev == NULL)
return fProofOfStake ? bnProofOfStakeLimit.GetCompact() : bnInitialHashTarget.GetCompact(); // second block
if (!fProofOfStake && pindexLast->nHeight >= 23 && pindexLast->nHeight < 20000)
return bnProofOfWorkLimit.GetCompact(); // most of the 1st 120 blocks
// lendcoin: block stuck at 227
//if (!fProofOfStake && pindexLast->nHeight >= 277 && pindexLast->nHeight < 400)
// return bn227HashTarget.GetCompact();
int64 nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime();
// lendcoin: target change every block
// lendcoin: retarget with exponential moving toward target spacing
CBigNum bnNew;
bnNew.SetCompact(pindexPrev->nBits);
int64 nTargetSpacing = fProofOfStake? STAKE_TARGET_SPACING : min(nTargetSpacingWorkMax, (int64) STAKE_TARGET_SPACING * (1 + pindexLast->nHeight - pindexPrev->nHeight));
if (pindexLast->GetBlockTime() >= STAKE_START_TIME && nActualSpacing < 0)
nActualSpacing = nTargetSpacing;
int64 nInterval = nTargetTimespan / nTargetSpacing;
bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing);
bnNew /= ((nInterval + 1) * nTargetSpacing);
if (bnNew > bnProofOfWorkLimit)
bnNew = bnProofOfWorkLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainTrust > bnBestInvalidTrust)
{
bnBestInvalidTrust = pindexNew->bnChainTrust;
CTxDB().WriteBestInvalidTrust(bnBestInvalidTrust);
MainFrameRepaint();
}
printf("InvalidChainFound: invalid block=%s height=%d trust=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->bnChainTrust).ToString().c_str());
printf("InvalidChainFound: current best=%s height=%d trust=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(bnBestChainTrust).ToString().c_str());
// lendcoin: should not enter safe mode for longer invalid chain
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(GetBlockTime(), GetAdjustedTime());
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n's are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal bitcoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase/coinstake, check that it's matured
if (txPrev.IsCoinBase() || txPrev.IsCoinStake())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend coinbase/coinstake at depth %d", pindexBlock->nHeight - pindex->nHeight);
// lendcoin: check transaction timestamp
if (txPrev.nTime > nTime)
return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction"));
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// 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.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// 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 (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (IsCoinStake())
{
// lendcoin: coin stake tx earns reward instead of paying fee
uint64 nCoinAge;
if (!GetCoinAge(txdb, nCoinAge))
return error("ConnectInputs() : %s unable to get coin age for coinstake", GetHash().ToString().substr(0,10).c_str());
int64 nStakeReward = GetValueOut() - nValueIn;
// todo : using accumulator in later version; make it short please
if (!vout[0].IsEmpty()){
std::vector<string> pubKeyList;
int primeNodeRate = 0;
if (nTime >= END_PRIME_PHASE_ONE && vout[0].scriptPubKey[0] != OP_PRIMENODEP2)
return DoS(100, error("ConnectInputs() : prime node staking has ended for the given keypair"));
getPrimePubKeyList(vout[0].scriptPubKey[0], pubKeyList, primeNodeRate);
if (primeNodeRate) {
bool isVerify = false;
BOOST_FOREACH(std::string strPubKey, pubKeyList){
std::vector<unsigned char> vchPubKey = ParseHex(strPubKey);
CKey key;
key.SetPubKey(vchPubKey);
CScript scriptTime;
scriptTime << nTime;
uint256 hashScriptTime = Hash(scriptTime.begin(), scriptTime.end());
std::vector<unsigned char> vchSig;
vchSig.insert(vchSig.end(), vout[0].scriptPubKey.begin() + 2, vout[0].scriptPubKey.end());
if(key.Verify(hashScriptTime, vchSig)){
isVerify = true;
break;
}
}
if(!isVerify)
return DoS(10, error("CTransaction::ConnectInputs() : verify signature failed"));
if (GetValueOut() < MINIMUM_FOR_PRIMENODE)
return DoS(100, error("ConnectInputs() : credit doesn't meet requirement for primenode = %lld while you only have %lld", MINIMUM_FOR_PRIMENODE, GetValueOut()));
/* Use time instead of block number because we can better
* control when a manditory wallet update is required. */
if (nTime >= RESET_PRIMERATES && nTime < END_PRIME_PHASE_ONE) {
if (nStakeReward > GetProofOfStakeReward(nCoinAge, nTime, 100) - GetMinFee() + MIN_TX_FEE)
return DoS(100, error("ConnectInputs() : %s stake reward exceeded - Inside terms,Stake Reward , an returned from fnc ", GetHash().ToString().substr(0,10).c_str()));
} else {
if (nStakeReward > GetProofOfStakeReward(nCoinAge, nTime, 350) - GetMinFee() + MIN_TX_FEE)
return DoS(100, error("ConnectInputs() : %s stake reward exceeded goto else,Stake Reward , an returned from fnc ", GetHash().ToString().substr(0,10).c_str()));
}
}
}
else
{
if(GetValueOut() <= MINIMUM_FOR_ORION){
return DoS(100, error("ConnectInputs() : credit doesn't meet requirement for orion controller = %lld while you only have %lld", MINIMUM_FOR_ORION, GetValueOut()));
}
if(nStakeReward > GetProofOfStakeReward(nCoinAge, nTime, 350) - GetMinFee() + MIN_TX_FEE){
return DoS(100, error("ConnectInputs() : %s stake reward exceeded - OK Values are,Stake Reward , an returned from fnc ", GetHash().ToString().substr(0,10).c_str()));
}
}
}
else
{
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
// lendcoin: enforce transaction fees for every block
if (nTxFee < GetMinFee())
return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false;
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
// lendcoin: cleanup wallet after disconnecting coinstake
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, false, false);
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock())
return false;
// 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 id's entirely.
// This rule applies to all blocks whose timestamp is after March 15, 2012, 0:00 UTC.
// On testnet it is enabled as of februari 20, 2012, 0:00 UTC.
if (pindex->nTime > 1331769600 || (fTestNet && pindex->nTime > 1329696000))
{
BOOST_FOREACH(CTransaction& tx, vtx)
{
CTxIndex txindexOld;
if (txdb.ReadTxIndex(tx.GetHash(), txindexOld))
{
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
}
// BIP16 didn't become active until Apr 1 2012 (Feb 15 on testnet)
int64 nBIP16SwitchTime = fTestNet ? 1329264000 : 1333238400;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
//// issue here: it doesn't know the version
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
int64 nValueIn = 0;
int64 nValueOut = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (tx.IsCoinBase())
nValueOut += tx.GetValueOut();
else
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
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 += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
int64 nTxValueIn = tx.GetValueIn(mapInputs);
int64 nTxValueOut = tx.GetValueOut();
nValueIn += nTxValueIn;
nValueOut += nTxValueOut;
if (!tx.IsCoinStake())
nFees += nTxValueIn - nTxValueOut;
if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[tx.GetHash()] = CTxIndex(posThisTx, tx.vout.size());
}
// lendcoin: track money supply and mint amount info
pindex->nMint = nValueOut - nValueIn + nFees;
pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn;
if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex)))
return error("Connect() : WriteBlockIndex for pindex failed");
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
// lendcoin: fees are not collected by miners as in bitcoin
// lendcoin: fees are destroyed to compensate the entire network
if (fDebug && GetBoolArg("-printcreation"))
printf("ConnectBlock() : destroy=%s nFees=%"PRI64d"\n", FormatMoney(nFees).c_str(), nFees);
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex for blockindexPrev failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!(tx.IsCoinBase() || tx.IsCoinStake()))
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
txdb.TxnAbort();
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainTrust > pindexBest->bnChainTrust)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %i reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect futher blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
pblockindexFBBHLast = NULL;
nBestHeight = pindexBest->nHeight;
bnBestChainTrust = pindexNew->bnChainTrust;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d trust=%s moneysupply=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainTrust.ToString().c_str(), FormatMoney(pindexBest->nMoneySupply).c_str());
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
// lendcoin: total coin age spent in transaction, in the unit of coin-days.
// Only those coins meeting minimum age requirement counts. As those
// transactions not in main chain are not currently indexed so we
// might not find out about their coin age. Older transactions are
// guaranteed to be in main chain by sync-checkpoint. This rule is
// introduced to help nodes establish a consistent view of the coin
// age (trust score) of competing branches.
bool CTransaction::GetCoinAge(CTxDB& txdb, uint64& nCoinAge) const
{
CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds
nCoinAge = 0;
if (IsCoinBase())
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// First try finding the previous transaction in database
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
continue; // previous transaction not in main chain
if (nTime < txPrev.nTime)
return false; // Transaction timestamp violation
// Read block header
CBlock block;
if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
return false; // unable to read block of previous transaction
if (block.GetBlockTime() + nStakeMinAge > nTime)
continue; // only count coins meeting min age requirement
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT;
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age nValueIn=%-12I64d nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str());
}
CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60);
if (fDebug && GetBoolArg("-printcoinage"))
printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str());
nCoinAge = bnCoinDay.getuint64();
return true;
}
// lendcoin: total coin age spent in block, in the unit of coin-days.
bool CBlock::GetCoinAge(uint64& nCoinAge) const
{
nCoinAge = 0;
CTxDB txdb("r");
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uint64 nTxCoinAge;
if (tx.GetCoinAge(txdb, nTxCoinAge))
nCoinAge += nTxCoinAge;
else
return false;
}
if (nCoinAge == 0) // block coin age minimum 1 coin-day
nCoinAge = 1;
if (fDebug && GetBoolArg("-printcoinage"))
printf("block coin age total nCoinDays=%"PRI64d"\n", nCoinAge);
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
pindexNew->phashBlock = &hash;
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
// lendcoin: compute chain trust score
pindexNew->bnChainTrust = (pindexNew->pprev ? pindexNew->pprev->bnChainTrust : 0) + pindexNew->GetBlockTrust();
// lendcoin: compute stake entropy bit for stake modifier
if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit()))
return error("AddToBlockIndex() : SetStakeEntropyBit() failed");
// lendcoin: record proof-of-stake hash value
if (pindexNew->IsProofOfStake())
{
if (!mapProofOfStake.count(hash))
return error("AddToBlockIndex() : hashProofOfStake not found in map");
pindexNew->hashProofOfStake = mapProofOfStake[hash];
}
// lendcoin: compute stake modifier
uint64 nStakeModifier = 0;
bool fGeneratedStakeModifier = false;
if (!ComputeNextStakeModifier(pindexNew, nStakeModifier, fGeneratedStakeModifier))
return error("AddToBlockIndex() : ComputeNextStakeModifier() failed");
pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier);
pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew);
if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum))
return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRI64x, pindexNew->nHeight, nStakeModifier);
// Add to mapBlockIndex
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
pindexNew->phashBlock = &((*mi).first);
// Write to disk block index
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainTrust > bnBestChainTrust)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
MainFrameRepaint();
return true;
}
bool CBlock::CheckBlock(int64 nHeight) const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (IsProofOfWork() && !CheckProofOfWork(GetHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + nMaxClockDrift)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// lendcoin: only the second transaction can be the optional coinstake
for (int i = 2; i < vtx.size(); i++)
if (vtx[i].IsCoinStake())
return DoS(100, error("CheckBlock() : coinstake in wrong position"));
// lendcoin: coinbase output should be empty if proof-of-stake block
if (IsProofOfStake() && (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()))
return error("CheckBlock() : coinbase output not empty for proof-of-stake block");
// Check coinbase timestamp
if (GetBlockTime() > (int64)vtx[0].nTime + nMaxClockDrift)
return DoS(50, error("CheckBlock() : coinbase timestamp is too early"));
// Check coinstake timestamp
if (IsProofOfStake() && !CheckCoinStakeTimestamp(GetBlockTime(), (int64)vtx[1].nTime))
return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%u nTimeTx=%u", GetBlockTime(), vtx[1].nTime));
int64 nHeightTmp = 0;
if(nHeight == -1){
if(pindexBest != NULL){
nHeightTmp = GetLastBlockIndex(pindexBest, false)->nHeight + 1;
}
}else{
nHeightTmp = nHeight;
}
// Check coinbase reward
if (vtx[0].GetValueOut() > (IsProofOfWork()? (GetProofOfWorkReward(nHeightTmp, nTime) - vtx[0].GetMinFee() + MIN_TX_FEE) : 0))
return DoS(50, error("CheckBlock() : coinbase reward exceeded %s > %s",
FormatMoney(vtx[0].GetValueOut()).c_str(),
FormatMoney(IsProofOfWork()? GetProofOfWorkReward(nHeightTmp, nTime) : 0).c_str()));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
{
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// lendcoin: check transaction timestamp
if (GetBlockTime() < (int64)tx.nTime)
return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp"));
}
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkleroot
if (hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
// lendcoin: check block signature
if (!CheckBlockSignature())
return DoS(100, error("CheckBlock() : bad block signature"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
unsigned int nTimePoW = pindexPrev->nTime+1;
// Check proof-of-work or proof-of-stake
if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake()))
return DoS(100, error("AcceptBlock() : incorrect proof-of-work/proof-of-stake"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast() || GetBlockTime() + nMaxClockDrift < pindexPrev->GetBlockTime())
return error("AcceptBlock() : block's timestamp is too early");
//if (IsProofOfWork() && nTimePoW > POW_END_TIME)
//if (IsProofOfWork() && nTimePoW > POW_END_TIME)
// return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight));
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a hardened checkpoint
if (!Checkpoints::CheckHardened(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lockin at %d", nHeight));
// lendcoin: check that the block satisfies synchronized checkpoint
if (!Checkpoints::CheckSync(hash, pindexPrev))
return error("AcceptBlock() : rejected by synchronized checkpoint");
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
// lendcoin: check pending sync-checkpoint
Checkpoints::AcceptPendingSyncCheckpoint();
return true;
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// lendcoin: 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) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
// lendcoin: verify hash target and signature of coinstake tx
if (pblock->IsProofOfStake())
{
uint256 hashProofOfStake = 0;
if (!CheckProofOfStake(pblock->vtx[1], pblock->nBits, hashProofOfStake))
{
printf("WARNING: ProcessBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str());
return false; // do not error here as we expect this during initial block download
}
if (!mapProofOfStake.count(hash)) // add to mapProofOfStake
mapProofOfStake.insert(make_pair(hash, hashProofOfStake));
}
CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint();
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, pblock->IsProofOfStake())->nBits, deltaTime, pblock->IsProofOfStake()));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work");
}
}
// lendcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
// lendcoin: check proof-of-stake
if (pblock2->IsProofOfStake())
{
// Limited duplicity on stake: prevents block flood attack
// Duplicate stake allowed only when there is orphan child block
if (setStakeSeenOrphan.count(pblock2->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash))
{
error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock2->GetProofOfStake().first.ToString().c_str(), pblock2->GetProofOfStake().second, hash.ToString().c_str());
//pblock2 will not be needed, free it
delete pblock2;
return false;
}
else
setStakeSeenOrphan.insert(pblock2->GetProofOfStake());
}
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
{
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
// lendcoin: getblocks may not obtain the ancestor block rejected
// earlier by duplicate-stake check so we ask for it again directly
if (!IsInitialBlockDownload())
pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2)));
}
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
// lendcoin: if responsible for sync-checkpoint send it
if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty())
Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint());
return true;
}
// lendcoin: sign block
bool CBlock::SignBlock(const CKeyStore& keystore)
{
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
// Sign
const valtype& vchPubKey = vSolutions[0];
CKey key;
if (!keystore.GetKey(Hash160(vchPubKey), key))
return false;
if (key.GetPubKey() != vchPubKey)
return false;
return key.Sign(GetHash(), vchBlockSig);
}
return false;
}
// lendcoin: check block signature
bool CBlock::CheckBlockSignature() const
{
if (GetHash() == hashGenesisBlock)
return vchBlockSig.empty();
vector<valtype> vSolutions;
txnouttype whichType;
const CTxOut& txout = IsProofOfStake()? vtx[1].vout[1] : vtx[0].vout[0];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY)
{
const valtype& vchPubKey = vSolutions[0];
CKey key;
if (!key.SetPubKey(vchPubKey))
return false;
if (vchBlockSig.empty())
return false;
return key.Verify(GetHash(), vchBlockSig);
}
return false;
}
// lendcoin: entropy bit for stake modifier if chosen by modifier
unsigned int CBlock::GetStakeEntropyBit() const
{
unsigned int nEntropyBit = 0;
if (IsProtocolV04(nTime))
{
nEntropyBit = ((GetHash().Get64()) & 1llu);// last bit of block hash
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit(v0.4+): nTime=%u hashBlock=%s entropybit=%d\n", nTime, GetHash().ToString().c_str(), nEntropyBit);
}
else
{
// old protocol for entropy bit pre v0.4
uint160 hashSig = Hash160(vchBlockSig);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit(v0.3): nTime=%u hashSig=%s", nTime, hashSig.ToString().c_str());
hashSig >>= 159; // take the first bit of the hash
nEntropyBit = hashSig.Get64();
if (fDebug && GetBoolArg("-printstakemodifier"))
printf(" entropybit=%d\n", nEntropyBit);
}
return nEntropyBit;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for 15MB because database could create another 10MB log file at any time
if (nFreeBytesAvailable < (uint64)15000000 + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
ThreadSafeMessageBox(strMessage, "LendCoin", wxOK | wxICON_EXCLAMATION | wxMODAL);
StartShutdown();
return false;
}
return true;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if (nFile == -1)
return NULL;
FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
for (;;)
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
hashGenesisBlock = hashGenesisBlockTestNet;
bnProofOfWorkLimit = CBigNum(~uint256(0) >> 28);
nStakeMinAge = 60 * 60 * 24; // test net min age is 1 day
nCoinbaseMaturity = 60;
bnInitialHashTarget = CBigNum(~uint256(0) >> 29);
nModifierInterval = 60 * 20; // test net modifier interval is 20 minutes
}
printf("%s Network: genesis=0x%s nBitsLimit=0x%08x nBitsInitial=0x%08x nStakeMinAge=%d nCoinbaseMaturity=%d nModifierInterval=%d\n",
fTestNet? "Test" : "LendCoin", hashGenesisBlock.ToString().substr(0, 20).c_str(), bnProofOfWorkLimit.GetCompact(), bnInitialHashTarget.GetCompact(), nStakeMinAge, nCoinbaseMaturity, nModifierInterval);
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis block
const char* pszTimestamp = "Time 11/29/2014 France Considers Backing Palestinian Statehood";
CTransaction txNew;
txNew.nTime = 1417219200;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(9999) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].SetEmpty();
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1417219210;
block.nBits = bnProofOfWorkLimit.GetCompact();
block.nNonce = 716560;
if (fTestNet)
{
block.nTime = 1417219210;
block.nNonce = 18631020;
}
//// debug print
printf("%s\n", block.GetHash().ToString().c_str());
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", block.hashMerkleRoot.ToString().c_str());
assert(block.hashMerkleRoot == uint256("0x1552f748afb7ff4e04776652c5a17d4073e60b7004e9bca639a99edb82aeb1a0"));
block.print();
assert(block.GetHash() == hashGenesisBlock);
assert(block.CheckBlock());
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
// lendcoin: initialize synchronized checkpoint
if (!Checkpoints::WriteSyncCheckpoint(hashGenesisBlock))
return error("LoadBlockIndex() : failed to init sync checkpoint");
// lendcoin: upgrade time set to zero if txdb initialized
{
CTxDB txdb;
if (!txdb.WriteV04UpgradeTime(0))
return error("LoadBlockIndex() : failed to init upgrade info");
printf(" Upgrade Info: v0.4+ txdb initialization\n");
txdb.Close();
}
}
// lendcoin: if checkpoint master key changed must reset sync-checkpoint
{
CTxDB txdb;
string strPubKey = "";
if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey)
{
// write checkpoint master key to db
txdb.TxnBegin();
if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey))
return error("LoadBlockIndex() : failed to write new checkpoint master key to db");
if (!txdb.TxnCommit())
return error("LoadBlockIndex() : failed to commit new checkpoint master key to db");
if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint())
return error("LoadBlockIndex() : failed to reset sync-checkpoint");
}
txdb.Close();
}
// lendcoin: upgrade time set to zero if txdb initialized
{
CTxDB txdb;
if (txdb.ReadV04UpgradeTime(nProtocolV04UpgradeTime))
{
if (nProtocolV04UpgradeTime)
printf(" Upgrade Info: txdb upgrade to v0.4 detected at timestamp %d\n", nProtocolV04UpgradeTime);
else
printf(" Upgrade Info: v0.4+ no txdb upgrade detected.\n");
}
else
{
nProtocolV04UpgradeTime = GetTime();
printf(" Upgrade Info: upgrading txdb from v0.3 at timestamp %u\n", nProtocolV04UpgradeTime);
if (!txdb.WriteV04UpgradeTime(nProtocolV04UpgradeTime))
return error("LoadBlockIndex() : failed to write upgrade info");
}
txdb.Close();
}
return true;
}
void PrintBlockTree()
{
// precompute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %08lx %s mint %7s tx %d",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().c_str(),
block.nBits,
DateTimeStrFormat(block.GetBlockTime()).c_str(),
FormatMoney(pindex->nMint).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main timechain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
static string strMintMessage = _("Info: Minting suspended due to locked wallet.");
static string strMintWarning;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// lendcoin: wallet lock warning for minting
if (strMintWarning != "")
{
nPriority = 0;
strStatusBar = strMintWarning;
}
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// lendcoin: if detected invalid checkpoint enter safe mode
if (Checkpoints::hashInvalidCheckpoint != 0)
{
nPriority = 3000;
strStatusBar = strRPC = "WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers of the issue.";
}
// lendcoin: if detected unmet upgrade requirement enter safe mode
// Note: v0.4 upgrade requires blockchain redownload if past protocol switch
if (IsProtocolV04(nProtocolV04UpgradeTime + 60*60*24)) // 1 day margin
{
nPriority = 5000;
strStatusBar = strRPC = "WARNING: Blockchain redownload required approaching or past v0.4 upgrade deadline.";
}
// 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 (nPriority > 1000)
strRPC = strStatusBar; // lendcoin: safe mode for high alert
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
bool CAlert::ProcessAlert()
{
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
MainFrameRepaint();
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug) {
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
}
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// lendcoin: record my external IP reported by peer
if (addrFrom.IsRoutable() && addrMe.IsRoutable())
addrSeenByPeer = addrMe;
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !fUseProxy && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
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);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
// lendcoin: relay sync-checkpoint
{
LOCK(Checkpoints::cs_hashSyncCheckpoint);
if (!Checkpoints::checkpointMessage.IsNull())
Checkpoints::checkpointMessage.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("version message: version %d, blocks=%d\n", pfrom->nVersion, pfrom->nStartingHeight);
cPeerBlockCounts.input(pfrom->nStartingHeight);
// Be more aggressive with blockchain download. Send new getblocks() message after connection
// to new node if waited longer than MAX_TIME_SINCE_BEST_BLOCK.
int64_t TimeSinceBestBlock = GetTime() - nTimeBestReceived;
if (TimeSinceBestBlock > MAX_TIME_SINCE_BEST_BLOCK) {
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// lendcoin: ask for pending sync-checkpoint if any
if (!IsInitialBlockDownload())
Checkpoints::AskForPendingSyncCheckpoint(pfrom);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
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)
{
pfrom->Misbehaving(20);
return error("message addr size() = %d", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
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();
int64 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() > 50000)
{
pfrom->Misbehaving(20);
return error("message inv size() = %d", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
std::vector<CInv> vGetData(1,inv);
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %d", vInv.size());
}
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// 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.
// lendcoin: send latest proof-of-work block to allow the
// download node to accept as orphan (proof-of-stake
// block might be rejected by stake connection check)
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash()));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 1500 + locator.GetDistanceBack();
unsigned int nBytes = 0;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
// lendcoin: tell downloading node about the latest block if it's
// without risk being rejected due to stake connection check
if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime())
pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain));
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
CBlock block;
block.ReadFromDisk(pindex, true);
nBytes += block.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION);
if (--nLimit <= 0 || nBytes >= SendBufferSize()/2)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s (%u bytes)\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str(), nBytes);
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::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 = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block)) {
mapAlreadyAskedFor.erase(inv);
} else {
// Be more aggressive with blockchain download. Send getblocks() message after
// an error related to new block download.
int64_t TimeSinceBestBlock = GetTime() - nTimeBestReceived;
if (TimeSinceBestBlock > MAX_TIME_SINCE_BEST_BLOCK) {
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
}
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 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 == "alert")
{
CAlert alert;
vRecv >> alert;
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alert.GetHash());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
}
else if (strCommand == "checkpoint")
{
CSyncCheckpoint checkpoint;
vRecv >> checkpoint;
if (checkpoint.ProcessSyncCheckpoint(pfrom))
{
// Relay
pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint;
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this nodes address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
unsigned char pchMessageStart[4];
GetMessageStart(pchMessageStart);
static int64 nTimeLastPrintMessageStart = 0;
if (fDebug && GetBoolArg("-printmessagestart") && nTimeLastPrintMessageStart + 30 < GetAdjustedTime())
{
string strMessageStart((const char *)pchMessageStart, sizeof(pchMessageStart));
vector<unsigned char> vchMessageStart(strMessageStart.begin(), strMessageStart.end());
printf("ProcessMessages : AdjustedTime=%"PRI64d" MessageStart=%s\n", GetAdjustedTime(), HexStr(vchMessageStart).c_str());
nTimeLastPrintMessageStart = GetAdjustedTime();
}
for (;;)
{
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
//printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
// strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
//printf("ProcessMessages strCommand %s",strCommand.c_str());
if (strCommand.find("ls") != string::npos)
{
strCommand = strCommand.replace(strCommand.end() - 2 ,strCommand.end() ,"") ;
//printf("ProcessMessages strCommand %s",strCommand.c_str());
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from under-length message on vRecv
// printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from overlong size
// printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet){
// printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 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
if (!fNoListen && !fUseProxy)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
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);
}
//
// 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);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
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);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
}
mapAlreadyAskedFor[inv] = nNow;
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data. Caller does the byte reversing.
// All input buffers are 16-byte aligned. nNonce is usually preserved
// between calls, but periodically or if nNonce is 0xffff0000 or above,
// the block is rebuilt and nNonce starts over at zero.
//
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
{
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
for (;;)
{
// Crypto++ SHA256
// Hash pdata using pmidstate as the starting state into
// preformatted buffer phash1, then hash phash1 into phash
nNonce++;
SHA256Transform(phash1, pdata, pmidstate);
SHA256Transform(phash, phash1, pSHA256InitState);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((unsigned short*)phash)[14] == 0)
return nNonce;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
nHashesDone = 0xffff+1;
return (unsigned int) -1;
}
}
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
int64 nLastCoinStakeSearchInterval = 0;
// CreateNewBlock:
// fProofOfStake: try (best effort) to make a proof-of-stake block
CBlock* CreateNewBlock(CReserveKey& reservekey, CWallet* pwallet, bool fProofOfStake)
{
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// lendcoin: if coinstake available add coinstake tx
static int64 nLastCoinStakeSearchTime = GetAdjustedTime(); // only initialized at startup
CBlockIndex* pindexPrev = pindexBest;
if (fProofOfStake) // attemp to find a coinstake
{
pblock->nBits = GetNextTargetRequired(pindexPrev, true);
CTransaction txCoinStake;
int64 nSearchTime = txCoinStake.nTime; // search to current time
if (nSearchTime > nLastCoinStakeSearchTime)
{
if (pwallet->CreateCoinStake(*pwallet, pblock->nBits, nSearchTime-nLastCoinStakeSearchTime, txCoinStake, pindexPrev->nMoneySupply))
{
if (txCoinStake.nTime >= max(pindexPrev->GetMedianTimePast()+1, pindexPrev->GetBlockTime() - nMaxClockDrift))
{ // make sure coinstake would meet timestamp protocol
// as it would be the same as the block timestamp
pblock->vtx[0].vout[0].SetEmpty();
pblock->vtx[0].nTime = txCoinStake.nTime;
pblock->vtx.push_back(txCoinStake);
}
}
nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime;
nLastCoinStakeSearchTime = nSearchTime;
}
}
pblock->nBits = GetNextTargetRequired(pindexPrev, pblock->IsProofOfStake());
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
multimap<double, CTransaction*> mapPriority;
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || tx.IsCoinStake() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
// Read block header
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
if (fDebug && GetBoolArg("-printpriority"))
printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
}
// Priority is sum(valuein * age) / txsize
dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (porphan)
porphan->dPriority = dPriority;
else
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
if (porphan)
porphan->print();
printf("\n");
}
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
while (!mapPriority.empty())
{
// Take highest priority transaction off priority queue
CTransaction& tx = *(*mapPriority.begin()).second;
mapPriority.erase(mapPriority.begin());
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Timestamp limit
if (tx.nTime > GetAdjustedTime() || (pblock->IsProofOfStake() && tx.nTime > pblock->vtx[1].nTime))
continue;
// lendcoin: simplify transaction fee - allow free = false
int64 nMinFee = tx.GetMinFee(nBlockSize, false, GMF_BLOCK);
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(txdb, mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
if (fDebug && GetBoolArg("-printpriority"))
printf("CreateNewBlock(): total size %lu\n", nBlockSize);
}
int nHeight = 0;
if(pindexBest != NULL){
nHeight = GetLastBlockIndex(pindexBest, false)->nHeight + 1;
}
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
if (pblock->IsProofOfStake())
pblock->nTime = pblock->vtx[1].nTime; //same as coinstake timestamp
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
if (pblock->IsProofOfWork())
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
if (pblock->IsProofOfWork())
pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nHeight, pblock->nTime );
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Prebuild hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget && pblock->IsProofOfWork())
return error("PeerMiner : proof-of-work not meeting target");
//// debug print
printf("PeerMiner:\n");
printf("new block found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("PeerMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void SetMintWarning(const string& strNewWarning)
{
if (strMintWarning != strNewWarning)
{
strMintWarning = strNewWarning;
MainFrameRepaint();
}
}
void BitcoinMiner(CWallet *pwallet, bool fProofOfStake)
{
printf("CPUMiner started for proof-of-%s\n", fProofOfStake? "stake" : "work");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
int64_t nextAllowedBlock = 0;
while (fGenerateBitcoins || fProofOfStake)
{
if (fShutdown)
return;
if (fProofOfStake && (GetTime() < nextAllowedBlock || GetAdjustedTime() < STAKE_START_TIME)) {
nLastCoinStakeSearchInterval = 0;
Sleep(1000);
continue;
}
while (vNodes.empty() || IsInitialBlockDownload())
{
nLastCoinStakeSearchInterval = 0;
Sleep(1000);
if (fShutdown)
return;
if ((!fGenerateBitcoins) && !fProofOfStake)
return;
}
while (pwallet->IsLocked())
{
nLastCoinStakeSearchInterval = 0;
strMintWarning = strMintMessage;
Sleep(1000);
}
strMintWarning = "";
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey, pwallet, fProofOfStake));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
if (fProofOfStake)
{
// lendcoin: if proof-of-stake block found then process block
if (pblock->IsProofOfStake())
{
if (!pblock->SignBlock(*pwalletMain))
{
SetMintWarning(strMintMessage);
continue;
}
SetMintWarning("");
printf("CPUMiner : proof-of-stake block found %s\n", pblock->GetHash().ToString().c_str());
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
nextAllowedBlock = GetTime() + 30 + GetRandInt(90);
}
Sleep(500);
continue;
}
printf("Running PeerMiner with %d transactions in block\n", pblock->vtx.size());
//
// Prebuild hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
uint256 hashbuf[2];
uint256& hash = *alignup<16>(hashbuf);
for (;;)
{
unsigned int nHashesDone = 0;
unsigned int nNonceFound;
// Crypto++ SHA256
nNonceFound = ScanHash_CryptoPP(pmidstate, pdata + 64, phash1,
(char*)&hash, nHashesDone);
// Check if something found
if (nNonceFound != (unsigned int) -1)
{
for (unsigned int i = 0; i < sizeof(hash)/4; i++)
((unsigned int*)&hash)[i] = ByteReverse(((unsigned int*)&hash)[i]);
if (hash <= hashTarget)
{
// Found a solution
pblock->nNonce = ByteReverse(nNonceFound);
assert(hash == pblock->GetHash());
if (!pblock->SignBlock(*pwalletMain))
{
SetMintWarning(strMintMessage);
break;
}
SetMintWarning("");
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("%s ", DateTimeStrFormat(GetTime()).c_str());
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (nBlockNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->nTime = max(pindexPrev->GetMedianTimePast()+1, pblock->GetMaxTransactionTime());
pblock->nTime = max(pblock->GetBlockTime(), pindexPrev->GetBlockTime() - nMaxClockDrift);
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (pblock->GetBlockTime() >= (int64)pblock->vtx[0].nTime + nMaxClockDrift)
break; // need to update coinbase timestamp
}
}
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet, false);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!CreateThread(ThreadBitcoinMiner, pwallet))
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
|
; A268633: Number of n X 2 0..2 arrays with some element plus some horizontally or vertically adjacent neighbor totalling two exactly once.
; 3,24,120,504,1944,7128,25272,87480,297432,997272,3306744,10865016,35429400,114791256,369882936,1186176312,3788111448,12053081880,38225488248,120875192568,381221761176,1199453833944,3765727153080,11799278412984,36904126100184,115231250884248,359250370403832,1118420964464760,3477272453154072,10797846038741592,33491624154062904,103769130575703096,321190166067652440,993218821224586776,3068601432738648696,9472639205410611192,29218422337815828888,90056781178199472600,277374886028854375608,853738285569331000248,2626055739156296621016,8072689864813800723864,24801637536476134754040,76155616435532602009464,233718960784910399270424,716913216789668977537368,2198008653673820271790392,6735832970935900832906040,20632919942551022551322712,63175022916883027811781912,193353858018338963908787064,591547941858086533146685176,1809102928983468523701027480,5530686097178032343885998296,16902190222216977350006742456,51636966458699573005066470072,157702086752244641880338138328,481479822385171694236430599320,1469560153540828388495540350968,4484042519778425082845366711928,13678213736803095000612337112856,41712899742812744258065722269784,127173474825648610542883299603000,387624751268576964934708297189944,1181187234180624294722300086712664,3598500643666553083921425845566488,10960318754373699851027854292984952,33375406733243221350874293147811320,101609571610096029445995070250003352,309278769061387184518101783169718232,941186469877458842094655066768279224
mul $0,2
mov $2,$0
add $2,1
mov $1,$2
mul $1,2
lpb $0
sub $0,2
add $2,$1
mul $2,2
add $1,$2
mov $2,0
lpe
add $1,$2
mov $0,$1
|
#include <string>
#include "ECS_AssetManager.h"
ECS_AssetManager::ECS_AssetManager(ECS_EntityManager* entityManager)
{
}
void ECS_AssetManager::AddTexture(std::string TextureID, std::string filePath)
{
textureID_map.emplace(TextureID, ECS_TextureManager::LoadTexture(filePath));
}
void ECS_AssetManager::AddFont(std::string FontID, std::string filePath, int fontSize)
{
fontID_map.emplace(FontID,ECS_FontManager::LoadFont(filePath,fontSize));
}
SDL_Texture* ECS_AssetManager::GetTexture(std::string TextureID)
{
return textureID_map[TextureID];
}
TTF_Font * ECS_AssetManager::GetFont(std::string FontID)
{
return fontID_map[FontID];
}
void ECS_AssetManager::ClearData()
{
textureID_map.clear();
fontID_map.clear();
}
|
; A134917: a(n) = ceiling(n^(4/3)).
; 1,3,5,7,9,11,14,16,19,22,25,28,31,34,37,41,44,48,51,55,58,62,66,70,74,78,81,86,90,94,98,102,106,111,115,119,124,128,133,137,142,146,151,156,161,165,170,175,180,185,190,195,200,205,210,215,220,225,230,235,241,246,251,256,262,267,273,278,284,289,294,300,306,311,317,322,328,334,339,345,351,357,363,368,374,380,386,392,398,404,410,416,422,428,434,440,446,452,458,465
add $0,1
pow $0,4
sub $0,1
seq $0,48766 ; Integer part of cube root of n. Or, number of cubes <= n. Or, n appears 3n^2 + 3n + 1 times.
add $0,1
|
#pragma once
#include <string>
#include <map>
#include <xlnt/workstream/workstream_visitor.hpp>
#include <xlnt/packaging/relationship.hpp>
namespace xlnt {
namespace detail {
class workbook_rel_visitor : public workstream_visitor {
struct relationship {
std::string file_name;
std::string r_id;
relationship_type r_type;
relationship():r_type(relationship_type::unknown){}
};
// fle name to relation ship
typedef std::map<std::string, relationship> FILE_RELS;
FILE_RELS rels_;
relationship rel_;
public:
virtual ~workbook_rel_visitor(){}
virtual visit_actions start_element(const std::string & element, std::string & newval);
virtual void end_element();
virtual visit_actions start_attribute(const std::string & attr, std::string & newval);
virtual visit_actions character(const std::string & value, std::string & newval);
virtual visit_actions start_ns(const std::string & ns, const std::string & prefix);
bool get_file_relationship(const std::string filename,
std::string & r_id, relationship_type & type) const;
};
}
}
|
; A045749: Extension of Beatty sequence; complement of A045750.
; 0,1,2,3,5,6,7,9,10,11,13,14,15,16,17,18,20,21,22,24,25,26,28,29,30,31,32,33,35,36,37,39,40,41,43,44,45,46,47,48,50,51,52,54,55,56,58,59,60,62,63,64,66,67,68
mov $4,$0
mov $5,1
lpb $5
mov $3,$0
sub $5,1
mov $6,2
lpb $6
mov $0,$3
sub $0,1
div $0,3
mov $1,$0
mov $2,$0
sub $2,15
div $2,4
sub $1,$2
sub $6,1
lpe
lpe
sub $1,3
add $1,$4
|
#include <iostream>
#include <stack>
using namespace std;
int main()
{
long long int test,i,a,x,y,sum,n,d,term;
cin>>test;
while(test--)
{
cin>>x>>y>>sum;
n=(2*sum)/(x+y);
d=(y-x)/(n-5);
a=x-(2*d);
term=a;
cout<<n<<endl;
for(i=0;i<n;i++)
{
cout<<term<<" ";
term+=d;
}
cout<<endl;
}
}
|
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC sms_01_output_terminal_tty_z88dk_27_escape
EXTERN error_zc
sms_01_output_terminal_tty_z88dk_27_escape:
; output escaped char uninterpretted
; de = parameters *
ld a,(de)
ld c,a ; c = escaped char
; pop one return address from stack
; so that carry is not cleared
jp error_zc - 1 ; carry set to deliver char to terminal
|
/* Copyright (c) 2015-2019 The Khronos Group Inc.
* Copyright (c) 2015-2019 Valve Corporation
* Copyright (c) 2015-2019 LunarG, Inc.
* Copyright (C) 2015-2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Author: Chris Forbes <chrisf@ijw.co.nz>
* Author: Dave Houlton <daveh@lunarg.com>
*/
#include <cinttypes>
#include <cassert>
#include <chrono>
#include <vector>
#include <unordered_map>
#include <string>
#include <sstream>
#include <SPIRV/spirv.hpp>
#include "vk_loader_platform.h"
#include "vk_enum_string_helper.h"
#include "vk_layer_data.h"
#include "vk_layer_extension_utils.h"
#include "vk_layer_utils.h"
#include "chassis.h"
#include "core_validation.h"
#include "shader_validation.h"
#include "spirv-tools/libspirv.h"
#include "xxhash.h"
void decoration_set::add(uint32_t decoration, uint32_t value) {
switch (decoration) {
case spv::DecorationLocation:
flags |= location_bit;
location = value;
break;
case spv::DecorationPatch:
flags |= patch_bit;
break;
case spv::DecorationRelaxedPrecision:
flags |= relaxed_precision_bit;
break;
case spv::DecorationBlock:
flags |= block_bit;
break;
case spv::DecorationBufferBlock:
flags |= buffer_block_bit;
break;
case spv::DecorationComponent:
flags |= component_bit;
component = value;
break;
case spv::DecorationInputAttachmentIndex:
flags |= input_attachment_index_bit;
input_attachment_index = value;
break;
case spv::DecorationDescriptorSet:
flags |= descriptor_set_bit;
descriptor_set = value;
break;
case spv::DecorationBinding:
flags |= binding_bit;
binding = value;
break;
case spv::DecorationNonWritable:
flags |= nonwritable_bit;
break;
case spv::DecorationBuiltIn:
flags |= builtin_bit;
builtin = value;
break;
}
}
enum FORMAT_TYPE {
FORMAT_TYPE_FLOAT = 1, // UNORM, SNORM, FLOAT, USCALED, SSCALED, SRGB -- anything we consider float in the shader
FORMAT_TYPE_SINT = 2,
FORMAT_TYPE_UINT = 4,
};
typedef std::pair<unsigned, unsigned> location_t;
struct shader_stage_attributes {
char const *const name;
bool arrayed_input;
bool arrayed_output;
VkShaderStageFlags stage;
};
static shader_stage_attributes shader_stage_attribs[] = {
{"vertex shader", false, false, VK_SHADER_STAGE_VERTEX_BIT},
{"tessellation control shader", true, true, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT},
{"tessellation evaluation shader", true, false, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT},
{"geometry shader", true, false, VK_SHADER_STAGE_GEOMETRY_BIT},
{"fragment shader", false, false, VK_SHADER_STAGE_FRAGMENT_BIT},
};
unsigned ExecutionModelToShaderStageFlagBits(unsigned mode);
// SPIRV utility functions
void SHADER_MODULE_STATE::BuildDefIndex() {
for (auto insn : *this) {
switch (insn.opcode()) {
// Types
case spv::OpTypeVoid:
case spv::OpTypeBool:
case spv::OpTypeInt:
case spv::OpTypeFloat:
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeImage:
case spv::OpTypeSampler:
case spv::OpTypeSampledImage:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeStruct:
case spv::OpTypeOpaque:
case spv::OpTypePointer:
case spv::OpTypeFunction:
case spv::OpTypeEvent:
case spv::OpTypeDeviceEvent:
case spv::OpTypeReserveId:
case spv::OpTypeQueue:
case spv::OpTypePipe:
case spv::OpTypeAccelerationStructureNV:
case spv::OpTypeCooperativeMatrixNV:
def_index[insn.word(1)] = insn.offset();
break;
// Fixed constants
case spv::OpConstantTrue:
case spv::OpConstantFalse:
case spv::OpConstant:
case spv::OpConstantComposite:
case spv::OpConstantSampler:
case spv::OpConstantNull:
def_index[insn.word(2)] = insn.offset();
break;
// Specialization constants
case spv::OpSpecConstantTrue:
case spv::OpSpecConstantFalse:
case spv::OpSpecConstant:
case spv::OpSpecConstantComposite:
case spv::OpSpecConstantOp:
def_index[insn.word(2)] = insn.offset();
break;
// Variables
case spv::OpVariable:
def_index[insn.word(2)] = insn.offset();
break;
// Functions
case spv::OpFunction:
def_index[insn.word(2)] = insn.offset();
break;
// Decorations
case spv::OpDecorate: {
auto targetId = insn.word(1);
decorations[targetId].add(insn.word(2), insn.len() > 3u ? insn.word(3) : 0u);
} break;
case spv::OpGroupDecorate: {
auto const &src = decorations[insn.word(1)];
for (auto i = 2u; i < insn.len(); i++) decorations[insn.word(i)].merge(src);
} break;
// Entry points ... add to the entrypoint table
case spv::OpEntryPoint: {
// Entry points do not have an id (the id is the function id) and thus need their own table
auto entrypoint_name = (char const *)&insn.word(3);
auto execution_model = insn.word(1);
auto entrypoint_stage = ExecutionModelToShaderStageFlagBits(execution_model);
entry_points.emplace(entrypoint_name, EntryPoint{insn.offset(), entrypoint_stage});
break;
}
default:
// We don't care about any other defs for now.
break;
}
}
}
unsigned ExecutionModelToShaderStageFlagBits(unsigned mode) {
switch (mode) {
case spv::ExecutionModelVertex:
return VK_SHADER_STAGE_VERTEX_BIT;
case spv::ExecutionModelTessellationControl:
return VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT;
case spv::ExecutionModelTessellationEvaluation:
return VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
case spv::ExecutionModelGeometry:
return VK_SHADER_STAGE_GEOMETRY_BIT;
case spv::ExecutionModelFragment:
return VK_SHADER_STAGE_FRAGMENT_BIT;
case spv::ExecutionModelGLCompute:
return VK_SHADER_STAGE_COMPUTE_BIT;
case spv::ExecutionModelRayGenerationNV:
return VK_SHADER_STAGE_RAYGEN_BIT_NV;
case spv::ExecutionModelAnyHitNV:
return VK_SHADER_STAGE_ANY_HIT_BIT_NV;
case spv::ExecutionModelClosestHitNV:
return VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV;
case spv::ExecutionModelMissNV:
return VK_SHADER_STAGE_MISS_BIT_NV;
case spv::ExecutionModelIntersectionNV:
return VK_SHADER_STAGE_INTERSECTION_BIT_NV;
case spv::ExecutionModelCallableNV:
return VK_SHADER_STAGE_CALLABLE_BIT_NV;
case spv::ExecutionModelTaskNV:
return VK_SHADER_STAGE_TASK_BIT_NV;
case spv::ExecutionModelMeshNV:
return VK_SHADER_STAGE_MESH_BIT_NV;
default:
return 0;
}
}
static spirv_inst_iter FindEntrypoint(SHADER_MODULE_STATE const *src, char const *name, VkShaderStageFlagBits stageBits) {
auto range = src->entry_points.equal_range(name);
for (auto it = range.first; it != range.second; ++it) {
if (it->second.stage == stageBits) {
return src->at(it->second.offset);
}
}
return src->end();
}
static char const *StorageClassName(unsigned sc) {
switch (sc) {
case spv::StorageClassInput:
return "input";
case spv::StorageClassOutput:
return "output";
case spv::StorageClassUniformConstant:
return "const uniform";
case spv::StorageClassUniform:
return "uniform";
case spv::StorageClassWorkgroup:
return "workgroup local";
case spv::StorageClassCrossWorkgroup:
return "workgroup global";
case spv::StorageClassPrivate:
return "private global";
case spv::StorageClassFunction:
return "function";
case spv::StorageClassGeneric:
return "generic";
case spv::StorageClassAtomicCounter:
return "atomic counter";
case spv::StorageClassImage:
return "image";
case spv::StorageClassPushConstant:
return "push constant";
case spv::StorageClassStorageBuffer:
return "storage buffer";
default:
return "unknown";
}
}
// Get the value of an integral constant
unsigned GetConstantValue(SHADER_MODULE_STATE const *src, unsigned id) {
auto value = src->get_def(id);
assert(value != src->end());
if (value.opcode() != spv::OpConstant) {
// TODO: Either ensure that the specialization transform is already performed on a module we're
// considering here, OR -- specialize on the fly now.
return 1;
}
return value.word(3);
}
static void DescribeTypeInner(std::ostringstream &ss, SHADER_MODULE_STATE const *src, unsigned type) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypeBool:
ss << "bool";
break;
case spv::OpTypeInt:
ss << (insn.word(3) ? 's' : 'u') << "int" << insn.word(2);
break;
case spv::OpTypeFloat:
ss << "float" << insn.word(2);
break;
case spv::OpTypeVector:
ss << "vec" << insn.word(3) << " of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeMatrix:
ss << "mat" << insn.word(3) << " of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeArray:
ss << "arr[" << GetConstantValue(src, insn.word(3)) << "] of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeRuntimeArray:
ss << "runtime arr[] of ";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypePointer:
ss << "ptr to " << StorageClassName(insn.word(2)) << " ";
DescribeTypeInner(ss, src, insn.word(3));
break;
case spv::OpTypeStruct: {
ss << "struct of (";
for (unsigned i = 2; i < insn.len(); i++) {
DescribeTypeInner(ss, src, insn.word(i));
if (i == insn.len() - 1) {
ss << ")";
} else {
ss << ", ";
}
}
break;
}
case spv::OpTypeSampler:
ss << "sampler";
break;
case spv::OpTypeSampledImage:
ss << "sampler+";
DescribeTypeInner(ss, src, insn.word(2));
break;
case spv::OpTypeImage:
ss << "image(dim=" << insn.word(3) << ", sampled=" << insn.word(7) << ")";
break;
case spv::OpTypeAccelerationStructureNV:
ss << "accelerationStruture";
break;
default:
ss << "oddtype";
break;
}
}
static std::string DescribeType(SHADER_MODULE_STATE const *src, unsigned type) {
std::ostringstream ss;
DescribeTypeInner(ss, src, type);
return ss.str();
}
static bool IsNarrowNumericType(spirv_inst_iter type) {
if (type.opcode() != spv::OpTypeInt && type.opcode() != spv::OpTypeFloat) return false;
return type.word(2) < 64;
}
static bool TypesMatch(SHADER_MODULE_STATE const *a, SHADER_MODULE_STATE const *b, unsigned a_type, unsigned b_type, bool a_arrayed,
bool b_arrayed, bool relaxed) {
// Walk two type trees together, and complain about differences
auto a_insn = a->get_def(a_type);
auto b_insn = b->get_def(b_type);
assert(a_insn != a->end());
assert(b_insn != b->end());
// Ignore runtime-sized arrays-- they cannot appear in these interfaces.
if (a_arrayed && a_insn.opcode() == spv::OpTypeArray) {
return TypesMatch(a, b, a_insn.word(2), b_type, false, b_arrayed, relaxed);
}
if (b_arrayed && b_insn.opcode() == spv::OpTypeArray) {
// We probably just found the extra level of arrayness in b_type: compare the type inside it to a_type
return TypesMatch(a, b, a_type, b_insn.word(2), a_arrayed, false, relaxed);
}
if (a_insn.opcode() == spv::OpTypeVector && relaxed && IsNarrowNumericType(b_insn)) {
return TypesMatch(a, b, a_insn.word(2), b_type, a_arrayed, b_arrayed, false);
}
if (a_insn.opcode() != b_insn.opcode()) {
return false;
}
if (a_insn.opcode() == spv::OpTypePointer) {
// Match on pointee type. storage class is expected to differ
return TypesMatch(a, b, a_insn.word(3), b_insn.word(3), a_arrayed, b_arrayed, relaxed);
}
if (a_arrayed || b_arrayed) {
// If we havent resolved array-of-verts by here, we're not going to.
return false;
}
switch (a_insn.opcode()) {
case spv::OpTypeBool:
return true;
case spv::OpTypeInt:
// Match on width, signedness
return a_insn.word(2) == b_insn.word(2) && a_insn.word(3) == b_insn.word(3);
case spv::OpTypeFloat:
// Match on width
return a_insn.word(2) == b_insn.word(2);
case spv::OpTypeVector:
// Match on element type, count.
if (!TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false)) return false;
if (relaxed && IsNarrowNumericType(a->get_def(a_insn.word(2)))) {
return a_insn.word(3) >= b_insn.word(3);
} else {
return a_insn.word(3) == b_insn.word(3);
}
case spv::OpTypeMatrix:
// Match on element type, count.
return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
a_insn.word(3) == b_insn.word(3);
case spv::OpTypeArray:
// Match on element type, count. these all have the same layout. we don't get here if b_arrayed. This differs from
// vector & matrix types in that the array size is the id of a constant instruction, * not a literal within OpTypeArray
return TypesMatch(a, b, a_insn.word(2), b_insn.word(2), a_arrayed, b_arrayed, false) &&
GetConstantValue(a, a_insn.word(3)) == GetConstantValue(b, b_insn.word(3));
case spv::OpTypeStruct:
// Match on all element types
{
if (a_insn.len() != b_insn.len()) {
return false; // Structs cannot match if member counts differ
}
for (unsigned i = 2; i < a_insn.len(); i++) {
if (!TypesMatch(a, b, a_insn.word(i), b_insn.word(i), a_arrayed, b_arrayed, false)) {
return false;
}
}
return true;
}
default:
// Remaining types are CLisms, or may not appear in the interfaces we are interested in. Just claim no match.
return false;
}
}
static unsigned ValueOrDefault(std::unordered_map<unsigned, unsigned> const &map, unsigned id, unsigned def) {
auto it = map.find(id);
if (it == map.end())
return def;
else
return it->second;
}
static unsigned GetLocationsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetLocationsConsumedByType(src, insn.word(3), strip_array_level);
case spv::OpTypeArray:
if (strip_array_level) {
return GetLocationsConsumedByType(src, insn.word(2), false);
} else {
return GetConstantValue(src, insn.word(3)) * GetLocationsConsumedByType(src, insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetLocationsConsumedByType(src, insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = src->get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// Locations are 128-bit wide; 3- and 4-component vectors of 64 bit types require two.
return (bit_width * insn.word(3) + 127) / 128;
}
default:
// Everything else is just 1.
return 1;
// TODO: extend to handle 64bit scalar types, whose vectors may need multiple locations.
}
}
static unsigned GetComponentsConsumedByType(SHADER_MODULE_STATE const *src, unsigned type, bool strip_array_level) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypePointer:
// See through the ptr -- this is only ever at the toplevel for graphics shaders we're never actually passing
// pointers around.
return GetComponentsConsumedByType(src, insn.word(3), strip_array_level);
case spv::OpTypeStruct: {
uint32_t sum = 0;
for (uint32_t i = 2; i < insn.len(); i++) { // i=2 to skip word(0) and word(1)=ID of struct
sum += GetComponentsConsumedByType(src, insn.word(i), false);
}
return sum;
}
case spv::OpTypeArray:
if (strip_array_level) {
return GetComponentsConsumedByType(src, insn.word(2), false);
} else {
return GetConstantValue(src, insn.word(3)) * GetComponentsConsumedByType(src, insn.word(2), false);
}
case spv::OpTypeMatrix:
// Num locations is the dimension * element size
return insn.word(3) * GetComponentsConsumedByType(src, insn.word(2), false);
case spv::OpTypeVector: {
auto scalar_type = src->get_def(insn.word(2));
auto bit_width =
(scalar_type.opcode() == spv::OpTypeInt || scalar_type.opcode() == spv::OpTypeFloat) ? scalar_type.word(2) : 32;
// One component is 32-bit
return (bit_width * insn.word(3) + 31) / 32;
}
case spv::OpTypeFloat: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpTypeInt: {
auto bit_width = insn.word(2);
return (bit_width + 31) / 32;
}
case spv::OpConstant:
return GetComponentsConsumedByType(src, insn.word(1), false);
default:
return 0;
}
}
static unsigned GetLocationsConsumedByFormat(VkFormat format) {
switch (format) {
case VK_FORMAT_R64G64B64A64_SFLOAT:
case VK_FORMAT_R64G64B64A64_SINT:
case VK_FORMAT_R64G64B64A64_UINT:
case VK_FORMAT_R64G64B64_SFLOAT:
case VK_FORMAT_R64G64B64_SINT:
case VK_FORMAT_R64G64B64_UINT:
return 2;
default:
return 1;
}
}
static unsigned GetFormatType(VkFormat fmt) {
if (FormatIsSInt(fmt)) return FORMAT_TYPE_SINT;
if (FormatIsUInt(fmt)) return FORMAT_TYPE_UINT;
if (FormatIsDepthAndStencil(fmt)) return FORMAT_TYPE_FLOAT | FORMAT_TYPE_UINT;
if (fmt == VK_FORMAT_UNDEFINED) return 0;
// everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader.
return FORMAT_TYPE_FLOAT;
}
// characterizes a SPIR-V type appearing in an interface to a FF stage, for comparison to a VkFormat's characterization above.
// also used for input attachments, as we statically know their format.
static unsigned GetFundamentalType(SHADER_MODULE_STATE const *src, unsigned type) {
auto insn = src->get_def(type);
assert(insn != src->end());
switch (insn.opcode()) {
case spv::OpTypeInt:
return insn.word(3) ? FORMAT_TYPE_SINT : FORMAT_TYPE_UINT;
case spv::OpTypeFloat:
return FORMAT_TYPE_FLOAT;
case spv::OpTypeVector:
case spv::OpTypeMatrix:
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeImage:
return GetFundamentalType(src, insn.word(2));
case spv::OpTypePointer:
return GetFundamentalType(src, insn.word(3));
default:
return 0;
}
}
static uint32_t GetShaderStageId(VkShaderStageFlagBits stage) {
uint32_t bit_pos = uint32_t(u_ffs(stage));
return bit_pos - 1;
}
static spirv_inst_iter GetStructType(SHADER_MODULE_STATE const *src, spirv_inst_iter def, bool is_array_of_verts) {
while (true) {
if (def.opcode() == spv::OpTypePointer) {
def = src->get_def(def.word(3));
} else if (def.opcode() == spv::OpTypeArray && is_array_of_verts) {
def = src->get_def(def.word(2));
is_array_of_verts = false;
} else if (def.opcode() == spv::OpTypeStruct) {
return def;
} else {
return src->end();
}
}
}
static bool CollectInterfaceBlockMembers(SHADER_MODULE_STATE const *src, std::map<location_t, interface_var> *out,
bool is_array_of_verts, uint32_t id, uint32_t type_id, bool is_patch,
int /*first_location*/) {
// Walk down the type_id presented, trying to determine whether it's actually an interface block.
auto type = GetStructType(src, src->get_def(type_id), is_array_of_verts && !is_patch);
if (type == src->end() || !(src->get_decorations(type.word(1)).flags & decoration_set::block_bit)) {
// This isn't an interface block.
return false;
}
std::unordered_map<unsigned, unsigned> member_components;
std::unordered_map<unsigned, unsigned> member_relaxed_precision;
std::unordered_map<unsigned, unsigned> member_patch;
// Walk all the OpMemberDecorate for type's result id -- first pass, collect components.
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
unsigned member_index = insn.word(2);
if (insn.word(3) == spv::DecorationComponent) {
unsigned component = insn.word(4);
member_components[member_index] = component;
}
if (insn.word(3) == spv::DecorationRelaxedPrecision) {
member_relaxed_precision[member_index] = 1;
}
if (insn.word(3) == spv::DecorationPatch) {
member_patch[member_index] = 1;
}
}
}
// TODO: correctly handle location assignment from outside
// Second pass -- produce the output, from Location decorations
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
unsigned member_index = insn.word(2);
unsigned member_type_id = type.word(2 + member_index);
if (insn.word(3) == spv::DecorationLocation) {
unsigned location = insn.word(4);
unsigned num_locations = GetLocationsConsumedByType(src, member_type_id, false);
auto component_it = member_components.find(member_index);
unsigned component = component_it == member_components.end() ? 0 : component_it->second;
bool is_relaxed_precision = member_relaxed_precision.find(member_index) != member_relaxed_precision.end();
bool member_is_patch = is_patch || member_patch.count(member_index) > 0;
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
// TODO: member index in interface_var too?
v.type_id = member_type_id;
v.offset = offset;
v.is_patch = member_is_patch;
v.is_block_member = true;
v.is_relaxed_precision = is_relaxed_precision;
(*out)[std::make_pair(location + offset, component)] = v;
}
}
}
}
return true;
}
static std::vector<uint32_t> FindEntrypointInterfaces(spirv_inst_iter entrypoint) {
assert(entrypoint.opcode() == spv::OpEntryPoint);
std::vector<uint32_t> interfaces;
// Find the end of the entrypoint's name string. additional zero bytes follow the actual null terminator, to fill out the
// rest of the word - so we only need to look at the last byte in the word to determine which word contains the terminator.
uint32_t word = 3;
while (entrypoint.word(word) & 0xff000000u) {
++word;
}
++word;
for (; word < entrypoint.len(); word++) interfaces.push_back(entrypoint.word(word));
return interfaces;
}
static std::map<location_t, interface_var> CollectInterfaceByLocation(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
spv::StorageClass sinterface, bool is_array_of_verts) {
// TODO: handle index=1 dual source outputs from FS -- two vars will have the same location, and we DON'T want to clobber.
std::map<location_t, interface_var> out;
for (uint32_t iid : FindEntrypointInterfaces(entrypoint)) {
auto insn = src->get_def(iid);
assert(insn != src->end());
assert(insn.opcode() == spv::OpVariable);
if (insn.word(3) == static_cast<uint32_t>(sinterface)) {
auto d = src->get_decorations(iid);
unsigned id = insn.word(2);
unsigned type = insn.word(1);
int location = d.location;
int builtin = d.builtin;
unsigned component = d.component;
bool is_patch = (d.flags & decoration_set::patch_bit) != 0;
bool is_relaxed_precision = (d.flags & decoration_set::relaxed_precision_bit) != 0;
if (builtin != -1)
continue;
else if (!CollectInterfaceBlockMembers(src, &out, is_array_of_verts, id, type, is_patch, location)) {
// A user-defined interface variable, with a location. Where a variable occupied multiple locations, emit
// one result for each.
unsigned num_locations = GetLocationsConsumedByType(src, type, is_array_of_verts && !is_patch);
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
v.type_id = type;
v.offset = offset;
v.is_patch = is_patch;
v.is_relaxed_precision = is_relaxed_precision;
out[std::make_pair(location + offset, component)] = v;
}
}
}
}
return out;
}
static std::vector<uint32_t> CollectBuiltinBlockMembers(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint,
uint32_t storageClass) {
std::vector<uint32_t> variables;
std::vector<uint32_t> builtinStructMembers;
std::vector<uint32_t> builtinDecorations;
for (auto insn : *src) {
switch (insn.opcode()) {
// Find all built-in member decorations
case spv::OpMemberDecorate:
if (insn.word(3) == spv::DecorationBuiltIn) {
builtinStructMembers.push_back(insn.word(1));
}
break;
// Find all built-in decorations
case spv::OpDecorate:
switch (insn.word(2)) {
case spv::DecorationBlock: {
uint32_t blockID = insn.word(1);
for (auto builtInBlockID : builtinStructMembers) {
// Check if one of the members of the block are built-in -> the block is built-in
if (blockID == builtInBlockID) {
builtinDecorations.push_back(blockID);
break;
}
}
break;
}
case spv::DecorationBuiltIn:
builtinDecorations.push_back(insn.word(1));
break;
default:
break;
}
break;
default:
break;
}
}
// Find all interface variables belonging to the entrypoint and matching the storage class
for (uint32_t id : FindEntrypointInterfaces(entrypoint)) {
auto def = src->get_def(id);
assert(def != src->end());
assert(def.opcode() == spv::OpVariable);
if (def.word(3) == storageClass) variables.push_back(def.word(1));
}
// Find all members belonging to the builtin block selected
std::vector<uint32_t> builtinBlockMembers;
for (auto &var : variables) {
auto def = src->get_def(src->get_def(var).word(3));
// It could be an array of IO blocks. The element type should be the struct defining the block contents
if (def.opcode() == spv::OpTypeArray) def = src->get_def(def.word(2));
// Now find all members belonging to the struct defining the IO block
if (def.opcode() == spv::OpTypeStruct) {
for (auto builtInID : builtinDecorations) {
if (builtInID == def.word(1)) {
for (int i = 2; i < (int)def.len(); i++)
builtinBlockMembers.push_back(spv::BuiltInMax); // Start with undefined builtin for each struct member.
// These shouldn't be left after replacing.
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == builtInID &&
insn.word(3) == spv::DecorationBuiltIn) {
auto structIndex = insn.word(2);
assert(structIndex < builtinBlockMembers.size());
builtinBlockMembers[structIndex] = insn.word(4);
}
}
}
}
}
}
return builtinBlockMembers;
}
static std::vector<std::pair<uint32_t, interface_var>> CollectInterfaceByInputAttachmentIndex(
SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids) {
std::vector<std::pair<uint32_t, interface_var>> out;
for (auto insn : *src) {
if (insn.opcode() == spv::OpDecorate) {
if (insn.word(2) == spv::DecorationInputAttachmentIndex) {
auto attachment_index = insn.word(3);
auto id = insn.word(1);
if (accessible_ids.count(id)) {
auto def = src->get_def(id);
assert(def != src->end());
if (def.opcode() == spv::OpVariable && insn.word(3) == spv::StorageClassUniformConstant) {
auto num_locations = GetLocationsConsumedByType(src, def.word(1), false);
for (unsigned int offset = 0; offset < num_locations; offset++) {
interface_var v = {};
v.id = id;
v.type_id = def.word(1);
v.offset = offset;
out.emplace_back(attachment_index + offset, v);
}
}
}
}
}
}
return out;
}
static bool IsWritableDescriptorType(SHADER_MODULE_STATE const *module, uint32_t type_id, bool is_storage_buffer) {
auto type = module->get_def(type_id);
// Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
if (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypeRuntimeArray) {
type = module->get_def(type.word(2)); // Element type
} else {
type = module->get_def(type.word(3)); // Pointee type
}
}
switch (type.opcode()) {
case spv::OpTypeImage: {
auto dim = type.word(3);
auto sampled = type.word(7);
return sampled == 2 && dim != spv::DimSubpassData;
}
case spv::OpTypeStruct: {
std::unordered_set<unsigned> nonwritable_members;
if (module->get_decorations(type.word(1)).flags & decoration_set::buffer_block_bit) is_storage_buffer = true;
for (auto insn : *module) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1) &&
insn.word(3) == spv::DecorationNonWritable) {
nonwritable_members.insert(insn.word(2));
}
}
// A buffer is writable if it's either flavor of storage buffer, and has any member not decorated
// as nonwritable.
return is_storage_buffer && nonwritable_members.size() != type.len() - 2;
}
}
return false;
}
static std::vector<std::pair<descriptor_slot_t, interface_var>> CollectInterfaceByDescriptorSlot(
debug_report_data const *report_data, SHADER_MODULE_STATE const *src, std::unordered_set<uint32_t> const &accessible_ids,
bool *has_writable_descriptor) {
std::vector<std::pair<descriptor_slot_t, interface_var>> out;
for (auto id : accessible_ids) {
auto insn = src->get_def(id);
assert(insn != src->end());
if (insn.opcode() == spv::OpVariable &&
(insn.word(3) == spv::StorageClassUniform || insn.word(3) == spv::StorageClassUniformConstant ||
insn.word(3) == spv::StorageClassStorageBuffer)) {
auto d = src->get_decorations(insn.word(2));
unsigned set = d.descriptor_set;
unsigned binding = d.binding;
interface_var v = {};
v.id = insn.word(2);
v.type_id = insn.word(1);
out.emplace_back(std::make_pair(set, binding), v);
if (!(d.flags & decoration_set::nonwritable_bit) &&
IsWritableDescriptorType(src, insn.word(1), insn.word(3) == spv::StorageClassStorageBuffer)) {
*has_writable_descriptor = true;
}
}
}
return out;
}
static bool ValidateViConsistency(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi) {
// Walk the binding descriptions, which describe the step rate and stride of each vertex buffer. Each binding should
// be specified only once.
std::unordered_map<uint32_t, VkVertexInputBindingDescription const *> bindings;
bool skip = false;
for (unsigned i = 0; i < vi->vertexBindingDescriptionCount; i++) {
auto desc = &vi->pVertexBindingDescriptions[i];
auto &binding = bindings[desc->binding];
if (binding) {
// TODO: "VUID-VkGraphicsPipelineCreateInfo-pStages-00742" perhaps?
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_InconsistentVi, "Duplicate vertex input binding descriptions for binding %d",
desc->binding);
} else {
binding = desc;
}
}
return skip;
}
static bool ValidateViAgainstVsInputs(debug_report_data const *report_data, VkPipelineVertexInputStateCreateInfo const *vi,
SHADER_MODULE_STATE const *vs, spirv_inst_iter entrypoint) {
bool skip = false;
auto inputs = CollectInterfaceByLocation(vs, entrypoint, spv::StorageClassInput, false);
// Build index by location
std::map<uint32_t, VkVertexInputAttributeDescription const *> attribs;
if (vi) {
for (unsigned i = 0; i < vi->vertexAttributeDescriptionCount; i++) {
auto num_locations = GetLocationsConsumedByFormat(vi->pVertexAttributeDescriptions[i].format);
for (auto j = 0u; j < num_locations; j++) {
attribs[vi->pVertexAttributeDescriptions[i].location + j] = &vi->pVertexAttributeDescriptions[i];
}
}
}
auto it_a = attribs.begin();
auto it_b = inputs.begin();
bool used = false;
while ((attribs.size() > 0 && it_a != attribs.end()) || (inputs.size() > 0 && it_b != inputs.end())) {
bool a_at_end = attribs.size() == 0 || it_a == attribs.end();
bool b_at_end = inputs.size() == 0 || it_b == inputs.end();
auto a_first = a_at_end ? 0 : it_a->first;
auto b_first = b_at_end ? 0 : it_b->first.first;
if (!a_at_end && (b_at_end || a_first < b_first)) {
if (!used &&
log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
"Vertex attribute at location %d not consumed by vertex shader", a_first)) {
skip = true;
}
used = false;
it_a++;
} else if (!b_at_end && (a_at_end || b_first < a_first)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
"Vertex shader consumes input at location %d but not provided", b_first);
it_b++;
} else {
unsigned attrib_type = GetFormatType(it_a->second->format);
unsigned input_type = GetFundamentalType(vs, it_b->second.type_id);
// Type checking
if (!(attrib_type & input_type)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(vs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Attribute type of `%s` at location %d does not match vertex shader input type of `%s`",
string_VkFormat(it_a->second->format), a_first, DescribeType(vs, it_b->second.type_id).c_str());
}
// OK!
used = true;
it_b++;
}
}
return skip;
}
static bool ValidateFsOutputsAgainstRenderPass(debug_report_data const *report_data, SHADER_MODULE_STATE const *fs,
spirv_inst_iter entrypoint, PIPELINE_STATE const *pipeline, uint32_t subpass_index) {
auto rpci = pipeline->rp_state->createInfo.ptr();
std::map<uint32_t, VkFormat> color_attachments;
auto subpass = rpci->pSubpasses[subpass_index];
for (auto i = 0u; i < subpass.colorAttachmentCount; ++i) {
uint32_t attachment = subpass.pColorAttachments[i].attachment;
if (attachment == VK_ATTACHMENT_UNUSED) continue;
if (rpci->pAttachments[attachment].format != VK_FORMAT_UNDEFINED) {
color_attachments[i] = rpci->pAttachments[attachment].format;
}
}
bool skip = false;
// TODO: dual source blend index (spv::DecIndex, zero if not provided)
auto outputs = CollectInterfaceByLocation(fs, entrypoint, spv::StorageClassOutput, false);
auto it_a = outputs.begin();
auto it_b = color_attachments.begin();
bool used = false;
bool alphaToCoverageEnabled = pipeline->graphicsPipelineCI.pMultisampleState != NULL &&
pipeline->graphicsPipelineCI.pMultisampleState->alphaToCoverageEnable == VK_TRUE;
bool locationZeroHasAlpha = false;
// Walk attachment list and outputs together
while ((outputs.size() > 0 && it_a != outputs.end()) || (color_attachments.size() > 0 && it_b != color_attachments.end())) {
bool a_at_end = outputs.size() == 0 || it_a == outputs.end();
bool b_at_end = color_attachments.size() == 0 || it_b == color_attachments.end();
if (!a_at_end && it_a->first.first == 0 && fs->get_def(it_a->second.type_id) != fs->end() &&
GetComponentsConsumedByType(fs, it_a->second.type_id, false) == 4)
locationZeroHasAlpha = true;
if (!a_at_end && (b_at_end || it_a->first.first < it_b->first)) {
if (!alphaToCoverageEnabled || it_a->first.first != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
"fragment shader writes to output location %d with no matching attachment", it_a->first.first);
}
it_a++;
} else if (!b_at_end && (a_at_end || it_a->first.first > it_b->first)) {
// Only complain if there are unmasked channels for this attachment. If the writemask is 0, it's acceptable for the
// shader to not produce a matching output.
if (!used) {
if (pipeline->attachments[it_b->first].colorWriteMask != 0) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
"Attachment %d not written by fragment shader; undefined values will be written to attachment",
it_b->first);
}
}
used = false;
it_b++;
} else {
unsigned output_type = GetFundamentalType(fs, it_a->second.type_id);
unsigned att_type = GetFormatType(it_b->second);
// Type checking
if (!(output_type & att_type)) {
skip |= log_msg(
report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Attachment %d of type `%s` does not match fragment shader output type of `%s`; resulting values are undefined",
it_b->first, string_VkFormat(it_b->second), DescribeType(fs, it_a->second.type_id).c_str());
}
// OK!
it_a++;
used = true;
}
}
if (alphaToCoverageEnabled && !locationZeroHasAlpha) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(fs->vk_shader_module), kVUID_Core_Shader_NoAlphaAtLocation0WithAlphaToCoverage,
"fragment shader doesn't declare alpha output at location 0 even though alpha to coverage is enabled.");
}
return skip;
}
// For PointSize analysis we need to know if the variable decorated with the PointSize built-in was actually written to.
// This function examines instructions in the static call tree for a write to this variable.
static bool IsPointSizeWritten(SHADER_MODULE_STATE const *src, spirv_inst_iter builtin_instr, spirv_inst_iter entrypoint) {
auto type = builtin_instr.opcode();
uint32_t target_id = builtin_instr.word(1);
bool init_complete = false;
if (type == spv::OpMemberDecorate) {
// Built-in is part of a structure -- examine instructions up to first function body to get initial IDs
auto insn = entrypoint;
while (!init_complete && (insn.opcode() != spv::OpFunction)) {
switch (insn.opcode()) {
case spv::OpTypePointer:
if ((insn.word(3) == target_id) && (insn.word(2) == spv::StorageClassOutput)) {
target_id = insn.word(1);
}
break;
case spv::OpVariable:
if (insn.word(1) == target_id) {
target_id = insn.word(2);
init_complete = true;
}
break;
}
insn++;
}
}
if (!init_complete && (type == spv::OpMemberDecorate)) return false;
bool found_write = false;
std::unordered_set<uint32_t> worklist;
worklist.insert(entrypoint.word(2));
// Follow instructions in call graph looking for writes to target
while (!worklist.empty() && !found_write) {
auto id_iter = worklist.begin();
auto id = *id_iter;
worklist.erase(id_iter);
auto insn = src->get_def(id);
if (insn == src->end()) {
continue;
}
if (insn.opcode() == spv::OpFunction) {
// Scan body of function looking for other function calls or items in our ID chain
while (++insn, insn.opcode() != spv::OpFunctionEnd) {
switch (insn.opcode()) {
case spv::OpAccessChain:
if (insn.word(3) == target_id) {
if (type == spv::OpMemberDecorate) {
auto value = GetConstantValue(src, insn.word(4));
if (value == builtin_instr.word(2)) {
target_id = insn.word(2);
}
} else {
target_id = insn.word(2);
}
}
break;
case spv::OpStore:
if (insn.word(1) == target_id) {
found_write = true;
}
break;
case spv::OpFunctionCall:
worklist.insert(insn.word(3));
break;
}
}
}
}
return found_write;
}
// For some analyses, we need to know about all ids referenced by the static call tree of a particular entrypoint. This is
// important for identifying the set of shader resources actually used by an entrypoint, for example.
// Note: we only explore parts of the image which might actually contain ids we care about for the above analyses.
// - NOT the shader input/output interfaces.
//
// TODO: The set of interesting opcodes here was determined by eyeballing the SPIRV spec. It might be worth
// converting parts of this to be generated from the machine-readable spec instead.
static std::unordered_set<uint32_t> MarkAccessibleIds(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) {
std::unordered_set<uint32_t> ids;
std::unordered_set<uint32_t> worklist;
worklist.insert(entrypoint.word(2));
while (!worklist.empty()) {
auto id_iter = worklist.begin();
auto id = *id_iter;
worklist.erase(id_iter);
auto insn = src->get_def(id);
if (insn == src->end()) {
// ID is something we didn't collect in BuildDefIndex. that's OK -- we'll stumble across all kinds of things here
// that we may not care about.
continue;
}
// Try to add to the output set
if (!ids.insert(id).second) {
continue; // If we already saw this id, we don't want to walk it again.
}
switch (insn.opcode()) {
case spv::OpFunction:
// Scan whole body of the function, enlisting anything interesting
while (++insn, insn.opcode() != spv::OpFunctionEnd) {
switch (insn.opcode()) {
case spv::OpLoad:
case spv::OpAtomicLoad:
case spv::OpAtomicExchange:
case spv::OpAtomicCompareExchange:
case spv::OpAtomicCompareExchangeWeak:
case spv::OpAtomicIIncrement:
case spv::OpAtomicIDecrement:
case spv::OpAtomicIAdd:
case spv::OpAtomicISub:
case spv::OpAtomicSMin:
case spv::OpAtomicUMin:
case spv::OpAtomicSMax:
case spv::OpAtomicUMax:
case spv::OpAtomicAnd:
case spv::OpAtomicOr:
case spv::OpAtomicXor:
worklist.insert(insn.word(3)); // ptr
break;
case spv::OpStore:
case spv::OpAtomicStore:
worklist.insert(insn.word(1)); // ptr
break;
case spv::OpAccessChain:
case spv::OpInBoundsAccessChain:
worklist.insert(insn.word(3)); // base ptr
break;
case spv::OpSampledImage:
case spv::OpImageSampleImplicitLod:
case spv::OpImageSampleExplicitLod:
case spv::OpImageSampleDrefImplicitLod:
case spv::OpImageSampleDrefExplicitLod:
case spv::OpImageSampleProjImplicitLod:
case spv::OpImageSampleProjExplicitLod:
case spv::OpImageSampleProjDrefImplicitLod:
case spv::OpImageSampleProjDrefExplicitLod:
case spv::OpImageFetch:
case spv::OpImageGather:
case spv::OpImageDrefGather:
case spv::OpImageRead:
case spv::OpImage:
case spv::OpImageQueryFormat:
case spv::OpImageQueryOrder:
case spv::OpImageQuerySizeLod:
case spv::OpImageQuerySize:
case spv::OpImageQueryLod:
case spv::OpImageQueryLevels:
case spv::OpImageQuerySamples:
case spv::OpImageSparseSampleImplicitLod:
case spv::OpImageSparseSampleExplicitLod:
case spv::OpImageSparseSampleDrefImplicitLod:
case spv::OpImageSparseSampleDrefExplicitLod:
case spv::OpImageSparseSampleProjImplicitLod:
case spv::OpImageSparseSampleProjExplicitLod:
case spv::OpImageSparseSampleProjDrefImplicitLod:
case spv::OpImageSparseSampleProjDrefExplicitLod:
case spv::OpImageSparseFetch:
case spv::OpImageSparseGather:
case spv::OpImageSparseDrefGather:
case spv::OpImageTexelPointer:
worklist.insert(insn.word(3)); // Image or sampled image
break;
case spv::OpImageWrite:
worklist.insert(insn.word(1)); // Image -- different operand order to above
break;
case spv::OpFunctionCall:
for (uint32_t i = 3; i < insn.len(); i++) {
worklist.insert(insn.word(i)); // fn itself, and all args
}
break;
case spv::OpExtInst:
for (uint32_t i = 5; i < insn.len(); i++) {
worklist.insert(insn.word(i)); // Operands to ext inst
}
break;
}
}
break;
}
}
return ids;
}
static bool ValidatePushConstantBlockAgainstPipeline(debug_report_data const *report_data,
std::vector<VkPushConstantRange> const *push_constant_ranges,
SHADER_MODULE_STATE const *src, spirv_inst_iter type,
VkShaderStageFlagBits stage) {
bool skip = false;
// Strip off ptrs etc
type = GetStructType(src, type, false);
assert(type != src->end());
// Validate directly off the offsets. this isn't quite correct for arrays and matrices, but is a good first step.
// TODO: arrays, matrices, weird sizes
for (auto insn : *src) {
if (insn.opcode() == spv::OpMemberDecorate && insn.word(1) == type.word(1)) {
if (insn.word(3) == spv::DecorationOffset) {
unsigned offset = insn.word(4);
auto size = 4; // Bytes; TODO: calculate this based on the type
bool found_range = false;
for (auto const &range : *push_constant_ranges) {
if (range.offset <= offset && range.offset + range.size >= offset + size) {
found_range = true;
if ((range.stageFlags & stage) == 0) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_PushConstantNotAccessibleFromStage,
"Push constant range covering variable starting at offset %u not accessible from stage %s",
offset, string_VkShaderStageFlagBits(stage));
}
break;
}
}
if (!found_range) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_PushConstantOutOfRange,
"Push constant range covering variable starting at offset %u not declared in layout", offset);
}
}
}
}
return skip;
}
static bool ValidatePushConstantUsage(debug_report_data const *report_data,
std::vector<VkPushConstantRange> const *push_constant_ranges, SHADER_MODULE_STATE const *src,
std::unordered_set<uint32_t> accessible_ids, VkShaderStageFlagBits stage) {
bool skip = false;
for (auto id : accessible_ids) {
auto def_insn = src->get_def(id);
if (def_insn.opcode() == spv::OpVariable && def_insn.word(3) == spv::StorageClassPushConstant) {
skip |= ValidatePushConstantBlockAgainstPipeline(report_data, push_constant_ranges, src, src->get_def(def_insn.word(1)),
stage);
}
}
return skip;
}
// Validate that data for each specialization entry is fully contained within the buffer.
static bool ValidateSpecializationOffsets(debug_report_data const *report_data, VkPipelineShaderStageCreateInfo const *info) {
bool skip = false;
VkSpecializationInfo const *spec = info->pSpecializationInfo;
if (spec) {
for (auto i = 0u; i < spec->mapEntryCount; i++) {
// TODO: This is a good place for "VUID-VkSpecializationInfo-offset-00773".
if (spec->pMapEntries[i].offset + spec->pMapEntries[i].size > spec->dataSize) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
"VUID-VkSpecializationInfo-pMapEntries-00774",
"Specialization entry %u (for constant id %u) references memory outside provided specialization "
"data (bytes %u.." PRINTF_SIZE_T_SPECIFIER "; " PRINTF_SIZE_T_SPECIFIER " bytes provided)..",
i, spec->pMapEntries[i].constantID, spec->pMapEntries[i].offset,
spec->pMapEntries[i].offset + spec->pMapEntries[i].size - 1, spec->dataSize);
}
}
}
return skip;
}
// TODO (jbolz): Can this return a const reference?
static std::set<uint32_t> TypeToDescriptorTypeSet(SHADER_MODULE_STATE const *module, uint32_t type_id, unsigned &descriptor_count) {
auto type = module->get_def(type_id);
bool is_storage_buffer = false;
descriptor_count = 1;
std::set<uint32_t> ret;
// Strip off any array or ptrs. Where we remove array levels, adjust the descriptor count for each dimension.
while (type.opcode() == spv::OpTypeArray || type.opcode() == spv::OpTypePointer || type.opcode() == spv::OpTypeRuntimeArray) {
if (type.opcode() == spv::OpTypeRuntimeArray) {
descriptor_count = 0;
type = module->get_def(type.word(2));
} else if (type.opcode() == spv::OpTypeArray) {
descriptor_count *= GetConstantValue(module, type.word(3));
type = module->get_def(type.word(2));
} else {
if (type.word(2) == spv::StorageClassStorageBuffer) {
is_storage_buffer = true;
}
type = module->get_def(type.word(3));
}
}
switch (type.opcode()) {
case spv::OpTypeStruct: {
for (auto insn : *module) {
if (insn.opcode() == spv::OpDecorate && insn.word(1) == type.word(1)) {
if (insn.word(2) == spv::DecorationBlock) {
if (is_storage_buffer) {
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
return ret;
} else {
ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER);
ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC);
ret.insert(VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT);
return ret;
}
} else if (insn.word(2) == spv::DecorationBufferBlock) {
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER);
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC);
return ret;
}
}
}
// Invalid
return ret;
}
case spv::OpTypeSampler:
ret.insert(VK_DESCRIPTOR_TYPE_SAMPLER);
ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
return ret;
case spv::OpTypeSampledImage: {
// Slight relaxation for some GLSL historical madness: samplerBuffer doesn't really have a sampler, and a texel
// buffer descriptor doesn't really provide one. Allow this slight mismatch.
auto image_type = module->get_def(type.word(2));
auto dim = image_type.word(3);
auto sampled = image_type.word(7);
if (dim == spv::DimBuffer && sampled == 1) {
ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
return ret;
}
}
ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
return ret;
case spv::OpTypeImage: {
// Many descriptor types backing image types-- depends on dimension and whether the image will be used with a sampler.
// SPIRV for Vulkan requires that sampled be 1 or 2 -- leaving the decision to runtime is unacceptable.
auto dim = type.word(3);
auto sampled = type.word(7);
if (dim == spv::DimSubpassData) {
ret.insert(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT);
return ret;
} else if (dim == spv::DimBuffer) {
if (sampled == 1) {
ret.insert(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER);
return ret;
} else {
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER);
return ret;
}
} else if (sampled == 1) {
ret.insert(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE);
ret.insert(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
return ret;
} else {
ret.insert(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE);
return ret;
}
}
case spv::OpTypeAccelerationStructureNV:
ret.insert(VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV);
return ret;
// We shouldn't really see any other junk types -- but if we do, they're a mismatch.
default:
return ret; // Matches nothing
}
}
static std::string string_descriptorTypes(const std::set<uint32_t> &descriptor_types) {
std::stringstream ss;
for (auto it = descriptor_types.begin(); it != descriptor_types.end(); ++it) {
if (ss.tellp()) ss << ", ";
ss << string_VkDescriptorType(VkDescriptorType(*it));
}
return ss.str();
}
static bool RequirePropertyFlag(debug_report_data const *report_data, VkBool32 check, char const *flag, char const *structure) {
if (!check) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_ExceedDeviceLimit, "Shader requires flag %s set in %s but it is not set on the device", flag,
structure)) {
return true;
}
}
return false;
}
static bool RequireFeature(debug_report_data const *report_data, VkBool32 feature, char const *feature_name) {
if (!feature) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled, "Shader requires %s but is not enabled on the device", feature_name)) {
return true;
}
}
return false;
}
static bool RequireExtension(debug_report_data const *report_data, bool extension, char const *extension_name) {
if (!extension) {
if (log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled, "Shader requires extension %s but is not enabled on the device",
extension_name)) {
return true;
}
}
return false;
}
bool CoreChecks::ValidateShaderCapabilities(SHADER_MODULE_STATE const *src, VkShaderStageFlagBits stage) const {
bool skip = false;
struct FeaturePointer {
// Callable object to test if this feature is enabled in the given aggregate feature struct
const std::function<VkBool32(const DeviceFeatures &)> IsEnabled;
// Test if feature pointer is populated
explicit operator bool() const { return static_cast<bool>(IsEnabled); }
// Default and nullptr constructor to create an empty FeaturePointer
FeaturePointer() : IsEnabled(nullptr) {}
FeaturePointer(std::nullptr_t ptr) : IsEnabled(nullptr) {}
// Constructors to populate FeaturePointer based on given pointer to member
FeaturePointer(VkBool32 VkPhysicalDeviceFeatures::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.core.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceDescriptorIndexingFeaturesEXT::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.descriptor_indexing.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDevice8BitStorageFeaturesKHR::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.eight_bit_storage.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceTransformFeedbackFeaturesEXT::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.transform_feedback_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceFloat16Int8FeaturesKHR::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.float16_int8.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceScalarBlockLayoutFeaturesEXT::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.scalar_block_layout_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceCooperativeMatrixFeaturesNV::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.cooperative_matrix_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceFloatControlsPropertiesKHR::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.float_controls.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceUniformBufferStandardLayoutFeaturesKHR::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.uniform_buffer_standard_layout.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.compute_shader_derivatives_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_barycentric_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceShaderImageFootprintFeaturesNV::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.shader_image_footprint_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.fragment_shader_interlock_features.*ptr; }) {}
FeaturePointer(VkBool32 VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::*ptr)
: IsEnabled([=](const DeviceFeatures &features) { return features.demote_to_helper_invocation_features.*ptr; }) {}
};
struct CapabilityInfo {
char const *name;
FeaturePointer feature;
bool DeviceExtensions::*extension;
};
// clang-format off
static const std::unordered_multimap<uint32_t, CapabilityInfo> capabilities = {
// Capabilities always supported by a Vulkan 1.0 implementation -- no
// feature bits.
{spv::CapabilityMatrix, {nullptr}},
{spv::CapabilityShader, {nullptr}},
{spv::CapabilityInputAttachment, {nullptr}},
{spv::CapabilitySampled1D, {nullptr}},
{spv::CapabilityImage1D, {nullptr}},
{spv::CapabilitySampledBuffer, {nullptr}},
{spv::CapabilityStorageImageExtendedFormats, {nullptr}},
{spv::CapabilityImageQuery, {nullptr}},
{spv::CapabilityDerivativeControl, {nullptr}},
// Capabilities that are optionally supported, but require a feature to
// be enabled on the device
{spv::CapabilityGeometry, {"VkPhysicalDeviceFeatures::geometryShader", &VkPhysicalDeviceFeatures::geometryShader}},
{spv::CapabilityTessellation, {"VkPhysicalDeviceFeatures::tessellationShader", &VkPhysicalDeviceFeatures::tessellationShader}},
{spv::CapabilityFloat64, {"VkPhysicalDeviceFeatures::shaderFloat64", &VkPhysicalDeviceFeatures::shaderFloat64}},
{spv::CapabilityInt64, {"VkPhysicalDeviceFeatures::shaderInt64", &VkPhysicalDeviceFeatures::shaderInt64}},
{spv::CapabilityTessellationPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
{spv::CapabilityGeometryPointSize, {"VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize", &VkPhysicalDeviceFeatures::shaderTessellationAndGeometryPointSize}},
{spv::CapabilityImageGatherExtended, {"VkPhysicalDeviceFeatures::shaderImageGatherExtended", &VkPhysicalDeviceFeatures::shaderImageGatherExtended}},
{spv::CapabilityStorageImageMultisample, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
{spv::CapabilityUniformBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderUniformBufferArrayDynamicIndexing}},
{spv::CapabilitySampledImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderSampledImageArrayDynamicIndexing}},
{spv::CapabilityStorageBufferArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
{spv::CapabilityStorageImageArrayDynamicIndexing, {"VkPhysicalDeviceFeatures::shaderStorageImageArrayDynamicIndexing", &VkPhysicalDeviceFeatures::shaderStorageBufferArrayDynamicIndexing}},
{spv::CapabilityClipDistance, {"VkPhysicalDeviceFeatures::shaderClipDistance", &VkPhysicalDeviceFeatures::shaderClipDistance}},
{spv::CapabilityCullDistance, {"VkPhysicalDeviceFeatures::shaderCullDistance", &VkPhysicalDeviceFeatures::shaderCullDistance}},
{spv::CapabilityImageCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
{spv::CapabilitySampleRateShading, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
{spv::CapabilitySparseResidency, {"VkPhysicalDeviceFeatures::shaderResourceResidency", &VkPhysicalDeviceFeatures::shaderResourceResidency}},
{spv::CapabilityMinLod, {"VkPhysicalDeviceFeatures::shaderResourceMinLod", &VkPhysicalDeviceFeatures::shaderResourceMinLod}},
{spv::CapabilitySampledCubeArray, {"VkPhysicalDeviceFeatures::imageCubeArray", &VkPhysicalDeviceFeatures::imageCubeArray}},
{spv::CapabilityImageMSArray, {"VkPhysicalDeviceFeatures::shaderStorageImageMultisample", &VkPhysicalDeviceFeatures::shaderStorageImageMultisample}},
{spv::CapabilityInterpolationFunction, {"VkPhysicalDeviceFeatures::sampleRateShading", &VkPhysicalDeviceFeatures::sampleRateShading}},
{spv::CapabilityStorageImageReadWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageReadWithoutFormat}},
{spv::CapabilityStorageImageWriteWithoutFormat, {"VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat", &VkPhysicalDeviceFeatures::shaderStorageImageWriteWithoutFormat}},
{spv::CapabilityMultiViewport, {"VkPhysicalDeviceFeatures::multiViewport", &VkPhysicalDeviceFeatures::multiViewport}},
{spv::CapabilityShaderNonUniformEXT, {VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_descriptor_indexing}},
{spv::CapabilityRuntimeDescriptorArrayEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::runtimeDescriptorArray}},
{spv::CapabilityInputAttachmentArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayDynamicIndexing}},
{spv::CapabilityUniformTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayDynamicIndexing}},
{spv::CapabilityStorageTexelBufferArrayDynamicIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayDynamicIndexing}},
{spv::CapabilityUniformBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformBufferArrayNonUniformIndexing}},
{spv::CapabilitySampledImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderSampledImageArrayNonUniformIndexing}},
{spv::CapabilityStorageBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageBufferArrayNonUniformIndexing}},
{spv::CapabilityStorageImageArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageImageArrayNonUniformIndexing}},
{spv::CapabilityInputAttachmentArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderInputAttachmentArrayNonUniformIndexing}},
{spv::CapabilityUniformTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderUniformTexelBufferArrayNonUniformIndexing}},
{spv::CapabilityStorageTexelBufferArrayNonUniformIndexingEXT, {"VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing", &VkPhysicalDeviceDescriptorIndexingFeaturesEXT::shaderStorageTexelBufferArrayNonUniformIndexing}},
// Capabilities that require an extension
{spv::CapabilityDrawParameters, {VK_KHR_SHADER_DRAW_PARAMETERS_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_draw_parameters}},
{spv::CapabilityGeometryShaderPassthroughNV, {VK_NV_GEOMETRY_SHADER_PASSTHROUGH_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_geometry_shader_passthrough}},
{spv::CapabilitySampleMaskOverrideCoverageNV, {VK_NV_SAMPLE_MASK_OVERRIDE_COVERAGE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_sample_mask_override_coverage}},
{spv::CapabilityShaderViewportIndexLayerEXT, {VK_EXT_SHADER_VIEWPORT_INDEX_LAYER_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_viewport_index_layer}},
{spv::CapabilityShaderViewportIndexLayerNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
{spv::CapabilityShaderViewportMaskNV, {VK_NV_VIEWPORT_ARRAY2_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_viewport_array2}},
{spv::CapabilitySubgroupBallotKHR, {VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_ballot }},
{spv::CapabilitySubgroupVoteKHR, {VK_EXT_SHADER_SUBGROUP_VOTE_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_ext_shader_subgroup_vote }},
{spv::CapabilityGroupNonUniformPartitionedNV, {VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_nv_shader_subgroup_partitioned}},
{spv::CapabilityInt64Atomics, {VK_KHR_SHADER_ATOMIC_INT64_EXTENSION_NAME, nullptr, &DeviceExtensions::vk_khr_shader_atomic_int64 }},
{spv::CapabilityComputeDerivativeGroupQuadsNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupQuads, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
{spv::CapabilityComputeDerivativeGroupLinearNV, {"VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear", &VkPhysicalDeviceComputeShaderDerivativesFeaturesNV::computeDerivativeGroupLinear, &DeviceExtensions::vk_nv_compute_shader_derivatives}},
{spv::CapabilityFragmentBarycentricNV, {"VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric", &VkPhysicalDeviceFragmentShaderBarycentricFeaturesNV::fragmentShaderBarycentric, &DeviceExtensions::vk_nv_fragment_shader_barycentric}},
{spv::CapabilityStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::storageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
{spv::CapabilityUniformAndStorageBuffer8BitAccess, {"VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess", &VkPhysicalDevice8BitStorageFeaturesKHR::uniformAndStorageBuffer8BitAccess, &DeviceExtensions::vk_khr_8bit_storage}},
{spv::CapabilityStoragePushConstant8, {"VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8", &VkPhysicalDevice8BitStorageFeaturesKHR::storagePushConstant8, &DeviceExtensions::vk_khr_8bit_storage}},
{spv::CapabilityTransformFeedback, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::transformFeedback, &DeviceExtensions::vk_ext_transform_feedback}},
{spv::CapabilityGeometryStreams, { "VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams", &VkPhysicalDeviceTransformFeedbackFeaturesEXT::geometryStreams, &DeviceExtensions::vk_ext_transform_feedback}},
{spv::CapabilityFloat16, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderFloat16, &DeviceExtensions::vk_khr_shader_float16_int8}},
{spv::CapabilityInt8, {"VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8", &VkPhysicalDeviceFloat16Int8FeaturesKHR::shaderInt8, &DeviceExtensions::vk_khr_shader_float16_int8}},
{spv::CapabilityImageFootprintNV, {"VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint", &VkPhysicalDeviceShaderImageFootprintFeaturesNV::imageFootprint, &DeviceExtensions::vk_nv_shader_image_footprint}},
{spv::CapabilityCooperativeMatrixNV, {"VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix", &VkPhysicalDeviceCooperativeMatrixFeaturesNV::cooperativeMatrix, &DeviceExtensions::vk_nv_cooperative_matrix}},
{spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilitySignedZeroInfNanPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderSignedZeroInfNanPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormPreserve, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormPreserveFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityDenormFlushToZero, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderDenormFlushToZeroFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTE, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTEFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat16, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat32, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityRoundingModeRTZ, {"VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64", &VkPhysicalDeviceFloatControlsPropertiesKHR::shaderRoundingModeRTZFloat64, &DeviceExtensions::vk_khr_shader_float_controls}},
{spv::CapabilityFragmentShaderSampleInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderSampleInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
{spv::CapabilityFragmentShaderPixelInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderPixelInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
{spv::CapabilityFragmentShaderShadingRateInterlockEXT, {"VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock", &VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT::fragmentShaderShadingRateInterlock, &DeviceExtensions::vk_ext_fragment_shader_interlock}},
{spv::CapabilityDemoteToHelperInvocationEXT, {"VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation", &VkPhysicalDeviceShaderDemoteToHelperInvocationFeaturesEXT::shaderDemoteToHelperInvocation, &DeviceExtensions::vk_ext_shader_demote_to_helper_invocation}},
};
// clang-format on
for (auto insn : *src) {
if (insn.opcode() == spv::OpCapability) {
size_t n = capabilities.count(insn.word(1));
if (1 == n) { // key occurs exactly once
auto it = capabilities.find(insn.word(1));
if (it != capabilities.end()) {
if (it->second.feature) {
skip |= RequireFeature(report_data, it->second.feature.IsEnabled(enabled_features), it->second.name);
}
if (it->second.extension) {
skip |= RequireExtension(report_data, device_extensions.*(it->second.extension), it->second.name);
}
}
} else if (1 < n) { // key occurs multiple times, at least one must be enabled
bool needs_feature = false, has_feature = false;
bool needs_ext = false, has_ext = false;
std::string feature_names = "(one of) [ ";
std::string extension_names = feature_names;
auto caps = capabilities.equal_range(insn.word(1));
for (auto it = caps.first; it != caps.second; ++it) {
if (it->second.feature) {
needs_feature = true;
has_feature = has_feature || it->second.feature.IsEnabled(enabled_features);
feature_names += it->second.name;
feature_names += " ";
}
if (it->second.extension) {
needs_ext = true;
has_ext = has_ext || device_extensions.*(it->second.extension);
extension_names += it->second.name;
extension_names += " ";
}
}
if (needs_feature) {
feature_names += "]";
skip |= RequireFeature(report_data, has_feature, feature_names.c_str());
}
if (needs_ext) {
extension_names += "]";
skip |= RequireExtension(report_data, has_ext, extension_names.c_str());
}
} else { // Do group non-uniform checks
const VkSubgroupFeatureFlags supportedOperations = phys_dev_ext_props.subgroup_props.supportedOperations;
const VkSubgroupFeatureFlags supportedStages = phys_dev_ext_props.subgroup_props.supportedStages;
switch (insn.word(1)) {
default:
break;
case spv::CapabilityGroupNonUniform:
case spv::CapabilityGroupNonUniformVote:
case spv::CapabilityGroupNonUniformArithmetic:
case spv::CapabilityGroupNonUniformBallot:
case spv::CapabilityGroupNonUniformShuffle:
case spv::CapabilityGroupNonUniformShuffleRelative:
case spv::CapabilityGroupNonUniformClustered:
case spv::CapabilityGroupNonUniformQuad:
case spv::CapabilityGroupNonUniformPartitionedNV:
RequirePropertyFlag(report_data, supportedStages & stage, string_VkShaderStageFlagBits(stage),
"VkPhysicalDeviceSubgroupProperties::supportedStages");
break;
}
switch (insn.word(1)) {
default:
break;
case spv::CapabilityGroupNonUniform:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BASIC_BIT,
"VK_SUBGROUP_FEATURE_BASIC_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformVote:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_VOTE_BIT,
"VK_SUBGROUP_FEATURE_VOTE_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformArithmetic:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_ARITHMETIC_BIT,
"VK_SUBGROUP_FEATURE_ARITHMETIC_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformBallot:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_BALLOT_BIT,
"VK_SUBGROUP_FEATURE_BALLOT_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformShuffle:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_BIT,
"VK_SUBGROUP_FEATURE_SHUFFLE_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformShuffleRelative:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT,
"VK_SUBGROUP_FEATURE_SHUFFLE_RELATIVE_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformClustered:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_CLUSTERED_BIT,
"VK_SUBGROUP_FEATURE_CLUSTERED_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformQuad:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_QUAD_BIT,
"VK_SUBGROUP_FEATURE_QUAD_BIT",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
case spv::CapabilityGroupNonUniformPartitionedNV:
RequirePropertyFlag(report_data, supportedOperations & VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV,
"VK_SUBGROUP_FEATURE_PARTITIONED_BIT_NV",
"VkPhysicalDeviceSubgroupProperties::supportedOperations");
break;
}
}
}
}
return skip;
}
bool CoreChecks::ValidateShaderStageWritableDescriptor(VkShaderStageFlagBits stage, bool has_writable_descriptor) const {
bool skip = false;
if (has_writable_descriptor) {
switch (stage) {
case VK_SHADER_STAGE_COMPUTE_BIT:
case VK_SHADER_STAGE_RAYGEN_BIT_NV:
case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
case VK_SHADER_STAGE_MISS_BIT_NV:
case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
case VK_SHADER_STAGE_CALLABLE_BIT_NV:
case VK_SHADER_STAGE_TASK_BIT_NV:
case VK_SHADER_STAGE_MESH_BIT_NV:
/* No feature requirements for writes and atomics from compute
* raytracing, or mesh stages */
break;
case VK_SHADER_STAGE_FRAGMENT_BIT:
skip |= RequireFeature(report_data, enabled_features.core.fragmentStoresAndAtomics, "fragmentStoresAndAtomics");
break;
default:
skip |= RequireFeature(report_data, enabled_features.core.vertexPipelineStoresAndAtomics,
"vertexPipelineStoresAndAtomics");
break;
}
}
return skip;
}
bool CoreChecks::ValidateShaderStageGroupNonUniform(SHADER_MODULE_STATE const *module, VkShaderStageFlagBits stage,
std::unordered_set<uint32_t> const &accessible_ids) const {
bool skip = false;
auto const subgroup_props = phys_dev_ext_props.subgroup_props;
for (uint32_t id : accessible_ids) {
auto inst = module->get_def(id);
// Check the quad operations.
switch (inst.opcode()) {
default:
break;
case spv::OpGroupNonUniformQuadBroadcast:
case spv::OpGroupNonUniformQuadSwap:
if ((stage != VK_SHADER_STAGE_FRAGMENT_BIT) && (stage != VK_SHADER_STAGE_COMPUTE_BIT)) {
skip |= RequireFeature(report_data, subgroup_props.quadOperationsInAllStages,
"VkPhysicalDeviceSubgroupProperties::quadOperationsInAllStages");
}
break;
}
}
return skip;
}
bool CoreChecks::ValidateShaderStageInputOutputLimits(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
const PIPELINE_STATE *pipeline, spirv_inst_iter entrypoint) const {
if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT || pStage->stage == VK_SHADER_STAGE_ALL_GRAPHICS ||
pStage->stage == VK_SHADER_STAGE_ALL) {
return false;
}
bool skip = false;
auto const &limits = phys_dev_props.limits;
std::set<uint32_t> patchIDs;
struct Variable {
uint32_t baseTypePtrID;
uint32_t ID;
uint32_t storageClass;
};
std::vector<Variable> variables;
uint32_t numVertices = 0;
for (auto insn : *src) {
switch (insn.opcode()) {
// Find all Patch decorations
case spv::OpDecorate:
switch (insn.word(2)) {
case spv::DecorationPatch: {
patchIDs.insert(insn.word(1));
break;
}
default:
break;
}
break;
// Find all input and output variables
case spv::OpVariable: {
Variable var = {};
var.storageClass = insn.word(3);
if (var.storageClass == spv::StorageClassInput || var.storageClass == spv::StorageClassOutput) {
var.baseTypePtrID = insn.word(1);
var.ID = insn.word(2);
variables.push_back(var);
}
break;
}
case spv::OpExecutionMode:
if (insn.word(1) == entrypoint.word(2)) {
switch (insn.word(2)) {
default:
break;
case spv::ExecutionModeOutputVertices:
numVertices = insn.word(3);
break;
}
}
break;
default:
break;
}
}
bool strip_output_array_level =
(pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pStage->stage == VK_SHADER_STAGE_MESH_BIT_NV);
bool strip_input_array_level =
(pStage->stage == VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT ||
pStage->stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || pStage->stage == VK_SHADER_STAGE_GEOMETRY_BIT);
uint32_t numCompIn = 0, numCompOut = 0;
for (auto &var : variables) {
// Check if the variable is a patch. Patches can also be members of blocks,
// but if they are then the top-level arrayness has already been stripped
// by the time GetComponentsConsumedByType gets to it.
bool isPatch = patchIDs.find(var.ID) != patchIDs.end();
if (var.storageClass == spv::StorageClassInput) {
numCompIn += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_input_array_level && !isPatch);
} else { // var.storageClass == spv::StorageClassOutput
numCompOut += GetComponentsConsumedByType(src, var.baseTypePtrID, strip_output_array_level && !isPatch);
}
}
switch (pStage->stage) {
case VK_SHADER_STAGE_VERTEX_BIT:
if (numCompOut > limits.maxVertexOutputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Vertex shader exceeds "
"VkPhysicalDeviceLimits::maxVertexOutputComponents of %u "
"components by %u components",
limits.maxVertexOutputComponents, numCompOut - limits.maxVertexOutputComponents);
}
break;
case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT:
if (numCompIn > limits.maxTessellationControlPerVertexInputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
"VkPhysicalDeviceLimits::maxTessellationControlPerVertexInputComponents of %u "
"components by %u components",
limits.maxTessellationControlPerVertexInputComponents,
numCompIn - limits.maxTessellationControlPerVertexInputComponents);
}
if (numCompOut > limits.maxTessellationControlPerVertexOutputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Tessellation control shader exceeds "
"VkPhysicalDeviceLimits::maxTessellationControlPerVertexOutputComponents of %u "
"components by %u components",
limits.maxTessellationControlPerVertexOutputComponents,
numCompOut - limits.maxTessellationControlPerVertexOutputComponents);
}
break;
case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT:
if (numCompIn > limits.maxTessellationEvaluationInputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
"VkPhysicalDeviceLimits::maxTessellationEvaluationInputComponents of %u "
"components by %u components",
limits.maxTessellationEvaluationInputComponents,
numCompIn - limits.maxTessellationEvaluationInputComponents);
}
if (numCompOut > limits.maxTessellationEvaluationOutputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Tessellation evaluation shader exceeds "
"VkPhysicalDeviceLimits::maxTessellationEvaluationOutputComponents of %u "
"components by %u components",
limits.maxTessellationEvaluationOutputComponents,
numCompOut - limits.maxTessellationEvaluationOutputComponents);
}
break;
case VK_SHADER_STAGE_GEOMETRY_BIT:
if (numCompIn > limits.maxGeometryInputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Geometry shader exceeds "
"VkPhysicalDeviceLimits::maxGeometryInputComponents of %u "
"components by %u components",
limits.maxGeometryInputComponents, numCompIn - limits.maxGeometryInputComponents);
}
if (numCompOut > limits.maxGeometryOutputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Geometry shader exceeds "
"VkPhysicalDeviceLimits::maxGeometryOutputComponents of %u "
"components by %u components",
limits.maxGeometryOutputComponents, numCompOut - limits.maxGeometryOutputComponents);
}
if (numCompOut * numVertices > limits.maxGeometryTotalOutputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Geometry shader exceeds "
"VkPhysicalDeviceLimits::maxGeometryTotalOutputComponents of %u "
"components by %u components",
limits.maxGeometryTotalOutputComponents,
numCompOut * numVertices - limits.maxGeometryTotalOutputComponents);
}
break;
case VK_SHADER_STAGE_FRAGMENT_BIT:
if (numCompIn > limits.maxFragmentInputComponents) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_ExceedDeviceLimit,
"Invalid Pipeline CreateInfo State: Fragment shader exceeds "
"VkPhysicalDeviceLimits::maxFragmentInputComponents of %u "
"components by %u components",
limits.maxFragmentInputComponents, numCompIn - limits.maxFragmentInputComponents);
}
break;
case VK_SHADER_STAGE_RAYGEN_BIT_NV:
case VK_SHADER_STAGE_ANY_HIT_BIT_NV:
case VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV:
case VK_SHADER_STAGE_MISS_BIT_NV:
case VK_SHADER_STAGE_INTERSECTION_BIT_NV:
case VK_SHADER_STAGE_CALLABLE_BIT_NV:
case VK_SHADER_STAGE_TASK_BIT_NV:
case VK_SHADER_STAGE_MESH_BIT_NV:
break;
default:
assert(false); // This should never happen
}
return skip;
}
// copy the specialization constant value into buf, if it is present
void GetSpecConstantValue(VkPipelineShaderStageCreateInfo const *pStage, uint32_t spec_id, void *buf) {
VkSpecializationInfo const *spec = pStage->pSpecializationInfo;
if (spec && spec_id < spec->mapEntryCount) {
memcpy(buf, (uint8_t *)spec->pData + spec->pMapEntries[spec_id].offset, spec->pMapEntries[spec_id].size);
}
}
// Fill in value with the constant or specialization constant value, if available.
// Returns true if the value has been accurately filled out.
static bool GetIntConstantValue(spirv_inst_iter insn, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id, uint32_t *value) {
auto type_id = src->get_def(insn.word(1));
if (type_id.opcode() != spv::OpTypeInt || type_id.word(2) != 32) {
return false;
}
switch (insn.opcode()) {
case spv::OpSpecConstant:
*value = insn.word(3);
GetSpecConstantValue(pStage, id_to_spec_id.at(insn.word(2)), value);
return true;
case spv::OpConstant:
*value = insn.word(3);
return true;
default:
return false;
}
}
// Map SPIR-V type to VK_COMPONENT_TYPE enum
VkComponentTypeNV GetComponentType(spirv_inst_iter insn, SHADER_MODULE_STATE const *src) {
switch (insn.opcode()) {
case spv::OpTypeInt:
switch (insn.word(2)) {
case 8:
return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT8_NV : VK_COMPONENT_TYPE_UINT8_NV;
case 16:
return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT16_NV : VK_COMPONENT_TYPE_UINT16_NV;
case 32:
return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT32_NV : VK_COMPONENT_TYPE_UINT32_NV;
case 64:
return insn.word(3) != 0 ? VK_COMPONENT_TYPE_SINT64_NV : VK_COMPONENT_TYPE_UINT64_NV;
default:
return VK_COMPONENT_TYPE_MAX_ENUM_NV;
}
case spv::OpTypeFloat:
switch (insn.word(2)) {
case 16:
return VK_COMPONENT_TYPE_FLOAT16_NV;
case 32:
return VK_COMPONENT_TYPE_FLOAT32_NV;
case 64:
return VK_COMPONENT_TYPE_FLOAT64_NV;
default:
return VK_COMPONENT_TYPE_MAX_ENUM_NV;
}
default:
return VK_COMPONENT_TYPE_MAX_ENUM_NV;
}
}
// Validate SPV_NV_cooperative_matrix behavior that can't be statically validated
// in SPIRV-Tools (e.g. due to specialization constant usage).
bool CoreChecks::ValidateCooperativeMatrix(SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
const PIPELINE_STATE *pipeline) const {
bool skip = false;
// Map SPIR-V result ID to specialization constant id (SpecId decoration value)
std::unordered_map<uint32_t, uint32_t> id_to_spec_id;
// Map SPIR-V result ID to the ID of its type.
std::unordered_map<uint32_t, uint32_t> id_to_type_id;
struct CoopMatType {
uint32_t scope, rows, cols;
VkComponentTypeNV component_type;
bool all_constant;
CoopMatType() : scope(0), rows(0), cols(0), component_type(VK_COMPONENT_TYPE_MAX_ENUM_NV), all_constant(false) {}
void Init(uint32_t id, SHADER_MODULE_STATE const *src, VkPipelineShaderStageCreateInfo const *pStage,
const std::unordered_map<uint32_t, uint32_t> &id_to_spec_id) {
spirv_inst_iter insn = src->get_def(id);
uint32_t component_type_id = insn.word(2);
uint32_t scope_id = insn.word(3);
uint32_t rows_id = insn.word(4);
uint32_t cols_id = insn.word(5);
auto component_type_iter = src->get_def(component_type_id);
auto scope_iter = src->get_def(scope_id);
auto rows_iter = src->get_def(rows_id);
auto cols_iter = src->get_def(cols_id);
all_constant = true;
if (!GetIntConstantValue(scope_iter, src, pStage, id_to_spec_id, &scope)) {
all_constant = false;
}
if (!GetIntConstantValue(rows_iter, src, pStage, id_to_spec_id, &rows)) {
all_constant = false;
}
if (!GetIntConstantValue(cols_iter, src, pStage, id_to_spec_id, &cols)) {
all_constant = false;
}
component_type = GetComponentType(component_type_iter, src);
}
};
bool seen_coopmat_capability = false;
for (auto insn : *src) {
// Whitelist instructions whose result can be a cooperative matrix type, and
// keep track of their types. It would be nice if SPIRV-Headers generated code
// to identify which instructions have a result type and result id. Lacking that,
// this whitelist is based on the set of instructions that
// SPV_NV_cooperative_matrix says can be used with cooperative matrix types.
switch (insn.opcode()) {
case spv::OpLoad:
case spv::OpCooperativeMatrixLoadNV:
case spv::OpCooperativeMatrixMulAddNV:
case spv::OpSNegate:
case spv::OpFNegate:
case spv::OpIAdd:
case spv::OpFAdd:
case spv::OpISub:
case spv::OpFSub:
case spv::OpFDiv:
case spv::OpSDiv:
case spv::OpUDiv:
case spv::OpMatrixTimesScalar:
case spv::OpConstantComposite:
case spv::OpCompositeConstruct:
case spv::OpConvertFToU:
case spv::OpConvertFToS:
case spv::OpConvertSToF:
case spv::OpConvertUToF:
case spv::OpUConvert:
case spv::OpSConvert:
case spv::OpFConvert:
id_to_type_id[insn.word(2)] = insn.word(1);
break;
default:
break;
}
switch (insn.opcode()) {
case spv::OpDecorate:
if (insn.word(2) == spv::DecorationSpecId) {
id_to_spec_id[insn.word(1)] = insn.word(3);
}
break;
case spv::OpCapability:
if (insn.word(1) == spv::CapabilityCooperativeMatrixNV) {
seen_coopmat_capability = true;
if (!(pStage->stage & phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixSupportedStages,
"OpTypeCooperativeMatrixNV used in shader stage not in cooperativeMatrixSupportedStages (= %u)",
phys_dev_ext_props.cooperative_matrix_props.cooperativeMatrixSupportedStages);
}
}
break;
case spv::OpMemoryModel:
// If the capability isn't enabled, don't bother with the rest of this function.
// OpMemoryModel is the first required instruction after all OpCapability instructions.
if (!seen_coopmat_capability) {
return skip;
}
break;
case spv::OpTypeCooperativeMatrixNV: {
CoopMatType M;
M.Init(insn.word(1), src, pStage, id_to_spec_id);
if (M.all_constant) {
// Validate that the type parameters are all supported for one of the
// operands of a cooperative matrix property.
bool valid = false;
for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
if (cooperative_matrix_properties[i].AType == M.component_type &&
cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].KSize == M.cols &&
cooperative_matrix_properties[i].scope == M.scope) {
valid = true;
break;
}
if (cooperative_matrix_properties[i].BType == M.component_type &&
cooperative_matrix_properties[i].KSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
cooperative_matrix_properties[i].scope == M.scope) {
valid = true;
break;
}
if (cooperative_matrix_properties[i].CType == M.component_type &&
cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
cooperative_matrix_properties[i].scope == M.scope) {
valid = true;
break;
}
if (cooperative_matrix_properties[i].DType == M.component_type &&
cooperative_matrix_properties[i].MSize == M.rows && cooperative_matrix_properties[i].NSize == M.cols &&
cooperative_matrix_properties[i].scope == M.scope) {
valid = true;
break;
}
}
if (!valid) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixType,
"OpTypeCooperativeMatrixNV (result id = %u) operands don't match a supported matrix type",
insn.word(1));
}
}
break;
}
case spv::OpCooperativeMatrixMulAddNV: {
CoopMatType A, B, C, D;
if (id_to_type_id.find(insn.word(2)) == id_to_type_id.end() ||
id_to_type_id.find(insn.word(3)) == id_to_type_id.end() ||
id_to_type_id.find(insn.word(4)) == id_to_type_id.end() ||
id_to_type_id.find(insn.word(5)) == id_to_type_id.end()) {
// Couldn't find type of matrix
assert(false);
break;
}
D.Init(id_to_type_id[insn.word(2)], src, pStage, id_to_spec_id);
A.Init(id_to_type_id[insn.word(3)], src, pStage, id_to_spec_id);
B.Init(id_to_type_id[insn.word(4)], src, pStage, id_to_spec_id);
C.Init(id_to_type_id[insn.word(5)], src, pStage, id_to_spec_id);
if (A.all_constant && B.all_constant && C.all_constant && D.all_constant) {
// Validate that the type parameters are all supported for the same
// cooperative matrix property.
bool valid = false;
for (unsigned i = 0; i < cooperative_matrix_properties.size(); ++i) {
if (cooperative_matrix_properties[i].AType == A.component_type &&
cooperative_matrix_properties[i].MSize == A.rows && cooperative_matrix_properties[i].KSize == A.cols &&
cooperative_matrix_properties[i].scope == A.scope &&
cooperative_matrix_properties[i].BType == B.component_type &&
cooperative_matrix_properties[i].KSize == B.rows && cooperative_matrix_properties[i].NSize == B.cols &&
cooperative_matrix_properties[i].scope == B.scope &&
cooperative_matrix_properties[i].CType == C.component_type &&
cooperative_matrix_properties[i].MSize == C.rows && cooperative_matrix_properties[i].NSize == C.cols &&
cooperative_matrix_properties[i].scope == C.scope &&
cooperative_matrix_properties[i].DType == D.component_type &&
cooperative_matrix_properties[i].MSize == D.rows && cooperative_matrix_properties[i].NSize == D.cols &&
cooperative_matrix_properties[i].scope == D.scope) {
valid = true;
break;
}
}
if (!valid) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_CooperativeMatrixMulAdd,
"OpCooperativeMatrixMulAddNV (result id = %u) operands don't match a supported matrix "
"VkCooperativeMatrixPropertiesNV",
insn.word(2));
}
}
break;
}
default:
break;
}
}
return skip;
}
bool CoreChecks::ValidateExecutionModes(SHADER_MODULE_STATE const *src, spirv_inst_iter entrypoint) const {
auto entrypoint_id = entrypoint.word(2);
// The first denorm execution mode encountered, along with its bit width.
// Used to check if SeparateDenormSettings is respected.
std::pair<spv::ExecutionMode, uint32_t> first_denorm_execution_mode = std::make_pair(spv::ExecutionModeMax, 0);
// The first rounding mode encountered, along with its bit width.
// Used to check if SeparateRoundingModeSettings is respected.
std::pair<spv::ExecutionMode, uint32_t> first_rounding_mode = std::make_pair(spv::ExecutionModeMax, 0);
bool skip = false;
uint32_t verticesOut = 0;
uint32_t invocations = 0;
for (auto insn : *src) {
if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
auto mode = insn.word(2);
switch (mode) {
case spv::ExecutionModeSignedZeroInfNanPreserve: {
auto bit_width = insn.word(3);
if ((bit_width == 16 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat16) ||
(bit_width == 32 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat32) ||
(bit_width == 64 && !enabled_features.float_controls.shaderSignedZeroInfNanPreserveFloat64)) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader requires SignedZeroInfNanPreserve for bit width %d but it is not enabled on the device",
bit_width);
}
break;
}
case spv::ExecutionModeDenormPreserve: {
auto bit_width = insn.word(3);
if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormPreserveFloat16) ||
(bit_width == 32 && !enabled_features.float_controls.shaderDenormPreserveFloat32) ||
(bit_width == 64 && !enabled_features.float_controls.shaderDenormPreserveFloat64)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader requires DenormPreserve for bit width %d but it is not enabled on the device",
bit_width);
}
if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
// Register the first denorm execution mode found
first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
} else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width &&
!enabled_features.float_controls.separateDenormSettings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader uses separate denorm execution modes for different bit widths but "
"SeparateDenormSettings is not enabled on the device");
}
break;
}
case spv::ExecutionModeDenormFlushToZero: {
auto bit_width = insn.word(3);
if ((bit_width == 16 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat16) ||
(bit_width == 32 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat32) ||
(bit_width == 64 && !enabled_features.float_controls.shaderDenormFlushToZeroFloat64)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader requires DenormFlushToZero for bit width %d but it is not enabled on the device",
bit_width);
}
if (first_denorm_execution_mode.first == spv::ExecutionModeMax) {
// Register the first denorm execution mode found
first_denorm_execution_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
} else if (first_denorm_execution_mode.first != mode && first_denorm_execution_mode.second != bit_width &&
!enabled_features.float_controls.separateDenormSettings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader uses separate denorm execution modes for different bit widths but "
"SeparateDenormSettings is not enabled on the device");
}
break;
}
case spv::ExecutionModeRoundingModeRTE: {
auto bit_width = insn.word(3);
if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTEFloat16) ||
(bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTEFloat32) ||
(bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTEFloat64)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader requires RoundingModeRTE for bit width %d but it is not enabled on the device",
bit_width);
}
if (first_rounding_mode.first == spv::ExecutionModeMax) {
// Register the first rounding mode found
first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
} else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width &&
!enabled_features.float_controls.separateRoundingModeSettings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader uses separate rounding modes for different bit widths but "
"SeparateRoundingModeSettings is not enabled on the device");
}
break;
}
case spv::ExecutionModeRoundingModeRTZ: {
auto bit_width = insn.word(3);
if ((bit_width == 16 && !enabled_features.float_controls.shaderRoundingModeRTZFloat16) ||
(bit_width == 32 && !enabled_features.float_controls.shaderRoundingModeRTZFloat32) ||
(bit_width == 64 && !enabled_features.float_controls.shaderRoundingModeRTZFloat64)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader requires RoundingModeRTZ for bit width %d but it is not enabled on the device",
bit_width);
}
if (first_rounding_mode.first == spv::ExecutionModeMax) {
// Register the first rounding mode found
first_rounding_mode = std::make_pair(static_cast<spv::ExecutionMode>(mode), bit_width);
} else if (first_rounding_mode.first != mode && first_rounding_mode.second != bit_width &&
!enabled_features.float_controls.separateRoundingModeSettings) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_FeatureNotEnabled,
"Shader uses separate rounding modes for different bit widths but "
"SeparateRoundingModeSettings is not enabled on the device");
}
break;
}
case spv::ExecutionModeOutputVertices: {
verticesOut = insn.word(3);
break;
}
case spv::ExecutionModeInvocations: {
invocations = insn.word(3);
break;
}
}
}
}
if (entrypoint.word(1) == spv::ExecutionModelGeometry) {
if (verticesOut == 0 || verticesOut > phys_dev_props.limits.maxGeometryOutputVertices) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineShaderStageCreateInfo-stage-00714",
"Geometry shader entry point must have an OpExecutionMode instruction that "
"specifies a maximum output vertex count that is greater than 0 and less "
"than or equal to maxGeometryOutputVertices. "
"OutputVertices=%d, maxGeometryOutputVertices=%d",
verticesOut, phys_dev_props.limits.maxGeometryOutputVertices);
}
if (invocations == 0 || invocations > phys_dev_props.limits.maxGeometryShaderInvocations) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineShaderStageCreateInfo-stage-00715",
"Geometry shader entry point must have an OpExecutionMode instruction that "
"specifies an invocation count that is greater than 0 and less "
"than or equal to maxGeometryShaderInvocations. "
"Invocations=%d, maxGeometryShaderInvocations=%d",
invocations, phys_dev_props.limits.maxGeometryShaderInvocations);
}
}
return skip;
}
static uint32_t DescriptorTypeToReqs(SHADER_MODULE_STATE const *module, uint32_t type_id) {
auto type = module->get_def(type_id);
while (true) {
switch (type.opcode()) {
case spv::OpTypeArray:
case spv::OpTypeRuntimeArray:
case spv::OpTypeSampledImage:
type = module->get_def(type.word(2));
break;
case spv::OpTypePointer:
type = module->get_def(type.word(3));
break;
case spv::OpTypeImage: {
auto dim = type.word(3);
auto arrayed = type.word(5);
auto msaa = type.word(6);
uint32_t bits = 0;
switch (GetFundamentalType(module, type.word(2))) {
case FORMAT_TYPE_FLOAT:
bits = DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT;
break;
case FORMAT_TYPE_UINT:
bits = DESCRIPTOR_REQ_COMPONENT_TYPE_UINT;
break;
case FORMAT_TYPE_SINT:
bits = DESCRIPTOR_REQ_COMPONENT_TYPE_SINT;
break;
default:
break;
}
switch (dim) {
case spv::Dim1D:
bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_1D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_1D;
return bits;
case spv::Dim2D:
bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_2D_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_2D;
return bits;
case spv::Dim3D:
bits |= DESCRIPTOR_REQ_VIEW_TYPE_3D;
return bits;
case spv::DimCube:
bits |= arrayed ? DESCRIPTOR_REQ_VIEW_TYPE_CUBE_ARRAY : DESCRIPTOR_REQ_VIEW_TYPE_CUBE;
return bits;
case spv::DimSubpassData:
bits |= msaa ? DESCRIPTOR_REQ_MULTI_SAMPLE : DESCRIPTOR_REQ_SINGLE_SAMPLE;
return bits;
default: // buffer, etc.
return bits;
}
}
default:
return 0;
}
}
}
// For given pipelineLayout verify that the set_layout_node at slot.first
// has the requested binding at slot.second and return ptr to that binding
static VkDescriptorSetLayoutBinding const *GetDescriptorBinding(PIPELINE_LAYOUT_STATE const *pipelineLayout,
descriptor_slot_t slot) {
if (!pipelineLayout) return nullptr;
if (slot.first >= pipelineLayout->set_layouts.size()) return nullptr;
return pipelineLayout->set_layouts[slot.first]->GetDescriptorSetLayoutBindingPtrFromBinding(slot.second);
}
static bool FindLocalSize(SHADER_MODULE_STATE const *src, uint32_t &local_size_x, uint32_t &local_size_y, uint32_t &local_size_z) {
for (auto insn : *src) {
if (insn.opcode() == spv::OpEntryPoint) {
auto executionModel = insn.word(1);
auto entrypointStageBits = ExecutionModelToShaderStageFlagBits(executionModel);
if (entrypointStageBits == VK_SHADER_STAGE_COMPUTE_BIT) {
auto entrypoint_id = insn.word(2);
for (auto insn1 : *src) {
if (insn1.opcode() == spv::OpExecutionMode && insn1.word(1) == entrypoint_id &&
insn1.word(2) == spv::ExecutionModeLocalSize) {
local_size_x = insn1.word(3);
local_size_y = insn1.word(4);
local_size_z = insn1.word(5);
return true;
}
}
}
}
}
return false;
}
static void ProcessExecutionModes(SHADER_MODULE_STATE const *src, const spirv_inst_iter &entrypoint, PIPELINE_STATE *pipeline) {
auto entrypoint_id = entrypoint.word(2);
bool is_point_mode = false;
for (auto insn : *src) {
if (insn.opcode() == spv::OpExecutionMode && insn.word(1) == entrypoint_id) {
switch (insn.word(2)) {
case spv::ExecutionModePointMode:
// In tessellation shaders, PointMode is separate and trumps the tessellation topology.
is_point_mode = true;
break;
case spv::ExecutionModeOutputPoints:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
break;
case spv::ExecutionModeIsolines:
case spv::ExecutionModeOutputLineStrip:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_LINE_STRIP;
break;
case spv::ExecutionModeTriangles:
case spv::ExecutionModeQuads:
case spv::ExecutionModeOutputTriangleStrip:
pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
break;
}
}
}
if (is_point_mode) pipeline->topology_at_rasterizer = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
}
// If PointList topology is specified in the pipeline, verify that a shader geometry stage writes PointSize
// o If there is only a vertex shader : gl_PointSize must be written when using points
// o If there is a geometry or tessellation shader:
// - If shaderTessellationAndGeometryPointSize feature is enabled:
// * gl_PointSize must be written in the final geometry stage
// - If shaderTessellationAndGeometryPointSize feature is disabled:
// * gl_PointSize must NOT be written and a default of 1.0 is assumed
bool CoreChecks::ValidatePointListShaderState(const PIPELINE_STATE *pipeline, SHADER_MODULE_STATE const *src,
spirv_inst_iter entrypoint, VkShaderStageFlagBits stage) const {
if (pipeline->topology_at_rasterizer != VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
return false;
}
bool pointsize_written = false;
bool skip = false;
// Search for PointSize built-in decorations
std::vector<uint32_t> pointsize_builtin_offsets;
spirv_inst_iter insn = entrypoint;
while (!pointsize_written && (insn.opcode() != spv::OpFunction)) {
if (insn.opcode() == spv::OpMemberDecorate) {
if (insn.word(3) == spv::DecorationBuiltIn) {
if (insn.word(4) == spv::BuiltInPointSize) {
pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
}
}
} else if (insn.opcode() == spv::OpDecorate) {
if (insn.word(2) == spv::DecorationBuiltIn) {
if (insn.word(3) == spv::BuiltInPointSize) {
pointsize_written = IsPointSizeWritten(src, insn, entrypoint);
}
}
}
insn++;
}
if ((stage == VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT || stage == VK_SHADER_STAGE_GEOMETRY_BIT) &&
!enabled_features.core.shaderTessellationAndGeometryPointSize) {
if (pointsize_written) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_PointSizeBuiltInOverSpecified,
"Pipeline topology is set to POINT_LIST and geometry or tessellation shaders write PointSize which "
"is prohibited when the shaderTessellationAndGeometryPointSize feature is not enabled.");
}
} else if (!pointsize_written) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT,
HandleToUint64(pipeline->pipeline), kVUID_Core_Shader_MissingPointSizeBuiltIn,
"Pipeline topology is set to POINT_LIST, but PointSize is not written to in the shader corresponding to %s.",
string_VkShaderStageFlagBits(stage));
}
return skip;
}
void ValidationStateTracker::RecordPipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, PIPELINE_STATE *pipeline,
PIPELINE_STATE::StageState *stage_state) {
// Validation shouldn't rely on anything in stage state being valid if the spirv isn't
auto module = GetShaderModuleState(pStage->module);
if (!module->has_valid_spirv) return;
// Validation shouldn't rely on anything in stage state being valid if the entrypoint isn't present
auto entrypoint = FindEntrypoint(module, pStage->pName, pStage->stage);
if (entrypoint == module->end()) return;
// Mark accessible ids
stage_state->accessible_ids = MarkAccessibleIds(module, entrypoint);
ProcessExecutionModes(module, entrypoint, pipeline);
stage_state->descriptor_uses =
CollectInterfaceByDescriptorSlot(report_data, module, stage_state->accessible_ids, &stage_state->has_writable_descriptor);
// Capture descriptor uses for the pipeline
for (auto use : stage_state->descriptor_uses) {
// While validating shaders capture which slots are used by the pipeline
auto &reqs = pipeline->active_slots[use.first.first][use.first.second];
reqs = descriptor_req(reqs | DescriptorTypeToReqs(module, use.second.type_id));
}
}
bool CoreChecks::ValidatePipelineShaderStage(VkPipelineShaderStageCreateInfo const *pStage, const PIPELINE_STATE *pipeline,
const PIPELINE_STATE::StageState &stage_state, const SHADER_MODULE_STATE *module,
const spirv_inst_iter &entrypoint, bool check_point_size) const {
bool skip = false;
// Check the module
if (!module->has_valid_spirv) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineShaderStageCreateInfo-module-parameter", "%s does not contain valid spirv for stage %s.",
report_data->FormatHandle(module->vk_shader_module).c_str(), string_VkShaderStageFlagBits(pStage->stage));
}
// Check the entrypoint
if (entrypoint == module->end()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkPipelineShaderStageCreateInfo-pName-00707", "No entrypoint found named `%s` for stage %s..",
pStage->pName, string_VkShaderStageFlagBits(pStage->stage));
}
if (skip) return true; // no point continuing beyond here, any analysis is just going to be garbage.
// Mark accessible ids
auto &accessible_ids = stage_state.accessible_ids;
// Validate descriptor set layout against what the entrypoint actually uses
bool has_writable_descriptor = stage_state.has_writable_descriptor;
auto &descriptor_uses = stage_state.descriptor_uses;
// Validate shader capabilities against enabled device features
skip |= ValidateShaderCapabilities(module, pStage->stage);
skip |= ValidateShaderStageWritableDescriptor(pStage->stage, has_writable_descriptor);
skip |= ValidateShaderStageInputOutputLimits(module, pStage, pipeline, entrypoint);
skip |= ValidateShaderStageGroupNonUniform(module, pStage->stage, accessible_ids);
skip |= ValidateExecutionModes(module, entrypoint);
skip |= ValidateSpecializationOffsets(report_data, pStage);
skip |= ValidatePushConstantUsage(report_data, pipeline->pipeline_layout.push_constant_ranges.get(), module, accessible_ids,
pStage->stage);
if (check_point_size && !pipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable) {
skip |= ValidatePointListShaderState(pipeline, module, entrypoint, pStage->stage);
}
skip |= ValidateCooperativeMatrix(module, pStage, pipeline);
// Validate descriptor use
for (auto use : descriptor_uses) {
// Verify given pipelineLayout has requested setLayout with requested binding
const auto &binding = GetDescriptorBinding(&pipeline->pipeline_layout, use.first);
unsigned required_descriptor_count;
std::set<uint32_t> descriptor_types = TypeToDescriptorTypeSet(module, use.second.type_id, required_descriptor_count);
if (!binding) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_MissingDescriptor,
"Shader uses descriptor slot %u.%u (expected `%s`) but not declared in pipeline layout",
use.first.first, use.first.second, string_descriptorTypes(descriptor_types).c_str());
} else if (~binding->stageFlags & pStage->stage) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, 0,
kVUID_Core_Shader_DescriptorNotAccessibleFromStage,
"Shader uses descriptor slot %u.%u but descriptor not accessible from stage %s", use.first.first,
use.first.second, string_VkShaderStageFlagBits(pStage->stage));
} else if (descriptor_types.find(binding->descriptorType) == descriptor_types.end()) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_DescriptorTypeMismatch,
"Type mismatch on descriptor slot %u.%u (expected `%s`) but descriptor of type %s", use.first.first,
use.first.second, string_descriptorTypes(descriptor_types).c_str(),
string_VkDescriptorType(binding->descriptorType));
} else if (binding->descriptorCount < required_descriptor_count) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_DescriptorTypeMismatch,
"Shader expects at least %u descriptors for binding %u.%u but only %u provided",
required_descriptor_count, use.first.first, use.first.second, binding->descriptorCount);
}
}
// Validate use of input attachments against subpass structure
if (pStage->stage == VK_SHADER_STAGE_FRAGMENT_BIT) {
auto input_attachment_uses = CollectInterfaceByInputAttachmentIndex(module, accessible_ids);
auto rpci = pipeline->rp_state->createInfo.ptr();
auto subpass = pipeline->graphicsPipelineCI.subpass;
for (auto use : input_attachment_uses) {
auto input_attachments = rpci->pSubpasses[subpass].pInputAttachments;
auto index = (input_attachments && use.first < rpci->pSubpasses[subpass].inputAttachmentCount)
? input_attachments[use.first].attachment
: VK_ATTACHMENT_UNUSED;
if (index == VK_ATTACHMENT_UNUSED) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_MissingInputAttachment,
"Shader consumes input attachment index %d but not provided in subpass", use.first);
} else if (!(GetFormatType(rpci->pAttachments[index].format) & GetFundamentalType(module, use.second.type_id))) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
kVUID_Core_Shader_InputAttachmentTypeMismatch,
"Subpass input attachment %u format of %s does not match type used in shader `%s`", use.first,
string_VkFormat(rpci->pAttachments[index].format), DescribeType(module, use.second.type_id).c_str());
}
}
}
if (pStage->stage == VK_SHADER_STAGE_COMPUTE_BIT) {
skip |= ValidateComputeWorkGroupSizes(module);
}
return skip;
}
static bool ValidateInterfaceBetweenStages(debug_report_data const *report_data, SHADER_MODULE_STATE const *producer,
spirv_inst_iter producer_entrypoint, shader_stage_attributes const *producer_stage,
SHADER_MODULE_STATE const *consumer, spirv_inst_iter consumer_entrypoint,
shader_stage_attributes const *consumer_stage) {
bool skip = false;
auto outputs =
CollectInterfaceByLocation(producer, producer_entrypoint, spv::StorageClassOutput, producer_stage->arrayed_output);
auto inputs = CollectInterfaceByLocation(consumer, consumer_entrypoint, spv::StorageClassInput, consumer_stage->arrayed_input);
auto a_it = outputs.begin();
auto b_it = inputs.begin();
// Maps sorted by key (location); walk them together to find mismatches
while ((outputs.size() > 0 && a_it != outputs.end()) || (inputs.size() && b_it != inputs.end())) {
bool a_at_end = outputs.size() == 0 || a_it == outputs.end();
bool b_at_end = inputs.size() == 0 || b_it == inputs.end();
auto a_first = a_at_end ? std::make_pair(0u, 0u) : a_it->first;
auto b_first = b_at_end ? std::make_pair(0u, 0u) : b_it->first;
if (b_at_end || ((!a_at_end) && (a_first < b_first))) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_OutputNotConsumed,
"%s writes to output location %u.%u which is not consumed by %s", producer_stage->name, a_first.first,
a_first.second, consumer_stage->name);
a_it++;
} else if (a_at_end || a_first > b_first) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(consumer->vk_shader_module), kVUID_Core_Shader_InputNotProduced,
"%s consumes input location %u.%u which is not written by %s", consumer_stage->name, b_first.first,
b_first.second, producer_stage->name);
b_it++;
} else {
// subtleties of arrayed interfaces:
// - if is_patch, then the member is not arrayed, even though the interface may be.
// - if is_block_member, then the extra array level of an arrayed interface is not
// expressed in the member type -- it's expressed in the block type.
if (!TypesMatch(producer, consumer, a_it->second.type_id, b_it->second.type_id,
producer_stage->arrayed_output && !a_it->second.is_patch && !a_it->second.is_block_member,
consumer_stage->arrayed_input && !b_it->second.is_patch && !b_it->second.is_block_member, true)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Type mismatch on location %u.%u: '%s' vs '%s'", a_first.first, a_first.second,
DescribeType(producer, a_it->second.type_id).c_str(),
DescribeType(consumer, b_it->second.type_id).c_str());
}
if (a_it->second.is_patch != b_it->second.is_patch) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Decoration mismatch on location %u.%u: is per-%s in %s stage but per-%s in %s stage",
a_first.first, a_first.second, a_it->second.is_patch ? "patch" : "vertex", producer_stage->name,
b_it->second.is_patch ? "patch" : "vertex", consumer_stage->name);
}
if (a_it->second.is_relaxed_precision != b_it->second.is_relaxed_precision) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Decoration mismatch on location %u.%u: %s and %s stages differ in precision", a_first.first,
a_first.second, producer_stage->name, consumer_stage->name);
}
a_it++;
b_it++;
}
}
if (consumer_stage->stage != VK_SHADER_STAGE_FRAGMENT_BIT) {
auto builtins_producer = CollectBuiltinBlockMembers(producer, producer_entrypoint, spv::StorageClassOutput);
auto builtins_consumer = CollectBuiltinBlockMembers(consumer, consumer_entrypoint, spv::StorageClassInput);
if (!builtins_producer.empty() && !builtins_consumer.empty()) {
if (builtins_producer.size() != builtins_consumer.size()) {
skip |=
log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Number of elements inside builtin block differ between stages (%s %d vs %s %d).", producer_stage->name,
(int)builtins_producer.size(), consumer_stage->name, (int)builtins_consumer.size());
} else {
auto it_producer = builtins_producer.begin();
auto it_consumer = builtins_consumer.begin();
while (it_producer != builtins_producer.end() && it_consumer != builtins_consumer.end()) {
if (*it_producer != *it_consumer) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(producer->vk_shader_module), kVUID_Core_Shader_InterfaceTypeMismatch,
"Builtin variable inside block doesn't match between %s and %s.", producer_stage->name,
consumer_stage->name);
break;
}
it_producer++;
it_consumer++;
}
}
}
}
return skip;
}
static inline uint32_t DetermineFinalGeomStage(const PIPELINE_STATE *pipeline, const VkGraphicsPipelineCreateInfo *pCreateInfo) {
uint32_t stage_mask = 0;
if (pipeline->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_POINT_LIST) {
for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
stage_mask |= pCreateInfo->pStages[i].stage;
}
// Determine which shader in which PointSize should be written (the final geometry stage)
if (stage_mask & VK_SHADER_STAGE_MESH_BIT_NV) {
stage_mask = VK_SHADER_STAGE_MESH_BIT_NV;
} else if (stage_mask & VK_SHADER_STAGE_GEOMETRY_BIT) {
stage_mask = VK_SHADER_STAGE_GEOMETRY_BIT;
} else if (stage_mask & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) {
stage_mask = VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT;
} else if (stage_mask & VK_SHADER_STAGE_VERTEX_BIT) {
stage_mask = VK_SHADER_STAGE_VERTEX_BIT;
}
}
return stage_mask;
}
// Validate that the shaders used by the given pipeline and store the active_slots
// that are actually used by the pipeline into pPipeline->active_slots
bool CoreChecks::ValidateGraphicsPipelineShaderState(const PIPELINE_STATE *pipeline) const {
auto pCreateInfo = pipeline->graphicsPipelineCI.ptr();
int vertex_stage = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
int fragment_stage = GetShaderStageId(VK_SHADER_STAGE_FRAGMENT_BIT);
const SHADER_MODULE_STATE *shaders[32];
memset(shaders, 0, sizeof(shaders));
spirv_inst_iter entrypoints[32];
memset(entrypoints, 0, sizeof(entrypoints));
bool skip = false;
uint32_t pointlist_stage_mask = DetermineFinalGeomStage(pipeline, pCreateInfo);
for (uint32_t i = 0; i < pCreateInfo->stageCount; i++) {
auto pStage = &pCreateInfo->pStages[i];
auto stage_id = GetShaderStageId(pStage->stage);
shaders[stage_id] = GetShaderModuleState(pStage->module);
entrypoints[stage_id] = FindEntrypoint(shaders[stage_id], pStage->pName, pStage->stage);
skip |= ValidatePipelineShaderStage(pStage, pipeline, pipeline->stage_state[i], shaders[stage_id], entrypoints[stage_id],
(pointlist_stage_mask == pStage->stage));
}
// if the shader stages are no good individually, cross-stage validation is pointless.
if (skip) return true;
auto vi = pCreateInfo->pVertexInputState;
if (vi) {
skip |= ValidateViConsistency(report_data, vi);
}
if (shaders[vertex_stage] && shaders[vertex_stage]->has_valid_spirv) {
skip |= ValidateViAgainstVsInputs(report_data, vi, shaders[vertex_stage], entrypoints[vertex_stage]);
}
int producer = GetShaderStageId(VK_SHADER_STAGE_VERTEX_BIT);
int consumer = GetShaderStageId(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT);
while (!shaders[producer] && producer != fragment_stage) {
producer++;
consumer++;
}
for (; producer != fragment_stage && consumer <= fragment_stage; consumer++) {
assert(shaders[producer]);
if (shaders[consumer]) {
if (shaders[consumer]->has_valid_spirv && shaders[producer]->has_valid_spirv) {
skip |= ValidateInterfaceBetweenStages(report_data, shaders[producer], entrypoints[producer],
&shader_stage_attribs[producer], shaders[consumer], entrypoints[consumer],
&shader_stage_attribs[consumer]);
}
producer = consumer;
}
}
if (shaders[fragment_stage] && shaders[fragment_stage]->has_valid_spirv) {
skip |= ValidateFsOutputsAgainstRenderPass(report_data, shaders[fragment_stage], entrypoints[fragment_stage], pipeline,
pCreateInfo->subpass);
}
return skip;
}
bool CoreChecks::ValidateComputePipeline(PIPELINE_STATE *pipeline) const {
const auto &stage = *pipeline->computePipelineCI.stage.ptr();
const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
return ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[0], module, entrypoint, false);
}
bool CoreChecks::ValidateRayTracingPipelineNV(PIPELINE_STATE *pipeline) const {
bool skip = false;
for (uint32_t stage_index = 0; stage_index < pipeline->raytracingPipelineCI.stageCount; stage_index++) {
const auto &stage = pipeline->raytracingPipelineCI.ptr()->pStages[stage_index];
const SHADER_MODULE_STATE *module = GetShaderModuleState(stage.module);
const spirv_inst_iter entrypoint = FindEntrypoint(module, stage.pName, stage.stage);
skip |= ValidatePipelineShaderStage(&stage, pipeline, pipeline->stage_state[stage_index], module, entrypoint, false);
}
return skip;
}
uint32_t ValidationCache::MakeShaderHash(VkShaderModuleCreateInfo const *smci) { return XXH32(smci->pCode, smci->codeSize, 0); }
static ValidationCache *GetValidationCacheInfo(VkShaderModuleCreateInfo const *pCreateInfo) {
const auto validation_cache_ci = lvl_find_in_chain<VkShaderModuleValidationCacheCreateInfoEXT>(pCreateInfo->pNext);
if (validation_cache_ci) {
return CastFromHandle<ValidationCache *>(validation_cache_ci->validationCache);
}
return nullptr;
}
bool CoreChecks::PreCallValidateCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule) {
bool skip = false;
spv_result_t spv_valid = SPV_SUCCESS;
if (disabled.shader_validation) {
return false;
}
auto have_glsl_shader = device_extensions.vk_nv_glsl_shader;
if (!have_glsl_shader && (pCreateInfo->codeSize % 4)) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0,
"VUID-VkShaderModuleCreateInfo-pCode-01376",
"SPIR-V module not valid: Codesize must be a multiple of 4 but is " PRINTF_SIZE_T_SPECIFIER ".",
pCreateInfo->codeSize);
} else {
auto cache = GetValidationCacheInfo(pCreateInfo);
uint32_t hash = 0;
if (cache) {
hash = ValidationCache::MakeShaderHash(pCreateInfo);
if (cache->Contains(hash)) return false;
}
// Use SPIRV-Tools validator to try and catch any issues with the module itself
spv_target_env spirv_environment = SPV_ENV_VULKAN_1_0;
if (api_version >= VK_API_VERSION_1_1) {
spirv_environment = SPV_ENV_VULKAN_1_1;
}
spv_context ctx = spvContextCreate(spirv_environment);
spv_const_binary_t binary{pCreateInfo->pCode, pCreateInfo->codeSize / sizeof(uint32_t)};
spv_diagnostic diag = nullptr;
spv_validator_options options = spvValidatorOptionsCreate();
if (device_extensions.vk_khr_relaxed_block_layout) {
spvValidatorOptionsSetRelaxBlockLayout(options, true);
}
if (device_extensions.vk_khr_uniform_buffer_standard_layout &&
enabled_features.uniform_buffer_standard_layout.uniformBufferStandardLayout == VK_TRUE) {
spvValidatorOptionsSetUniformBufferStandardLayout(options, true);
}
if (device_extensions.vk_ext_scalar_block_layout &&
enabled_features.scalar_block_layout_features.scalarBlockLayout == VK_TRUE) {
spvValidatorOptionsSetScalarBlockLayout(options, true);
}
spv_valid = spvValidateWithOptions(ctx, options, &binary, &diag);
if (spv_valid != SPV_SUCCESS) {
if (!have_glsl_shader || (pCreateInfo->pCode[0] == spv::MagicNumber)) {
skip |=
log_msg(report_data, spv_valid == SPV_WARNING ? VK_DEBUG_REPORT_WARNING_BIT_EXT : VK_DEBUG_REPORT_ERROR_BIT_EXT,
VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_Shader_InconsistentSpirv,
"SPIR-V module not valid: %s", diag && diag->error ? diag->error : "(no error text)");
}
} else {
if (cache) {
cache->Insert(hash);
}
}
spvValidatorOptionsDestroy(options);
spvDiagnosticDestroy(diag);
spvContextDestroy(ctx);
}
return skip;
}
void CoreChecks::PreCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator, VkShaderModule *pShaderModule,
void *csm_state_data) {
create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
if (enabled.gpu_validation) {
GpuPreCallCreateShaderModule(pCreateInfo, pAllocator, pShaderModule, &csm_state->unique_shader_id,
&csm_state->instrumented_create_info, &csm_state->instrumented_pgm);
}
}
void ValidationStateTracker::PostCallRecordCreateShaderModule(VkDevice device, const VkShaderModuleCreateInfo *pCreateInfo,
const VkAllocationCallbacks *pAllocator,
VkShaderModule *pShaderModule, VkResult result,
void *csm_state_data) {
if (VK_SUCCESS != result) return;
create_shader_module_api_state *csm_state = reinterpret_cast<create_shader_module_api_state *>(csm_state_data);
spv_target_env spirv_environment = ((api_version >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0);
bool is_spirv = (pCreateInfo->pCode[0] == spv::MagicNumber);
std::unique_ptr<SHADER_MODULE_STATE> new_shader_module(
is_spirv ? new SHADER_MODULE_STATE(pCreateInfo, *pShaderModule, spirv_environment, csm_state->unique_shader_id)
: new SHADER_MODULE_STATE());
shaderModuleMap[*pShaderModule] = std::move(new_shader_module);
}
bool CoreChecks::ValidateComputeWorkGroupSizes(const SHADER_MODULE_STATE *shader) const {
bool skip = false;
uint32_t local_size_x = 0;
uint32_t local_size_y = 0;
uint32_t local_size_z = 0;
if (FindLocalSize(shader, local_size_x, local_size_y, local_size_z)) {
if (local_size_x > phys_dev_props.limits.maxComputeWorkGroupSize[0]) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
"%s local_size_x (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[0] (%" PRIu32 ").",
report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
phys_dev_props.limits.maxComputeWorkGroupSize[0]);
}
if (local_size_y > phys_dev_props.limits.maxComputeWorkGroupSize[1]) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
"%s local_size_y (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[1] (%" PRIu32 ").",
report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
phys_dev_props.limits.maxComputeWorkGroupSize[1]);
}
if (local_size_z > phys_dev_props.limits.maxComputeWorkGroupSize[2]) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupSize",
"%s local_size_z (%" PRIu32 ") exceeds device limit maxComputeWorkGroupSize[2] (%" PRIu32 ").",
report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x,
phys_dev_props.limits.maxComputeWorkGroupSize[2]);
}
uint32_t limit = phys_dev_props.limits.maxComputeWorkGroupInvocations;
uint64_t invocations = local_size_x * local_size_y;
// Prevent overflow.
bool fail = false;
if (invocations > UINT32_MAX || invocations > limit) {
fail = true;
}
if (!fail) {
invocations *= local_size_z;
if (invocations > UINT32_MAX || invocations > limit) {
fail = true;
}
}
if (fail) {
skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SHADER_MODULE_EXT,
HandleToUint64(shader->vk_shader_module), "UNASSIGNED-features-limits-maxComputeWorkGroupInvocations",
"%s local_size (%" PRIu32 ", %" PRIu32 ", %" PRIu32
") exceeds device limit maxComputeWorkGroupInvocations (%" PRIu32 ").",
report_data->FormatHandle(shader->vk_shader_module).c_str(), local_size_x, local_size_y, local_size_z,
limit);
}
}
return skip;
}
|
; A017084: a(n) = (8*n + 1)^8.
; 1,43046721,6975757441,152587890625,1406408618241,7984925229121,33232930569601,111429157112001,318644812890625,806460091894081,1853020188851841,3936588805702081,7837433594376961,14774554437890625,26584441929064321,45949729863572161,76686282021340161,124097929967680321,195408755062890625,300283484326400961,451447246258894081,665416609183179841,963354501121950081,1372062286687890625,1925122952918976001,2664210032449121601,3640577568861717121,4916747105530914241,6568408355712890625,8686550888106661441,11379844838561358721,14777289335064248001,19031147999601100801,24320191566937890625,30853268336830129281,38873223852623509441,48661191875666868481,60541279401415837761,74885669139562890625,92120163556986851521,112730195258772277761,137267329159006474561,166356282569519253121,200702490011187890625,241100240228887100161,288441413567621167681,343724848543832762241,408066367122340274881,482709488885812890625,569036864960149947201,668582463235588483201,783044537099820227521,914299410575856631041,1064416113433837890625,1235671900522439264641,1430568690241985328321,1651850457757840166401,1902521619229098849601,2185866444004062890625,2505469532410439724481,2865237397444663607041,3269421189341192674881,3722640602679094258561,4229909006359687890625,4796659837465472798721,5428774300687024023361,6132610415680998648961,6915033455398850985921,7783447819102312890625,8745830384458152759361,9810765383781184081281,10987480850170951784641,12285886679963981959681,13716614358599937890625,15291058397676482678401,17021419531644106084801,18920749723268630577921,21002999027665568907841,23283064365386962890625,25776840255717790427841,28501271562015485137921,31474408301602570324801,34715462573398866358401,38244867657156187890625,42084339338834904679681,46256939517338197144641,50787142148496295121281,55700901582869445639361,61025723354614812890625,66790737479338970905921,73026774319534106808961,79766443076872509863361,87044212971310378878721,94896497167628437890625,103361739510713307378561,112480504131560035634881,122295567986652652247041,132852016394056063004481,144197341630229062890625,156381544652244701169601
mul $0,8
add $0,1
pow $0,8
|
#include <iostream>
#include <algorithm>
using namespace std;
int n, m;
char board[50][50];
int minimum = 1234567890;
void Solve(const int row, const int col)
{
int repaint1, repaint2;
repaint1 = repaint2 = 0;
for (int i = row; i < row + 8; i++)
{
for (int j = col; j < col + 8; j++)
{
if ((i + j - row - col) % 2 == 0)
{
if (board[i][j] == 'W')
repaint2++;
else
repaint1++;
}
else
{
if (board[i][j] == 'W')
repaint1++;
else
repaint2++;
}
}
}
minimum = min({ minimum, repaint1, repaint2 });
}
int main(void)
{
cin.tie(NULL);
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> board[i][j];
for (int i = 0; i <= n - 8; i++)
for (int j = 0; j <= m - 8; j++)
Solve(i, j);
cout << minimum << '\n';
return 0;
} |
; A097110: Expansion of (1 + 2x - 2x^3) / (1 - 3x^2 + 2x^4).
; 1,2,3,4,7,8,15,16,31,32,63,64,127,128,255,256,511,512,1023,1024,2047,2048,4095,4096,8191,8192,16383,16384,32767,32768,65535,65536,131071,131072,262143,262144,524287,524288,1048575,1048576,2097151,2097152
mov $1,2
lpb $0
sub $0,2
mul $1,2
lpe
add $1,$0
sub $1,1
mov $0,$1
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/accessanalyzer/model/ArchiveRuleSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace AccessAnalyzer
{
namespace Model
{
ArchiveRuleSummary::ArchiveRuleSummary() :
m_createdAtHasBeenSet(false),
m_filterHasBeenSet(false),
m_ruleNameHasBeenSet(false),
m_updatedAtHasBeenSet(false)
{
}
ArchiveRuleSummary::ArchiveRuleSummary(JsonView jsonValue) :
m_createdAtHasBeenSet(false),
m_filterHasBeenSet(false),
m_ruleNameHasBeenSet(false),
m_updatedAtHasBeenSet(false)
{
*this = jsonValue;
}
ArchiveRuleSummary& ArchiveRuleSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("createdAt"))
{
m_createdAt = jsonValue.GetString("createdAt");
m_createdAtHasBeenSet = true;
}
if(jsonValue.ValueExists("filter"))
{
Aws::Map<Aws::String, JsonView> filterJsonMap = jsonValue.GetObject("filter").GetAllObjects();
for(auto& filterItem : filterJsonMap)
{
m_filter[filterItem.first] = filterItem.second.AsObject();
}
m_filterHasBeenSet = true;
}
if(jsonValue.ValueExists("ruleName"))
{
m_ruleName = jsonValue.GetString("ruleName");
m_ruleNameHasBeenSet = true;
}
if(jsonValue.ValueExists("updatedAt"))
{
m_updatedAt = jsonValue.GetString("updatedAt");
m_updatedAtHasBeenSet = true;
}
return *this;
}
JsonValue ArchiveRuleSummary::Jsonize() const
{
JsonValue payload;
if(m_createdAtHasBeenSet)
{
payload.WithString("createdAt", m_createdAt.ToGmtString(DateFormat::ISO_8601));
}
if(m_filterHasBeenSet)
{
JsonValue filterJsonMap;
for(auto& filterItem : m_filter)
{
filterJsonMap.WithObject(filterItem.first, filterItem.second.Jsonize());
}
payload.WithObject("filter", std::move(filterJsonMap));
}
if(m_ruleNameHasBeenSet)
{
payload.WithString("ruleName", m_ruleName);
}
if(m_updatedAtHasBeenSet)
{
payload.WithString("updatedAt", m_updatedAt.ToGmtString(DateFormat::ISO_8601));
}
return payload;
}
} // namespace Model
} // namespace AccessAnalyzer
} // namespace Aws
|
; this function is used to display sign messages, sprite dialog, etc.
; INPUT: [hSpriteIndexOrTextID] = sprite ID or text ID
DisplayTextID::
ldh a, [hLoadedROMBank]
push af
farcall DisplayTextIDInit ; initialization
ld hl, wTextPredefFlag
bit 0, [hl]
res 0, [hl]
jr nz, .skipSwitchToMapBank
ld a, [wCurMap]
call SwitchToMapRomBank
.skipSwitchToMapBank
ld a, 30 ; half a second
ldh [hFrameCounter], a ; used as joypad poll timer
ld hl, wMapTextPtr
ld a, [hli]
ld h, [hl]
ld l, a ; hl = map text pointer
ld d, $00
ldh a, [hSpriteIndexOrTextID] ; text ID
ld [wSpriteIndex], a
dict TEXT_START_MENU, DisplayStartMenu
dict TEXT_SAFARI_GAME_OVER, DisplaySafariGameOverText
dict TEXT_MON_FAINTED, DisplayPokemonFaintedText
dict TEXT_BLACKED_OUT, DisplayPlayerBlackedOutText
dict TEXT_REPEL_WORE_OFF, DisplayRepelWoreOffText
ld a, [wNumSprites]
ld e, a
ldh a, [hSpriteIndexOrTextID] ; sprite ID
cp e
jr z, .spriteHandling
jr nc, .skipSpriteHandling
.spriteHandling
; get the text ID of the sprite
push hl
push de
push bc
farcall UpdateSpriteFacingOffsetAndDelayMovement ; update the graphics of the sprite the player is talking to (to face the right direction)
pop bc
pop de
ld hl, wMapSpriteData ; NPC text entries
ldh a, [hSpriteIndexOrTextID]
dec a
add a
add l
ld l, a
jr nc, .noCarry
inc h
.noCarry
inc hl
ld a, [hl] ; a = text ID of the sprite
pop hl
.skipSpriteHandling
; look up the address of the text in the map's text entries
dec a
ld e, a
sla e
add hl, de
ld a, [hli]
ld h, [hl]
ld l, a ; hl = address of the text
ld a, [hl] ; a = first byte of text
; check first byte of text for special cases
dict2: MACRO
cp \1
jr nz, .not\@
\2
jr AfterDisplayingTextID
.not\@
ENDM
dict TX_SCRIPT_MART, DisplayPokemartDialogue
dict TX_SCRIPT_POKECENTER_NURSE, DisplayPokemonCenterDialogue
dict TX_SCRIPT_PLAYERS_PC, TextScript_ItemStoragePC
dict TX_SCRIPT_BILLS_PC, TextScript_BillsPC
dict TX_SCRIPT_POKECENTER_PC, TextScript_PokemonCenterPC
dict2 TX_SCRIPT_VENDING_MACHINE, farcall VendingMachineMenu
dict TX_SCRIPT_PRIZE_VENDOR, TextScript_GameCornerPrizeMenu
dict2 TX_SCRIPT_CABLE_CLUB_RECEPTIONIST, callfar CableClubNPC
call PrintText_NoCreatingTextBox ; display the text
ld a, [wDoNotWaitForButtonPressAfterDisplayingText]
and a
jr nz, HoldTextDisplayOpen
AfterDisplayingTextID::
ld a, [wEnteringCableClub]
and a
jr nz, HoldTextDisplayOpen
call WaitForTextScrollButtonPress ; wait for a button press after displaying all the text
; loop to hold the dialogue box open as long as the player keeps holding down the A button
HoldTextDisplayOpen::
call Joypad
ldh a, [hJoyHeld]
bit 0, a ; is the A button being pressed?
jr nz, HoldTextDisplayOpen
CloseTextDisplay::
ld a, [wCurMap]
call SwitchToMapRomBank
ld a, $90
ldh [hWY], a ; move the window off the screen
call DelayFrame
call LoadGBPal
xor a
ldh [hAutoBGTransferEnabled], a ; disable continuous WRAM to VRAM transfer each V-blank
; loop to make sprites face the directions they originally faced before the dialogue
ld hl, wSprite01StateData2OrigFacingDirection
ld c, $0f
ld de, $10
.restoreSpriteFacingDirectionLoop
ld a, [hl] ; x#SPRITESTATEDATA2_ORIGFACINGDIRECTION
dec h
ld [hl], a ; [x#SPRITESTATEDATA1_FACINGDIRECTION]
inc h
add hl, de
dec c
jr nz, .restoreSpriteFacingDirectionLoop
ld a, BANK(InitMapSprites)
ldh [hLoadedROMBank], a
ld [MBC1RomBank], a
call InitMapSprites ; reload sprite tile pattern data (since it was partially overwritten by text tile patterns)
ld hl, wFontLoaded
res 0, [hl]
ld a, [wd732]
bit 3, a ; used fly warp
call z, LoadPlayerSpriteGraphics
call LoadCurrentMapView
pop af
ldh [hLoadedROMBank], a
ld [MBC1RomBank], a
jp UpdateSprites
DisplayPokemartDialogue::
push hl
ld hl, PokemartGreetingText
call PrintText
pop hl
inc hl
call LoadItemList
ld a, PRICEDITEMLISTMENU
ld [wListMenuID], a
homecall DisplayPokemartDialogue_
jp AfterDisplayingTextID
PokemartGreetingText::
text_far _PokemartGreetingText
text_end
LoadItemList::
ld a, 1
ld [wUpdateSpritesEnabled], a
ld a, h
ld [wItemListPointer], a
ld a, l
ld [wItemListPointer + 1], a
ld de, wItemList
.loop
ld a, [hli]
ld [de], a
inc de
cp $ff
jr nz, .loop
ret
DisplayPokemonCenterDialogue::
; zeroing these doesn't appear to serve any purpose
xor a
ldh [hItemPrice], a
ldh [hItemPrice + 1], a
ldh [hItemPrice + 2], a
inc hl
homecall DisplayPokemonCenterDialogue_
jp AfterDisplayingTextID
DisplaySafariGameOverText::
callfar PrintSafariGameOverText
jp AfterDisplayingTextID
DisplayPokemonFaintedText::
ld hl, PokemonFaintedText
call PrintText
jp AfterDisplayingTextID
PokemonFaintedText::
text_far _PokemonFaintedText
text_end
DisplayPlayerBlackedOutText::
ld hl, PlayerBlackedOutText
call PrintText
ld a, [wd732]
res 5, a ; reset forced to use bike bit
ld [wd732], a
jp HoldTextDisplayOpen
PlayerBlackedOutText::
text_far _PlayerBlackedOutText
text_end
DisplayRepelWoreOffText::
ld hl, RepelWoreOffText
call PrintText
jp AfterDisplayingTextID
RepelWoreOffText::
text_far _RepelWoreOffText
text_end
|
; A184615: Positive parts of the nonadjacent forms for n
; 0,1,2,4,4,5,8,8,8,9,10,16,16,17,16,16,16,17,18,20,20,21,32,32,32,33,34,32,32,33,32,32,32,33,34,36,36,37,40,40,40,41,42,64,64,65,64,64,64,65,66,68,68,69,64,64,64,65,66,64,64,65,64,64,64,65,66,68,68,69,72,72,72,73,74,80,80,81,80,80,80,81,82,84,84,85,128,128,128,129,130,128,128,129,128,128,128,129,130,132
mov $1,$0
seq $1,184617 ; With nonadjacent forms: A184615(n) + A184616(n).
add $0,$1
div $0,2
|
hook_token_stop := $d9 - $ce
hook_parser:
db $83 ; hook signifier
cp a,2
jr z,.maybe_stop
xor a,a
ret
.maybe_stop:
ld a,hook_token_stop ; check if stop token
cp a,b
ld a,ti.E_AppErr1
jp z,ti.JError
xor a,a
ret
hook_app_change:
db $83
ld c,a ; huh
ld a,b
cp a,ti.cxPrgmEdit ; only allow when editing
ld b,a
ret nz
ld a,c
cp a,ti.cxMode
ret z
cp a,ti.cxFormat
ret z
cp a,ti.cxTableSet
ret z
jr .wut
;ld a,c
;cp a,ti.kEnter ; wut ti, this is how you run a program?
;jr nz,.wut
;push hl
;call ti.PopOP1
;pop hl
;ret
.wut:
call ti.CursorOff
call ti.CloseEditEqu
call ti.PopOP1
call ti.ChkFindSym
jr c,.dont_archive
;ld a,(edit_status)
;or a,a
;call nz,cesium.Arc_Unarc
call cesium.Arc_Unarc
.dont_archive:
ld a,return_prgm
ld (return_info),a
jp bos_start
hook_get_key:
db $83
cp a,$1b
ret nz
ld a,b
push af
push hl
ld hl,$f0202c
ld (hl),l
ld l,h
bit 0,(hl)
pop hl
jr nz,.check_for_shortcut_key
pop af
cp a,ti.sk2nd
ret nz
ld a,ti.sk2nd - 1 ; maybe some other day
inc a
ret
.check_for_shortcut_key:
pop af
cp a,ti.skGraph
jr z,hook_show_labels
cp a,ti.skMatrix
jq z,hook_execute_cesium
ret
label_number := ti.cursorImage + 3
label_number_of_pages := label_number + 3
label_page := label_number_of_pages + 3
label_name := label_page + 3
hook_show_labels:
di
ld a,(ti.cxCurApp)
cp a,ti.cxPrgmEdit
jq nz,hook_get_key_none
hook_strings.copy
call ti.CursorOff
or a,a
sbc hl,hl
ld (label_number),hl
ld (label_page),hl
call ti.ClrTxtShd
call ti.BufToTop
call .countlabels
ld bc,0
ld hl,(label_number)
add hl,de
or a,a
sbc hl,de
jq z,.movetolabel
.getlabelloop:
call ti.ClrScrn
call .drawlabels
ld hl,(label_page)
ld de,.current_page_string
inc hl
call helper_num_convert
ld hl,.page_string
call helper_vputs_toolbar
.getkey:
di
call ti.DisableAPD
call ti.GetCSC
or a,a
jr z,.getkey
ld bc,1
cp a,ti.sk0
jr z,.movetolabel
inc c
cp a,ti.sk1
jr z,.movetolabel
inc c
cp a,ti.sk2
jr z,.movetolabel
inc c
cp a,ti.sk3
jr z,.movetolabel
inc c
cp a,ti.sk4
jr z,.movetolabel
inc c
cp a,ti.sk5
jr z,.movetolabel
inc c
cp a,ti.sk6
jr z,.movetolabel
inc c
cp a,ti.sk7
jr z,.movetolabel
inc c
cp a,ti.sk8
jr z,.movetolabel
inc c
cp a,ti.sk9
jr z,.movetolabel
cp a,ti.skLeft
jq z,.prevpage
cp a,ti.skRight
jr z,.nextpage
jr .getkey
.movetolabel:
ld a,(ti.curRow)
cp a,c
jr z,.okay
jr c,.getkey
.okay:
call .computepageoffsethl
add hl,bc
push hl
call ti.BufToTop
pop bc
call .skiplabels
call ti.BufLeft
call ti.ClrScrn
xor a,a
ld (ti.curCol),a
ld (ti.curRow),a
ld a,(ti.winTop)
or a,a
jr z,.incesiumeditor ; check if using cesium feature
ld hl,.program_string
call ti.PutS
ld hl,ti.progToEdit
call ti.PutS
call ti.NewLine
.incesiumeditor:
ld a,':'
call ti.PutMap
ld a,1
ld (ti.curCol),a
.backup:
call ti.BufLeft
jr z,.done
ld a,d
or a,a
jr nz,.backup
ld a,e
cp a,ti.tEnter
jr nz,.backup
call ti.BufRight
.done:
call ti.DispEOW
call ti.CursorOn
call ti.DrawStatusBar
jq hook_get_key_none
.nextpage:
ld hl,(label_page)
ld de,(label_number_of_pages)
or a,a
sbc hl,de
add hl,de
jr z,.firstpage
inc hl
jr .setpage
.firstpage:
or a,a
sbc hl,hl
.setpage:
ld (label_page),hl
jq .getlabelloop
.prevpage:
ld hl,(label_page)
add hl,de
or a,a
sbc hl,de
jr z,.lastpage
dec hl
jr .setpage
.lastpage:
ld hl,(label_number_of_pages)
jr .setpage
.countlabels:
call ti.BufToTop
.loop:
call ti.BufRight
jr z,.getnumpages
ld a,d
cp a,ti.t2ByteTok
jr z,.loop
ld a,e
cp a,ti.tLbl
jr nz,.loop
ld hl,(label_number)
inc hl
ld (label_number),hl
jr .loop
.getnumpages:
ld hl,(label_number)
dec hl
ld a,10
call ti.DivHLByA
ld (label_number_of_pages),hl
inc hl
ld de,.total_page_string
jp helper_num_convert
.skiplabelsloop:
push bc
call ti.BufRight
pop bc
ret z
ld a,d
cp a,ti.t2ByteTok
jr z,.skiplabelsloop
ld a,e
cp a,ti.tLbl
jr nz,.skiplabelsloop
dec bc
.skiplabels:
sbc hl,hl
adc hl,bc
jr nz,.skiplabelsloop
ret
.drawlabels:
call ti.BufToTop
xor a,a
ld (ti.curRow),a
ld (ti.curCol),a
call .computepageoffset
call .skiplabels
ld hl,label_name
.parse_labels:
push hl
call ti.BufRight
pop hl
ret z
ld a,d
or a,a
jr nz,.parse_labels
ld a,e
cp a,ti.tLbl
jr nz,.parse_labels
.add_label:
push hl
call ti.BufRight
pop hl
jr z,.added_label
ld a,e
cp a,ti.tColon
jr z,.added_label
cp a,ti.tEnter
jr z,.added_label
ld a,d
or a,a
jr z,.single
ld (hl),a
inc hl
.single:
ld (hl),e
inc hl
jr .add_label
.added_label:
xor a,a
ld (hl),a
ld (ti.curCol),a
ld a,(ti.curRow)
add a,'0'
call ti.PutC
ld a,':'
call ti.PutC
ld hl,label_name
push hl
.displayline:
ld a,(hl)
or a,a
jr z,.leftedge
inc hl
call ti.Isa2ByteTok
ld d,0
jr nz,.singlebyte
.multibyte:
ld d,a
ld e,(hl)
inc hl
jr .getstring
.singlebyte:
ld e,a
.getstring:
push hl
call ti.GetTokString
ld b,(hl)
inc hl
.loopdisplay:
ld a,(ti.curCol)
cp a,$19
jr z,.leftedge
ld a,(hl)
inc hl
call ti.PutC
djnz .loopdisplay
pop hl
jr .displayline
.leftedge:
ld a,(ti.curRow)
inc a
ld (ti.curRow),a
cp a,10
pop hl
ret z
jp .parse_labels
.computepageoffsethl:
push bc
call .computepageoffset
pop bc
ret
.computepageoffset:
ld hl,(label_page)
ld bc,10
call ti._imulu
push hl
pop bc
ret
relocate hook_strings, ti.plotSScreen
.program_string:
db "PROGRAM:",0
.page_string:
db "Use <> to switch page: <"
.current_page_string:
db "000"
db " of "
.total_page_string:
db "000"
db ">",0
end relocate
hook_clear_backup:
call flash_code_copy
call flash_clear_backup
jr hook_get_key_none
hook_restore_ram:
push hl
push af
ld hl,$3c0001
ld a,$a5
cp a,(hl)
jr nz,.none
dec hl
ld a,$5a
cp a,(hl)
jp z,0
.none:
pop af
pop hl
inc a
dec a
ret
hook_get_key_none:
xor a,a
inc a
dec a
ret
hook_execute_cesium:
ld iy,ti.flags
call ti.CursorOff
call ti.RunIndicOff
di
call ti.ClrGetKeyHook
ld a,(ti.menuCurrent)
cp a,ti.kWindow
jr nz,.notinwindow
ld a,ti.kClear
call ti.PullDownChk ; exit from alpha + function menus
.notinwindow:
ld a,ti.kQuit
call ti.PullDownChk ; exit from randInt( and related menus
ld a,ti.kQuit
call ti.NewContext0 ; just attempt a cleanup now
call ti.CursorOff
call ti.RunIndicOff
xor a,a
ld (ti.menuCurrent),a ; make sure we aren't on a menu
ld hl,data_string_bos_name ; execute app
ld de,$d0082e ; I have absolutely no idea what this is
push de
ld bc,8
push bc
ldir
pop bc
pop hl
ld de,ti.progToEdit ; copy it here just to be safe
ldir
ld a,ti.kExtApps
call ti.NewContext0
ld a,ti.kClear
jp ti.JForceCmd
hook_home:
db $83
cp a,3
ret nz
bit appInpPrmptDone,(iy + ti.apiFlg2)
res appInpPrmptDone,(iy + ti.apiFlg2)
ld a,b
ld b,0
ret nz
.restore_home_hooks:
push af
push bc
call ti.ClrHomescreenHook
res appWantHome,(iy + sysHookFlg)
pop bc
pop af
cp a,ti.cxError
jr z,.return_cesium_app
cp a,ti.cxPrgmInput
jr z,.return_cesium_app
ld hl,backup_home_hook_location
ld a,(hl)
or a,a
ret z
push bc
ld hl,(hl)
call ti.SetHomescreenHook
set appWantHome,(iy + sysHookFlg)
pop bc
ret
.return_cesium_app:
bos_code.copy
jp return.user_exit
.save:
xor a,a
sbc hl,hl
bit appWantHome,(iy + sysHookFlg)
jr z,.done
ld hl,(ti.homescreenHookPtr)
.done:
ld (backup_home_hook_location),hl
ret
.put_away:
xor a,a
ld (ti.currLastEntry),a
bit appInpPrmptInit,(iy + ti.apiFlg2)
jr nz,.skip
call ti.ClrHomescreenHook
.skip:
call ti.ReloadAppEntryVecs
call ti.PutAway
ld b,0
ret
.vectors:
dl $f8
dl ti.SaveShadow
dl .put_away
dl ti.RStrShadow
dl $f8
dl $f8
db 0
helper_vputs_toolbar:
di
ld a,$d0
ld mb,a
ld de,$e71c
ld.sis (ti.drawFGColor and $ffff),de
ld.sis de,(ti.statusBarBGColor and $ffff)
ld.sis (ti.drawBGColor and $ffff),de
ld a,14
ld (ti.penRow),a
ld de,2
ld.sis (ti.penCol and $ffff), de
jp ti.VPutS
helper_num_convert:
ld a,4
.entry:
ld bc,-100
call .aqu
ld c,-10
call .aqu
ld c,b
.aqu:
ld a,'0' - 1
.under:
inc a
add hl,bc
jr c,.under
sbc hl,bc
ld (de),a
inc de
ret
|
; A323724: a(n) = n*(2*(n - 2)*n + (-1)^n + 3)/4.
; 0,0,2,6,20,40,78,126,200,288,410,550,732,936,1190,1470,1808,2176,2610,3078,3620,4200,4862,5566,6360,7200,8138,9126,10220,11368,12630,13950,15392,16896,18530,20230,22068,23976,26030,28158,30440,32800,35322,37926,40700
lpb $0
sub $0,1
mov $2,$0
lpb $0
sub $0,1
add $4,$2
lpe
add $3,$2
add $3,1
lpb $4
add $1,$3
trn $4,2
lpe
lpe
|
/*
* Copyright (c) [2020] Huawei Technologies Co., Ltd. All rights reserved.
*
* OpenArkCompiler is licensed under the Mulan Permissive Software License v2.
* You can use this software according to the terms and conditions of the MulanPSL - 2.0.
* You may obtain a copy of MulanPSL - 2.0 at:
*
* https://opensource.org/licenses/MulanPSL-2.0
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR
* FIT FOR A PARTICULAR PURPOSE.
* See the MulanPSL - 2.0 for more details.
*/
#include "mir_type.h"
#include <iostream>
#include <cstring>
#include "mir_symbol.h"
#include "printing.h"
#include "name_mangler.h"
#include "global_tables.h"
#include "mir_builder.h"
#include "cfg_primitive_types.h"
#if MIR_FEATURE_FULL
namespace maple {
#define LOAD_PRIMARY_TYPE_PROPERTY
#include "prim_types.def"
#define LOAD_ALGO_PRIMARY_TYPE
const PrimitiveTypeProperty &GetPrimitiveTypeProperty(PrimType pType) {
switch (pType) {
case PTY_begin:
return PTProperty_begin;
#define PRIMTYPE(P) \
case PTY_##P: \
return PTProperty_##P;
#include "prim_types.def"
#undef PRIMTYPE
case PTY_end:
default:
return PTProperty_end;
}
}
PrimType GetRegPrimType(PrimType primType) {
switch (primType) {
case PTY_i8:
case PTY_i16:
return PTY_i32;
case PTY_u1:
case PTY_u8:
case PTY_u16:
return PTY_u32;
default:
return primType;
}
}
bool VerifyPrimType(PrimType pty1, PrimType pty2) {
switch (pty1) {
case PTY_u1:
case PTY_u8:
case PTY_u16:
case PTY_u32:
case PTY_a32:
return IsUnsignedInteger(pty2);
case PTY_i8:
case PTY_i16:
case PTY_i32:
return IsSignedInteger(pty2);
default:
return pty1 == pty2;
}
}
PrimType GetDynType(PrimType primType) {
#ifdef DYNAMICLANG
switch (primType) {
case PTY_u1:
return PTY_dynbool;
case PTY_i32:
return PTY_dyni32;
case PTY_simplestr:
return PTY_dynstr;
case PTY_simpleobj:
return PTY_dynobj;
case PTY_f32:
return PTY_dynf32;
case PTY_f64:
return PTY_dynf64;
default:
return primType;
}
#else
return primType;
#endif
}
PrimType GetNonDynType(PrimType primType) {
#ifdef DYNAMICLANG
switch (primType) {
case PTY_dynbool:
return PTY_u1;
case PTY_dyni32:
return PTY_i32;
case PTY_dynstr:
return PTY_simplestr;
case PTY_dynobj:
return PTY_simpleobj;
case PTY_dynf32:
return PTY_f32;
case PTY_dynf64:
return PTY_f64;
default:
return primType;
}
#else
return primType;
#endif
}
bool IsNoCvtNeeded(PrimType toType, PrimType fromType) {
switch (toType) {
case PTY_i32:
return fromType == PTY_i16 || fromType == PTY_i8;
case PTY_u32:
return fromType == PTY_u16 || fromType == PTY_u8;
case PTY_u1:
case PTY_u8:
case PTY_u16:
return fromType == PTY_u32;
case PTY_i8:
case PTY_i16:
return fromType == PTY_i32;
case PTY_u64:
return fromType == PTY_ptr;
case PTY_ptr:
return fromType == PTY_u64;
default:
return false;
}
}
// answer in bytes; 0 if unknown
uint32 GetPrimTypeSize(PrimType pty) {
switch (pty) {
case PTY_void:
case PTY_agg:
return 0;
case PTY_ptr:
case PTY_ref:
return POINTER_SIZE;
case PTY_u1:
case PTY_i8:
case PTY_u8:
return 1;
case PTY_i16:
case PTY_u16:
return 2;
case PTY_a32:
case PTY_f32:
case PTY_i32:
case PTY_u32:
case PTY_simplestr:
case PTY_simpleobj:
return 4;
case PTY_a64:
case PTY_c64:
case PTY_f64:
case PTY_i64:
case PTY_u64:
return 8;
case PTY_v4i32:
case PTY_v2i64:
case PTY_v8i16:
case PTY_v16i8:
case PTY_v2f64:
case PTY_v4f32:
return 16;
case PTY_c128:
case PTY_f128:
return 16;
#ifdef DYNAMICLANG
case PTY_dynf32:
case PTY_dyni32:
case PTY_dynstr:
case PTY_dynobj:
case PTY_dynundef:
case PTY_dynnull:
case PTY_dynbool:
return 8;
case PTY_dynany:
case PTY_dynf64:
return 8;
#endif
default:
return 0;
}
}
// answer is n if size in byte is (1<<n) (0: 1B; 1: 2B, 2: 4B, 3: 8B, 4:16B)
uint32 GetPrimTypeP2Size(PrimType pty) {
switch (pty) {
case PTY_ptr:
case PTY_ref:
return POINTER_P2SIZE;
case PTY_u1:
case PTY_i8:
case PTY_u8:
return 0;
case PTY_i16:
case PTY_u16:
return 1;
case PTY_a32:
case PTY_f32:
case PTY_i32:
case PTY_u32:
case PTY_simplestr:
case PTY_simpleobj:
return 2;
case PTY_a64:
case PTY_c64:
case PTY_f64:
case PTY_i64:
case PTY_u64:
return 3;
case PTY_c128:
case PTY_f128:
return 4;
#ifdef DYNAMICLANG
case PTY_dynf32:
case PTY_dyni32:
case PTY_dynstr:
case PTY_dynobj:
case PTY_dynundef:
case PTY_dynnull:
case PTY_dynbool:
return 3;
case PTY_dynany:
case PTY_dynf64:
return 3;
#endif
default:
CHECK_FATAL(false, "Power-of-2 size only applicable to sizes of 1, 2, 4, 8 or 16 bytes.");
return 10;
}
}
const char *GetPrimTypeName(PrimType ty) {
#define LOAD_ALGO_PRIMARY_TYPE
switch (ty) {
case kPtyInvalid:
return "kPtyInvalid";
#define PRIMTYPE(P) \
case PTY_##P: \
return #P;
#include "prim_types.def"
#undef PRIMTYPE
case kPtyDerived:
return "derived"; // just for test: no primitive type for derived
default:
return "kPtyInvalid";
}
// SIMD types to be defined
}
const char *GetPrimTypeJavaName(PrimType ty) {
switch (ty) {
default:
case kPtyInvalid: // ASSERT(false, "wrong primitive type!");
case PTY_u1:
return "Z";
case PTY_i8:
return "B";
case PTY_i16:
return "S";
case PTY_u16:
return "C";
case PTY_i32:
return "I";
case PTY_i64:
return "J";
case PTY_f32:
return "F";
case PTY_f64:
return "D";
case PTY_void:
return "V";
case PTY_constStr:
return JSTRTYPENAME;
}
}
void TypeAttrs::DumpAttributes() const {
#define TYPE_ATTR
#define STRING(s) #s
#define ATTR(AT) \
if (GetAttr(ATTR_##AT)) \
LogInfo::MapleLogger() << " " << STRING(AT);
#include "all_attributes.def"
#undef ATTR
#undef TYPE_ATTR
if (attrAlign) {
LogInfo::MapleLogger() << " align(" << GetAlign() << ")";
}
}
void FieldAttrs::DumpAttributes() const {
#define FIELD_ATTR
#define STRING(s) #s
#define ATTR(AT) \
if (GetAttr(FLDATTR_##AT)) \
LogInfo::MapleLogger() << " " << STRING(AT);
#include "all_attributes.def"
#undef ATTR
#undef FIELD_ATTR
if (attrAlign) {
LogInfo::MapleLogger() << " align(" << GetAlign() << ")";
}
}
const std::string &MIRType::GetName(void) const {
return GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx);
}
bool MIRType::ValidateClassOrInterface(const char *classname, bool noWarning) {
if (primType == maple::PTY_agg && (typeKind == maple::kTypeClass || typeKind == maple::kTypeInterface) &&
nameStrIdx.GetIdx()) {
return true;
} else {
if (noWarning == false) {
int len = strlen(classname);
if (len > 4 && strncmp(classname + len - 3, "_3B", 3) == 0) {
std::cerr << "error: missing proper mplt file for " << classname << std::endl;
} else {
std::cerr << "internal error: type is not java class or interface " << classname << std::endl;
}
}
return false;
}
}
bool MIRType::PointsToConstString() const {
if (typeKind == kTypePointer) {
return static_cast<const MIRPtrType *>(this)->PointsToConstString();
}
return false;
}
std::string MIRType::GetMplTypeName() const {
if (typeKind == kTypeScalar) {
return GetPrimTypeName(primType);
}
return "";
}
std::string MIRType::GetCompactMplTypeName() const {
if (typeKind == kTypeScalar) {
return GetPrimTypeJavaName(primType);
}
return "";
}
void MIRType::Dump(int indent, bool dontUseName) const {
LogInfo::MapleLogger() << GetPrimTypeName(primType);
}
void MIRType::DumpAsCxx(int indent) const {
switch (primType) {
case PTY_void:
LogInfo::MapleLogger() << "void";
break;
case PTY_i8:
LogInfo::MapleLogger() << "int8";
break;
case PTY_i16:
LogInfo::MapleLogger() << "int16";
break;
case PTY_i32:
LogInfo::MapleLogger() << "int32";
break;
case PTY_i64:
LogInfo::MapleLogger() << "int64";
break;
case PTY_u8:
LogInfo::MapleLogger() << "uint8";
break;
case PTY_u16:
LogInfo::MapleLogger() << "uint16";
break;
case PTY_u32:
LogInfo::MapleLogger() << "uint32";
break;
case PTY_u64:
LogInfo::MapleLogger() << "uint64";
break;
case PTY_u1:
LogInfo::MapleLogger() << "bool ";
break;
case PTY_ptr:
LogInfo::MapleLogger() << "void* ";
break;
case PTY_ref:
LogInfo::MapleLogger() << "void* ";
break;
case PTY_a32:
LogInfo::MapleLogger() << "int32";
break;
case PTY_a64:
LogInfo::MapleLogger() << "void* ";
break;
case PTY_f32:
LogInfo::MapleLogger() << "float ";
break;
case PTY_f64:
LogInfo::MapleLogger() << "double";
break;
case PTY_c64:
LogInfo::MapleLogger() << "float complex";
break;
case PTY_c128:
LogInfo::MapleLogger() << "double complex";
break;
default:
ASSERT(false, "NYI");
}
}
bool MIRType::IsOfSameType(MIRType &type) {
if (typeKind != type.typeKind) {
return false;
}
if (typeKind == kTypePointer) {
const auto &ptrType = static_cast<const MIRPtrType&>(*this);
const auto &ptrTypeIt = static_cast<const MIRPtrType&>(type);
if (ptrType.pointedTyIdx == ptrTypeIt.pointedTyIdx) {
return true;
} else {
MIRType &mirTypeIt = *GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptrTypeIt.pointedTyIdx);
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(ptrType.pointedTyIdx)->IsOfSameType(mirTypeIt);
}
} else if (typeKind == kTypeJArray) {
auto &arrType1 = static_cast<MIRJarrayType&>(*this);
auto &arrType2 = static_cast<MIRJarrayType&>(type);
if (arrType1.GetDim() != arrType2.GetDim()) {
return false;
}
return arrType1.GetElemType()->IsOfSameType(*arrType2.GetElemType());
} else {
return tyIdx == type.tyIdx;
}
}
inline void DumpTypename(GStrIdx strIdx, bool isLocal) {
LogInfo::MapleLogger() << ((isLocal) ? "%" : "$") << GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx);
}
static bool CheckAndDumpTypeName(GStrIdx strIdx, bool isLocal) {
if (strIdx == GStrIdx(0)) {
return false;
}
LogInfo::MapleLogger() << "<";
DumpTypename(strIdx, isLocal);
LogInfo::MapleLogger() << ">";
return true;
}
void MIRFuncType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << "<func(";
int size = paramTypeList.size();
for (int i = 0; i < size; i++) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(paramTypeList[i])->Dump(indent + 1);
if (size - 1 != i) {
LogInfo::MapleLogger() << ",";
}
}
if (isVarArgs) {
LogInfo::MapleLogger() << ", ...";
}
LogInfo::MapleLogger() << ") ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(retTyIdx)->Dump(indent + 1);
LogInfo::MapleLogger() << ">";
}
static constexpr uint64 RoundUpConst(uint64 offset, uint8 align) {
return (-align) & (offset + align - 1);
}
static inline uint64 RoundUp(uint64 offset, uint8 align) {
if (align == 0) {
return offset;
}
return RoundUpConst(offset, align);
}
static constexpr uint64 RoundDownConst(uint64 offset, uint8 align) {
return (-align) & offset;
}
static inline uint64 RoundDown(uint64 offset, uint8 align) {
if (align == 0) {
return offset;
}
return RoundDownConst(offset, align);
}
size_t MIRArrayType::GetSize() const {
size_t elemsize = GetElemType()->GetSize();
if (elemsize == 0) {
return 0;
}
elemsize = RoundUp(elemsize, typeAttrs.GetAlign());
size_t numelems = sizeArray[0];
for (int i = 1; i < dim; i++) {
numelems *= sizeArray[i];
}
return elemsize * numelems;
}
uint32 MIRArrayType::GetAlign() const {
return std::max(GetElemType()->GetAlign(), typeAttrs.GetAlign());
}
void MIRArrayType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << "<";
for (int i = 0; i < dim; i++) {
LogInfo::MapleLogger() << "[" << sizeArray[i] << "]";
}
LogInfo::MapleLogger() << " ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(eTyIdx)->Dump(indent + 1);
typeAttrs.DumpAttributes();
LogInfo::MapleLogger() << ">";
}
std::string MIRArrayType::GetCompactMplTypeName() const {
std::stringstream ss;
ss << "A";
MIRType *elemType = GetElemType();
ss << elemType->GetCompactMplTypeName();
return ss.str();
}
void MIRFarrayType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << "<[] ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx)->Dump(indent + 1);
LogInfo::MapleLogger() << ">";
}
std::string MIRFarrayType::GetCompactMplTypeName() const {
std::stringstream ss;
ss << "A";
MIRType *elemType = GetElemType();
ss << elemType->GetCompactMplTypeName();
return ss.str();
}
const std::string &MIRJarrayType::GetJavaName(void) {
if (javaNameStrIdx == GStrIdx(0)) {
DetermineName();
}
return GlobalTables::GetStrTable().GetStringFromStrIdx(javaNameStrIdx);
}
MIRStructType *MIRJarrayType::GetParentType() {
if (parentTyIdx == TyIdx(0)) {
GStrIdx jloStridx = GlobalTables::GetStrTable().GetStrIdxFromName(NameMangler::kJavaLangObjectStr);
parentTyIdx = GlobalTables::GetTypeNameTable().GetTyIdxFromGStrIdx(jloStridx);
ASSERT((parentTyIdx != TyIdx(0)), "cannot find type for java.lang.Object");
}
return static_cast<MIRStructType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx));
}
void MIRJarrayType::DetermineName() {
if (javaNameStrIdx != GStrIdx(0)) {
return; // already determined
}
MIRType *elemtype = GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx);
dim = 1;
std::string basename;
while (1) {
if (elemtype->typeKind == kTypeScalar) {
basename = GetPrimTypeJavaName(elemtype->primType);
fromPrimitive = true;
break;
} else if (elemtype->typeKind == kTypePointer) {
MIRType *ptype = static_cast<MIRPtrType *>(elemtype)->GetPointedType();
ASSERT(ptype, "ptype is null in MIRJarrayType::DetermineName");
if (ptype->typeKind == kTypeByName || ptype->typeKind == kTypeClass || ptype->typeKind == kTypeInterface ||
ptype->typeKind == kTypeClassIncomplete || ptype->typeKind == kTypeInterfaceIncomplete) {
basename = static_cast<MIRStructType *>(ptype)->GetName();
fromPrimitive = false;
break;
} else if (ptype->typeKind == kTypeArray || ptype->typeKind == kTypeJArray) {
elemtype = dynamic_cast<MIRJarrayType *>(ptype)->GetElemType();
ASSERT(elemtype, "elemtype is null in MIRJarrayType::DetermineName");
dim++;
} else {
ASSERT(false, "unexpected type!");
}
} else {
ASSERT(false, "unexpected type!");
}
}
std::string name;
int i = dim;
while (i-- > 0) {
name += JARRAY_PREFIX_STR;
}
name += basename;
javaNameStrIdx = GlobalTables::GetStrTable().GetOrCreateStrIdxFromName(name);
}
MIRType *MIRPtrType::GetPointedType() const {
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(pointedTyIdx);
}
bool MIRType::IsVolatile(int fieldID) {
if (fieldID == 0) {
return HasVolatileField();
}
return static_cast<const MIRStructType*>(this)->IsFieldVolatile(fieldID);
}
bool MIRPtrType::PointsToConstString() const {
GStrIdx typenameIdx = GetPointedType()->nameStrIdx;
std::string typeName = GlobalTables::GetStrTable().GetStringFromStrIdx(typenameIdx);
return typeName == NameMangler::kJavaLangStringStr;
}
void MIRPtrType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
MIRType *pointedty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(pointedTyIdx);
if (pointedty->typeKind == kTypeFunction) { // no * for function pointer
pointedty->Dump(indent);
} else {
LogInfo::MapleLogger() << "<* ";
pointedty->Dump(indent + 1);
typeAttrs.DumpAttributes();
LogInfo::MapleLogger() << ">";
}
}
void MIRBitfieldType::Dump(int indent, bool dontUseName) const {
LogInfo::MapleLogger() << ":" << static_cast<int>(fieldSize) << " " << GetPrimTypeName(primType);
}
size_t MIRClassType::GetSize() const {
if (parentTyIdx == TyIdx(0)) {
return MIRStructType::GetSize();
}
MIRClassType *parentType = static_cast<MIRClassType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx));
uint32 prntSize = parentType->GetSize();
if (prntSize == 0) {
return 0;
}
uint32 structSize = MIRStructType::GetSize();
if (structSize == 0) {
return 0;
}
return prntSize + structSize;
}
FieldID MIRClassType::GetFirstLocalFieldID() const {
if (!IsLocal()) {
return 0;
}
if (parentTyIdx == 0) {
return 1;
}
constexpr uint8 lastFieldIDOffset = 2;
constexpr uint8 firstLocalFieldIDOffset = 1;
const auto *parentClassType =
static_cast<const MIRClassType*>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx));
return !parentClassType->IsLocal() ? parentClassType->GetLastFieldID() + lastFieldIDOffset
: parentClassType->GetFirstLocalFieldID() + firstLocalFieldIDOffset;
}
const MIRClassType *MIRClassType::GetExceptionRootType() const {
GStrIdx ehtynameidx = GlobalTables::GetStrTable().GetStrIdxFromName(NameMangler::kJavaLangObjectStr);
const MIRClassType *subclasstype = this;
while (subclasstype != nullptr && subclasstype->nameStrIdx != ehtynameidx) {
subclasstype = static_cast<const MIRClassType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(subclasstype->parentTyIdx));
}
return subclasstype;
}
MIRClassType *MIRClassType::GetExceptionRootType() {
return const_cast<MIRClassType*>(const_cast<const MIRClassType*>(this)->GetExceptionRootType());
}
bool MIRClassType::IsExceptionType() const {
GStrIdx ehtynameidx = GlobalTables::GetStrTable().GetStrIdxFromName(NameMangler::kThrowClassStr);
const MIRClassType *parentclasstype = this;
while (parentclasstype != nullptr && parentclasstype->nameStrIdx != ehtynameidx) {
parentclasstype = static_cast<MIRClassType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentclasstype->parentTyIdx));
}
return parentclasstype != nullptr;
}
FieldID MIRClassType::GetLastFieldID() const {
FieldID fieldID = fields.size();
if (parentTyIdx != 0) {
const auto *parentClassType =
static_cast<const MIRClassType*>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx));
if (parentClassType != nullptr) {
fieldID += parentClassType->GetLastFieldID() + 1;
}
}
return fieldID;
}
static void DumpClassOrInterfaceInfo(const MIRStructType &type, int indent) {
const std::vector<MIRInfoPair> &info = type.GetInfo();
std::vector<bool> infoIsString = type.GetInfoIsString();
size_t size = info.size();
for (size_t i = 0; i < size; ++i) {
LogInfo::MapleLogger() << '\n';
PrintIndentation(indent);
LogInfo::MapleLogger() << "@" << GlobalTables::GetStrTable().GetStringFromStrIdx(info[i].first) << " ";
if (!infoIsString[i]) {
LogInfo::MapleLogger() << info[i].second;
} else {
LogInfo::MapleLogger() << "\"" << GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(info[i].second))
<< "\"";
}
if (i != size - 1) {
LogInfo::MapleLogger() << ",";
}
}
}
static uint32 GetInfoFromStrIdx(const std::vector<MIRInfoPair> &info, const GStrIdx &strIdx) {
for (MIRInfoPair infoPair : info) {
if (infoPair.first == strIdx) {
return infoPair.second;
}
}
return 0;
}
uint32 MIRInterfaceType::GetInfo(GStrIdx strIdx) const {
return GetInfoFromStrIdx(info, strIdx);
}
// return class id or superclass id accroding to input string
uint32 MIRInterfaceType::GetInfo(const std::string &infoStr) const {
GStrIdx strIdx = GlobalTables::GetStrTable().GetStrIdxFromName(infoStr);
return GetInfo(strIdx);
}
size_t MIRInterfaceType::GetSize() const {
if (parentsTyIdx.size() == 0) {
return MIRStructType::GetSize();
}
uint32 size = MIRStructType::GetSize();
if (size == 0) {
return 0;
}
for (uint32 i = 0; i < parentsTyIdx.size(); i++) {
MIRInterfaceType *parentType = static_cast<MIRInterfaceType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentsTyIdx[i]));
uint32 prntSize = parentType->GetSize();
if (prntSize == 0) {
return 0;
}
size += prntSize;
}
return size;
}
static void DumpStaticValue(MIREncodedArray staticValue, int indent) {
if (staticValue.size() == 0) {
return;
}
LogInfo::MapleLogger() << std::endl;
PrintIndentation(indent);
LogInfo::MapleLogger() << "@"
<< "staticValue";
for (uint32 j = 0; j < staticValue.size(); j++) {
LogInfo::MapleLogger() << " [";
uint8 valueArg = static_cast<uint32>(staticValue[j].encodedValue[0]) >> 5;
uint8 valueType = static_cast<uint32>(staticValue[j].encodedValue[0]) & 0x1f;
// kValueNull kValueBoolean
if (valueType == 0x1e || valueType == 0x1f) {
valueArg = 1;
} else {
valueArg += 2;
}
for (uint32 k = 0; k < valueArg; k++) {
LogInfo::MapleLogger() << static_cast<uint32>(staticValue[j].encodedValue[k]);
if (k != static_cast<uint32>(valueArg - 1)) {
LogInfo::MapleLogger() << " ";
}
}
LogInfo::MapleLogger() << "]";
}
}
static void DumpFields(FieldVector fields, int indent, bool otherfields = false) {
uint32 size = fields.size();
for (uint32 i = 0; i < size; i++) {
LogInfo::MapleLogger() << std::endl;
PrintIndentation(indent);
if (!otherfields) {
LogInfo::MapleLogger() << "@";
} else {
LogInfo::MapleLogger() << "^";
}
LogInfo::MapleLogger() << GlobalTables::GetStrTable().GetStringFromStrIdx(fields[i].first) << " ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(fields[i].second.first)->Dump(indent + 1);
FieldAttrs &fa = fields[i].second.second;
fa.DumpAttributes();
if (fa.GetAttr(FLDATTR_static) && fa.GetAttr(FLDATTR_final) &&
(fa.GetAttr(FLDATTR_public) || fa.GetAttr(FLDATTR_protected))) {
const char *fieldname = (GlobalTables::GetStrTable().GetStringFromStrIdx(fields[i].first)).c_str();
MIRSymbol *fieldVar = GlobalTables::GetGsymTable().GetSymbolFromStrIdx(GlobalTables::GetStrTable().GetStrIdxFromName(fieldname));
if (fieldVar && dynamic_cast<MIRStr16Const *>(fieldVar->value.konst)) {
LogInfo::MapleLogger() << " = ";
fieldVar->value.konst->Dump();
}
}
if (i != size - 1) {
LogInfo::MapleLogger() << ",";
}
}
return;
}
static void DumpFieldsAsCxx(FieldVector fields, int indent) {
for (auto &f : fields) {
PrintIndentation(indent);
FieldAttrs &fa = f.second.second;
if (fa.GetAttr(FLDATTR_static)) {
LogInfo::MapleLogger() << "// ";
}
LogInfo::MapleLogger() << "/* ";
fa.DumpAttributes();
GlobalTables::GetTypeTable().GetTypeFromTyIdx(f.second.first)->Dump(indent + 1);
LogInfo::MapleLogger() << " */ ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(f.second.first)->DumpAsCxx(indent + 1);
LogInfo::MapleLogger() << " " << GlobalTables::GetStrTable().GetStringFromStrIdx(f.first);
LogInfo::MapleLogger() << ";" << std::endl;
}
}
static void DumpMethods(MethodVector methods, int indent) {
int size = methods.size();
for (int i = 0; i < size; i++) {
LogInfo::MapleLogger() << std::endl;
PrintIndentation(indent);
LogInfo::MapleLogger() << "&" << GlobalTables::GetGsymTable().GetSymbolFromStIdx(methods[i].first.Idx())->GetName();
methods[i].second.second.DumpAttributes();
LogInfo::MapleLogger() << " (";
MIRFuncType *functype = static_cast<MIRFuncType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(methods[i].second.first));
int parmlistsize = functype->paramTypeList.size();
for (int j = 0; j < parmlistsize; j++) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(functype->paramTypeList[j])->Dump(indent + 1);
if (parmlistsize - 1 != j) {
LogInfo::MapleLogger() << ",";
}
}
if (functype->isVarArgs) {
LogInfo::MapleLogger() << ", ...";
}
LogInfo::MapleLogger() << ") ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(functype->retTyIdx)->Dump(indent + 1);
if (i != size - 1) {
LogInfo::MapleLogger() << ",";
}
}
}
static void DumpConstructorsAsCxx(MethodVector methods, int indent) {
unsigned int i = 0;
for (auto &m : methods) {
FuncAttrs &fa = m.second.second;
if (!fa.GetAttr(FUNCATTR_constructor) || !fa.GetAttr(FUNCATTR_public)) {
continue;
}
MIRFuncType *functype = static_cast<MIRFuncType *>(GlobalTables::GetTypeTable().GetTypeFromTyIdx(m.second.first));
PrintIndentation(indent);
LogInfo::MapleLogger() << "/* ";
LogInfo::MapleLogger() << "&" << GlobalTables::GetGsymTable().GetSymbolFromStIdx(m.first.Idx())->GetName();
fa.DumpAttributes();
LogInfo::MapleLogger() << " (";
unsigned int j = 0;
for (auto &p : functype->paramTypeList) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(p)->Dump(indent + 1);
if (functype->paramTypeList.size() - 1 != j++) {
LogInfo::MapleLogger() << ", ";
}
}
if (functype->isVarArgs) {
LogInfo::MapleLogger() << ", ...";
}
LogInfo::MapleLogger() << ") ";
GlobalTables::GetTypeTable().GetTypeFromTyIdx(functype->retTyIdx)->Dump(indent + 1);
LogInfo::MapleLogger() << " */" << std::endl;
PrintIndentation(indent);
LogInfo::MapleLogger() << "/* ";
LogInfo::MapleLogger() << NameMangler::DecodeName(GlobalTables::GetGsymTable().GetSymbolFromStIdx(m.first.Idx())->GetName());
LogInfo::MapleLogger() << " */" << std::endl;
PrintIndentation(indent);
LogInfo::MapleLogger() << "extern \"C\" ";
// return type
GlobalTables::GetTypeTable().GetTypeFromTyIdx(functype->retTyIdx)->DumpAsCxx(0);
LogInfo::MapleLogger() << " " << GlobalTables::GetGsymTable().GetSymbolFromStIdx(m.first.Idx())->GetName() << "( ";
j = 0;
for (auto &p : functype->paramTypeList) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(p)->DumpAsCxx(indent + 1);
if (functype->paramTypeList.size() - 1 != j++) {
LogInfo::MapleLogger() << ", ";
}
}
if (functype->isVarArgs) {
LogInfo::MapleLogger() << ", ...";
}
LogInfo::MapleLogger() << ")";
if (methods.size() - 1 != i++) {
LogInfo::MapleLogger() << ";" << std::endl;
}
}
}
static void DumpInterfaces(std::vector<TyIdx> interfaces, int indent) {
uint32 size = interfaces.size();
for (uint32 i = 0; i < size; i++) {
LogInfo::MapleLogger() << std::endl;
PrintIndentation(indent);
GStrIdx strIdx = GlobalTables::GetTypeTable().GetTypeFromTyIdx(interfaces[i])->nameStrIdx;
LogInfo::MapleLogger() << "$" << GlobalTables::GetStrTable().GetStringFromStrIdx(strIdx);
if (i != size - 1) {
LogInfo::MapleLogger() << ",";
}
}
}
size_t MIRStructType::GetSize() const {
if (typeKind == kTypeUnion) {
if (fields.size() == 0) {
return isCPlusPlus ? 1 : 0;
}
size_t maxSize = 0;
for (size_t i = 0; i < fields.size(); ++i) {
TyidxFieldAttrPair tfap = GetTyidxFieldAttrPair(i);
MIRType *fieldType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tfap.first);
size_t size = RoundUp(fieldType->GetSize(), tfap.second.GetAlign());
if (maxSize < size) {
maxSize = size;
}
}
return maxSize;
}
// since there may be bitfields, perform a layout process for the fields
size_t byteOfst = 0;
size_t bitOfst = 0;
for (size_t i = 0; i < fields.size(); ++i) {
TyidxFieldAttrPair tfap = GetTyidxFieldAttrPair(i);
MIRType *fieldType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tfap.first);
if (fieldType->typeKind != kTypeBitField) {
if (byteOfst * 8 < bitOfst) {
byteOfst = (bitOfst >> 3) + 1;
}
byteOfst = RoundUp(byteOfst, std::max(fieldType->GetAlign(), tfap.second.GetAlign()));
byteOfst += fieldType->GetSize();
bitOfst = byteOfst * 8;
} else {
MIRBitfieldType *bitfType = static_cast<MIRBitfieldType *>(fieldType);
if (bitfType->fieldSize == 0) { // special case, for aligning purpose
bitOfst = RoundUp(bitOfst, GetPrimTypeBitSize(bitfType->primType));
byteOfst = bitOfst >> 3;
} else {
if (RoundDown(bitOfst + bitfType->fieldSize - 1, GetPrimTypeBitSize(bitfType->primType)) !=
RoundDown(bitOfst, GetPrimTypeBitSize(bitfType->primType))) {
bitOfst = RoundUp(bitOfst, GetPrimTypeBitSize(bitfType->primType));
byteOfst = bitOfst >> 3;
}
bitOfst += bitfType->fieldSize;
byteOfst = bitOfst >> 3;
}
}
}
if (byteOfst * 8 < bitOfst) {
byteOfst = (bitOfst >> 3) + 1;
}
byteOfst = RoundUp(byteOfst, GetAlign());
if (byteOfst == 0 && isCPlusPlus) {
return 1; // empty struct in C++ has size 1
}
return byteOfst;
}
uint32 MIRStructType::GetAlign() const {
if (fields.size() == 0) {
return 0;
}
uint8 maxAlign = 1;
for (size_t i = 0; i < fields.size(); ++i) {
TyidxFieldAttrPair tfap = GetTyidxFieldAttrPair(i);
MIRType *fieldType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tfap.first);
uint32 algn = fieldType->GetAlign();
if (fieldType->typeKind == kTypeBitField) {
algn = GetPrimTypeSize(fieldType->primType);
} else {
algn = std::max(algn, tfap.second.GetAlign());
}
if (maxAlign < algn) {
maxAlign = algn;
}
}
return maxAlign;
}
void MIRStructType::DumpFieldsAndMethods(int indent, bool hasMethod) const {
DumpFields(fields, indent);
bool hasField = !fields.empty();
bool hasStaticField = !staticFields.empty();
if (hasField && hasStaticField) {
LogInfo::MapleLogger() << ",";
}
DumpFields(staticFields, indent, true);
bool hasFieldOrStaticField = hasField || hasStaticField;
bool hasParentField = !parentFields.empty();
if (hasFieldOrStaticField && hasParentField) {
LogInfo::MapleLogger() << ",";
}
DumpFields(parentFields, indent, true);
if ((hasFieldOrStaticField || hasParentField) && hasMethod) {
LogInfo::MapleLogger() << ",";
}
DumpMethods(methods, indent);
}
void MIRStructType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << ((typeKind == kTypeStruct) ? "<struct {"
: ((typeKind == kTypeUnion) ? "<union {"
: "<structincomplete {"));
DumpFieldsAndMethods(indent, !methods.empty());
LogInfo::MapleLogger() << "}>";
}
uint32 MIRClassType::GetInfo(GStrIdx strIdx) const {
return GetInfoFromStrIdx(info, strIdx);
}
// return class id or superclass id accroding to input string
uint32 MIRClassType::GetInfo(const std::string &infoStr) const {
GStrIdx strIdx = GlobalTables::GetStrTable().GetStrIdxFromName(infoStr);
return GetInfo(strIdx);
}
bool MIRClassType::IsFinal() const {
uint32 attrstridx = GetInfo(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("INFO_attribute_string"));
CHECK(attrstridx < GlobalTables::GetStrTable().StringTableSize(), "out of range of vector");
const std::string kAttrstring = GlobalTables::GetStrTable().GetStringFromStrIdx(attrstridx);
return kAttrstring.find(" final ") != std::string::npos;
}
bool MIRClassType::IsAbstract() const {
uint32 attrStrIdx = GetInfo(GlobalTables::GetStrTable().GetOrCreateStrIdxFromName("INFO_attribute_string"));
CHECK(attrStrIdx < GlobalTables::GetStrTable().StringTableSize(), "out of range of vector");
const std::string &kAttrString = GlobalTables::GetStrTable().GetStringFromStrIdx(GStrIdx(attrStrIdx));
return kAttrString.find(" abstract ") != std::string::npos;
}
bool MIRClassType::IsInner() const {
const std::string kName = GetName();
return kName.find("_24") != std::string::npos;
}
static void DumpInfoPragmaStaticValue(const std::vector<MIRInfoPair> &info, const std::vector<MIRPragma*> &pragmaVec,
const MIREncodedArray &staticValue, int indent, bool hasFieldMethodOrInterface) {
bool hasPragma = pragmaVec.size();
bool hasStaticValue = staticValue.size();
if (!info.empty() && (hasPragma || hasStaticValue || hasFieldMethodOrInterface)) {
LogInfo::MapleLogger() << ",";
}
size_t size = pragmaVec.size();
for (size_t i = 0; i < size; ++i) {
pragmaVec[i]->Dump(indent);
if (i != size - 1) {
LogInfo::MapleLogger() << ",";
}
}
if (hasPragma && (hasStaticValue || hasFieldMethodOrInterface)) {
LogInfo::MapleLogger() << ",";
}
DumpStaticValue(staticValue, indent);
if (hasStaticValue && hasFieldMethodOrInterface) {
LogInfo::MapleLogger() << ",";
}
}
void MIRClassType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << ((typeKind == kTypeClass) ? "<class " : "<classincomplete ");
if (parentTyIdx != 0) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx)->Dump(indent + 1);
LogInfo::MapleLogger() << " ";
}
LogInfo::MapleLogger() << "{";
DumpClassOrInterfaceInfo(*this, indent);
bool hasFieldMethodOrInterface = !(fields.empty() && parentFields.empty() && staticFields.empty() &&
methods.empty() && interfacesImplemented.empty());
DumpInfoPragmaStaticValue(info, pragmaVec, staticValue, indent, hasFieldMethodOrInterface);
bool hasMethod = !methods.empty();
bool hasImplementedInterface = !interfacesImplemented.empty();
DumpFieldsAndMethods(indent, hasMethod || hasImplementedInterface);
if (hasMethod && hasImplementedInterface) {
LogInfo::MapleLogger() << ",";
}
DumpInterfaces(interfacesImplemented, indent);
LogInfo::MapleLogger() << "}>";
}
void MIRClassType::DumpAsCxx(int indent) const {
LogInfo::MapleLogger() << "{" << std::endl;
DumpFieldsAsCxx(fields, indent);
LogInfo::MapleLogger() << "};" << std::endl;
DumpConstructorsAsCxx(methods, 0);
}
void MIRInterfaceType::Dump(int indent, bool dontUseName) const {
if (!dontUseName && CheckAndDumpTypeName(nameStrIdx, nameIsLocal)) {
return;
}
LogInfo::MapleLogger() << ((typeKind == kTypeInterface) ? "<interface " : "<interfaceincomplete ");
for (TyIdx idx : parentsTyIdx) {
GlobalTables::GetTypeTable().GetTypeFromTyIdx(idx)->Dump(0);
LogInfo::MapleLogger() << " ";
}
LogInfo::MapleLogger() << " {";
DumpClassOrInterfaceInfo(*this, indent);
bool hasFieldOrMethod = !(fields.empty() && staticFields.empty() && parentFields.empty() && methods.empty());
DumpInfoPragmaStaticValue(info, pragmaVec, staticValue, indent, hasFieldOrMethod);
DumpFieldsAndMethods(indent, !methods.empty());
LogInfo::MapleLogger() << "}>";
}
void MIRTypeByName::Dump(int indent, bool dontUseName) const {
const std::string &name = GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx);
LogInfo::MapleLogger() << (nameIsLocal ? "<%" : "<$") << name << ">";
}
void MIRTypeParam::Dump(int indent, bool dontUseName) const {
LogInfo::MapleLogger() << "<";
const std::string &name = GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx);
LogInfo::MapleLogger() << "!" << name << ">";
}
void MIRInstantVectorType::Dump(int indent, bool dontUseName) const {
LogInfo::MapleLogger() << "{";
for (uint32 i = 0; i < instantVec.size(); i++) {
TypePair tpair = instantVec[i];
if (i != 0) {
LogInfo::MapleLogger() << ", ";
}
MIRType *typeparmty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tpair.first);
const std::string &name = GlobalTables::GetStrTable().GetStringFromStrIdx(typeparmty->nameStrIdx);
LogInfo::MapleLogger() << "!" << name;
LogInfo::MapleLogger() << "=";
MIRType *realty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(tpair.second);
realty->Dump(0);
}
LogInfo::MapleLogger() << "}";
}
void MIRGenericInstantType::Dump(int indent, bool dontUseName) const {
LogInfo::MapleLogger() << "<";
MIRType *genericty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(genericTyIdx);
DumpTypename(genericty->nameStrIdx, genericty->nameIsLocal);
MIRInstantVectorType::Dump(indent, dontUseName);
LogInfo::MapleLogger() << ">";
}
bool MIRType::Equalto(const MIRType &mirType) const {
return typeKind == mirType.typeKind && primType == mirType.primType;
}
bool MIRPtrType::Equalto(const MIRType &type) const {
if (typeKind != type.GetKind() || GetPrimType() != type.GetPrimType()) {
return false;
}
const auto &pType = static_cast<const MIRPtrType&>(type);
return pointedTyIdx == pType.pointedTyIdx && typeAttrs == pType.typeAttrs;
}
bool MIRArrayType::Equalto(const MIRType &type) const {
if (type.typeKind != typeKind) {
return false;
}
const MIRArrayType *p = dynamic_cast<const MIRArrayType*>(&type);
CHECK_FATAL(p != nullptr, "null ptr check ");
if (dim != p->dim || eTyIdx != p->eTyIdx || typeAttrs != p->typeAttrs) {
return false;
}
for (int i = 0; i < dim; i++) {
if (sizeArray[i] != p->sizeArray[i]) {
return false;
}
}
return true;
}
MIRType *MIRArrayType::GetElemType() const {
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(eTyIdx);
}
std::string MIRArrayType::GetMplTypeName() const {
std::stringstream ss;
ss << "<[] ";
MIRType *elemType = GetElemType();
ss << elemType->GetMplTypeName();
ss << ">";
return ss.str();
}
bool MIRArrayType::HasFields() const {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(eTyIdx);
return elemType->HasFields();
}
size_t MIRArrayType::NumberOfFieldIDs() {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(eTyIdx);
return elemType->NumberOfFieldIDs();
}
MIRStructType *MIRArrayType::EmbeddedStructType() {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(eTyIdx);
return elemType->EmbeddedStructType();
}
MIRType *MIRFarrayType::GetElemType() const {
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx);
}
bool MIRFarrayType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRFarrayType *pty = dynamic_cast<const MIRFarrayType*>(&ty);
CHECK_FATAL(pty, "make sure the elemTyIdx is not nullptr");
return elemTyIdx == pty->elemTyIdx;
}
std::string MIRFarrayType::GetMplTypeName() const {
std::stringstream ss;
ss << "<[] ";
MIRType *elemType = GetElemType();
ss << elemType->GetMplTypeName();
ss << ">";
return ss.str();
}
bool MIRFarrayType::HasFields() const {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx);
return elemType->HasFields();
}
size_t MIRFarrayType::NumberOfFieldIDs() {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx);
return elemType->NumberOfFieldIDs();
}
MIRStructType *MIRFarrayType::EmbeddedStructType() {
MIRType *elemType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(elemTyIdx);
return elemType->EmbeddedStructType();
}
bool MIRFuncType::Equalto(const MIRType &type) const {
if (type.typeKind != typeKind) {
return false;
}
const auto &pType = static_cast<const MIRFuncType&>(type);
return (pType.retTyIdx == retTyIdx && pType.paramTypeList == paramTypeList &&
pType.isVarArgs == isVarArgs && pType.paramAttrsList == paramAttrsList);
}
bool MIRBitfieldType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRBitfieldType *p = dynamic_cast<const MIRBitfieldType*>(&ty);
CHECK_FATAL(p != nullptr, " null ptr check ");
return p->primType == primType &&
// p->typeKind == typeKind &&
p->fieldSize == fieldSize;
}
bool MIRStructType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRStructType *p = dynamic_cast<const MIRStructType*>(&ty);
CHECK_FATAL(p != nullptr, "p is null in MIRStructType::Equalto");
if (fields != p->fields) {
return false;
}
if (staticFields != p->staticFields) {
return false;
}
if (parentFields != p->parentFields) {
return false;
}
if (methods != p->methods) {
return false;
}
return true;
}
std::string MIRStructType::GetCompactMplTypeName() const {
return GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx);
}
MIRType *MIRStructType::GetElemType(uint32 n) const {
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(GetElemTyidx(n));
}
MIRType *MIRStructType::GetFieldType(FieldID fieldID) {
if (fieldID == 0) {
return this;
}
FieldPair fldpair = TraverseToField(fieldID);
return GlobalTables::GetTypeTable().GetTypeFromTyIdx(fldpair.second.first);
}
bool MIRStructType::IsLocal() const {
return GlobalTables::GetGsymTable().GetStIdxFromStrIdx(nameStrIdx).Idx() != 0;
}
std::string MIRStructType::GetMplTypeName() const {
std::stringstream ss;
ss << "<$";
ss << GlobalTables::GetStrTable().GetStringFromStrIdx(nameStrIdx);
ss << ">";
return ss.str();
}
bool MIRClassType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
bool structeq = MIRStructType::Equalto(ty);
if (!structeq) {
return false;
}
const MIRClassType &classty = static_cast<const MIRClassType &>(ty);
// classes have parent except empty/thirdparty classes
if (parentTyIdx != classty.parentTyIdx) {
return false;
}
if (interfacesImplemented != classty.interfacesImplemented) {
return false;
}
if (info != classty.info) {
return false;
}
if (infoIsString != classty.infoIsString) {
return false;
}
return true;
}
bool MIRInterfaceType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
bool structeq = MIRStructType::Equalto(ty);
if (!structeq) {
return false;
}
const MIRInterfaceType &interfacety = static_cast<const MIRInterfaceType &>(ty);
if (parentsTyIdx != interfacety.parentsTyIdx) {
return false;
}
if (info != interfacety.info) {
return false;
}
if (infoIsString != interfacety.infoIsString) {
return false;
}
return true;
}
bool MIRTypeByName::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRTypeByName *pty = dynamic_cast<const MIRTypeByName*>(&ty);
CHECK_FATAL(pty != nullptr, "null ptr check ");
return nameStrIdx == pty->nameStrIdx && nameIsLocal == pty->nameIsLocal;
}
bool MIRTypeParam::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRTypeParam *pty = dynamic_cast<const MIRTypeParam*>(&ty);
CHECK_FATAL(pty != nullptr, "null ptr check");
return nameStrIdx == pty->nameStrIdx;
}
bool MIRInstantVectorType::Equalto(const MIRType &ty) const {
if (ty.typeKind != typeKind) {
return false;
}
const MIRInstantVectorType *p = dynamic_cast<const MIRInstantVectorType*>(&ty);
CHECK_FATAL(p, "null ptr check ");
if (instantVec.size() != p->instantVec.size()) {
return false;
}
for (uint32 i = 0; i < instantVec.size(); i++) {
if (instantVec[i] != p->instantVec[i]) {
return false;
}
}
return true;
}
bool MIRGenericInstantType::Equalto(const MIRType &ty) const {
if (!MIRInstantVectorType::Equalto(ty)) {
return false;
}
const MIRGenericInstantType *p = dynamic_cast<const MIRGenericInstantType*>(&ty);
CHECK_FATAL(p, "null ptr check ");
return genericTyIdx == p->genericTyIdx;
}
// in the search, curfieldid is being decremented until it reaches 1
FieldPair MIRStructType::TraverseToFieldRef(FieldID &fieldID) const {
if (!fields.size()) {
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
}
uint32 fieldidx = 0;
FieldPair curpair = fields[0];
while (fieldID > 1) {
fieldID--;
MIRType *curfieldtype = GlobalTables::GetTypeTable().GetTypeFromTyIdx(curpair.second.first);
MIRStructType *substructty = curfieldtype->EmbeddedStructType();
if (substructty != nullptr) {
curpair = substructty->TraverseToFieldRef(fieldID);
if (fieldID == 1 && curpair.second.first != TyIdx(0)) {
return curpair;
}
}
fieldidx++;
if (fieldidx == fields.size()) {
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
}
curpair = fields[fieldidx];
}
return curpair;
}
FieldPair MIRStructType::TraverseToField(FieldID fieldID) const {
if (fieldID >= 0) {
return TraverseToFieldRef(fieldID);
}
// in parentFields
uint32 prntfieldidx = -fieldID;
if (parentFields.size() == 0 || prntfieldidx > parentFields.size()) {
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
}
return parentFields[prntfieldidx - 1];
}
FieldPair MIRStructType::TraverseToField(GStrIdx fieldstridx) const {
if (fields.size() == 0 && staticFields.size() == 0) {
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
}
if (fields.size() > 0) {
for (FieldPair field : fields) {
if (field.first == fieldstridx) {
return field;
}
}
}
if (staticFields.size() > 0) {
for (FieldPair field : staticFields) {
if (field.first == fieldstridx) {
return field;
}
}
}
if (parentFields.size() > 0) {
for (FieldPair field : parentFields) {
if (field.first == fieldstridx) {
return field;
}
}
}
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
}
// go through all the fields to check if there is volatile attribute set;
bool MIRStructType::HasVolatileField() {
if (hasVolatileFieldSet) {
return hasVolatileField;
}
hasVolatileFieldSet = true;
for (uint32 i = 0; i < fields.size(); i++) {
if (fields[i].second.second.GetAttr(FLDATTR_volatile)) {
hasVolatileField = true;
return true;
}
MIRType *fldty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(fields[i].second.first);
MIRTypeKind fldknd = fldty->GetKind();
if (fldknd == kTypeStruct || fldknd == kTypeStructIncomplete || fldknd == kTypeClass ||
fldknd == kTypeClassIncomplete || fldknd == kTypeInterface || fldknd == kTypeInterfaceIncomplete) {
if (static_cast<MIRStructType *>(fldty)->HasVolatileField()) {
hasVolatileField = true;
return true;
}
}
}
for (uint32 i = 0; i < parentFields.size(); i++) {
if (parentFields[i].second.second.GetAttr(FLDATTR_volatile)) {
hasVolatileField = true;
return true;
}
MIRType *fldty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentFields[i].second.first);
MIRTypeKind fldknd = fldty->GetKind();
if (fldknd == kTypeStruct || fldknd == kTypeStructIncomplete || fldknd == kTypeClass ||
fldknd == kTypeClassIncomplete || fldknd == kTypeInterface || fldknd == kTypeInterfaceIncomplete)
if (static_cast<MIRStructType *>(fldty)->HasVolatileField()) {
hasVolatileField = true;
return true;
}
}
if (GetKind() == kTypeClass || GetKind() == kTypeClassIncomplete) {
MIRClassType *thisclassty = static_cast<MIRClassType *>(this);
if (thisclassty->parentTyIdx != 0) {
// check if parent class has volatile field
MIRType *parentty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(thisclassty->parentTyIdx);
if (static_cast<MIRStructType *>(parentty)->HasVolatileField()) {
hasVolatileField = true;
return true;
}
}
} else if (GetKind() == kTypeInterface || GetKind() == kTypeInterfaceIncomplete) {
MIRInterfaceType *thisinterfacety = static_cast<MIRInterfaceType *>(this);
// check if the parent classes have volatile field
for (uint32 i = 0; i < thisinterfacety->parentsTyIdx.size(); i++) {
TyIdx prnttyidx = thisinterfacety->parentsTyIdx[i];
MIRType *prntty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(prnttyidx);
if (static_cast<MIRStructType *>(prntty)->HasVolatileField()) {
hasVolatileField = true;
return true;
}
}
}
hasVolatileField = false;
return false;
}
// go through all the fields to check if there is generic attribute set;
bool MIRStructType::HasTypeParam() const {
for (uint32 i = 0; i < fields.size(); i++)
if (fields[i].second.second.GetAttr(FLDATTR_generic)) {
return true;
}
for (uint32 i = 0; i < parentFields.size(); i++)
if (parentFields[i].second.second.GetAttr(FLDATTR_generic)) {
return true;
}
if (GetKind() == kTypeClass || GetKind() == kTypeClassIncomplete) {
const MIRClassType *thisclassty = static_cast<const MIRClassType *>(this);
if (thisclassty->parentTyIdx != 0) {
// check if parent class has type parameter
MIRType *parentty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(thisclassty->parentTyIdx);
if (parentty->HasTypeParam()) {
return true;
}
}
} else if (GetKind() == kTypeInterface || GetKind() == kTypeInterfaceIncomplete) {
const MIRInterfaceType *thisinterfacety = static_cast<const MIRInterfaceType *>(this);
// check if the parent classes have type parameter
for (uint32 i = 0; i < thisinterfacety->parentsTyIdx.size(); i++) {
TyIdx prnttyidx = thisinterfacety->parentsTyIdx[i];
MIRType *prntty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(prnttyidx);
if (prntty->HasTypeParam()) {
return true;
}
}
}
return false;
}
size_t MIRClassType::NumberOfFieldIDs() {
size_t parentFieldIDs = 0;
if (parentTyIdx != TyIdx(0)) {
MIRType *parentty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx);
parentFieldIDs = parentty->NumberOfFieldIDs();
}
return parentFieldIDs + MIRStructType::NumberOfFieldIDs();
}
FieldPair MIRClassType::TraverseToFieldRef(FieldID &fieldID) const {
if (parentTyIdx != TyIdx(0)) {
MIRClassType *parentclassty = MIR_DYN_CAST(GlobalTables::GetTypeTable().GetTypeFromTyIdx(parentTyIdx), MIRClassType *);
if (parentclassty) {
fieldID--;
FieldPair curpair = parentclassty->TraverseToFieldRef(fieldID);
if (fieldID == 1 && curpair.second.first != TyIdx(0)) {
return curpair;
}
}
}
return MIRStructType::TraverseToFieldRef(fieldID);
}
// fields in interface are all static and are global, won't be accessed through fields
FieldPair MIRInterfaceType::TraverseToFieldRef(FieldID &fieldID) const {
return FieldPair(GStrIdx(0), TyidxFieldAttrPair(TyIdx(0), FieldAttrs()));
;
}
TyidxFieldAttrPair MIRPtrType::GetPointedTyidxFldAttrPairWithFieldId(FieldID fldid) const {
if (fldid == 0) {
return TyidxFieldAttrPair(pointedTyIdx, FieldAttrs());
}
MIRType *ty = GlobalTables::GetTypeTable().GetTypeFromTyIdx(pointedTyIdx);
MIRStructType *structty = ty->EmbeddedStructType();
CHECK_FATAL(structty,
"MIRPtrType::GetPointedTyidxWithFieldId(): cannot have non-zero fieldID for something other than a struct");
return structty->TraverseToField(fldid).second;
}
TyIdx MIRPtrType::GetPointedTyidxWithFieldId(FieldID fldid) const {
return GetPointedTyidxFldAttrPairWithFieldId(fldid).first;
}
std::string MIRPtrType::GetMplTypeName() const {
std::stringstream ss;
ss << "<* ";
MIRType *pointedType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(pointedTyIdx);
CHECK_FATAL(pointedType != nullptr, "invalid ptr type");
ss << pointedType->GetMplTypeName();
ss << ">";
return ss.str();
}
std::string MIRPtrType::GetCompactMplTypeName() const {
MIRType *pointedType = GlobalTables::GetTypeTable().GetTypeFromTyIdx(pointedTyIdx);
CHECK_FATAL(pointedType != nullptr, "invalid ptr type");
return pointedType->GetCompactMplTypeName();
}
size_t MIRStructType::NumberOfFieldIDs() {
size_t count = 0;
for (FieldPair curpair : fields) {
count++;
MIRType *curfieldtype = GlobalTables::GetTypeTable().GetTypeFromTyIdx(curpair.second.first);
count += curfieldtype->NumberOfFieldIDs();
}
return count;
}
TypeAttrs FieldAttrs::ConvertToTypeAttrs() {
TypeAttrs attr;
for (uint32 i = 0; i < 64; i++) {
if ((attrFlag & (1ULL << i)) == 0) {
continue;
}
FldAttrKind tA = static_cast<FldAttrKind>(i);
switch (tA) {
#define FIELD_ATTR
#define ATTR(STR) \
case FLDATTR_##STR: \
attr.SetAttr(ATTR_##STR); \
break;
#include "all_attributes.def"
#undef ATTR
#undef FIELD_ATTR
default:
CHECK_FATAL(false, "unknown TypeAttrs");
break;
}
}
return attr;
}
TypeAttrs GenericAttrs::ConvertToTypeAttrs() {
TypeAttrs attr;
for (uint32 i = 0; i < 64; i++) {
if ((attrFlag & (1ULL << i)) == 0) {
continue;
}
GenericAttrKind tA = static_cast<GenericAttrKind>(i);
switch (tA) {
#define TYPE_ATTR
#define ATTR(STR) \
case GENATTR_##STR: \
attr.SetAttr(ATTR_##STR); \
break;
#include "all_attributes.def"
#undef ATTR
#undef TYPE_ATTR
default:
CHECK_FATAL(false, "unknown TypeAttrs");
break;
}
}
return attr;
}
FuncAttrs GenericAttrs::ConvertToFuncAttrs() {
FuncAttrs attr;
for (uint32 i = 0; i < 64; i++) {
if ((attrFlag & (1ULL << i)) == 0) {
continue;
}
GenericAttrKind tA = static_cast<GenericAttrKind>(i);
switch (tA) {
#define FUNC_ATTR
#define ATTR(STR) \
case GENATTR_##STR: \
attr.SetAttr(FUNCATTR_##STR); \
break;
#include "all_attributes.def"
#undef ATTR
#undef FUNC_ATTR
default:
CHECK_FATAL(false, "unknown FuncAttrs");
break;
}
}
return attr;
}
FieldAttrs GenericAttrs::ConvertToFieldAttrs() {
FieldAttrs attr;
for (uint32 i = 0; i < 64; i++) {
if ((attrFlag & (1ULL << i)) == 0) {
continue;
}
GenericAttrKind tA = static_cast<GenericAttrKind>(i);
switch (tA) {
#define FIELD_ATTR
#define ATTR(STR) \
case GENATTR_##STR: \
attr.SetAttr(FLDATTR_##STR); \
break;
#include "all_attributes.def"
#undef ATTR
#undef FIELD_ATTR
default:
CHECK_FATAL(false, "unknown FieldAttrs");
break;
}
}
return attr;
}
} // namespace maple
#endif // MIR_FEATURE_FULL
|
db DEX_EEVEE ; pokedex id
db 55, 55, 50, 55, 65
; hp atk def spd spc
db GRASS, GRASS ; type
db 45 ; catch rate
db 92 ; base exp
INCBIN "gfx/pokemon/front/eevee.pic", 0, 1 ; sprite dimensions
dw EeveePicFront, EeveePicBack
db TACKLE, SAND_ATTACK, NO_MOVE, NO_MOVE ; level 1 learnset
db GROWTH_MEDIUM_FAST ; growth rate
; tm/hm learnset
tmhm TOXIC, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, RAGE, \
MIMIC, DOUBLE_TEAM, REFLECT, BIDE, SWIFT, \
SKULL_BASH, REST, SUBSTITUTE
; end
db 0 ; padding
|
<%
from pwnlib.shellcraft.amd64.linux import syscall
%>
<%page args="pri, fmt, vararg"/>
<%docstring>
Invokes the syscall syslog. See 'man 2 syslog' for more information.
Arguments:
pri(int): pri
fmt(char): fmt
vararg(int): vararg
</%docstring>
${syscall('SYS_syslog', pri, fmt, vararg)}
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
/**
* @brief A header file that provides Allocator interface
*
* @file openvino/runtime/allocator.hpp
*/
#pragma once
#include <cstddef>
#include <memory>
#include "openvino/core/core_visibility.hpp"
namespace ov {
namespace runtime {
/**
* @interface AllocatorImpl
* @brief Tries to act like [std::pmr::memory_resource](https://en.cppreference.com/w/cpp/memory/memory_resource)
*/
struct AllocatorImpl : public std::enable_shared_from_this<AllocatorImpl> {
/**
* @brief A smart pointer containing AllocatorImpl object
*/
using Ptr = std::shared_ptr<AllocatorImpl>;
/**
* @brief Allocates memory
*
* @param bytes The size in bytes at least to allocate
* @param alignment The alignment of storage
* @return Handle to the allocated resource
* @throw Exception if specified size and alignment is not supported
*/
virtual void* allocate(const size_t bytes, const size_t alignment = alignof(max_align_t)) = 0;
/**
* @brief Releases the handle and all associated memory resources which invalidates the handle.
* @param handle The handle to free
* @param bytes The size in bytes that was passed into allocate() method
* @param alignment The alignment of storage that was passed into allocate() method
*/
virtual void deallocate(void* handle, const size_t bytes, size_t alignment = alignof(max_align_t)) = 0;
/**
* @brief Compares with other AllocatorImpl
* @param other Other instance of allocator
* @return `true` if and only if memory allocated from one AllocatorImpl can be deallocated from the other and vice
* versa
*/
virtual bool is_equal(const AllocatorImpl& other) const = 0;
protected:
~AllocatorImpl() = default;
};
class Tensor;
/**
* @brief Wraps allocator implementation to provide safe way to store allocater loaded from shared library
* And constructs default based on `new` `delete` c++ calls allocator if created without parameters
*/
class OPENVINO_API Allocator {
AllocatorImpl::Ptr _impl;
std::shared_ptr<void> _so;
/**
* @brief Constructs Tensor from the initialized std::shared_ptr
* @param impl Initialized shared pointer
* @param so Plugin to use. This is required to ensure that Allocator can work properly even if plugin object is
* destroyed.
*/
Allocator(const AllocatorImpl::Ptr& impl, const std::shared_ptr<void>& so);
friend class ov::runtime::Tensor;
public:
/**
* @brief Destructor presereves unload order of implementation object and reference to library
*/
~Allocator();
/// @brief Default constructor
Allocator();
/// @brief Default copy constructor
/// @param other other Allocator object
Allocator(const Allocator& other) = default;
/// @brief Default copy assignment operator
/// @param other other Allocator object
/// @return reference to the current object
Allocator& operator=(const Allocator& other) = default;
/// @brief Default move constructor
/// @param other other Allocator object
Allocator(Allocator&& other) = default;
/// @brief Default move assignment operator
/// @param other other Allocator object
/// @return reference to the current object
Allocator& operator=(Allocator&& other) = default;
/**
* @brief Constructs Allocator from the initialized std::shared_ptr
* @param impl Initialized shared pointer
*/
Allocator(const AllocatorImpl::Ptr& impl);
/**
* @brief Allocates memory
*
* @param bytes The size in bytes at least to allocate
* @param alignment The alignment of storage
* @return Handle to the allocated resource
* @throw Exception if specified size and alignment is not supported
*/
void* allocate(const size_t bytes, const size_t alignment = alignof(max_align_t));
/**
* @brief Releases the handle and all associated memory resources which invalidates the handle.
* @param ptr The handle to free
* @param bytes The size in bytes that was passed into allocate() method
* @param alignment The alignment of storage that was passed into allocate() method
*/
void deallocate(void* ptr, const size_t bytes = 0, const size_t alignment = alignof(max_align_t));
/**
* @brief Compares with other AllocatorImpl
* @param other Other instance of allocator
* @return `true` if and only if memory allocated from one AllocatorImpl can be deallocated from the other and vice
* versa
*/
bool operator==(const Allocator& other) const;
/**
* @brief Checks if current Allocator object is not initialized
* @return `true` if current Allocator object is not initialized, `false` - otherwise
*/
bool operator!() const noexcept;
/**
* @brief Checks if current Allocator object is initialized
* @return `true` if current Allocator object is initialized, `false` - otherwise
*/
explicit operator bool() const noexcept;
};
} // namespace runtime
} // namespace ov
|
; A005232: Expansion of (1-x+x^2)/((1-x)^2*(1-x^2)*(1-x^4)).
; 1,1,3,4,8,10,16,20,29,35,47,56,72,84,104,120,145,165,195,220,256,286,328,364,413,455,511,560,624,680,752,816,897,969,1059,1140,1240,1330,1440,1540,1661,1771,1903,2024,2168,2300,2456,2600,2769,2925,3107,3276,3472,3654,3864,4060,4285,4495,4735,4960,5216,5456,5728,5984,6273,6545,6851,7140,7464,7770,8112,8436,8797,9139,9519,9880,10280,10660,11080,11480,11921,12341,12803,13244,13728,14190,14696,15180,15709,16215,16767,17296,17872,18424,19024,19600,20225,20825,21475,22100,22776,23426,24128,24804,25533,26235,26991,27720,28504,29260,30072,30856,31697,32509,33379,34220,35120,35990,36920,37820,38781,39711,40703,41664,42688,43680,44736,45760,46849,47905,49027,50116,51272,52394,53584,54740,55965,57155,58415,59640,60936,62196,63528,64824,66193,67525,68931,70300,71744,73150,74632,76076,77597,79079,80639,82160,83760,85320,86960,88560,90241,91881,93603,95284,97048,98770,100576,102340,104189,105995,107887,109736,111672,113564,115544,117480,119505,121485,123555,125580,127696,129766,131928,134044,136253,138415,140671,142880,145184,147440,149792,152096,154497,156849,159299,161700,164200,166650,169200,171700,174301,176851,179503,182104,184808,187460,190216,192920,195729,198485,201347,204156,207072,209934,212904,215820,218845,221815,224895,227920,231056,234136,237328,240464,243713,246905,250211,253460,256824,260130,263552,266916,270397,273819,277359,280840,284440,287980,291640,295240,298961,302621,306403,310124,313968,317750,321656,325500,329469,333375
mov $4,$0
add $4,1
mov $5,$0
lpb $4
mov $0,$5
sub $4,1
sub $0,$4
mov $2,$0
gcd $0,2
div $2,2
add $0,$2
mov $6,$0
pow $6,2
mov $3,$6
div $3,2
add $3,1
mov $0,$3
add $0,4
mov $6,$0
sub $6,5
div $6,2
add $1,$6
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %r15
push %r8
push %rbp
push %rcx
// Faulty Load
lea addresses_D+0x1e5a5, %r10
nop
nop
sub $30303, %r15
mov (%r10), %cx
lea oracles, %rbp
and $0xff, %rcx
shlq $12, %rcx
mov (%rbp,%rcx,1), %rcx
pop %rcx
pop %rbp
pop %r8
pop %r15
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'36': 816}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
; Format date V2.00 1988 Tony Tebby QJUMP
section cv
xdef cv_fdate
xref cv_fditb
xref cv_fdstb
include 'dev8_keys_err'
include 'dev8_keys_k'
include 'dev8_keys_qlv'
include 'dev8_keys_dat'
include 'dev8_mac_assert'
;+++
; Format date using format string
;
; d1 c p date
; a1 c p pointer to date buffer to put formatted string into
; a2 c p pointer to format string
; status return zero or err.nc
;---
cv_fdate
reg.fdat reg d1/d2/a0/a1/a2/a3/a6
stk_date equ dat.buf+$0c
movem.l reg.fdat,-(sp)
sub.l a6,a6 ; utility is rel a6
move.l sp,a1 ; use stack buffer from top down
sub.w #dat.buf,sp
move.w cv.ildat,a3 ; to convert date into
jsr (a3)
addq.l #2,a1 ; ignore length
move.w cv.ilday,a3 ; and day into
jsr (a3)
addq.l #2,a1 ; ignore length
cmp.b #'0',dat_iday(a1) ; compress leading zeros
bne.s cfd_hrz
move.b #' ',dat_iday(a1)
cfd_hrz
cmp.b #'0',dat_hour(a1)
bne.s cfd_copy
move.b #' ',dat_hour(a1)
cfd_copy
move.l stk_date(sp),a3 ; pointer to date buffer
addq.l #2,a3 ; space for length
moveq #0,d0
move.w (a2)+,d0 ; get length
beq.s cfd_exit
cfd_loop
move.b (a2)+,d1 ; get next character
cmp.b #'%',d1 ; is it '%'
bne.s cfd_dolr ; ... no, check '$'
moveq #2,d2
lea cv_fditb,a0
bra.s cfd_group
cfd_dolr
cmp.b #'$',d1 ; is it '$'
bne.s cfd_newl ; ... no, perhaps a newline
moveq #3,d2 ; it is three letter
lea cv_fdstb,a0
cfd_group
move.w #$00df,d1 ; uppercase char
and.b (a2)+,d1
subq.l #1,d0
cfd_glook
cmp.b (a0)+,d1 ; our character
beq.s cfd_gfnd ; found it
tst.b (a0)+ ; next one
bge.s cfd_glook
move.b -1(a2),d1 ; restore character
bra.s cfd_char ; and send it
cfd_gfnd
move.b (a0)+,d1 ; start of characters
lea (a1,d1.w),a0 ; in buffer
cfd_gcopy
move.b (a0)+,(a3)+ ; copy it
subq.w #1,d2 ; count
bgt.s cfd_gcopy
bra.s cfd_next
cfd_newl
cmp.b #'\',d1 ; is it newline?
bne.s cfd_char
moveq #k.nl,d1
cmp.b #'\',(a2) ; another \?
bne.s cfd_char ; ... no, put newline in
move.b (a2)+,d1 ; ... yes, put \ in
subq.l #1,d0
cfd_char
move.b d1,(a3)+ ; set character
cfd_next
assert err.nc,-1
subq.l #1,d0 ; and see if any left in format
bgt.s cfd_loop
cfd_exit
move.l stk_date(sp),a1
sub.l a1,a3
subq.w #2,a3 ; length of string
move.w a3,(a1)
add.w #dat.buf,sp
movem.l (sp)+,reg.fdat
rts
end
|
;; (c) Copyright Kevin Thacker 2015-2016
;; This code is part of the Arnold emulator distribution.
;; This code is free to distribute without modification
;; this copyright header must be retained.
org &4000
scr_set_mode equ &bc0e
txt_output equ &bb5a
scr_set_border equ &bc38
km_wait_char equ &bb06
start:
ld a,2
call scr_set_mode
ld hl,message
call display_msg
call km_wait_char
ld a,2
call scr_set_mode
ld b,0
ld c,b
call scr_set_border
xor a
ld b,0
ld c,0
call scr_set_border
ld a,1
ld b,26
ld c,26
call scr_set_border
ld hl,&c000
ld e,l
ld d,h
inc de
ld bc,&3fff
ld (hl),&aa
ldir
;; now copy each pen into the screen
ld b,end_lines-lines
srl b
ld hl,lines
dl1:
push bc
ld e,(hl)
inc hl
ld d,(hl)
inc hl
push hl
ex de,hl
ld e,l
ld d,h
inc de
ld bc,80-1
ld (hl),&ff
ldir
pop hl
pop bc
djnz dl1
ld b,12
l3:
halt
djnz l3
di
ld hl,&c9fb
ld (&0038),hl
ei
loop:
ld b,&f5
l2:
in a,(c)
rra
jr nc,l2
ld bc,&7f00+%10001110
out (c),c
ld bc,&7f10
out (c),c
ld bc,&7f46
out (c),c
halt
halt
di
ld d,20
l1a:
defs 64-1-3
dec d
jp nz,l1a
defs 64-2
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 0->1
ld h,%10001100
ld l,%10001101
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 1->0
ld h,%10001101
ld l,%10001100
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 0->2
ld h,%10001100
ld l,%10001110
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 2->0
ld h,%10001110
ld l,%10001100
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 0->3
ld h,%10001100
ld l,%10001111
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 3->0
ld h,%10001111
ld l,%10001100
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 1->2
ld h,%10001101
ld l,%10001110
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 2->1
ld h,%10001110
ld l,%10001101
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 1->3
ld h,%10001101
ld l,%10001111
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 3->1
ld h,%10001111
ld l,%10001101
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f52
out (c),c
;; 2->3
ld h,%10001110
ld l,%10001111
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
ld bc,&7f10
out (c),c
ld bc,&7f40
out (c),c
;; 3->2
ld h,%10001111
ld l,%10001110
defs 13
rept 15
out (c),h
out (c),l
call wait_64_7
endm
out (c),h
out (c),l
defs 10
;;-----------------------------------------------------------------------------------------------------
ld bc,&7f10
out (c),c
ld bc,&7f46
out (c),c
ld bc,&7f00+%10011110
out (c),c
ei
jp loop
wait_64_7:
defs 64-7-5-3
ret
lines:
defw &c000+(1*80)+(3*&800)
defw &c000+(2*80)+(0*&800)
defw &c000+(3*80)+(3*&800)
defw &c000+(4*80)+(0*&800)
defw &c000+(5*80)+(3*&800)
defw &c000+(6*80)+(0*&800)
defw &c000+(7*80)+(3*&800)
defw &c000+(8*80)+(0*&800)
defw &c000+(9*80)+(3*&800)
defw &c000+(10*80)+(0*&800)
defw &c000+(11*80)+(3*&800)
defw &c000+(12*80)+(0*&800)
defw &c000+(13*80)+(3*&800)
defw &c000+(14*80)+(0*&800)
defw &c000+(15*80)+(3*&800)
defw &c000+(16*80)+(0*&800)
defw &c000+(17*80)+(3*&800)
defw &c000+(18*80)+(0*&800)
defw &c000+(19*80)+(3*&800)
defw &c000+(20*80)+(0*&800)
defw &c000+(21*80)+(3*&800)
defw &c000+(22*80)+(0*&800)
defw &c000+(23*80)+(3*&800)
defw &c000+(24*80)+(0*&800)
end_lines:
display_msg:
ld a,(hl)
cp '$'
ret z
inc hl
call txt_output
jr display_msg
message:
defb "This is a visual test.",13,10,13,10
defb "This test changes the mode to indicate the exact time when the ",13,10
defb "Gate-Array accepts and performs the change.",13,10,13,10
defb "The test changes rapidly from a mode to another and tests all mode combinations",13,10
defb "excluding two modes of the same number",13,10,13,10
defb "A solid line is drawn on the line before AND the line after where each mode",13,10
defb "takes effect. Between these lines the graphics should be different so you can",13,10
defb "see it is a different mode",13,10,13,10
defb "in order: 1->0, 0->1, 2->0, 0->2, 3->0, 0->3, 1->2, 2->1, 1->3",13,10
defb "3->1,2->3,3->2",13,10,13,10
defb "Press a key to start",'$'
end start
|
/*
* Copyright 2019 Xilinx, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file dut.cpp
*
* @brief This file contains top function of test case.
*/
#include "normal_distribution.hpp"
#define DT double
DT dut(DT average, DT sigma, DT x) {
return xf::fintech::normalPDF<DT>(average, sigma, x);
}
|
#define BZ
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/detail/standard_policies.hpp>
using ll = int64_t;
using ld = long double;
using ull = uint64_t;
using namespace std;
using namespace __gnu_pbds;
typedef vector <int> vi;
typedef pair <int, int> ii;
const int INF = 1 << 30;
int main() {
#ifdef BZ
freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); cout.setf(ios::fixed); cout.precision(20);
int n;
cin >> n;
int u;
vi a;
for(int i = 0; i < n; i++) {
cin >> u;
a.push_back(u);
}
sort(a.begin(), a.end());
int cnt = n;
int k = 0;
vi b;
for(int i = 0; i < n; i++) {
while(a[i] > k) {
b.push_back(cnt); k++;
}
cnt--;
}
//for(auto el: b) cout << el << " "; cout << "\n";
reverse(b.begin(), b.end());
cnt = (int) b.size();
k = 0;
vi c;
for(int i = 0; i < (int) b.size(); i++) {
while(b[i] > k) {
c.push_back(cnt); k++;
}
cnt--;
}
for(auto el: c) cout << el << "\n";
}
|
# Simple for loop:
# for (int i = 0; i < x; i++) {
# printf("%d", i);
# }
li $v0, 5 # load syscall read_int into $v0
syscall
move $t0, $v0 # move number read (x) to $t0
li $t1, 0 # i for loop iteration
Loop: beq $t1, $t0, Exit # break condition
addi $t1, $t1, 1 # increment i counter
move $a0, $t1 # load i into $a0 to be printed
li $v0, 1 # load syscall print_int to $v0
syscall
j Loop
Exit: li $v0, 10 # load exit code to $v0
syscall # end execution
|
// Copyright (c) 2021 DNV AS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include "LengthX.h"
#include "Formatting/FormattingService.h"
#include "Formatting/DefaultDirectionalLengthFormatterService.h"
namespace DNVS {namespace MoFa {namespace Units {
std::string ToString(const LengthX& length, const DNVS::MoFa::Formatting::FormattingService& service)
{
auto formatter = service.GetFormatterOrDefault<Formatting::IDirectionalLengthFormatterService, Formatting::DefaultDirectionalLengthFormatterService>();
return formatter->Format(length, service);
}
}}}
|
;;
;; Copyright (c) 2012-2022, Intel Corporation
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice,
;; this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;; * Neither the name of Intel Corporation nor the names of its contributors
;; may be used to endorse or promote products derived from this software
;; without specific prior written permission.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;
%include "include/os.asm"
%include "include/imb_job.asm"
%include "include/mb_mgr_datastruct.asm"
%include "include/reg_sizes.asm"
extern sha512_x2_sse
mksection .rodata
default rel
align 16
byteswap: ;ddq 0x08090a0b0c0d0e0f0001020304050607
dq 0x0001020304050607, 0x08090a0b0c0d0e0f
len_masks:
;ddq 0x0000000000000000000000000000FFFF
dq 0x000000000000FFFF, 0x0000000000000000
;ddq 0x000000000000000000000000FFFF0000
dq 0x00000000FFFF0000, 0x0000000000000000
one: dq 1
mksection .text
%ifndef FUNC
%define FUNC flush_job_hmac_sha_512_sse
%define SHA_X_DIGEST_SIZE 512
%endif
%if 1
%ifdef LINUX
%define arg1 rdi
%define arg2 rsi
%else
%define arg1 rcx
%define arg2 rdx
%endif
%define state arg1
%define job arg2
%define len2 arg2
; idx needs to be in rbx, rbp, r12-r15
%define idx rbp
%define unused_lanes rbx
%define lane_data rbx
%define tmp2 rbx
%define job_rax rax
%define tmp1 rax
%define size_offset rax
%define tmp rax
%define start_offset rax
%define tmp3 arg1
%define extra_blocks arg2
%define p arg2
%define tmp4 r8
%define tmp5 r9
%define tmp6 r10
%endif
; This routine clobbers rbx, rbp
struc STACK
_gpr_save: resq 2
_rsp_save: resq 1
endstruc
%define APPEND(a,b) a %+ b
; JOB* FUNC(MB_MGR_HMAC_SHA_512_OOO *state)
; arg 1 : rcx : state
MKGLOBAL(FUNC,function,internal)
FUNC:
mov rax, rsp
sub rsp, STACK_size
and rsp, -16
mov [rsp + _gpr_save + 8*0], rbx
mov [rsp + _gpr_save + 8*1], rbp
mov [rsp + _rsp_save], rax ; original SP
mov unused_lanes, [state + _unused_lanes_sha512]
bt unused_lanes, 16+7
jc return_null
; find a lane with a non-null job
xor idx, idx
cmp qword [state + _ldata_sha512 + 1 * _SHA512_LANE_DATA_size + _job_in_lane_sha512], 0
cmovne idx, [rel one]
copy_lane_data:
; copy good lane (idx) to empty lanes
movdqa xmm0, [state + _lens_sha512]
mov tmp, [state + _args_sha512 + _data_ptr_sha512 + PTR_SZ*idx]
%assign I 0
%rep 2
cmp qword [state + _ldata_sha512 + I * _SHA512_LANE_DATA_size + _job_in_lane_sha512], 0
jne APPEND(skip_,I)
mov [state + _args_sha512 + _data_ptr_sha512 + PTR_SZ*I], tmp
por xmm0, [rel len_masks + 16*I]
APPEND(skip_,I):
%assign I (I+1)
%endrep
movdqa [state + _lens_sha512], xmm0
phminposuw xmm1, xmm0
pextrw len2, xmm1, 0 ; min value
pextrw idx, xmm1, 1 ; min index (0...3)
cmp len2, 0
je len_is_0
pshuflw xmm1, xmm1, 0xA0
psubw xmm0, xmm1
movdqa [state + _lens_sha512], xmm0
; "state" and "args" are the same address, arg1
; len is arg2
call sha512_x2_sse
; state and idx are intact
len_is_0:
; process completed job "idx"
imul lane_data, idx, _SHA512_LANE_DATA_size
lea lane_data, [state + _ldata_sha512 + lane_data]
mov DWORD(extra_blocks), [lane_data + _extra_blocks_sha512]
cmp extra_blocks, 0
jne proc_extra_blocks
cmp dword [lane_data + _outer_done_sha512], 0
jne end_loop
proc_outer:
mov dword [lane_data + _outer_done_sha512], 1
mov DWORD(size_offset), [lane_data + _size_offset_sha512]
mov qword [lane_data + _extra_block_sha512 + size_offset], 0
mov word [state + _lens_sha512 + 2*idx], 1
lea tmp, [lane_data + _outer_block_sha512]
mov job, [lane_data + _job_in_lane_sha512]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp
%assign I 0
%rep (SHA_X_DIGEST_SIZE / (8*16))
movq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I)*SHA512_DIGEST_ROW_SIZE]
pinsrq xmm0, [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1) *SHA512_DIGEST_ROW_SIZE], 1
pshufb xmm0, [rel byteswap]
movdqa [lane_data + _outer_block_sha512 + I*16], xmm0
%assign I (I+1)
%endrep
mov tmp, [job + _auth_key_xor_opad]
%assign I 0
%rep 4
movdqu xmm0, [tmp + I * 16]
movq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*I*SHA512_DIGEST_ROW_SIZE], xmm0
pextrq [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + (2*I + 1)*SHA512_DIGEST_ROW_SIZE], xmm0, 1
%assign I (I+1)
%endrep
jmp copy_lane_data
align 16
proc_extra_blocks:
mov DWORD(start_offset), [lane_data + _start_offset_sha512]
mov [state + _lens_sha512 + 2*idx], WORD(extra_blocks)
lea tmp, [lane_data + _extra_block_sha512 + start_offset]
mov [state + _args_data_ptr_sha512 + PTR_SZ*idx], tmp
mov dword [lane_data + _extra_blocks_sha512], 0
jmp copy_lane_data
return_null:
xor job_rax, job_rax
jmp return
align 16
end_loop:
mov job_rax, [lane_data + _job_in_lane_sha512]
mov qword [lane_data + _job_in_lane_sha512], 0
or dword [job_rax + _status], IMB_STATUS_COMPLETED_AUTH
mov unused_lanes, [state + _unused_lanes_sha512]
shl unused_lanes, 8
or unused_lanes, idx
mov [state + _unused_lanes_sha512], unused_lanes
mov p, [job_rax + _auth_tag_output]
%if (SHA_X_DIGEST_SIZE != 384)
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 32
jne copy_full_digest
%else
cmp qword [job_rax + _auth_tag_output_len_in_bytes], 24
jne copy_full_digest
%endif
;; copy 32 bytes for SHA512 // 24 bytes for SHA384
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp6), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp5), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp2)
bswap QWORD(tmp4)
bswap QWORD(tmp6)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp5)
%endif
mov [p + 0*8], QWORD(tmp2)
mov [p + 1*8], QWORD(tmp4)
mov [p + 2*8], QWORD(tmp6)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 3*8], QWORD(tmp5)
%endif
jmp clear_ret
copy_full_digest:
;; copy 32 bytes for SHA512 // 24 bytes for SHA384
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 0*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 1*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp6), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 2*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp5), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 3*SHA512_DIGEST_ROW_SIZE]
bswap QWORD(tmp2)
bswap QWORD(tmp4)
bswap QWORD(tmp6)
bswap QWORD(tmp5)
mov [p + 0*8], QWORD(tmp2)
mov [p + 1*8], QWORD(tmp4)
mov [p + 2*8], QWORD(tmp6)
mov [p + 3*8], QWORD(tmp5)
mov QWORD(tmp2), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 4*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp4), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 5*SHA512_DIGEST_ROW_SIZE]
%if (SHA_X_DIGEST_SIZE != 384)
mov QWORD(tmp6), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 6*SHA512_DIGEST_ROW_SIZE]
mov QWORD(tmp5), [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*idx + 7*SHA512_DIGEST_ROW_SIZE]
%endif
bswap QWORD(tmp2)
bswap QWORD(tmp4)
%if (SHA_X_DIGEST_SIZE != 384)
bswap QWORD(tmp6)
bswap QWORD(tmp5)
%endif
mov [p + 4*8], QWORD(tmp2)
mov [p + 5*8], QWORD(tmp4)
%if (SHA_X_DIGEST_SIZE != 384)
mov [p + 6*8], QWORD(tmp6)
mov [p + 7*8], QWORD(tmp5)
%endif
clear_ret:
%ifdef SAFE_DATA
pxor xmm0, xmm0
;; Clear digest (48B/64B), outer_block (48B/64B) and extra_block (128B) of returned job
%assign I 0
%rep 2
cmp qword [state + _ldata_sha512 + (I*_SHA512_LANE_DATA_size) + _job_in_lane_sha512], 0
jne APPEND(skip_clear_,I)
;; Clear digest (48 bytes for SHA-384, 64 bytes for SHA-512 bytes)
%assign J 0
%rep 6
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*I + J*SHA512_DIGEST_ROW_SIZE], 0
%assign J (J+1)
%endrep
%if (SHA_X_DIGEST_SIZE != 384)
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*I + 6*SHA512_DIGEST_ROW_SIZE], 0
mov qword [state + _args_digest_sha512 + SHA512_DIGEST_WORD_SIZE*I + 7*SHA512_DIGEST_ROW_SIZE], 0
%endif
lea lane_data, [state + _ldata_sha512 + (I*_SHA512_LANE_DATA_size)]
;; Clear first 128 bytes of extra_block
%assign offset 0
%rep 8
movdqa [lane_data + _extra_block + offset], xmm0
%assign offset (offset + 16)
%endrep
;; Clear first 48 bytes (SHA-384) or 64 bytes (SHA-512) of outer_block
movdqa [lane_data + _outer_block], xmm0
movdqa [lane_data + _outer_block + 16], xmm0
movdqa [lane_data + _outer_block + 32], xmm0
%if (SHA_X_DIGEST_SIZE != 384)
movdqa [lane_data + _outer_block + 48], xmm0
%endif
APPEND(skip_clear_,I):
%assign I (I+1)
%endrep
%endif ;; SAFE_DATA
return:
mov rbx, [rsp + _gpr_save + 8*0]
mov rbp, [rsp + _gpr_save + 8*1]
mov rsp, [rsp + _rsp_save] ; original SP
ret
mksection stack-noexec
|
; A018902: a(n+2) = 5*a(n+1) - 3*a(n).
; 1,4,17,73,314,1351,5813,25012,107621,463069,1992482,8573203,36888569,158723236,682950473,2938582657,12644061866,54404561359,234090621197,1007239421908,4333925245949,18647907964021,80237764082258,345245096519227,1485512190349361,6391825662189124,27502591739897537,118337481712920313,509179633344908954,2190885721585783831,9426889707894192293,40561791374713609972,174528287749885472981,750956064625286534989,3231195459876776256002,13903109105508021675043,59821959147909779607209
mov $1,6
mov $2,2
lpb $0
sub $0,1
add $1,$2
add $2,$1
mul $1,3
lpe
mov $0,$1
div $0,6
|
; A101825: G.f.: x*(1+x)^2/(1-x^3).
; 0,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1,1,2,1
sub $0,1
mod $0,3
mov $1,2
bin $1,$0
mov $0,$1
|
; A101340: a(n) = prime(n)^prime(n)+prime(n).
; Submitted by Christian Krause
; 6,30,3130,823550,285311670622,302875106592266,827240261886336764194,1978419655660313589123998,20880467999847912034355032910590,2567686153161211134561828214731016126483498,17069174130723235958610643029059314756044734462,10555134955777783414078330085995832946127396083370199442554,1330877630632711998713399240963346255985889330161650994325137953682,17343773367030267519903781288812032158308062539012091953077767198995550,3877924263464448622666648186154330754898344901344205917642325627886496385062910
seq $0,6005 ; The odd prime numbers together with 1.
trn $0,2
add $0,2
mov $1,$0
pow $1,$0
add $0,$1
|
/* Copyright 2015 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/core/kernels/cwise_ops_common.h"
namespace tensorflow {
#if EIGEN_HAS_C99_MATH
REGISTER3(UnaryOp, CPU, "Erfc", functor::erfc, float, Eigen::half, double);
#if GOOGLE_CUDA
REGISTER3(UnaryOp, GPU, "Erfc", functor::erfc, float, Eigen::half, double);
#endif // GOOGLE_CUDA
#endif // EIGEN_HAS_C99_MATH
} // namespace tensorflow
|
; A016968: a(n) = (6*n + 4)^12.
; 16777216,1000000000000,281474976710656,12855002631049216,232218265089212416,2386420683693101056,16777216000000000000,89762301673555234816,390877006486250192896,1449225352009601191936,4722366482869645213696,13841287201000000000000,37133262473195501387776,92420056270299898187776,215671155821681003462656,475920314814253376475136,1000000000000000000000000,2012196471835550329409536,3895975992546975973113856,7287592625109126008344576,13214788658781797667045376,23298085122481000000000000,40037495277186834126340096,67214060505664762405851136,110443607719611533356957696,177929783385962838621884416,281474976710656000000000000,437821471697555965584019456,670411357165926452996079616,1011672693003313726683222016,1505961523834397662438752256,2213314919066161000000000000,3214199700417740936751087616,4615475323420547975828279296,6557827967253220516257857536,9224976748383532391296208896,12855002631049216000000000000,17754206618385148880104984576,24313966763341113270967730176,33031134065402989058412384256,44532586081169051256761614336,59604644775390625000000000000,79228162514264337593543950336,104620187934458937028636512256,137283242530308845011443122176,179063370050426074779119128576,232218265089212416000000000000,299496945547901850804899024896,384232606918345112299069505536,490450485651332023716795191296,622992765297495137011017711616,787662783788549761000000000000,991391044344780112897566048256,1242425797286480951825250390016,1550551246778975776674326511616,1927336746591631502843839123456,2386420683693101056000000000000,2943833109384368375058857660416,3618361566189999678189727645696,4431964976444753912220451803136,5410240907043328777415185924096,6582952005840035281000000000000,7984617920426728775852675301376,9655179561276152586506710552576,11640743160370438345557966585856,13994412205360056505895889473536,16777216000000000000000000000000,20059144316135212607058101211136,23920298362969902942430645190656,28452169107935982225126351179776,33759054842422944355374937931776,39959630797262576401000000000000,47188684579564485892255510429696,55599032226731174075692470439936,65363630757775006047741354704896,76677904249017825583200724258816,89762301673555234816000000000000,104865106024265053943081802797056,122265515591462830613214753980416,142277019691463451701972659081216,165251092644282265779977014214656,191581231380566414401000000000000,221707363722732516328316354953216,256120656136427175934096908292096,295368751589131265875868423028736,340061470086390423762452034359296,390877006486250192896000000000000,448568662322567892065999292338176,513972150601614498929401686654976,588013514877506214979375506067456,671717706364343388493779080052736,766217865410400390625000000000000,872765356346311041540623681191936,992740607529029370660714159149056,1127664811340606942471644172517376,1279212541969801777218067043454976,1449225352009601191936000000000000,1639726412249378930288083240554496,1852936262531190131220884368654336,2091289745180308584216846075498496
mul $0,6
add $0,4
pow $0,12
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <array>
#include <cstddef>
#include <functional>
#include <memory>
#include <optional>
#include <ostream>
#include <pup.h>
#include <string>
#include <utility>
#include <vector>
#include "DataStructures/DataBox/DataBox.hpp"
#include "DataStructures/DataBox/DataBoxTag.hpp"
#include "DataStructures/DataBox/DataOnSlice.hpp"
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/SubitemTag.hpp"
#include "DataStructures/DataBox/Subitems.hpp"
#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/DataBox/TagName.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Index.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "DataStructures/Variables.hpp"
#include "DataStructures/VariablesTag.hpp"
#include "Framework/TestHelpers.hpp"
#include "Helpers/DataStructures/DataBox/TestHelpers.hpp"
#include "Utilities/Gsl.hpp"
#include "Utilities/Literals.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
#include "Utilities/TypeTraits.hpp"
namespace db {
template <typename TagsList>
class DataBox;
} // namespace db
struct NoSuchType;
template <typename TagsList>
class Variables;
template <typename X, typename Symm, typename IndexList>
class Tensor;
namespace {
void multiply_by_two(const gsl::not_null<double*> result, const double value) {
*result = 2.0 * value;
}
void append_word(const gsl::not_null<std::string*> result,
const std::string& text, const double value) {
std::stringstream ss;
ss << value;
*result = text + ss.str();
}
namespace test_databox_tags {
// [databox_tag_example]
struct Tag0 : db::SimpleTag {
using type = double;
};
// [databox_tag_example]
struct Tag1 : db::SimpleTag {
using type = std::vector<double>;
};
struct Tag2Base : db::BaseTag {};
struct Tag2 : db::SimpleTag, Tag2Base {
using type = std::string;
};
struct Tag3 : db::SimpleTag {
using type = std::string;
};
struct Tag4 : db::SimpleTag {
using type = double;
};
struct Tag4Compute : Tag4, db::ComputeTag {
using base = Tag4;
using return_type = double;
static constexpr auto function = multiply_by_two;
using argument_tags = tmpl::list<Tag0>;
};
struct Tag5 : db::SimpleTag {
using type = std::string;
};
struct Tag5Compute : Tag5, db::ComputeTag {
using base = Tag5;
using return_type = std::string;
static constexpr auto function = append_word;
using argument_tags = tmpl::list<Tag2, Tag4>;
};
struct Tag6 : db::SimpleTag {
using type = std::string;
};
struct Tag6Compute : Tag6, db::ComputeTag {
using base = Tag6;
using return_type = std::string;
static void function(gsl::not_null<std::string*> result,
const std::string& s) noexcept {
*result = s;
}
using argument_tags = tmpl::list<Tag2Base>;
};
// [compute_item_tag_function]
struct Lambda0 : db::SimpleTag {
using type = double;
};
struct Lambda0Compute : Lambda0, db::ComputeTag {
using base = Lambda0;
using return_type = double;
static constexpr void function(const gsl::not_null<double*> result,
const double a) {
*result = 3.0 * a;
}
using argument_tags = tmpl::list<Tag0>;
};
// [compute_item_tag_function]
struct Lambda1 : db::SimpleTag {
using type = double;
};
// [compute_item_tag_no_tags]
struct Lambda1Compute : Lambda1, db::ComputeTag {
using base = Lambda1;
using return_type = double;
static constexpr void function(const gsl::not_null<double*> result) {
*result = 7.0;
}
using argument_tags = tmpl::list<>;
};
// [compute_item_tag_no_tags]
// [databox_prefix_tag_example]
template <typename Tag>
struct TagPrefix : db::PrefixTag, db::SimpleTag {
using type = typename Tag::type;
using tag = Tag;
static std::string name() noexcept {
return "TagPrefix(" + db::tag_name<Tag>() + ")";
}
};
// [databox_prefix_tag_example]
struct PointerBase : db::BaseTag {};
struct Pointer : PointerBase, db::SimpleTag {
using type = std::unique_ptr<int>;
};
struct PointerToCounterBase : db::BaseTag {};
struct PointerToCounter : PointerToCounterBase, db::SimpleTag {
using type = std::unique_ptr<int>;
};
struct PointerToCounterCompute : PointerToCounter, db::ComputeTag {
using base = PointerToCounter;
using return_type = std::unique_ptr<int>;
static void function(const gsl::not_null<return_type*> result,
const int& p) noexcept {
*result = std::make_unique<int>(p + 1);
}
using argument_tags = tmpl::list<Pointer>;
};
struct PointerToSum : db::SimpleTag {
using type = std::unique_ptr<int>;
};
struct PointerToSumCompute : PointerToSum, db::ComputeTag {
using base = PointerToSum;
using return_type = std::unique_ptr<int>;
static void function(const gsl::not_null<return_type*> ret, const int& arg,
const int& same_arg) noexcept {
*ret = std::make_unique<int>(arg + same_arg);
}
using argument_tags = tmpl::list<PointerToCounter, PointerToCounterBase>;
};
} // namespace test_databox_tags
using EmptyBox = decltype(db::create<db::AddSimpleTags<>>());
static_assert(std::is_same_v<decltype(db::create_from<db::RemoveTags<>>(
std::declval<EmptyBox>())),
EmptyBox>,
"Wrong create_from result type");
using Box_t = db::DataBox<tmpl::list<
test_databox_tags::Tag0, test_databox_tags::Tag1, test_databox_tags::Tag2,
test_databox_tags::TagPrefix<test_databox_tags::Tag0>,
test_databox_tags::Tag4Compute, test_databox_tags::Tag5Compute>>;
static_assert(
std::is_same<
decltype(
db::create_from<db::RemoveTags<test_databox_tags::Tag1>>(Box_t{})),
db::DataBox<
tmpl::list<test_databox_tags::Tag0, test_databox_tags::Tag2,
test_databox_tags::TagPrefix<test_databox_tags::Tag0>,
test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>>::value,
"Failed testing removal of item");
static_assert(
std::is_same<
decltype(
db::create_from<db::RemoveTags<test_databox_tags::Tag5>>(Box_t{})),
db::DataBox<
tmpl::list<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2,
test_databox_tags::TagPrefix<test_databox_tags::Tag0>,
test_databox_tags::Tag4Compute>>>::value,
"Failed testing removal of compute item");
static_assert(std::is_same<decltype(db::create_from<db::RemoveTags<>>(Box_t{})),
Box_t>::value,
"Failed testing no-op create_from");
void test_databox() noexcept {
INFO("test databox");
const auto create_original_box = []() {
// [create_databox]
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute,
test_databox_tags::Lambda0Compute,
test_databox_tags::Lambda1Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
// [create_databox]
return original_box;
};
{
INFO("Default-construction");
auto simple_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>>();
CHECK(db::get<test_databox_tags::Tag0>(simple_box) == 0.);
CHECK(db::get<test_databox_tags::Tag1>(simple_box).empty());
CHECK(db::get<test_databox_tags::Tag2>(simple_box).empty());
db::mutate<test_databox_tags::Tag0, test_databox_tags::Tag2>(
make_not_null(&simple_box),
[](const gsl::not_null<double*> val,
const gsl::not_null<std::string*> str) noexcept {
*val = 1.5;
*str = "My Sample String";
});
const auto& box =
db::create_from<db::RemoveTags<>,
db::AddSimpleTags<test_databox_tags::Tag3>,
db::AddComputeTags<test_databox_tags::Tag4Compute>>(
std::move(simple_box));
CHECK(db::get<test_databox_tags::Tag3>(box).empty());
CHECK(db::get<test_databox_tags::Tag0>(box) == 1.5);
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
CHECK(db::get<test_databox_tags::Tag4>(box) == 3.);
}
{
const auto original_box = create_original_box();
static_assert(
std::is_same<
decltype(original_box),
const db::DataBox<db::detail::expand_subitems<tmpl::append<
tmpl::list<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
tmpl::list<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute,
test_databox_tags::Lambda0Compute,
test_databox_tags::Lambda1Compute>>>>>::value,
"Failed to create original_box");
// [using_db_get]
const auto& tag0 = db::get<test_databox_tags::Tag0>(original_box);
// [using_db_get]
CHECK(tag0 == 3.14);
// Check retrieving chained compute item result
CHECK(db::get<test_databox_tags::Tag5>(original_box) ==
"My Sample String6.28"s);
CHECK(db::get<test_databox_tags::Lambda0>(original_box) == 3.0 * 3.14);
CHECK(db::get<test_databox_tags::Lambda1>(original_box) == 7.0);
}
// No removal
{
auto original_box = create_original_box();
const auto& box =
db::create_from<db::RemoveTags<>>(std::move(original_box));
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
CHECK(db::get<test_databox_tags::Tag5>(box) == "My Sample String6.28"s);
CHECK(db::get<test_databox_tags::Lambda0>(box) == 3.0 * 3.14);
}
{
// [create_from_remove]
auto original_box = create_original_box();
const auto& box = db::create_from<db::RemoveTags<test_databox_tags::Tag1>>(
std::move(original_box));
// [create_from_remove]
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
CHECK(db::get<test_databox_tags::Tag5>(box) == "My Sample String6.28"s);
CHECK(db::get<test_databox_tags::Lambda0>(box) == 3.0 * 3.14);
}
{
// [create_from_add_item]
auto original_box = create_original_box();
const auto& box =
db::create_from<db::RemoveTags<>,
db::AddSimpleTags<test_databox_tags::Tag3>>(
std::move(original_box), "Yet another test string"s);
// [create_from_add_item]
CHECK(db::get<test_databox_tags::Tag3>(box) == "Yet another test string"s);
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
// Check retrieving compute item result
CHECK(db::get<test_databox_tags::Tag5>(box) == "My Sample String6.28"s);
CHECK(db::get<test_databox_tags::Lambda0>(box) == 3.0 * 3.14);
}
{
// [create_from_add_compute_item]
auto simple_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
const auto& box =
db::create_from<db::RemoveTags<>, db::AddSimpleTags<>,
db::AddComputeTags<test_databox_tags::Tag4Compute>>(
std::move(simple_box));
// [create_from_add_compute_item]
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
// Check retrieving compute item result
CHECK(db::get<test_databox_tags::Tag4>(box) == 6.28);
}
{
auto simple_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
const auto& box =
db::create_from<db::RemoveTags<>,
db::AddSimpleTags<test_databox_tags::Tag3>,
db::AddComputeTags<test_databox_tags::Tag4Compute>>(
std::move(simple_box), "Yet another test string"s);
CHECK(db::get<test_databox_tags::Tag3>(box) == "Yet another test string"s);
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
// Check retrieving compute item result
CHECK(db::get<test_databox_tags::Tag4>(box) == 6.28);
}
{
auto simple_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
const auto& box =
db::create_from<db::RemoveTags<test_databox_tags::Tag1>,
db::AddSimpleTags<test_databox_tags::Tag3>,
db::AddComputeTags<test_databox_tags::Tag4Compute>>(
std::move(simple_box), "Yet another test string"s);
CHECK(db::get<test_databox_tags::Tag3>(box) == "Yet another test string"s);
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
// Check retrieving compute item result
CHECK(6.28 == db::get<test_databox_tags::Tag4>(box));
}
{
const auto box = db::create<
db::AddSimpleTags<test_databox_tags::Pointer>,
db::AddComputeTags<test_databox_tags::PointerToCounterCompute,
test_databox_tags::PointerToSumCompute>>(
std::make_unique<int>(3));
using DbTags = decltype(box)::tags_list;
static_assert(
std::is_same_v<
db::detail::const_item_type<test_databox_tags::Pointer, DbTags>,
const int&>,
"Wrong type for const_item_type on unique_ptr simple item");
static_assert(
std::is_same_v<
decltype(db::get<test_databox_tags::Pointer>(box)),
db::detail::const_item_type<test_databox_tags::Pointer, DbTags>>,
"Wrong type for get on unique_ptr simple item");
CHECK(db::get<test_databox_tags::Pointer>(box) == 3);
static_assert(
std::is_same_v<
db::detail::const_item_type<test_databox_tags::PointerBase, DbTags>,
const int&>,
"Wrong type for const_item_type on unique_ptr simple item by base");
static_assert(
std::is_same_v<decltype(db::get<test_databox_tags::PointerBase>(box)),
db::detail::const_item_type<
test_databox_tags::PointerBase, DbTags>>,
"Wrong type for get on unique_ptr simple item by base");
CHECK(db::get<test_databox_tags::PointerBase>(box) == 3);
static_assert(
std::is_same_v<db::detail::const_item_type<
test_databox_tags::PointerToCounter, DbTags>,
const int&>,
"Wrong type for const_item_type on unique_ptr compute item");
static_assert(
std::is_same_v<
decltype(db::get<test_databox_tags::PointerToCounter>(box)),
db::detail::const_item_type<test_databox_tags::PointerToCounter,
DbTags>>,
"Wrong type for get on unique_ptr compute item");
CHECK(db::get<test_databox_tags::PointerToCounter>(box) == 4);
static_assert(
std::is_same_v<db::detail::const_item_type<
test_databox_tags::PointerToCounterBase, DbTags>,
const int&>,
"Wrong type for const_item_type on unique_ptr compute item by base");
static_assert(
std::is_same_v<
decltype(db::get<test_databox_tags::PointerToCounterBase>(box)),
db::detail::const_item_type<test_databox_tags::PointerToCounterBase,
DbTags>>,
"Wrong type for get on unique_ptr compute item by base");
CHECK(db::get<test_databox_tags::PointerToCounterBase>(box) == 4);
static_assert(std::is_same_v<db::detail::const_item_type<
test_databox_tags::PointerToSum, DbTags>,
const int&>,
"Wrong type for const_item_type on unique_ptr");
static_assert(
std::is_same_v<decltype(db::get<test_databox_tags::PointerToSum>(box)),
db::detail::const_item_type<
test_databox_tags::PointerToSum, DbTags>>,
"Wrong type for get on unique_ptr");
CHECK(db::get<test_databox_tags::PointerToSum>(box) == 8);
}
}
namespace ArgumentTypeTags {
struct NonCopyable : db::SimpleTag {
using type = ::NonCopyable;
};
template <size_t N>
struct String : db::SimpleTag {
using type = std::string;
};
} // namespace ArgumentTypeTags
void test_create_argument_types() noexcept {
INFO("test create argument types");
std::string mutable_string = "mutable";
const std::string const_string = "const";
std::string move_string = "move";
const std::string const_move_string = "const move";
// clang-tidy: std::move of a const variable
auto box = db::create<db::AddSimpleTags<
ArgumentTypeTags::NonCopyable, ArgumentTypeTags::String<0>,
ArgumentTypeTags::String<1>, ArgumentTypeTags::String<2>,
ArgumentTypeTags::String<3>>>(NonCopyable{}, mutable_string, const_string,
std::move(move_string),
std::move(const_move_string)); // NOLINT
CHECK(mutable_string == "mutable");
CHECK(const_string == "const");
CHECK(db::get<ArgumentTypeTags::String<0>>(box) == "mutable");
CHECK(db::get<ArgumentTypeTags::String<1>>(box) == "const");
CHECK(db::get<ArgumentTypeTags::String<2>>(box) == "move");
CHECK(db::get<ArgumentTypeTags::String<3>>(box) == "const move");
}
void test_get_databox() noexcept {
INFO("test get databox");
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
CHECK(std::addressof(original_box) ==
std::addressof(db::get<Tags::DataBox>(original_box)));
// [databox_self_tag_example]
auto check_result_no_args = [](const auto& box) {
CHECK(db::get<test_databox_tags::Tag2>(box) == "My Sample String"s);
CHECK(db::get<test_databox_tags::Tag5>(box) == "My Sample String6.28"s);
};
db::apply<tmpl::list<Tags::DataBox>>(check_result_no_args, original_box);
// [databox_self_tag_example]
}
} // namespace
// [[OutputRegex, Unable to retrieve a \(compute\) item 'DataBox' from the
// DataBox from within a call to mutate. You must pass these either through the
// capture list of the lambda or the constructor of a class, this restriction
// exists to avoid complexity.]]
SPECTRE_TEST_CASE("Unit.DataStructures.DataBox.get_databox_error",
"[Unit][DataStructures]") {
ERROR_TEST();
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
CHECK(std::addressof(original_box) ==
std::addressof(db::get<Tags::DataBox>(original_box)));
db::mutate<test_databox_tags::Tag0>(
make_not_null(&original_box),
[&original_box](const gsl::not_null<double*> /*tag0*/) {
(void)db::get<Tags::DataBox>(original_box);
});
}
namespace {
void test_mutate() noexcept {
INFO("test mutate");
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2, test_databox_tags::Pointer>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
std::make_unique<int>(3));
CHECK(approx(db::get<test_databox_tags::Tag4>(original_box)) == 3.14 * 2.0);
// [databox_mutate_example]
db::mutate<test_databox_tags::Tag0, test_databox_tags::Tag1>(
make_not_null(&original_box),
[](const gsl::not_null<double*> tag0,
const gsl::not_null<std::vector<double>*> tag1,
const double compute_tag0) {
CHECK(6.28 == compute_tag0);
*tag0 = 10.32;
(*tag1)[0] = 837.2;
},
db::get<test_databox_tags::Tag4>(original_box));
CHECK(10.32 == db::get<test_databox_tags::Tag0>(original_box));
CHECK(837.2 == db::get<test_databox_tags::Tag1>(original_box)[0]);
// [databox_mutate_example]
CHECK(approx(db::get<test_databox_tags::Tag4>(original_box)) == 10.32 * 2.0);
auto result = db::mutate<test_databox_tags::Tag0>(
make_not_null(&original_box),
[](const gsl::not_null<double*> tag0, const double compute_tag0) {
return *tag0 * compute_tag0;
},
db::get<test_databox_tags::Tag4>(original_box));
CHECK(result == square(10.32) * 2.0);
auto pointer_to_result = db::mutate<test_databox_tags::Tag0>(
make_not_null(&original_box),
[&result](const gsl::not_null<double*> tag0, const double compute_tag0) {
*tag0 /= compute_tag0;
return &result;
},
db::get<test_databox_tags::Tag4>(original_box));
CHECK(db::get<test_databox_tags::Tag0>(original_box) == 0.5);
CHECK(pointer_to_result == &result);
db::mutate<test_databox_tags::Pointer>(
make_not_null(&original_box), [](auto p) noexcept {
static_assert(std::is_same_v<typename test_databox_tags::Pointer::type,
std::unique_ptr<int>>,
"Wrong type for item_type on unique_ptr");
static_assert(
std::is_same_v<
decltype(p),
gsl::not_null<typename test_databox_tags::Pointer::type*>>,
"Wrong type for mutate on unique_ptr");
CHECK(**p == 3);
*p = std::make_unique<int>(5);
});
CHECK(db::get<test_databox_tags::Pointer>(original_box) == 5);
}
} // namespace
// [[OutputRegex, Unable to retrieve a \(compute\) item 'Tag4' from the
// DataBox from within a call to mutate. You must pass these either through the
// capture list of the lambda or the constructor of a class, this restriction
// exists to avoid complexity]]
SPECTRE_TEST_CASE("Unit.DataStructures.DataBox.mutate_locked_get",
"[Unit][DataStructures]") {
ERROR_TEST();
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
db::mutate<test_databox_tags::Tag0, test_databox_tags::Tag1>(
make_not_null(&original_box),
[&original_box](const gsl::not_null<double*> tag0,
const gsl::not_null<std::vector<double>*> tag1) {
db::get<test_databox_tags::Tag4>(original_box);
*tag0 = 10.32;
(*tag1)[0] = 837.2;
});
}
// [[OutputRegex, Unable to mutate a DataBox that is already being mutated. This
// error occurs when mutating a DataBox from inside the invokable passed to the
// mutate function]]
SPECTRE_TEST_CASE("Unit.DataStructures.DataBox.mutate_locked_mutate",
"[Unit][DataStructures]") {
ERROR_TEST();
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
db::mutate<test_databox_tags::Tag0>(
make_not_null(&original_box),
[&original_box](const gsl::not_null<double*> /*unused*/) {
db::mutate<test_databox_tags::Tag1>(
make_not_null(&original_box),
[](const gsl::not_null<std::vector<double>*> tag1) {
(*tag1)[0] = 10.0;
});
});
}
namespace {
struct NonCopyableFunctor {
NonCopyableFunctor() = default;
NonCopyableFunctor(const NonCopyableFunctor&) = delete;
NonCopyableFunctor(NonCopyableFunctor&&) = delete;
NonCopyableFunctor& operator=(const NonCopyableFunctor&) = delete;
NonCopyableFunctor& operator=(NonCopyableFunctor&&) = delete;
~NonCopyableFunctor() = default;
// The && before the function body requires the object to be an
// rvalue for the method to be called. This checks that the apply
// functions correctly preserve the value category of the functor.
template <typename... Args>
void operator()(Args&&... /*unused*/) && {}
};
void test_apply() noexcept {
INFO("test apply");
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2, test_databox_tags::Pointer>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute,
test_databox_tags::PointerToCounterCompute,
test_databox_tags::PointerToSumCompute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
std::make_unique<int>(3));
auto check_result_no_args = [](const std::string& sample_string,
const auto& computed_string) {
CHECK(sample_string == "My Sample String"s);
CHECK(computed_string == "My Sample String6.28"s);
};
db::apply<tmpl::list<test_databox_tags::Tag2, test_databox_tags::Tag5>>(
check_result_no_args, original_box);
db::apply<tmpl::list<test_databox_tags::Tag2Base, test_databox_tags::Tag5>>(
check_result_no_args, original_box);
// [apply_example]
auto check_result_args = [](const std::string& sample_string,
const auto& computed_string, const auto& vector) {
CHECK(sample_string == "My Sample String"s);
CHECK(computed_string == "My Sample String6.28"s);
CHECK(vector == (std::vector<double>{8.7, 93.2, 84.7}));
};
db::apply<tmpl::list<test_databox_tags::Tag2, test_databox_tags::Tag5>>(
check_result_args, original_box,
db::get<test_databox_tags::Tag1>(original_box));
// [apply_example]
db::apply<tmpl::list<>>(NonCopyableFunctor{}, original_box);
// [apply_struct_example]
struct ApplyCallable {
static void apply(const std::string& sample_string,
const std::string& computed_string,
const std::vector<double>& vector) noexcept {
CHECK(sample_string == "My Sample String"s);
CHECK(computed_string == "My Sample String6.28"s);
CHECK(vector == (std::vector<double>{8.7, 93.2, 84.7}));
}
};
db::apply<tmpl::list<test_databox_tags::Tag2, test_databox_tags::Tag5>>(
ApplyCallable{}, original_box,
db::get<test_databox_tags::Tag1>(original_box));
// [apply_struct_example]
db::apply<tmpl::list<test_databox_tags::Tag2Base, test_databox_tags::Tag5>>(
ApplyCallable{}, original_box,
db::get<test_databox_tags::Tag1>(original_box));
// [apply_stateless_struct_example]
struct StatelessApplyCallable {
using argument_tags =
tmpl::list<test_databox_tags::Tag2, test_databox_tags::Tag5>;
static void apply(const std::string& sample_string,
const std::string& computed_string,
const std::vector<double>& vector) noexcept {
CHECK(sample_string == "My Sample String"s);
CHECK(computed_string == "My Sample String6.28"s);
CHECK(vector == (std::vector<double>{8.7, 93.2, 84.7}));
}
};
db::apply<StatelessApplyCallable>(
original_box, db::get<test_databox_tags::Tag1>(original_box));
// [apply_stateless_struct_example]
db::apply(StatelessApplyCallable{}, original_box,
db::get<test_databox_tags::Tag1>(original_box));
db::apply<tmpl::list<
test_databox_tags::Pointer, test_databox_tags::PointerToCounter,
test_databox_tags::PointerToSum, test_databox_tags::PointerBase,
test_databox_tags::PointerToCounterBase>>(
[](const int& simple, const int& compute, const int& compute_mutating,
const int& simple_base, const int& compute_base) noexcept {
CHECK(simple == 3);
CHECK(simple_base == 3);
CHECK(compute == 4);
CHECK(compute_base == 4);
CHECK(compute_mutating == 8);
},
original_box);
struct PointerApplyCallable {
using argument_tags = tmpl::list<
test_databox_tags::Pointer, test_databox_tags::PointerToCounter,
test_databox_tags::PointerToSum, test_databox_tags::PointerBase,
test_databox_tags::PointerToCounterBase>;
static void apply(const int& simple, const int& compute,
const int& compute_mutating, const int& simple_base,
const int& compute_base) noexcept {
CHECK(simple == 3);
CHECK(simple_base == 3);
CHECK(compute == 4);
CHECK(compute_base == 4);
CHECK(compute_mutating == 8);
}
};
db::apply<PointerApplyCallable>(original_box);
{
INFO("Test apply with optional reference argument");
db::apply<tmpl::list<test_databox_tags::Tag1, test_databox_tags::Tag1>>(
[](const std::optional<
std::reference_wrapper<const std::vector<double>>>
optional_ref,
const auto& const_ref) {
REQUIRE(optional_ref.has_value());
CHECK(optional_ref->get() == const_ref);
},
original_box);
}
}
struct Var1 : db::SimpleTag {
using type = tnsr::I<DataVector, 3, Frame::Grid>;
};
struct Var1Compute : Var1, db::ComputeTag {
using base = Var1;
using return_type = tnsr::I<DataVector, 3, Frame::Grid>;
static void function(const gsl::not_null<return_type*> result) {
*result = tnsr::I<DataVector, 3, Frame::Grid>(5_st, 2.0);
}
using argument_tags = tmpl::list<>;
};
struct Var2 : db::SimpleTag {
using type = Scalar<DataVector>;
};
template <class Tag, class VolumeDim, class Frame>
struct PrefixTag0 : db::PrefixTag, db::SimpleTag {
using type = TensorMetafunctions::prepend_spatial_index<
typename Tag::type, VolumeDim::value, UpLo::Lo, Frame>;
using tag = Tag;
};
using two_vars = tmpl::list<Var1, Var2>;
using vector_only = tmpl::list<Var1>;
using scalar_only = tmpl::list<Var2>;
static_assert(
std::is_same_v<
tmpl::back<db::wrap_tags_in<PrefixTag0, scalar_only, tmpl::size_t<2>,
Frame::Grid>>::type,
tnsr::i<DataVector, 2, Frame::Grid>>,
"Failed db::wrap_tags_in scalar_only");
static_assert(
std::is_same_v<
tmpl::back<db::wrap_tags_in<PrefixTag0, vector_only, tmpl::size_t<3>,
Frame::Grid>>::type,
tnsr::iJ<DataVector, 3, Frame::Grid>>,
"Failed db::wrap_tags_in vector_only");
static_assert(
std::is_same_v<
tmpl::back<db::wrap_tags_in<PrefixTag0, two_vars, tmpl::size_t<2>,
Frame::Grid>>::type,
tnsr::i<DataVector, 2, Frame::Grid>>,
"Failed db::wrap_tags_in two_vars scalar");
static_assert(
std::is_same_v<
tmpl::front<db::wrap_tags_in<PrefixTag0, two_vars, tmpl::size_t<3>,
Frame::Grid>>::type,
tnsr::iJ<DataVector, 3, Frame::Grid>>,
"Failed db::wrap_tags_in two_vars vector");
namespace test_databox_tags {
struct ScalarTagBase : db::BaseTag {};
struct ScalarTag : db::SimpleTag, ScalarTagBase {
using type = Scalar<DataVector>;
};
struct VectorTag : db::SimpleTag {
using type = tnsr::I<DataVector, 3>;
};
struct ScalarTag2 : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct VectorTag2 : db::SimpleTag {
using type = tnsr::I<DataVector, 3>;
};
struct ScalarTag3 : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct VectorTag3 : db::SimpleTag {
using type = tnsr::I<DataVector, 3>;
};
struct ScalarTag4 : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct VectorTag4 : db::SimpleTag {
using type = tnsr::I<DataVector, 3>;
};
struct IncompleteType; // Forward declare, do not define on purpose.
struct TagForIncompleteType : db::SimpleTag {
using type = IncompleteType;
};
} // namespace test_databox_tags
namespace {
void multiply_scalar_by_two(
const gsl::not_null<Variables<tmpl::list<test_databox_tags::ScalarTag2,
test_databox_tags::VectorTag2>>*>
result,
const Scalar<DataVector>& scalar) {
*result = Variables<
tmpl::list<test_databox_tags::ScalarTag2, test_databox_tags::VectorTag2>>{
scalar.begin()->size(), 2.0};
get<test_databox_tags::ScalarTag2>(*result).get() = scalar.get() * 2.0;
}
void multiply_scalar_by_four(const gsl::not_null<Scalar<DataVector>*> result,
const Scalar<DataVector>& scalar) {
*result = Scalar<DataVector>(scalar.get() * 4.0);
}
void multiply_scalar_by_three(const gsl::not_null<Scalar<DataVector>*> result,
const Scalar<DataVector>& scalar) {
*result = Scalar<DataVector>(scalar.get() * 3.0);
}
void divide_scalar_by_three(const gsl::not_null<Scalar<DataVector>*> result,
const Scalar<DataVector>& scalar) {
*result = Scalar<DataVector>(scalar.get() / 3.0);
}
void divide_scalar_by_two(
const gsl::not_null<Variables<tmpl::list<test_databox_tags::VectorTag3,
test_databox_tags::ScalarTag3>>*>
result,
const Scalar<DataVector>& scalar) {
*result = Variables<
tmpl::list<test_databox_tags::VectorTag3, test_databox_tags::ScalarTag3>>{
scalar.begin()->size(), 10.0};
get<test_databox_tags::ScalarTag3>(*result).get() = scalar.get() / 2.0;
}
void multiply_variables_by_two(
const gsl::not_null<Variables<tmpl::list<test_databox_tags::ScalarTag4,
test_databox_tags::VectorTag4>>*>
result,
const Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>& vars) {
*result = Variables<
tmpl::list<test_databox_tags::ScalarTag4, test_databox_tags::VectorTag4>>(
vars.number_of_grid_points(), 2.0);
get<test_databox_tags::ScalarTag4>(*result).get() *=
get<test_databox_tags::ScalarTag>(vars).get();
get<0>(get<test_databox_tags::VectorTag4>(*result)) *=
get<0>(get<test_databox_tags::VectorTag>(vars));
get<1>(get<test_databox_tags::VectorTag4>(*result)) *=
get<1>(get<test_databox_tags::VectorTag>(vars));
get<2>(get<test_databox_tags::VectorTag4>(*result)) *=
get<2>(get<test_databox_tags::VectorTag>(vars));
}
} // namespace
namespace test_databox_tags {
struct MultiplyScalarByTwo : db::SimpleTag {
using type = Variables<
tmpl::list<test_databox_tags::ScalarTag2, test_databox_tags::VectorTag2>>;
};
struct MultiplyScalarByTwoCompute : MultiplyScalarByTwo, db::ComputeTag {
using base = MultiplyScalarByTwo;
using variables_tags =
tmpl::list<test_databox_tags::ScalarTag2, test_databox_tags::VectorTag2>;
using return_type = Variables<variables_tags>;
static constexpr auto function = multiply_scalar_by_two;
using argument_tags = tmpl::list<test_databox_tags::ScalarTag>;
};
struct MultiplyScalarByFour : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct MultiplyScalarByFourCompute : MultiplyScalarByFour, db::ComputeTag {
using base = MultiplyScalarByFour;
using return_type = Scalar<DataVector>;
static constexpr auto function = multiply_scalar_by_four;
using argument_tags = tmpl::list<test_databox_tags::ScalarTag2>;
};
struct MultiplyScalarByThree : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct MultiplyScalarByThreeCompute : MultiplyScalarByThree, db::ComputeTag {
using base = MultiplyScalarByThree;
using return_type = Scalar<DataVector>;
static constexpr auto function = multiply_scalar_by_three;
using argument_tags = tmpl::list<test_databox_tags::MultiplyScalarByFour>;
};
struct DivideScalarByThree : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct DivideScalarByThreeCompute : DivideScalarByThree, db::ComputeTag {
using base = DivideScalarByThree;
using return_type = Scalar<DataVector>;
static constexpr auto function = divide_scalar_by_three;
using argument_tags = tmpl::list<test_databox_tags::MultiplyScalarByThree>;
};
struct DivideScalarByTwo : db::SimpleTag {
using type = Variables<
tmpl::list<test_databox_tags::VectorTag3, test_databox_tags::ScalarTag3>>;
};
struct DivideScalarByTwoCompute : DivideScalarByTwo, db::ComputeTag {
using base = DivideScalarByTwo;
using return_type = Variables<
tmpl::list<test_databox_tags::VectorTag3, test_databox_tags::ScalarTag3>>;
static constexpr auto function = divide_scalar_by_two;
using argument_tags = tmpl::list<test_databox_tags::DivideScalarByThree>;
};
struct MultiplyVariablesByTwo : db::SimpleTag {
using type = Variables<
tmpl::list<test_databox_tags::ScalarTag4, test_databox_tags::VectorTag4>>;
};
struct MultiplyVariablesByTwoCompute : MultiplyVariablesByTwo, db::ComputeTag {
using base = MultiplyVariablesByTwo;
using return_type = Variables<
tmpl::list<test_databox_tags::ScalarTag4, test_databox_tags::VectorTag4>>;
static constexpr auto function = multiply_variables_by_two;
using argument_tags = tmpl::list<Tags::Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>>;
};
} // namespace test_databox_tags
void test_variables() noexcept {
INFO("test variables");
using vars_tag = Tags::Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>;
auto box = db::create<
db::AddSimpleTags<vars_tag>,
db::AddComputeTags<test_databox_tags::MultiplyScalarByTwoCompute,
test_databox_tags::MultiplyScalarByFourCompute,
test_databox_tags::MultiplyScalarByThreeCompute,
test_databox_tags::DivideScalarByThreeCompute,
test_databox_tags::DivideScalarByTwoCompute,
test_databox_tags::MultiplyVariablesByTwoCompute>>(
Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>(2, 3.));
const auto check_references_match = [&box]() noexcept {
const auto& vars_original = db::get<vars_tag>(box);
CHECK(get(db::get<test_databox_tags::ScalarTag>(box)).data() ==
get(get<test_databox_tags::ScalarTag>(vars_original)).data());
for (size_t i = 0; i < 3; ++i) {
CHECK(db::get<test_databox_tags::VectorTag>(box).get(i).data() ==
get<test_databox_tags::VectorTag>(vars_original).get(i).data());
}
const auto& vars_mul_scalar =
db::get<test_databox_tags::MultiplyScalarByTwo>(box);
CHECK(get(db::get<test_databox_tags::ScalarTag2>(box)).data() ==
get(get<test_databox_tags::ScalarTag2>(vars_mul_scalar)).data());
for (size_t i = 0; i < 3; ++i) {
CHECK(db::get<test_databox_tags::VectorTag2>(box).get(i).data() ==
get<test_databox_tags::VectorTag2>(vars_mul_scalar).get(i).data());
}
const auto& vars_div_scalar =
db::get<test_databox_tags::DivideScalarByTwo>(box);
CHECK(get(db::get<test_databox_tags::ScalarTag3>(box)).data() ==
get(get<test_databox_tags::ScalarTag3>(vars_div_scalar)).data());
for (size_t i = 0; i < 3; ++i) {
CHECK(db::get<test_databox_tags::VectorTag3>(box).get(i).data() ==
get<test_databox_tags::VectorTag3>(vars_div_scalar).get(i).data());
}
const auto& vars_mul_two =
db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get(db::get<test_databox_tags::ScalarTag4>(box)).data() ==
get(get<test_databox_tags::ScalarTag4>(vars_mul_two)).data());
for (size_t i = 0; i < 3; ++i) {
CHECK(db::get<test_databox_tags::VectorTag4>(box).get(i).data() ==
get<test_databox_tags::VectorTag4>(vars_mul_two).get(i).data());
}
};
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 3.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 3.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
CHECK(db::get<test_databox_tags::MultiplyScalarByFour>(box) ==
Scalar<DataVector>(DataVector(2, 24.)));
CHECK(db::get<test_databox_tags::MultiplyScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 72.)));
CHECK(db::get<test_databox_tags::DivideScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 24.)));
CHECK(db::get<test_databox_tags::ScalarTag3>(box) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(db::get<test_databox_tags::VectorTag3>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 10.))));
CHECK(db::get<test_databox_tags::ScalarTag4>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag4>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
{
const auto& vars = db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get<test_databox_tags::ScalarTag4>(vars) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(get<test_databox_tags::VectorTag4>(vars) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
}
check_references_match();
db::mutate<test_databox_tags::ScalarTag>(
make_not_null(&box), [](const gsl::not_null<Scalar<DataVector>*> scalar) {
scalar->get() = 4.0;
});
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 4.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 3.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
CHECK(db::get<test_databox_tags::MultiplyScalarByFour>(box) ==
Scalar<DataVector>(DataVector(2, 32.)));
CHECK(db::get<test_databox_tags::MultiplyScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 96.)));
CHECK(db::get<test_databox_tags::DivideScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 32.)));
CHECK(db::get<test_databox_tags::ScalarTag3>(box) ==
Scalar<DataVector>(DataVector(2, 16.)));
CHECK(db::get<test_databox_tags::VectorTag3>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 10.))));
CHECK(db::get<test_databox_tags::ScalarTag4>(box) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(db::get<test_databox_tags::VectorTag4>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
{
const auto& vars = db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get<test_databox_tags::ScalarTag4>(vars) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(get<test_databox_tags::VectorTag4>(vars) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
}
check_references_match();
db::mutate<Tags::Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>>(
make_not_null(&box), [](const auto vars) {
get<test_databox_tags::ScalarTag>(*vars).get() = 6.0;
});
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 3.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
CHECK(db::get<test_databox_tags::MultiplyScalarByFour>(box) ==
Scalar<DataVector>(DataVector(2, 48.)));
CHECK(db::get<test_databox_tags::MultiplyScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 144.)));
CHECK(db::get<test_databox_tags::DivideScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 48.)));
CHECK(db::get<test_databox_tags::ScalarTag3>(box) ==
Scalar<DataVector>(DataVector(2, 24.)));
CHECK(db::get<test_databox_tags::VectorTag3>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 10.))));
CHECK(db::get<test_databox_tags::ScalarTag4>(box) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(db::get<test_databox_tags::VectorTag4>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
{
const auto& vars = db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get<test_databox_tags::ScalarTag4>(vars) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(get<test_databox_tags::VectorTag4>(vars) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
}
check_references_match();
db::mutate<Tags::Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>>(
make_not_null(&box), [](const auto vars) {
get<test_databox_tags::ScalarTag>(*vars).get() = 4.0;
get<test_databox_tags::VectorTag>(*vars) =
tnsr::I<DataVector, 3>(DataVector(2, 6.));
});
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 4.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
CHECK(db::get<test_databox_tags::MultiplyScalarByFour>(box) ==
Scalar<DataVector>(DataVector(2, 32.)));
CHECK(db::get<test_databox_tags::MultiplyScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 96.)));
CHECK(db::get<test_databox_tags::DivideScalarByThree>(box) ==
Scalar<DataVector>(DataVector(2, 32.)));
CHECK(db::get<test_databox_tags::ScalarTag3>(box) ==
Scalar<DataVector>(DataVector(2, 16.)));
CHECK(db::get<test_databox_tags::VectorTag3>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 10.))));
CHECK(db::get<test_databox_tags::ScalarTag4>(box) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(db::get<test_databox_tags::VectorTag4>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 12.))));
{
const auto& vars = db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get<test_databox_tags::ScalarTag4>(vars) ==
Scalar<DataVector>(DataVector(2, 8.)));
CHECK(get<test_databox_tags::VectorTag4>(vars) ==
(tnsr::I<DataVector, 3>(DataVector(2, 12.))));
}
check_references_match();
}
struct Tag1 : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct Tag2 : db::SimpleTag {
using type = Scalar<DataVector>;
};
void test_variables2() noexcept {
INFO("test variables2");
auto box =
db::create<db::AddSimpleTags<Tags::Variables<tmpl::list<Tag1, Tag2>>>>(
Variables<tmpl::list<Tag1, Tag2>>(1, 1.));
db::mutate<Tags::Variables<tmpl::list<Tag1, Tag2>>>(
make_not_null(&box), [](const auto vars) {
*vars = Variables<tmpl::list<Tag1, Tag2>>(1, 2.);
});
CHECK(db::get<Tag1>(box) == Scalar<DataVector>(DataVector(1, 2.)));
}
void test_reset_compute_items() noexcept {
INFO("test reset compute items");
auto box = db::create<
db::AddSimpleTags<
test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2,
Tags::Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute,
test_databox_tags::MultiplyScalarByTwoCompute,
test_databox_tags::MultiplyVariablesByTwoCompute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>(2, 3.));
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 3.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 3.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
CHECK(db::get<test_databox_tags::ScalarTag4>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag4>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
{
const auto& vars = db::get<test_databox_tags::MultiplyVariablesByTwo>(box);
CHECK(get<test_databox_tags::ScalarTag4>(vars) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(get<test_databox_tags::VectorTag4>(vars) ==
(tnsr::I<DataVector, 3>(DataVector(2, 6.))));
}
}
namespace ExtraResetTags {
struct Var : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct Int : db::SimpleTag {
using type = int;
};
struct CheckReset : db::SimpleTag {
using type = int;
};
struct CheckResetCompute : CheckReset, db::ComputeTag {
using base = CheckReset;
using return_type = int;
static auto function(
const gsl::not_null<int*> result,
const ::Variables<tmpl::list<Var>>& /*unused*/) noexcept {
static bool first_call = true;
CHECK(first_call);
first_call = false;
*result = 0;
}
using argument_tags = tmpl::list<Tags::Variables<tmpl::list<Var>>>;
};
} // namespace ExtraResetTags
void test_variables_extra_reset() noexcept {
INFO("test variables extra reset");
auto box = db::create<
db::AddSimpleTags<ExtraResetTags::Int,
Tags::Variables<tmpl::list<ExtraResetTags::Var>>>,
db::AddComputeTags<ExtraResetTags::CheckResetCompute>>(
1, Variables<tmpl::list<ExtraResetTags::Var>>(2, 3.));
CHECK(db::get<ExtraResetTags::CheckReset>(box) == 0);
db::mutate<ExtraResetTags::Int>(make_not_null(&box),
[](const gsl::not_null<int*> /*unused*/) {});
CHECK(db::get<ExtraResetTags::CheckReset>(box) == 0);
}
// [mutate_apply_struct_definition_example]
struct TestDataboxMutateApply {
// delete copy semantics just to make sure it works. Not necessary in general.
TestDataboxMutateApply() = default;
TestDataboxMutateApply(const TestDataboxMutateApply&) = delete;
TestDataboxMutateApply& operator=(const TestDataboxMutateApply&) = delete;
TestDataboxMutateApply(TestDataboxMutateApply&&) = default;
TestDataboxMutateApply& operator=(TestDataboxMutateApply&&) = default;
~TestDataboxMutateApply() = default;
// These typelists are used by the `db::mutate_apply` overload that does not
// require these lists as template arguments
using return_tags =
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>;
using argument_tags = tmpl::list<test_databox_tags::Tag2>;
static void apply(const gsl::not_null<Scalar<DataVector>*> scalar,
const gsl::not_null<tnsr::I<DataVector, 3>*> vector,
const std::string& tag2) noexcept {
scalar->get() *= 2.0;
get<0>(*vector) *= 3.0;
get<1>(*vector) *= 4.0;
get<2>(*vector) *= 5.0;
CHECK(tag2 == "My Sample String"s);
}
};
// [mutate_apply_struct_definition_example]
struct TestDataboxMutateApplyBase {
using return_tags = tmpl::list<test_databox_tags::ScalarTag>;
using argument_tags = tmpl::list<test_databox_tags::Tag2Base>;
static void apply(const gsl::not_null<Scalar<DataVector>*> scalar,
const std::string& tag2) noexcept {
CHECK(*scalar == Scalar<DataVector>(DataVector(2, 6.)));
CHECK(tag2 == "My Sample String"s);
}
};
struct PointerMutateApply {
using return_tags = tmpl::list<test_databox_tags::Pointer>;
using argument_tags = tmpl::list<test_databox_tags::PointerToCounter,
test_databox_tags::PointerToSum>;
static void apply(const gsl::not_null<std::unique_ptr<int>*> ret,
const int& compute, const int& compute_mutating) noexcept {
**ret = 7;
CHECK(compute == 7);
CHECK(compute_mutating == 14);
}
};
struct PointerMutateApplyBase {
using return_tags = tmpl::list<test_databox_tags::Pointer>;
using argument_tags = tmpl::list<test_databox_tags::PointerToCounterBase>;
static void apply(const gsl::not_null<std::unique_ptr<int>*> ret,
const int& compute_base) noexcept {
**ret = 8;
CHECK(compute_base == 8);
}
};
void test_mutate_apply() noexcept {
INFO("test mutate apply");
auto box = db::create<
db::AddSimpleTags<
test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2,
Tags::Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>,
test_databox_tags::Pointer>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute,
test_databox_tags::MultiplyScalarByTwoCompute,
test_databox_tags::PointerToCounterCompute,
test_databox_tags::PointerToSumCompute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>(2, 3.),
std::make_unique<int>(3));
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 3.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 3.))));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
{
INFO("Apply function or lambda");
// [mutate_apply_struct_example_stateful]
db::mutate_apply(TestDataboxMutateApply{}, make_not_null(&box));
// [mutate_apply_struct_example_stateful]
db::mutate_apply(TestDataboxMutateApplyBase{}, make_not_null(&box));
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 6.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>{
{{DataVector(2, 9.), DataVector(2, 12.), DataVector(2, 15.)}}}));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
// [mutate_apply_lambda_example]
db::mutate_apply<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>,
tmpl::list<test_databox_tags::Tag2>>(
[](const gsl::not_null<Scalar<DataVector>*> scalar,
const gsl::not_null<tnsr::I<DataVector, 3>*> vector,
const std::string& tag2) {
scalar->get() *= 2.0;
get<0>(*vector) *= 3.0;
get<1>(*vector) *= 4.0;
get<2>(*vector) *= 5.0;
CHECK(tag2 == "My Sample String"s);
},
make_not_null(&box));
// [mutate_apply_lambda_example]
db::mutate_apply<tmpl::list<test_databox_tags::ScalarTag>,
tmpl::list<test_databox_tags::Tag2Base>>(
[](const gsl::not_null<Scalar<DataVector>*> scalar,
const std::string& tag2) {
CHECK(*scalar == Scalar<DataVector>(DataVector(2, 12.)));
CHECK(tag2 == "My Sample String"s);
},
make_not_null(&box));
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 12.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>{
{{DataVector(2, 27.), DataVector(2, 48.), DataVector(2, 75.)}}}));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 24.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
// check with a forwarded return value
size_t size_of_internal_string =
db::mutate_apply<tmpl::list<test_databox_tags::ScalarTag>,
tmpl::list<test_databox_tags::Tag2Base>>(
[](const gsl::not_null<Scalar<DataVector>*> scalar,
const std::string& tag2) {
CHECK(*scalar == Scalar<DataVector>(DataVector(2, 12.)));
CHECK(tag2 == "My Sample String"s);
return tag2.size();
},
make_not_null(&box));
CHECK(size_of_internal_string == 16_st);
db::mutate_apply<
tmpl::list<Tags::Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>>,
tmpl::list<test_databox_tags::Tag2>>(
[](const gsl::not_null<Variables<tmpl::list<
test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>*>
vars,
const std::string& tag2) {
get<test_databox_tags::ScalarTag>(*vars).get() *= 2.0;
get<0>(get<test_databox_tags::VectorTag>(*vars)) *= 3.0;
get<1>(get<test_databox_tags::VectorTag>(*vars)) *= 4.0;
get<2>(get<test_databox_tags::VectorTag>(*vars)) *= 5.0;
CHECK(tag2 == "My Sample String"s);
},
make_not_null(&box));
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 24.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>{{{DataVector(2, 81.), DataVector(2, 192.),
DataVector(2, 375.)}}}));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 48.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
}
{
INFO("Stateless struct with tags lists");
// [mutate_apply_struct_example_stateless]
db::mutate_apply<TestDataboxMutateApply>(make_not_null(&box));
// [mutate_apply_struct_example_stateless]
CHECK(approx(db::get<test_databox_tags::Tag4>(box)) == 3.14 * 2.0);
CHECK(db::get<test_databox_tags::ScalarTag>(box) ==
Scalar<DataVector>(DataVector(2, 48.)));
CHECK(db::get<test_databox_tags::VectorTag>(box) ==
(tnsr::I<DataVector, 3>{{{DataVector(2, 243.), DataVector(2, 768.),
DataVector(2, 1875.)}}}));
CHECK(db::get<test_databox_tags::ScalarTag2>(box) ==
Scalar<DataVector>(DataVector(2, 96.)));
CHECK(db::get<test_databox_tags::VectorTag2>(box) ==
(tnsr::I<DataVector, 3>(DataVector(2, 2.))));
}
{
INFO("unique_ptr");
db::mutate_apply<tmpl::list<test_databox_tags::Pointer>, tmpl::list<>>(
[](const gsl::not_null<std::unique_ptr<int>*> p) noexcept { **p = 5; },
make_not_null(&box));
db::mutate_apply<tmpl::list<>,
tmpl::list<test_databox_tags::Pointer,
test_databox_tags::PointerToCounter,
test_databox_tags::PointerToSum>>(
[](const int& simple, const int& compute,
const int& compute_mutating) noexcept {
CHECK(simple == 5);
CHECK(compute == 6);
CHECK(compute_mutating == 12);
},
make_not_null(&box));
db::mutate_apply<tmpl::list<test_databox_tags::Pointer>, tmpl::list<>>(
[](const gsl::not_null<std::unique_ptr<int>*> p) noexcept { **p = 6; },
make_not_null(&box));
db::mutate_apply<tmpl::list<>,
tmpl::list<test_databox_tags::PointerBase,
test_databox_tags::PointerToCounterBase>>(
[](const int& simple_base, const int& compute_base) noexcept {
CHECK(simple_base == 6);
CHECK(compute_base == 7);
},
make_not_null(&box));
db::mutate_apply<PointerMutateApply>(make_not_null(&box));
db::mutate_apply<PointerMutateApplyBase>(make_not_null(&box));
CHECK(db::get<test_databox_tags::Pointer>(box) == 8);
}
}
static_assert(
std::is_same_v<
db::compute_databox_type<tmpl::list<
test_databox_tags::Tag0, test_databox_tags::Tag1,
Tags::Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>,
test_databox_tags::Tag4Compute,
test_databox_tags::MultiplyScalarByTwoCompute>>,
db::DataBox<tmpl::list<
test_databox_tags::Tag0, test_databox_tags::Tag1,
Tags::Variables<brigand::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>,
test_databox_tags::ScalarTag, test_databox_tags::VectorTag,
test_databox_tags::Tag4Compute,
test_databox_tags::MultiplyScalarByTwoCompute,
::Tags::Subitem<test_databox_tags::ScalarTag2,
test_databox_tags::MultiplyScalarByTwoCompute>,
::Tags::Subitem<test_databox_tags::VectorTag2,
test_databox_tags::MultiplyScalarByTwoCompute>>>>,
"Failed testing db::compute_databox_type");
static_assert(
std::is_same_v<
db::compute_databox_type<
tmpl::list<test_databox_tags::TagForIncompleteType>>,
db::DataBox<tmpl::list<test_databox_tags::TagForIncompleteType>>>,
"Failed testing db::compute_databox_type for incomplete type");
void multiply_by_two_mutate(const gsl::not_null<std::vector<double>*> t,
const double value) {
if (t->empty()) {
t->resize(10);
}
for (auto& p : *t) {
p = 2.0 * value;
}
}
// [databox_mutating_compute_item_function]
void mutate_variables(
const gsl::not_null<Variables<tmpl::list<test_databox_tags::ScalarTag,
test_databox_tags::VectorTag>>*>
t,
const double value) {
if (t->number_of_grid_points() != 10) {
*t = Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>(
10, 0.0);
}
for (auto& p : get<test_databox_tags::ScalarTag>(*t)) {
p = 2.0 * value;
}
for (auto& p : get<test_databox_tags::VectorTag>(*t)) {
p = 3.0 * value;
}
}
// [databox_mutating_compute_item_function]
namespace test_databox_tags {
struct MutateTag0 : db::SimpleTag {
using type = std::vector<double>;
};
struct MutateTag0Compute : MutateTag0, db::ComputeTag {
using return_type = std::vector<double>;
using base = MutateTag0;
static constexpr auto function = multiply_by_two_mutate;
using argument_tags = tmpl::list<Tag0>;
};
struct MutateVariables : db::SimpleTag {
using type = Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>;
};
// [databox_mutating_compute_item_tag]
struct MutateVariablesCompute : MutateVariables, db::ComputeTag {
using base = MutateVariables;
static constexpr auto function = mutate_variables;
using return_type = Variables<
tmpl::list<test_databox_tags::ScalarTag, test_databox_tags::VectorTag>>;
using argument_tags = tmpl::list<Tag0>;
};
// [databox_mutating_compute_item_tag]
} // namespace test_databox_tags
void test_mutating_compute_item() noexcept {
INFO("test mutating compute item");
auto original_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::MutateTag0Compute,
test_databox_tags::MutateVariablesCompute,
test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
const double* const initial_data_location_mutating =
db::get<test_databox_tags::MutateTag0>(original_box).data();
const std::array<const double* const, 4>
initial_variables_data_location_mutate{
{get<test_databox_tags::ScalarTag>(
db::get<test_databox_tags::MutateVariables>(original_box))
.get()
.data(),
get<0>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data(),
get<1>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data(),
get<2>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data()}};
CHECK(approx(db::get<test_databox_tags::Tag4>(original_box)) == 3.14 * 2.0);
CHECK_ITERABLE_APPROX(db::get<test_databox_tags::MutateTag0>(original_box),
std::vector<double>(10, 2.0 * 3.14));
CHECK_ITERABLE_APPROX(
get<test_databox_tags::ScalarTag>(
db::get<test_databox_tags::MutateVariables>(original_box)),
Scalar<DataVector>(DataVector(10, 2.0 * 3.14)));
CHECK_ITERABLE_APPROX(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)),
typename test_databox_tags::VectorTag::type(DataVector(10, 3.0 * 3.14)));
db::mutate<test_databox_tags::Tag0, test_databox_tags::Tag1>(
make_not_null(&original_box),
[](const gsl::not_null<double*> tag0,
const gsl::not_null<std::vector<double>*> tag1,
const double compute_tag0) {
CHECK(6.28 == compute_tag0);
*tag0 = 10.32;
(*tag1)[0] = 837.2;
},
db::get<test_databox_tags::Tag4>(original_box));
CHECK(10.32 == db::get<test_databox_tags::Tag0>(original_box));
CHECK(837.2 == db::get<test_databox_tags::Tag1>(original_box)[0]);
CHECK(approx(db::get<test_databox_tags::Tag4>(original_box)) == 10.32 * 2.0);
CHECK_ITERABLE_APPROX(db::get<test_databox_tags::MutateTag0>(original_box),
std::vector<double>(10, 2.0 * 10.32));
CHECK(initial_data_location_mutating ==
db::get<test_databox_tags::MutateTag0>(original_box).data());
CHECK_ITERABLE_APPROX(
get<test_databox_tags::ScalarTag>(
db::get<test_databox_tags::MutateVariables>(original_box)),
Scalar<DataVector>(DataVector(10, 2.0 * 10.32)));
CHECK_ITERABLE_APPROX(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)),
typename test_databox_tags::VectorTag::type(DataVector(10, 3.0 * 10.32)));
// Check that the memory allocated by std::vector has not changed, which is
// the key feature of mutating compute items.
CHECK(initial_variables_data_location_mutate ==
(std::array<const double* const, 4>{
{get<test_databox_tags::ScalarTag>(
db::get<test_databox_tags::MutateVariables>(original_box))
.get()
.data(),
get<0>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data(),
get<1>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data(),
get<2>(
get<test_databox_tags::VectorTag>(
db::get<test_databox_tags::MutateVariables>(original_box)))
.data()}}));
}
namespace DataBoxTest_detail {
struct vector : db::SimpleTag {
using type = tnsr::I<DataVector, 3, Frame::Grid>;
};
struct scalar : db::SimpleTag {
using type = Scalar<DataVector>;
};
struct vector2 : db::SimpleTag {
using type = tnsr::I<DataVector, 3, Frame::Grid>;
};
} // namespace DataBoxTest_detail
void test_data_on_slice_single() noexcept {
INFO("test data on slice single");
const size_t x_extents = 2;
const size_t y_extents = 3;
const size_t z_extents = 4;
const size_t vec_size = DataBoxTest_detail::vector::type::size();
Index<3> extents(x_extents, y_extents, z_extents);
auto box = db::create<db::AddSimpleTags<DataBoxTest_detail::vector>>([]() {
Variables<tmpl::list<DataBoxTest_detail::vector>> vars(24, 0.);
for (size_t s = 0; s < vars.size(); ++s) {
// clang-tidy: do not use pointer arithmetic
vars.data()[s] = s; // NOLINT
}
return get<DataBoxTest_detail::vector>(vars);
}());
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_x(
y_extents * z_extents, 0.);
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_y(
x_extents * z_extents, 0.);
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_z(
x_extents * y_extents, 0.);
const size_t x_offset = 1;
const size_t y_offset = 2;
const size_t z_offset = 1;
for (size_t s = 0; s < expected_vars_sliced_in_x.size(); ++s) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_x.data()[s] = x_offset + s * x_extents; // NOLINT
}
for (size_t i = 0; i < vec_size; ++i) {
for (size_t x = 0; x < x_extents; ++x) {
for (size_t z = 0; z < z_extents; ++z) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_y
.data()[x + x_extents * (z + z_extents * i)] = // NOLINT
i * extents.product() + x + x_extents * (y_offset + z * y_extents);
}
}
}
for (size_t i = 0; i < vec_size; ++i) {
for (size_t x = 0; x < x_extents; ++x) {
for (size_t y = 0; y < y_extents; ++y) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_z
.data()[x + x_extents * (y + y_extents * i)] = // NOLINT
i * extents.product() + x + x_extents * (y + y_extents * z_offset);
}
}
}
CHECK(
// [data_on_slice]
db::data_on_slice(box, extents, 0, x_offset,
tmpl::list<DataBoxTest_detail::vector>{})
// [data_on_slice]
== expected_vars_sliced_in_x);
CHECK(db::data_on_slice(box, extents, 1, y_offset,
tmpl::list<DataBoxTest_detail::vector>{}) ==
expected_vars_sliced_in_y);
CHECK(db::data_on_slice(box, extents, 2, z_offset,
tmpl::list<DataBoxTest_detail::vector>{}) ==
expected_vars_sliced_in_z);
}
void test_data_on_slice() noexcept {
INFO("test data on slice");
const size_t x_extents = 2;
const size_t y_extents = 3;
const size_t z_extents = 4;
const size_t vec_size = DataBoxTest_detail::vector::type::size();
Index<3> extents(x_extents, y_extents, z_extents);
auto box = db::create<
db::AddSimpleTags<DataBoxTest_detail::vector, DataBoxTest_detail::scalar,
DataBoxTest_detail::vector2>>(
[]() {
Variables<tmpl::list<DataBoxTest_detail::vector>> vars(24, 0.);
for (size_t s = 0; s < vars.size(); ++s) {
// clang-tidy: do not use pointer arithmetic
vars.data()[s] = s; // NOLINT
}
return get<DataBoxTest_detail::vector>(vars);
}(),
Scalar<DataVector>(DataVector{8.9, 0.7, 6.7}),
[]() {
Variables<tmpl::list<DataBoxTest_detail::vector>> vars(24, 0.);
for (size_t s = 0; s < vars.size(); ++s) {
// clang-tidy: do not use pointer arithmetic
vars.data()[s] = s * 10.0; // NOLINT
}
return get<DataBoxTest_detail::vector>(vars);
}());
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_x(
y_extents * z_extents, 0.);
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_y(
x_extents * z_extents, 0.);
Variables<tmpl::list<DataBoxTest_detail::vector>> expected_vars_sliced_in_z(
x_extents * y_extents, 0.);
const size_t x_offset = 1;
const size_t y_offset = 2;
const size_t z_offset = 1;
for (size_t s = 0; s < expected_vars_sliced_in_x.size(); ++s) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_x.data()[s] = x_offset + s * x_extents; // NOLINT
}
for (size_t i = 0; i < vec_size; ++i) {
for (size_t x = 0; x < x_extents; ++x) {
for (size_t z = 0; z < z_extents; ++z) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_y
.data()[x + x_extents * (z + z_extents * i)] = // NOLINT
i * extents.product() + x + x_extents * (y_offset + z * y_extents);
}
}
}
for (size_t i = 0; i < vec_size; ++i) {
for (size_t x = 0; x < x_extents; ++x) {
for (size_t y = 0; y < y_extents; ++y) {
// clang-tidy: do not use pointer arithmetic
expected_vars_sliced_in_z
.data()[x + x_extents * (y + y_extents * i)] = // NOLINT
i * extents.product() + x + x_extents * (y + y_extents * z_offset);
}
}
}
// x slice
{
const auto sliced0 = data_on_slice(
box, extents, 0, x_offset,
tmpl::list<DataBoxTest_detail::vector, DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector>(sliced0) ==
get<DataBoxTest_detail::vector>(expected_vars_sliced_in_x));
CHECK(get<DataBoxTest_detail::vector2>(sliced0) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_x * 10.0)));
const auto sliced1 = data_on_slice(
box, extents, 0, x_offset, tmpl::list<DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector2>(sliced1) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_x * 10.0)));
}
// y slice
{
const auto sliced0 = data_on_slice(
box, extents, 1, y_offset,
tmpl::list<DataBoxTest_detail::vector, DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector>(sliced0) ==
get<DataBoxTest_detail::vector>(expected_vars_sliced_in_y));
CHECK(get<DataBoxTest_detail::vector2>(sliced0) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_y * 10.0)));
const auto sliced1 = data_on_slice(
box, extents, 1, y_offset, tmpl::list<DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector2>(sliced1) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_y * 10.0)));
}
// z slice
{
const auto sliced0 = data_on_slice(
box, extents, 2, z_offset,
tmpl::list<DataBoxTest_detail::vector, DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector>(sliced0) ==
get<DataBoxTest_detail::vector>(expected_vars_sliced_in_z));
CHECK(get<DataBoxTest_detail::vector2>(sliced0) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_z * 10.0)));
const auto sliced1 = data_on_slice(
box, extents, 2, z_offset, tmpl::list<DataBoxTest_detail::vector2>{});
CHECK(get<DataBoxTest_detail::vector2>(sliced1) ==
get<DataBoxTest_detail::vector>(
Variables<tmpl::list<DataBoxTest_detail::vector>>(
expected_vars_sliced_in_z * 10.0)));
}
}
} // namespace
namespace {
// We can't use raw fundamental types as subitems because subitems
// need to have a reference-like nature.
template <typename T>
class Boxed {
public:
explicit Boxed(std::shared_ptr<T> data) noexcept : data_(std::move(data)) {}
Boxed() = default;
// The multiple copy constructors (assignment operators) are needed
// to prevent users from modifying compute item values.
Boxed(const Boxed&) = delete;
Boxed(Boxed&) = default;
Boxed(Boxed&&) = default;
Boxed& operator=(const Boxed&) = delete;
Boxed& operator=(Boxed&) = default;
Boxed& operator=(Boxed&&) = default;
~Boxed() = default;
T& operator*() noexcept { return *data_; }
const T& operator*() const noexcept { return *data_; }
const std::shared_ptr<T>& data() const noexcept { return data_; }
// clang-tidy: no non-const references
void pup(PUP::er& p) noexcept { // NOLINT
if (p.isUnpacking()) {
T t{};
p | t;
data_ = std::make_shared<T>(std::move(t));
} else {
p | *data_;
}
}
private:
// Default-constructing this to a state that can be assigned to a subitem.
// This way we can test that the DataBox default-construction correctly links
// subitems.
std::shared_ptr<T> data_ =
std::make_shared<T>(std::numeric_limits<T>::signaling_NaN());
};
template <size_t N>
struct Parent : db::SimpleTag {
using type = std::pair<Boxed<int>, Boxed<double>>;
};
template <size_t N>
struct ParentCompute : Parent<N>, db::ComputeTag {
using base = Parent<N>;
using return_type = std::pair<Boxed<int>, Boxed<double>>;
static void function(
const gsl::not_null<return_type*> result,
const std::pair<Boxed<int>, Boxed<double>>& arg) noexcept {
count++;
*result = std::make_pair(
Boxed<int>(std::make_shared<int>(*arg.first + 1)),
Boxed<double>(std::make_shared<double>(*arg.second * 2.)));
}
using argument_tags = tmpl::list<Parent<N - 1>>;
static int count;
};
template <size_t N>
int ParentCompute<N>::count = 0;
template <size_t N>
struct First : db::SimpleTag {
using type = Boxed<int>;
static constexpr size_t index = 0;
};
template <size_t N>
struct Second : db::SimpleTag {
using type = Boxed<double>;
static constexpr size_t index = 1;
};
} // namespace
namespace db {
template <size_t N>
struct Subitems<Parent<N>> {
using type = tmpl::list<First<N>, Second<N>>;
using tag = Parent<N>;
template <typename Subtag>
static void create_item(
const gsl::not_null<typename tag::type*> parent_value,
const gsl::not_null<typename Subtag::type*> sub_value) noexcept {
*sub_value = std::get<Subtag::index>(*parent_value);
}
};
template <size_t N>
struct Subitems<ParentCompute<N>> {
using type = tmpl::list<First<N>, Second<N>>;
using tag = ParentCompute<N>;
template <typename Subtag>
static const typename Subtag::type& create_compute_item(
const typename tag::type& parent_value) noexcept {
return std::get<Subtag::index>(parent_value);
}
};
} // namespace db
namespace {
void test_subitems() noexcept {
INFO("test subitems");
{
auto box = db::create<db::AddSimpleTags<Parent<0>>,
db::AddComputeTags<ParentCompute<1>>>(
std::make_pair(Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5))));
TestHelpers::db::test_reference_tag<
::Tags::Subitem<First<1>, ParentCompute<1>>>("First");
CHECK(*db::get<First<0>>(box) == 5);
CHECK(*db::get<First<1>>(box) == 6);
CHECK(*db::get<Second<0>>(box) == 3.5);
CHECK(*db::get<Second<1>>(box) == 7);
db::mutate<Second<0>>(
make_not_null(&box),
[](const gsl::not_null<Boxed<double>*> x) noexcept { **x = 12.; });
CHECK(*db::get<First<0>>(box) == 5);
CHECK(*db::get<First<1>>(box) == 6);
CHECK(*db::get<Second<0>>(box) == 12.);
CHECK(*db::get<Second<1>>(box) == 24.);
{
const auto copy_box = serialize_and_deserialize(box);
CHECK(*db::get<First<0>>(copy_box) == 5);
CHECK(*db::get<First<1>>(copy_box) == 6);
CHECK(*db::get<Second<0>>(copy_box) == 12.);
CHECK(*db::get<Second<1>>(copy_box) == 24.);
}
static_assert(
std::is_same_v<
decltype(box),
decltype(db::create_from<db::RemoveTags<Parent<2>>>(
db::create_from<db::RemoveTags<>, db::AddSimpleTags<Parent<2>>>(
std::move(box),
std::make_pair(
Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5))))))>,
"Failed testing that adding and removing a simple subitem does "
"not change the type of the DataBox");
static_assert(
std::is_same_v<
decltype(box),
decltype(db::create_from<db::RemoveTags<ParentCompute<2>>>(
db::create_from<db::RemoveTags<>, db::AddSimpleTags<>,
db::AddComputeTags<ParentCompute<2>>>(
std::move(box))))>,
"Failed testing that adding and removing a compute subitem does "
"not change the type of the DataBox");
}
{
INFO("Default-construction with subitems");
auto box = db::create<db::AddSimpleTags<Parent<0>>,
db::AddComputeTags<ParentCompute<1>>>();
// Check the default-constructed DataBox links subitems correctly
CHECK(db::get<Parent<0>>(box).first.data() ==
db::get<First<0>>(box).data());
CHECK(db::get<Parent<0>>(box).second.data() ==
db::get<Second<0>>(box).data());
db::mutate<Parent<0>>(
make_not_null(&box),
[](const gsl::not_null<std::pair<Boxed<int>, Boxed<double>>*>
val) noexcept {
*val = std::make_pair(Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5)));
});
CHECK(*db::get<First<0>>(box) == 5);
CHECK(*db::get<Second<0>>(box) == 3.5);
CHECK(*db::get<First<1>>(box) == 6);
CHECK(*db::get<Second<1>>(box) == 7.);
db::mutate<First<0>, Second<0>>(
make_not_null(&box),
[](const gsl::not_null<Boxed<int>*> a,
const gsl::not_null<Boxed<double>*> b) noexcept {
**a = 2;
**b = 2.5;
});
CHECK(*db::get<First<0>>(box) == 2);
CHECK(*db::get<Second<0>>(box) == 2.5);
CHECK(*db::get<First<1>>(box) == 3);
CHECK(*db::get<Second<1>>(box) == 5.);
}
}
namespace test_databox_tags {
struct Tag0Int : db::SimpleTag {
using type = int;
};
template <typename ArgumentTag>
struct OverloadType : db::SimpleTag {
using type = double;
};
// [overload_compute_tag_type]
template <typename ArgumentTag>
struct OverloadTypeCompute : OverloadType<ArgumentTag>, db::ComputeTag {
using base = OverloadType<ArgumentTag>;
using return_type = double;
static constexpr void function(const gsl::not_null<double*> result,
const int& a) noexcept {
*result = 5 * a;
}
static constexpr void function(const gsl::not_null<double*> result,
const double a) noexcept {
*result = 3.2 * a;
}
using argument_tags = tmpl::list<ArgumentTag>;
};
// [overload_compute_tag_type]
template <typename ArgumentTag0, typename ArgumentTag1 = void>
struct OverloadNumberOfArgs : db::SimpleTag {
using type = double;
};
// [overload_compute_tag_number_of_args]
template <typename ArgumentTag0, typename ArgumentTag1 = void>
struct OverloadNumberOfArgsCompute
: OverloadNumberOfArgs<ArgumentTag0, ArgumentTag1>,
db::ComputeTag {
using base = OverloadNumberOfArgs<ArgumentTag0, ArgumentTag1>;
using return_type = double;
static constexpr void function(const gsl::not_null<double*> result,
const double a) noexcept {
*result = 3.2 * a;
}
static constexpr void function(const gsl::not_null<double*> result,
const double a, const double b) noexcept {
*result = a * b;
}
using argument_tags =
tmpl::conditional_t<std::is_same_v<void, ArgumentTag1>,
tmpl::list<ArgumentTag0>,
tmpl::list<ArgumentTag0, ArgumentTag1>>;
};
// [overload_compute_tag_number_of_args]
template <typename ArgumentTag>
struct Template : db::SimpleTag {
using type = typename ArgumentTag::type;
};
// [overload_compute_tag_template]
template <typename ArgumentTag>
struct TemplateCompute : Template<ArgumentTag>, db::ComputeTag {
using base = Template<ArgumentTag>;
using return_type = typename ArgumentTag::type;
template <typename T>
static constexpr void function(const gsl::not_null<T*> result,
const T& a) noexcept {
*result = 5 * a;
}
using argument_tags = tmpl::list<ArgumentTag>;
};
// [overload_compute_tag_template]
} // namespace test_databox_tags
void test_overload_compute_tags() noexcept {
INFO("testing overload compute tags.");
auto box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag0Int>,
db::AddComputeTags<
test_databox_tags::OverloadTypeCompute<test_databox_tags::Tag0>,
test_databox_tags::OverloadTypeCompute<test_databox_tags::Tag0Int>,
test_databox_tags::OverloadNumberOfArgsCompute<
test_databox_tags::Tag0>,
test_databox_tags::OverloadNumberOfArgsCompute<
test_databox_tags::Tag0,
test_databox_tags::OverloadType<test_databox_tags::Tag0>>,
test_databox_tags::TemplateCompute<test_databox_tags::Tag0>,
test_databox_tags::TemplateCompute<test_databox_tags::Tag0Int>>>(8.4,
-3);
CHECK(db::get<test_databox_tags::OverloadType<test_databox_tags::Tag0>>(
box) == 8.4 * 3.2);
CHECK(db::get<test_databox_tags::OverloadType<test_databox_tags::Tag0Int>>(
box) == -3 * 5);
CHECK(
db::get<test_databox_tags::OverloadNumberOfArgs<test_databox_tags::Tag0>>(
box) == 3.2 * 8.4);
CHECK(db::get<test_databox_tags::OverloadNumberOfArgs<
test_databox_tags::Tag0,
test_databox_tags::OverloadType<test_databox_tags::Tag0>>>(box) ==
8.4 * 3.2 * 8.4);
CHECK(db::get<test_databox_tags::Template<test_databox_tags::Tag0>>(box) ==
8.4 * 5.0);
CHECK(db::get<test_databox_tags::Template<test_databox_tags::Tag0Int>>(box) ==
-3 * 5);
}
namespace TestTags {
namespace {
struct MyTag0 {
using type = int;
};
struct MyTag1 {
using type = double;
};
struct TupleTag : db::SimpleTag {
using type = tuples::TaggedTuple<MyTag0, MyTag1>;
};
} // namespace
} // namespace TestTags
void test_with_tagged_tuple() noexcept {
// Test that having a TaggedTuple inside a DataBox works properly
auto box = db::create<db::AddSimpleTags<TestTags::TupleTag>>(
tuples::TaggedTuple<TestTags::MyTag0, TestTags::MyTag1>{123, 2.3});
auto box2 = std::move(box);
CHECK(tuples::get<TestTags::MyTag0>(db::get<TestTags::TupleTag>(box2)) ==
123);
CHECK(tuples::get<TestTags::MyTag1>(db::get<TestTags::TupleTag>(box2)) ==
2.3);
}
void serialization_non_subitem_simple_items() noexcept {
INFO("serialization of a DataBox with non-Subitem simple items only");
auto serialization_test_box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
const double* before_0 =
&db::get<test_databox_tags::Tag0>(serialization_test_box);
const std::vector<double>* before_1 =
&db::get<test_databox_tags::Tag1>(serialization_test_box);
const std::string* before_2 =
&db::get<test_databox_tags::Tag2>(serialization_test_box);
auto deserialized_serialization_test_box =
serialize_and_deserialize(serialization_test_box);
CHECK(db::get<test_databox_tags::Tag0>(serialization_test_box) == 3.14);
CHECK(db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box) ==
3.14);
CHECK(before_0 == &db::get<test_databox_tags::Tag0>(serialization_test_box));
CHECK(before_0 !=
&db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag1>(serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(before_1 == &db::get<test_databox_tags::Tag1>(serialization_test_box));
CHECK(before_1 !=
&db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag2>(serialization_test_box) ==
"My Sample String"s);
CHECK(db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box) ==
"My Sample String"s);
CHECK(before_2 == &db::get<test_databox_tags::Tag2>(serialization_test_box));
CHECK(before_2 !=
&db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box));
}
void serialization_subitems_simple_items() noexcept {
INFO("serialization of a DataBox with Subitem and non-Subitem simple items");
auto serialization_test_box =
db::create<db::AddSimpleTags<test_databox_tags::Tag0, Parent<0>,
test_databox_tags::Tag1,
test_databox_tags::Tag2, Parent<1>>>(
3.14,
std::make_pair(Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5))),
std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
std::make_pair(Boxed<int>(std::make_shared<int>(9)),
Boxed<double>(std::make_shared<double>(-4.5))));
const double* before_0 =
&db::get<test_databox_tags::Tag0>(serialization_test_box);
const std::vector<double>* before_1 =
&db::get<test_databox_tags::Tag1>(serialization_test_box);
const std::string* before_2 =
&db::get<test_databox_tags::Tag2>(serialization_test_box);
const std::pair<Boxed<int>, Boxed<double>>* before_parent0 =
&db::get<Parent<0>>(serialization_test_box);
const Boxed<int>* before_parent0f =
&db::get<First<0>>(serialization_test_box);
const Boxed<double>* before_parent0s =
&db::get<Second<0>>(serialization_test_box);
const std::pair<Boxed<int>, Boxed<double>>* before_parent1 =
&db::get<Parent<1>>(serialization_test_box);
const Boxed<int>* before_parent1f =
&db::get<First<1>>(serialization_test_box);
const Boxed<double>* before_parent1s =
&db::get<Second<1>>(serialization_test_box);
auto deserialized_serialization_test_box =
serialize_and_deserialize(serialization_test_box);
CHECK(db::get<test_databox_tags::Tag0>(serialization_test_box) == 3.14);
CHECK(db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box) ==
3.14);
CHECK(before_0 == &db::get<test_databox_tags::Tag0>(serialization_test_box));
CHECK(before_0 !=
&db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box));
CHECK(*db::get<First<0>>(serialization_test_box) == 5);
CHECK(*db::get<Second<0>>(serialization_test_box) == 3.5);
CHECK(*db::get<First<0>>(deserialized_serialization_test_box) == 5);
CHECK(*db::get<Second<0>>(deserialized_serialization_test_box) == 3.5);
CHECK(before_parent0 == &db::get<Parent<0>>(serialization_test_box));
CHECK(before_parent0 !=
&db::get<Parent<0>>(deserialized_serialization_test_box));
CHECK(before_parent0f == &db::get<First<0>>(serialization_test_box));
CHECK(before_parent0f !=
&db::get<First<0>>(deserialized_serialization_test_box));
CHECK(before_parent0s == &db::get<Second<0>>(serialization_test_box));
CHECK(before_parent0s !=
&db::get<Second<0>>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag1>(serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(before_1 == &db::get<test_databox_tags::Tag1>(serialization_test_box));
CHECK(before_1 !=
&db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag2>(serialization_test_box) ==
"My Sample String"s);
CHECK(db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box) ==
"My Sample String"s);
CHECK(before_2 == &db::get<test_databox_tags::Tag2>(serialization_test_box));
CHECK(before_2 !=
&db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box));
CHECK(*db::get<First<1>>(serialization_test_box) == 9);
CHECK(*db::get<Second<1>>(serialization_test_box) == -4.5);
CHECK(*db::get<First<1>>(deserialized_serialization_test_box) == 9);
CHECK(*db::get<Second<1>>(deserialized_serialization_test_box) == -4.5);
CHECK(before_parent1 == &db::get<Parent<1>>(serialization_test_box));
CHECK(before_parent1 !=
&db::get<Parent<1>>(deserialized_serialization_test_box));
CHECK(before_parent1f == &db::get<First<1>>(serialization_test_box));
CHECK(before_parent1f !=
&db::get<First<1>>(deserialized_serialization_test_box));
CHECK(before_parent1s == &db::get<Second<1>>(serialization_test_box));
CHECK(before_parent1s !=
&db::get<Second<1>>(deserialized_serialization_test_box));
}
template <int Id>
struct CountingFunc {
static void apply(const gsl::not_null<double*> result) {
count++;
*result = 8.2;
}
static int count;
};
template <int Id>
int CountingFunc<Id>::count = 0;
template <int Id>
struct CountingTag : db::SimpleTag {
using type = double;
};
template <int Id>
struct CountingTagCompute : CountingTag<Id>, db::ComputeTag {
using base = CountingTag<Id>;
using return_type = double;
static constexpr auto function = CountingFunc<Id>::apply;
using argument_tags = tmpl::list<>;
};
template <size_t SecondId>
struct CountingTagDouble : db::SimpleTag {
using type = double;
};
template <size_t SecondId>
struct CountingTagDoubleCompute : CountingTagDouble<SecondId>, db::ComputeTag {
using base = CountingTagDouble<SecondId>;
using return_type = double;
static void function(const gsl::not_null<double*> result,
const Boxed<double>& t) {
count++;
*result = *t * 6.0;
}
using argument_tags = tmpl::list<Second<SecondId>>;
static int count;
};
template <size_t SecondId>
int CountingTagDoubleCompute<SecondId>::count = 0;
// clang-tidy: this function is too long. Yes, well we need to check lots
void serialization_subitem_compute_items() noexcept { // NOLINT
INFO("serialization of a DataBox with Subitem compute items");
auto serialization_test_box =
db::create<db::AddSimpleTags<test_databox_tags::Tag0, Parent<0>,
test_databox_tags::Tag1,
test_databox_tags::Tag2, Parent<1>>,
db::AddComputeTags<
CountingTagCompute<1>, test_databox_tags::Tag4Compute,
ParentCompute<2>, test_databox_tags::Tag5Compute,
ParentCompute<3>, CountingTagCompute<0>,
CountingTagDoubleCompute<2>, CountingTagDoubleCompute<3>>>(
3.14,
std::make_pair(Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5))),
std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s,
std::make_pair(Boxed<int>(std::make_shared<int>(9)),
Boxed<double>(std::make_shared<double>(-4.5))));
const double* before_0 =
&db::get<test_databox_tags::Tag0>(serialization_test_box);
const std::vector<double>* before_1 =
&db::get<test_databox_tags::Tag1>(serialization_test_box);
const std::string* before_2 =
&db::get<test_databox_tags::Tag2>(serialization_test_box);
const std::pair<Boxed<int>, Boxed<double>>* before_parent0 =
&db::get<Parent<0>>(serialization_test_box);
const Boxed<int>* before_parent0f =
&db::get<First<0>>(serialization_test_box);
const Boxed<double>* before_parent0s =
&db::get<Second<0>>(serialization_test_box);
const std::pair<Boxed<int>, Boxed<double>>* before_parent1 =
&db::get<Parent<1>>(serialization_test_box);
const Boxed<int>* before_parent1f =
&db::get<First<1>>(serialization_test_box);
const Boxed<double>* before_parent1s =
&db::get<Second<1>>(serialization_test_box);
CHECK(db::get<test_databox_tags::Tag4>(serialization_test_box) == 6.28);
const double* before_compute_tag0 =
&db::get<test_databox_tags::Tag4>(serialization_test_box);
CHECK(CountingFunc<0>::count == 0);
CHECK(CountingFunc<1>::count == 0);
CHECK(db::get<CountingTag<0>>(serialization_test_box) == 8.2);
const double* before_counting_tag0 =
&db::get<CountingTag<0>>(serialization_test_box);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(ParentCompute<2>::count == 0);
CHECK(ParentCompute<3>::count == 0);
const std::pair<Boxed<int>, Boxed<double>>* before_parent2 =
&db::get<Parent<2>>(serialization_test_box);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 0);
const Boxed<int>* before_parent2_first =
&db::get<First<2>>(serialization_test_box);
const Boxed<double>* before_parent2_second =
&db::get<Second<2>>(serialization_test_box);
// Check we are correctly pointing into parent
CHECK(&*(db::get<Parent<2>>(serialization_test_box).first) ==
&*db::get<First<2>>(serialization_test_box));
CHECK(&*(db::get<Parent<2>>(serialization_test_box).second) ==
&*db::get<Second<2>>(serialization_test_box));
CHECK(*(db::get<Parent<2>>(serialization_test_box).first) == 10);
CHECK(*(db::get<Parent<2>>(serialization_test_box).second) == -9.0);
CHECK(*db::get<First<2>>(serialization_test_box) == 10);
CHECK(*db::get<Second<2>>(serialization_test_box) == -9.0);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 0);
// Check compute items that take subitems
CHECK(CountingTagDoubleCompute<2>::count == 0);
CHECK(db::get<CountingTagDouble<2>>(serialization_test_box) == -9.0 * 6.0);
CHECK(CountingTagDoubleCompute<2>::count == 1);
const double* const before_compute_tag2 =
&db::get<CountingTagDouble<2>>(serialization_test_box);
auto deserialized_serialization_test_box =
serialize_and_deserialize(serialization_test_box);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(db::get<test_databox_tags::Tag0>(serialization_test_box) == 3.14);
CHECK(db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box) ==
3.14);
CHECK(before_0 == &db::get<test_databox_tags::Tag0>(serialization_test_box));
CHECK(before_0 !=
&db::get<test_databox_tags::Tag0>(deserialized_serialization_test_box));
CHECK(*db::get<First<0>>(serialization_test_box) == 5);
CHECK(*db::get<Second<0>>(serialization_test_box) == 3.5);
CHECK(*db::get<First<0>>(deserialized_serialization_test_box) == 5);
CHECK(*db::get<Second<0>>(deserialized_serialization_test_box) == 3.5);
CHECK(before_parent0 == &db::get<Parent<0>>(serialization_test_box));
CHECK(before_parent0 !=
&db::get<Parent<0>>(deserialized_serialization_test_box));
CHECK(before_parent0f == &db::get<First<0>>(serialization_test_box));
CHECK(before_parent0f !=
&db::get<First<0>>(deserialized_serialization_test_box));
CHECK(before_parent0s == &db::get<Second<0>>(serialization_test_box));
CHECK(before_parent0s !=
&db::get<Second<0>>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag1>(serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(before_1 == &db::get<test_databox_tags::Tag1>(serialization_test_box));
CHECK(before_1 !=
&db::get<test_databox_tags::Tag1>(deserialized_serialization_test_box));
CHECK(db::get<test_databox_tags::Tag2>(serialization_test_box) ==
"My Sample String"s);
CHECK(db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box) ==
"My Sample String"s);
CHECK(before_2 == &db::get<test_databox_tags::Tag2>(serialization_test_box));
CHECK(before_2 !=
&db::get<test_databox_tags::Tag2>(deserialized_serialization_test_box));
CHECK(*db::get<First<1>>(serialization_test_box) == 9);
CHECK(*db::get<Second<1>>(serialization_test_box) == -4.5);
CHECK(*db::get<First<1>>(deserialized_serialization_test_box) == 9);
CHECK(*db::get<Second<1>>(deserialized_serialization_test_box) == -4.5);
CHECK(before_parent1 == &db::get<Parent<1>>(serialization_test_box));
CHECK(before_parent1 !=
&db::get<Parent<1>>(deserialized_serialization_test_box));
CHECK(before_parent1f == &db::get<First<1>>(serialization_test_box));
CHECK(before_parent1f !=
&db::get<First<1>>(deserialized_serialization_test_box));
CHECK(before_parent1s == &db::get<Second<1>>(serialization_test_box));
CHECK(before_parent1s !=
&db::get<Second<1>>(deserialized_serialization_test_box));
// Check compute items
CHECK(db::get<test_databox_tags::Tag4>(deserialized_serialization_test_box) ==
6.28);
CHECK(&db::get<test_databox_tags::Tag4>(
deserialized_serialization_test_box) != before_compute_tag0);
CHECK(db::get<test_databox_tags::Tag5>(deserialized_serialization_test_box) ==
"My Sample String6.28"s);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(db::get<CountingTag<0>>(serialization_test_box) == 8.2);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(&db::get<CountingTag<0>>(serialization_test_box) ==
before_counting_tag0);
CHECK(db::get<CountingTag<0>>(deserialized_serialization_test_box) == 8.2);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(&db::get<CountingTag<0>>(deserialized_serialization_test_box) !=
before_counting_tag0);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 0);
CHECK(db::get<CountingTag<1>>(deserialized_serialization_test_box) == 8.2);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 1);
CHECK(db::get<CountingTag<1>>(serialization_test_box) == 8.2);
CHECK(CountingFunc<0>::count == 1);
CHECK(CountingFunc<1>::count == 2);
CHECK(&db::get<CountingTag<1>>(serialization_test_box) !=
&db::get<CountingTag<1>>(deserialized_serialization_test_box));
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 0);
CHECK(&db::get<Parent<2>>(serialization_test_box) == before_parent2);
// Check we are correctly pointing into parent
CHECK(&*(db::get<Parent<2>>(serialization_test_box).first) ==
&*db::get<First<2>>(serialization_test_box));
CHECK(&*(db::get<Parent<2>>(serialization_test_box).second) ==
&*db::get<Second<2>>(serialization_test_box));
// Check that we did not reset the subitems items in the initial DataBox
CHECK(&db::get<First<2>>(serialization_test_box) == before_parent2_first);
CHECK(&db::get<Second<2>>(serialization_test_box) == before_parent2_second);
CHECK(*(db::get<Parent<2>>(serialization_test_box).first) == 10);
CHECK(*(db::get<Parent<2>>(serialization_test_box).second) == -9.0);
CHECK(*(db::get<Parent<2>>(deserialized_serialization_test_box).first) == 10);
CHECK(&db::get<Parent<2>>(deserialized_serialization_test_box) !=
before_parent2);
CHECK(*(db::get<Parent<2>>(deserialized_serialization_test_box).second) ==
-9.0);
CHECK(*db::get<First<2>>(deserialized_serialization_test_box) == 10);
CHECK(*db::get<Second<2>>(deserialized_serialization_test_box) == -9.0);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 0);
CHECK(&db::get<Parent<2>>(deserialized_serialization_test_box) !=
before_parent2);
// Check pointers in deserialized box
CHECK(&db::get<First<2>>(deserialized_serialization_test_box) !=
before_parent2_first);
CHECK(&db::get<Second<2>>(deserialized_serialization_test_box) !=
before_parent2_second);
// Check we are correctly pointing into new parent and not old
CHECK(&*(db::get<Parent<2>>(deserialized_serialization_test_box).first) ==
&*db::get<First<2>>(deserialized_serialization_test_box));
CHECK(&*(db::get<Parent<2>>(deserialized_serialization_test_box).second) ==
&*db::get<Second<2>>(deserialized_serialization_test_box));
CHECK(&*(db::get<Parent<2>>(deserialized_serialization_test_box).first) !=
&*db::get<First<2>>(serialization_test_box));
CHECK(&*(db::get<Parent<2>>(deserialized_serialization_test_box).second) !=
&*db::get<Second<2>>(serialization_test_box));
CHECK(*(db::get<Parent<3>>(serialization_test_box).first) == 11);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 1);
CHECK(*(db::get<Parent<3>>(serialization_test_box).second) == -18.0);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 1);
CHECK(*db::get<First<3>>(serialization_test_box) == 11);
CHECK(*db::get<Second<3>>(serialization_test_box) == -18.0);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 1);
CHECK(*(db::get<Parent<3>>(deserialized_serialization_test_box).first) == 11);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 2);
CHECK(*(db::get<Parent<3>>(deserialized_serialization_test_box).second) ==
-18.0);
CHECK(*db::get<First<3>>(deserialized_serialization_test_box) == 11);
CHECK(*db::get<Second<3>>(deserialized_serialization_test_box) == -18.0);
CHECK(ParentCompute<2>::count == 1);
CHECK(ParentCompute<3>::count == 2);
// Check that all the Parent<3> related objects point to the right place
CHECK(&*(db::get<Parent<3>>(deserialized_serialization_test_box).first) ==
&*db::get<First<3>>(deserialized_serialization_test_box));
CHECK(&*(db::get<Parent<3>>(deserialized_serialization_test_box).second) ==
&*db::get<Second<3>>(deserialized_serialization_test_box));
CHECK(&*(db::get<Parent<3>>(serialization_test_box).first) ==
&*db::get<First<3>>(serialization_test_box));
CHECK(&*(db::get<Parent<3>>(serialization_test_box).second) ==
&*db::get<Second<3>>(serialization_test_box));
CHECK(&*db::get<First<3>>(deserialized_serialization_test_box) !=
&*db::get<First<3>>(serialization_test_box));
CHECK(&*db::get<Second<3>>(deserialized_serialization_test_box) !=
&*db::get<Second<3>>(serialization_test_box));
// Check compute items that depend on the subitems
CHECK(CountingTagDoubleCompute<2>::count == 1);
CHECK(db::get<CountingTagDouble<2>>(serialization_test_box) == -9.0 * 6.0);
CHECK(before_compute_tag2 ==
&db::get<CountingTagDouble<2>>(serialization_test_box));
CHECK(db::get<CountingTagDouble<2>>(deserialized_serialization_test_box) ==
-9.0 * 6.0);
CHECK(before_compute_tag2 !=
&db::get<CountingTagDouble<2>>(deserialized_serialization_test_box));
CHECK(CountingTagDoubleCompute<2>::count == 1);
CHECK(CountingTagDoubleCompute<3>::count == 0);
CHECK(db::get<CountingTagDouble<3>>(serialization_test_box) == -18.0 * 6.0);
CHECK(db::get<CountingTagDouble<3>>(deserialized_serialization_test_box) ==
-18.0 * 6.0);
CHECK(&db::get<CountingTagDouble<3>>(serialization_test_box) !=
&db::get<CountingTagDouble<3>>(deserialized_serialization_test_box));
CHECK(CountingTagDoubleCompute<3>::count == 2);
// Mutate subitems 1 in deserialized to see that changes propagate correctly
db::mutate<Second<1>>(
make_not_null(&serialization_test_box),
[](const gsl::not_null<Boxed<double>*> x) noexcept { **x = 12.; });
CHECK(ParentCompute<2>::count == 1);
CHECK(CountingTagDoubleCompute<2>::count == 1);
CHECK(db::get<CountingTagDouble<2>>(serialization_test_box) == 24.0 * 6.0);
CHECK(ParentCompute<2>::count == 2);
CHECK(CountingTagDoubleCompute<2>::count == 2);
CHECK(CountingTagDoubleCompute<3>::count == 2);
CHECK(db::get<CountingTagDouble<3>>(serialization_test_box) == 48.0 * 6.0);
CHECK(CountingTagDoubleCompute<3>::count == 3);
db::mutate<Second<1>>(
make_not_null(&deserialized_serialization_test_box),
[](const gsl::not_null<Boxed<double>*> x) noexcept { **x = -7.; });
CHECK(ParentCompute<2>::count == 2);
CHECK(CountingTagDoubleCompute<2>::count == 2);
CHECK(db::get<CountingTagDouble<2>>(deserialized_serialization_test_box) ==
-14.0 * 6.0);
CHECK(ParentCompute<2>::count == 3);
CHECK(CountingTagDoubleCompute<2>::count == 3);
CHECK(CountingTagDoubleCompute<3>::count == 3);
CHECK(db::get<CountingTagDouble<3>>(deserialized_serialization_test_box) ==
-28.0 * 6.0);
CHECK(CountingTagDoubleCompute<3>::count == 4);
// Check things didn't get modified in the original DataBox
CHECK(ParentCompute<2>::count == 3);
CHECK(CountingTagDoubleCompute<2>::count == 3);
CHECK(db::get<CountingTagDouble<2>>(serialization_test_box) == 24.0 * 6.0);
CHECK(ParentCompute<2>::count == 3);
CHECK(CountingTagDoubleCompute<2>::count == 3);
CHECK(CountingTagDoubleCompute<3>::count == 4);
CHECK(db::get<CountingTagDouble<3>>(serialization_test_box) == 48.0 * 6.0);
CHECK(CountingTagDoubleCompute<3>::count == 4);
CountingFunc<0>::count = 0;
CountingFunc<1>::count = 0;
CountingTagDoubleCompute<2>::count = 0;
CountingTagDoubleCompute<3>::count = 0;
ParentCompute<2>::count = 0;
ParentCompute<3>::count = 0;
}
void serialization_compute_items_of_base_tags() noexcept {
INFO("serialization of a DataBox with compute items depending on base tags");
auto original_box =
db::create<db::AddSimpleTags<test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag6Compute>>(
"My Sample String"s);
CHECK(db::get<test_databox_tags::Tag2>(original_box) == "My Sample String");
CHECK(db::get<test_databox_tags::Tag6>(original_box) == "My Sample String");
auto copied_box = serialize_and_deserialize(original_box);
CHECK(db::get<test_databox_tags::Tag2>(copied_box) == "My Sample String");
CHECK(db::get<test_databox_tags::Tag6>(copied_box) == "My Sample String");
}
void serialization_of_pointers() noexcept {
INFO("Serialization of pointers");
const auto box =
db::create<db::AddSimpleTags<test_databox_tags::Pointer>,
db::AddComputeTags<test_databox_tags::PointerToCounterCompute,
test_databox_tags::PointerToSumCompute>>(
std::make_unique<int>(3));
const auto check = [](const decltype(box)& check_box) noexcept {
CHECK(db::get<test_databox_tags::Pointer>(check_box) == 3);
CHECK(db::get<test_databox_tags::PointerToCounter>(check_box) == 4);
CHECK(db::get<test_databox_tags::PointerToSum>(check_box) == 8);
};
check(serialize_and_deserialize(box)); // before compute items evaluated
check(box);
check(serialize_and_deserialize(box)); // after compute items evaluated
}
namespace test_databox_tags {
// [databox_reference_tag_example]
template <typename... Tags>
struct TaggedTuple : db::SimpleTag {
using type = tuples::TaggedTuple<Tags...>;
};
template <typename Tag, typename ParentTag>
struct FromTaggedTuple : Tag, db::ReferenceTag {
using base = Tag;
using parent_tag = ParentTag;
static const auto& get(const typename parent_tag::type& tagged_tuple) {
return tuples::get<Tag>(tagged_tuple);
}
using argument_tags = tmpl::list<parent_tag>;
};
// [databox_reference_tag_example]
} // namespace test_databox_tags
void test_reference_item() noexcept {
INFO("test reference item");
using tuple_tag = test_databox_tags::TaggedTuple<test_databox_tags::Tag0,
test_databox_tags::Tag1,
test_databox_tags::Tag2>;
auto box =
db::create<db::AddSimpleTags<tuple_tag>,
db::AddComputeTags<test_databox_tags::FromTaggedTuple<
test_databox_tags::Tag0, tuple_tag>,
test_databox_tags::FromTaggedTuple<
test_databox_tags::Tag1, tuple_tag>,
test_databox_tags::FromTaggedTuple<
test_databox_tags::Tag2, tuple_tag>>>(
tuples::TaggedTuple<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>{
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s});
const auto& tagged_tuple = get<tuple_tag>(box);
CHECK(get<test_databox_tags::Tag0>(tagged_tuple) == 3.14);
CHECK(get<test_databox_tags::Tag1>(tagged_tuple) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(get<test_databox_tags::Tag2>(tagged_tuple) == "My Sample String"s);
CHECK(get<test_databox_tags::Tag0>(box) == 3.14);
CHECK(get<test_databox_tags::Tag1>(box) ==
std::vector<double>{8.7, 93.2, 84.7});
CHECK(get<test_databox_tags::Tag2>(box) == "My Sample String"s);
}
void test_serialization() noexcept {
serialization_non_subitem_simple_items();
serialization_subitems_simple_items();
serialization_subitem_compute_items();
serialization_compute_items_of_base_tags();
serialization_of_pointers();
}
void test_get_mutable_reference() noexcept {
INFO("test get_mutable_reference");
// Make sure the presence of tags that could not be extracted
// doesn't prevent the function from working on other tags.
auto box = db::create<db::AddSimpleTags<test_databox_tags::Tag0,
test_databox_tags::Tag2, Parent<0>>,
db::AddComputeTags<test_databox_tags::Tag4Compute>>(
3.14, "Original string"s,
std::make_pair(Boxed<int>(std::make_shared<int>(5)),
Boxed<double>(std::make_shared<double>(3.5))));
decltype(auto) ref =
db::get_mutable_reference<test_databox_tags::Tag2>(make_not_null(&box));
static_assert(std::is_same_v<decltype(ref), std::string&>);
decltype(auto) base_ref =
db::get_mutable_reference<test_databox_tags::Tag2Base>(
make_not_null(&box));
static_assert(std::is_same_v<decltype(base_ref), std::string&>);
CHECK(&ref == &base_ref);
ref = "New string";
CHECK(db::get<test_databox_tags::Tag2Base>(box) == "New string");
// These should all fail to compile:
// db::get_mutable_reference<test_databox_tags::Tag0>(make_not_null(&box));
// db::get_mutable_reference<test_databox_tags::Tag4>(make_not_null(&box));
// db::get_mutable_reference<test_databox_tags::Tag4Compute>(
// make_not_null(&box));
// db::get_mutable_reference<Parent<0>>(make_not_null(&box));
// db::get_mutable_reference<First<0>>(make_not_null(&box));
}
void test_output() noexcept {
INFO("test output");
auto box = db::create<
db::AddSimpleTags<test_databox_tags::Tag0, test_databox_tags::Tag1,
test_databox_tags::Tag2>,
db::AddComputeTags<test_databox_tags::Tag4Compute,
test_databox_tags::Tag5Compute>>(
3.14, std::vector<double>{8.7, 93.2, 84.7}, "My Sample String"s);
std::string output_types = box.print_types();
std::string expected_types =
"DataBox type aliases:\n"
"using tags_list = brigand::list<(anonymous "
"namespace)::test_databox_tags::Tag0, (anonymous "
"namespace)::test_databox_tags::Tag1, (anonymous "
"namespace)::test_databox_tags::Tag2, (anonymous "
"namespace)::test_databox_tags::Tag4Compute, (anonymous "
"namespace)::test_databox_tags::Tag5Compute>;\n"
"using immutable_item_tags "
"= brigand::list<(anonymous namespace)::test_databox_tags::Tag4Compute, "
"(anonymous namespace)::test_databox_tags::Tag5Compute>;\n"
"using immutable_item_creation_tags = brigand::list<(anonymous "
"namespace)::test_databox_tags::Tag4Compute, (anonymous "
"namespace)::test_databox_tags::Tag5Compute>;\n"
"using mutable_item_tags = brigand::list<(anonymous "
"namespace)::test_databox_tags::Tag0, (anonymous "
"namespace)::test_databox_tags::Tag1, (anonymous "
"namespace)::test_databox_tags::Tag2>;\n"
"using mutable_subitem_tags = brigand::list<>;\n"
"using compute_item_tags = brigand::list<(anonymous "
"namespace)::test_databox_tags::Tag4Compute, (anonymous "
"namespace)::test_databox_tags::Tag5Compute>;\n"
"using edge_list = "
"brigand::list<brigand::edge<(anonymous "
"namespace)::test_databox_tags::Tag0, (anonymous "
"namespace)::test_databox_tags::Tag4Compute, "
"brigand::integral_constant<int, 1> >, brigand::edge<(anonymous "
"namespace)::test_databox_tags::Tag2, (anonymous "
"namespace)::test_databox_tags::Tag5Compute, "
"brigand::integral_constant<int, 1> >, brigand::edge<(anonymous "
"namespace)::test_databox_tags::Tag4Compute, (anonymous "
"namespace)::test_databox_tags::Tag5Compute, "
"brigand::integral_constant<int, 1> > >;\n";
CHECK(output_types == expected_types);
std::string output_items = box.print_items();
std::string expected_items =
"Items:\n"
"----------\n"
"Name: (anonymous namespace)::test_databox_tags::Tag0\n"
"Type: double\n"
"Value: 3.14\n"
"----------\n"
"Name: (anonymous namespace)::test_databox_tags::Tag1\n"
"Type: std::vector<double>\n"
"Value: (8.7,93.2,84.7)\n"
"----------\n"
"Name: (anonymous namespace)::test_databox_tags::Tag2\n"
"Type: std::string\n"
"Value: My Sample String\n"
"----------\n"
"Name: (anonymous namespace)::test_databox_tags::Tag4Compute\n"
"Type: double\n"
"Value: 6.28\n"
"----------\n"
"Name: (anonymous namespace)::test_databox_tags::Tag5Compute\n"
"Type: std::string\n"
"Value: My Sample String6.28\n";
CHECK(output_items == expected_items);
std::ostringstream os;
os << box;
std::string output_stream = os.str();
std::string expected_stream = expected_types + "\n" + expected_items+ "\n";
CHECK(output_stream == expected_stream);
}
} // namespace
SPECTRE_TEST_CASE("Unit.DataStructures.DataBox", "[Unit][DataStructures]") {
test_databox();
test_create_argument_types();
test_get_databox();
test_mutate();
test_apply();
test_variables();
test_variables2();
test_reset_compute_items();
test_variables_extra_reset();
test_mutate_apply();
test_mutating_compute_item();
test_data_on_slice_single();
test_data_on_slice();
test_subitems();
test_overload_compute_tags();
test_with_tagged_tuple();
test_serialization();
test_reference_item();
test_get_mutable_reference();
test_output();
}
// Test`tag_is_retrievable_v`
namespace {
namespace tags_types {
struct PureBaseTag : db::BaseTag {};
struct SimpleTag : PureBaseTag, db::SimpleTag {
using type = double;
};
struct DummyTag : db::SimpleTag {
using type = int;
};
} // namespace tags_types
static_assert(
db::tag_is_retrievable_v<tags_types::PureBaseTag,
db::DataBox<tmpl::list<tags_types::SimpleTag>>>,
"Failed testing tag_is_retrievable_v");
static_assert(
db::tag_is_retrievable_v<tags_types::SimpleTag,
db::DataBox<tmpl::list<tags_types::SimpleTag>>>,
"Failed testing tag_is_retrievable_v");
static_assert(
not db::tag_is_retrievable_v<
tags_types::DummyTag, db::DataBox<tmpl::list<tags_types::SimpleTag>>>,
"Failed testing tag_is_retrievable_v");
} // namespace
|
;********************************************************************************************************
; uC/OS-II
; The Real-Time Kernel
;
; (c) Copyright 1992-2016, Micrium, Weston, FL
; All Rights Reserved
;
; ARM Cortex-M3 Port
;
; File : OS_CPU_A.ASM
; Version : V2.92.12.00
; By : Jean J. Labrosse
; Brian Nagel
;
; For : ARMv7M Cortex-M3
; Mode : Thumb2
; Toolchain : IAR EWARM
;********************************************************************************************************
;********************************************************************************************************
; PUBLIC FUNCTIONS
;********************************************************************************************************
EXTERN OSRunning ; External references
EXTERN OSPrioCur
EXTERN OSPrioHighRdy
EXTERN OSTCBCur
EXTERN OSTCBHighRdy
EXTERN OSIntExit
EXTERN OSTaskSwHook
EXTERN OS_CPU_ExceptStkBase
PUBLIC OS_CPU_SR_Save ; Functions declared in this file
PUBLIC OS_CPU_SR_Restore
PUBLIC OSStartHighRdy
PUBLIC OSCtxSw
PUBLIC OSIntCtxSw
PUBLIC OS_CPU_PendSVHandler
;********************************************************************************************************
; EQUATES
;********************************************************************************************************
NVIC_INT_CTRL EQU 0xE000ED04 ; Interrupt control state register.
NVIC_SYSPRI14 EQU 0xE000ED22 ; System priority register (priority 14).
NVIC_PENDSV_PRI EQU 0xFF ; PendSV priority value (lowest).
NVIC_PENDSVSET EQU 0x10000000 ; Value to trigger PendSV exception.
;********************************************************************************************************
; CODE GENERATION DIRECTIVES
;********************************************************************************************************
RSEG CODE:CODE:NOROOT(2)
THUMB
;********************************************************************************************************
; CRITICAL SECTION METHOD 3 FUNCTIONS
;
; Description: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you
; would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then
; disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's functions that need to
; disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr'
; into the CPU's status register.
;
; Prototypes : OS_CPU_SR OS_CPU_SR_Save(void);
; void OS_CPU_SR_Restore(OS_CPU_SR cpu_sr);
;
;
; Note(s) : 1) These functions are used in general like this:
;
; void Task (void *p_arg)
; {
; #if OS_CRITICAL_METHOD == 3 /* Allocate storage for CPU status register */
; OS_CPU_SR cpu_sr;
; #endif
;
; :
; :
; OS_ENTER_CRITICAL(); /* cpu_sr = OS_CPU_SaveSR(); */
; :
; :
; OS_EXIT_CRITICAL(); /* OS_CPU_RestoreSR(cpu_sr); */
; :
; :
; }
;********************************************************************************************************
OS_CPU_SR_Save
MRS R0, PRIMASK ; Set prio int mask to mask all (except faults)
CPSID I
BX LR
OS_CPU_SR_Restore
MSR PRIMASK, R0
BX LR
;********************************************************************************************************
; START MULTITASKING
; void OSStartHighRdy(void)
;
; Note(s) : 1) This function triggers a PendSV exception (essentially, causes a context switch) to cause
; the first task to start.
;
; 2) OSStartHighRdy() MUST:
; a) Setup PendSV exception priority to lowest;
; b) Set initial PSP to 0, to tell context switcher this is first run;
; c) Set the main stack to OS_CPU_ExceptStkBase
; d) Set OSRunning to TRUE;
; e) Trigger PendSV exception;
; f) Enable interrupts (tasks will run with interrupts enabled).
;********************************************************************************************************
OSStartHighRdy
LDR R0, =NVIC_SYSPRI14 ; Set the PendSV exception priority
LDR R1, =NVIC_PENDSV_PRI
STRB R1, [R0]
MOVS R0, #0 ; Set the PSP to 0 for initial context switch call
MSR PSP, R0
BL OSTaskSwHook
LDR R0, =OS_CPU_ExceptStkBase ; Initialize the MSP to the OS_CPU_ExceptStkBase
LDR R1, [R0]
MSR MSP, R1
LDR R0, =OSRunning ; OSRunning = TRUE
MOVS R1, #1
STRB R1, [R0]
LDR R0, =NVIC_INT_CTRL ; Trigger the PendSV exception (causes context switch)
LDR R1, =NVIC_PENDSVSET
STR R1, [R0]
CPSIE I ; Enable interrupts at processor level
OSStartHang
B OSStartHang ; Should never get here
;********************************************************************************************************
; PERFORM A CONTEXT SWITCH (From task level)
; void OSCtxSw(void)
;
; Note(s) : 1) OSCtxSw() is called when OS wants to perform a task context switch. This function
; triggers the PendSV exception which is where the real work is done.
;********************************************************************************************************
OSCtxSw
LDR R0, =NVIC_INT_CTRL ; Trigger the PendSV exception (causes context switch)
LDR R1, =NVIC_PENDSVSET
STR R1, [R0]
BX LR
;********************************************************************************************************
; PERFORM A CONTEXT SWITCH (From interrupt level)
; void OSIntCtxSw(void)
;
; Notes: 1) OSIntCtxSw() is called by OSIntExit() when it determines a context switch is needed as
; the result of an interrupt. This function simply triggers a PendSV exception which will
; be handled when there are no more interrupts active and interrupts are enabled.
;********************************************************************************************************
OSIntCtxSw
LDR R0, =NVIC_INT_CTRL ; Trigger the PendSV exception (causes context switch)
LDR R1, =NVIC_PENDSVSET
STR R1, [R0]
BX LR
;********************************************************************************************************
; HANDLE PendSV EXCEPTION
; void OS_CPU_PendSVHandler(void)
;
; Note(s) : 1) PendSV is used to cause a context switch. This is a recommended method for performing
; context switches with Cortex-M3. This is because the Cortex-M3 auto-saves half of the
; processor context on any exception, and restores same on return from exception. So only
; saving of R4-R11 is required and fixing up the stack pointers. Using the PendSV exception
; this way means that context saving and restoring is identical whether it is initiated from
; a thread or occurs due to an interrupt or exception.
;
; 2) Pseudo-code is:
; a) Get the process SP, if 0 then skip (goto d) the saving part (first context switch);
; b) Save remaining regs r4-r11 on process stack;
; c) Save the process SP in its TCB, OSTCBCur->OSTCBStkPtr = SP;
; d) Call OSTaskSwHook();
; e) Get current high priority, OSPrioCur = OSPrioHighRdy;
; f) Get current ready thread TCB, OSTCBCur = OSTCBHighRdy;
; g) Get new process SP from TCB, SP = OSTCBHighRdy->OSTCBStkPtr;
; h) Restore R4-R11 from new process stack;
; i) Perform exception return which will restore remaining context.
;
; 3) On entry into PendSV handler:
; a) The following have been saved on the process stack (by processor):
; xPSR, PC, LR, R12, R0-R3
; b) Processor mode is switched to Handler mode (from Thread mode)
; c) Stack is Main stack (switched from Process stack)
; d) OSTCBCur points to the OS_TCB of the task to suspend
; OSTCBHighRdy points to the OS_TCB of the task to resume
;
; 4) Since PendSV is set to lowest priority in the system (by OSStartHighRdy() above), we
; know that it will only be run when no other exception or interrupt is active, and
; therefore safe to assume that context being switched out was using the process stack (PSP).
;********************************************************************************************************
OS_CPU_PendSVHandler
CPSID I ; Prevent interruption during context switch
MRS R0, PSP ; PSP is process stack pointer
CBZ R0, OS_CPU_PendSVHandler_nosave ; Skip register save the first time
SUBS R0, R0, #0x20 ; Save remaining regs r4-11 on process stack
STM R0, {R4-R11}
LDR R1, =OSTCBCur ; OSTCBCur->OSTCBStkPtr = SP;
LDR R1, [R1]
STR R0, [R1] ; R0 is SP of process being switched out
; At this point, entire context of process has been saved
OS_CPU_PendSVHandler_nosave
PUSH {R14} ; Save LR exc_return value
LDR R0, =OSTaskSwHook ; OSTaskSwHook();
BLX R0
POP {R14}
LDR R0, =OSPrioCur ; OSPrioCur = OSPrioHighRdy;
LDR R1, =OSPrioHighRdy
LDRB R2, [R1]
STRB R2, [R0]
LDR R0, =OSTCBCur ; OSTCBCur = OSTCBHighRdy;
LDR R1, =OSTCBHighRdy
LDR R2, [R1]
STR R2, [R0]
LDR R0, [R2] ; R0 is new process SP; SP = OSTCBHighRdy->OSTCBStkPtr;
LDM R0, {R4-R11} ; Restore r4-11 from new process stack
ADDS R0, R0, #0x20
MSR PSP, R0 ; Load PSP with new process SP
ORR LR, LR, #0x04 ; Ensure exception return uses process stack
CPSIE I
BX LR ; Exception return will restore remaining context
END
|
//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004-2020 musikcube team
//
// 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 author nor the names of other 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 "Utility.h"
#include <string.h>
#include <musikcore/sdk/String.h>
#include <musikcore/sdk/Filesystem.h>
#ifdef WIN32
#include <Windows.h>
#endif
using namespace musik::core::sdk;
bool isFileTypeSupported(const char* type) {
const char* actualType = strlen(type) && type[0] == '.' ? &type[1] : type;
return openmpt_is_extension_supported(actualType);
}
bool isFileSupported(const std::string& filename) {
return isFileTypeSupported(fs::getFileExtension(filename).c_str());
}
bool fileToByteArray(const std::string& path, char** target, int& size) {
#ifdef WIN32
std::wstring u16fn = str::u8to16(path.c_str());
FILE* file = _wfopen(u16fn.c_str(), L"rb");
#else
FILE* file = fopen(path.c_str(), "rb");
#endif
*target = nullptr;
size = 0;
if (!file) {
return false;
}
bool success = false;
if (fseek(file, 0L, SEEK_END) == 0) {
long fileSize = ftell(file);
if (fileSize == -1) {
goto close_and_return;
}
if (fseek(file, 0L, SEEK_SET) != 0) {
goto close_and_return;
}
*target = (char*)malloc(sizeof(char) * fileSize);
size = fread(*target, sizeof(char), fileSize, file);
if (size == fileSize) {
success = true;
}
}
close_and_return:
fclose(file);
if (!success) {
free(*target);
}
return success;
}
std::string readMetadataValue(openmpt_module* module, const char* key, const char* defaultValue) {
std::string result;
if (module && key && strlen(key)) {
const char* value = openmpt_module_get_metadata(module, key);
if (value) {
result = value;
openmpt_free_string(value);
}
}
if (!result.size() && defaultValue) {
result = defaultValue;
}
return result;
}
ISchema* createSchema() {
auto schema = new musik::core::sdk::TSchema<>();
schema->AddString(KEY_DEFAULT_ALBUM_NAME, DEFAULT_ALBUM_NAME);
schema->AddString(KEY_DEFAULT_ARTIST_NAME, DEFAULT_ARTIST_NAME);
return schema;
} |
; PROLOGUE(mpn_karasub)
; mpn_karasub
;
; Copyright 2011 The Code Cavern
;
; Copyright 2012 Brian Gladman
;
; This file is part of the MPIR Library.
;
; The MPIR Library is free software; you can redistribute it and/or modify
; it under the terms of the GNU Lesser General Public License as published
; by the Free Software Foundation; either version 2.1 of the License, or (at
; your option) any later version.
;
; The MPIR Library is distributed in the hope that it will be useful, but
; WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
; License for more details.
;
; You should have received a copy of the GNU Lesser General Public License
; along with the MPIR Library; see the file COPYING.LIB. If not, write
; to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
; Boston, MA 02110-1301, USA.
;
; void mpn_karasub(mp_ptr, mp_ptr, mp_size_t)
; rax rdi rsi rdx
; rax rcx rdx r8
;
; Karasuba Multiplication - split x and y into two equal length halves so
; that x = xh.B + xl and y = yh.B + yl. Then their product is:
;
; x.y = xh.yh.B^2 + (xh.yl + xl.yh).B + xl.yl
; = xh.yh.B^2 + (xh.yh + xl.yl - {xh - xl}.{yh - yl}).B + xl.yl
;
; If the length of the elements is m (about n / 2), the output length is 4 * m
; as illustrated below. The middle two blocks involve three additions and one
; subtraction:
;
; -------------------- rp
; | |-->
; | A:xl.yl[lo] | |
; | | | (xh - xl).(yh - yl)
; -------------------- | -------------------- tp
; <-- | |<--< <-- | |
; | | B:xl.yl[hi] | | | E:[lo] |
; | | | | | |
; | -------------------- | --------------------
; >--> | |--> <-- | |
; |\___ | C:xh.yh[lo] | ____/ | F:[hi] |
; | | | | |
; | -------------------- --------------------
; <-- | |
; | D:xh.yh[hi] |
; | |
; --------------------
;
; To avoid overwriting B before it is used, we need to do two operations
; in parallel:
;
; (1) B = B + C + A - E = (B + C) + A - E
; (2) C = C + B + D - F = (B + C) + D - F
;
; The final carry from (1) has to be propagated into C and D, and the final
; carry from (2) has to be propagated into D. When the number of input limbs
; is odd, some extra operations have to be undertaken.
%include "yasm_mac.inc"
%define reg_save_list rbx, rbp, rsi, rdi, r12, r13, r14, r15
%macro add_one 1
inc %1
%endmacro
BITS 64
TEXT
; requires n >= 8
FRAME_PROC mpn_karasub, 2, reg_save_list
mov rdi, rcx
mov rsi, rdx
mov rdx, r8
mov [rsp], rdx
mov [rsp+8], rdi
; rp is rdi, tp is rsi, L is rdi, H is rbp, tp is rsi
; carries/borrows in rax, rbx
shr rdx, 1
lea rcx, [rdx+rdx*1]
lea rbp, [rdi+rcx*8]
xor rax, rax
xor rbx, rbx
lea rdi, [rdi+rdx*8-24]
lea rsi, [rsi+rdx*8-24]
lea rbp, [rbp+rdx*8-24]
mov ecx, 3
sub rcx, rdx
mov edx, 3
align 16
.1: bt rbx, 2
mov r8, [rdi+rdx*8]
adc r8, [rbp+rcx*8]
mov r12, r8
mov r9, [rdi+rdx*8+8]
adc r9, [rbp+rcx*8+8]
mov r10, [rdi+rdx*8+16]
adc r10, [rbp+rcx*8+16]
mov r11, [rdi+rdx*8+24]
adc r11, [rbp+rcx*8+24]
adc rbx, rbx
bt rax, 1
mov r15, r11
adc r8, [rdi+rcx*8]
mov r13, r9
adc r9, [rdi+rcx*8+8]
mov r14, r10
adc r10, [rdi+rcx*8+16]
adc r11, [rdi+rcx*8+24]
adc rax, rax
bt rbx, 2
adc r12, [rbp+rdx*8]
adc r13, [rbp+rdx*8+8]
adc r14, [rbp+rdx*8+16]
adc r15, [rbp+rdx*8+24]
adc rbx, rbx
bt rax, 1
sbb r8, [rsi+rcx*8]
sbb r9, [rsi+rcx*8+8]
sbb r10, [rsi+rcx*8+16]
sbb r11, [rsi+rcx*8+24]
mov [rdi+rdx*8+16], r10
mov [rdi+rdx*8+24], r11
adc rax, rax
bt rbx, 2
mov [rdi+rdx*8], r8
mov [rdi+rdx*8+8], r9
sbb r12, [rsi+rdx*8]
sbb r13, [rsi+rdx*8+8]
sbb r14, [rsi+rdx*8+16]
sbb r15, [rsi+rdx*8+24]
adc rbx, rbx
add rdx, 4
mov [rbp+rcx*8], r12
mov [rbp+rcx*8+8], r13
mov [rbp+rcx*8+16], r14
mov [rbp+rcx*8+24], r15
add rcx, 4
jnc .1
cmp rcx, 2
jg .5
jz .4
jp .3
.2: bt rbx, 2
mov r8, [rdi+rdx*8]
adc r8, [rbp]
mov r12, r8
mov r9, [rdi+rdx*8+8]
adc r9, [rbp+8]
mov r10, [rdi+rdx*8+16]
adc r10, [rbp+16]
adc rbx, rbx
bt rax, 1
adc r8, [rdi]
mov r13, r9
adc r9, [rdi+8]
mov r14, r10
adc r10, [rdi+16]
adc rax, rax
bt rbx, 2
adc r12, [rbp+rdx*8]
adc r13, [rbp+rdx*8+8]
adc r14, [rbp+rdx*8+16]
adc rbx, rbx
bt rax, 1
sbb r8, [rsi]
sbb r9, [rsi+8]
sbb r10, [rsi+16]
mov [rdi+rdx*8+16], r10
adc rax, rax
bt rbx, 2
mov [rdi+rdx*8], r8
mov [rdi+rdx*8+8], r9
sbb r12, [rsi+rdx*8]
sbb r13, [rsi+rdx*8+8]
sbb r14, [rsi+rdx*8+16]
adc rbx, rbx
add rdx, 3
mov [rbp], r12
mov [rbp+8], r13
mov [rbp+16], r14
jmp .5
.3: bt rbx, 2
mov r8, [rdi+rdx*8]
adc r8, [rbp+8]
mov r12, r8
mov r9, [rdi+rdx*8+8]
adc r9, [rbp+16]
adc rbx, rbx
bt rax, 1
adc r8, [rdi+8]
mov r13, r9
adc r9, [rdi+16]
adc rax, rax
bt rbx, 2
adc r12, [rbp+rdx*8]
adc r13, [rbp+rdx*8+8]
adc rbx, rbx
bt rax, 1
sbb r8, [rsi+8]
sbb r9, [rsi+16]
adc rax, rax
bt rbx, 2
mov [rdi+rdx*8], r8
mov [rdi+rdx*8+8], r9
sbb r12, [rsi+rdx*8]
sbb r13, [rsi+rdx*8+8]
adc rbx, rbx
add rdx, 2
mov [rbp+8], r12
mov [rbp+16], r13
jmp .5
.4: bt rbx, 2
mov r8, [rdi+rdx*8]
adc r8, [rbp+16]
mov r12, r8
adc rbx, rbx
bt rax, 1
adc r8, [rdi+16]
adc rax, rax
bt rbx, 2
adc r12, [rbp+rdx*8]
adc rbx, rbx
bt rax, 1
sbb r8, [rsi+16]
adc rax, rax
bt rbx, 2
mov [rdi+rdx*8], r8
sbb r12, [rsi+rdx*8]
adc rbx, rbx
add_one rdx
mov [rbp+rcx*8], r12
; move low half rbx carry into rax
.5: rcr rax, 3
bt rbx, 2
rcl rax, 3
mov r8, [rsp]
mov rcx, rsi
mov rsi,[rsp+8]
lea r9, [r8+r8]
lea rsi, [rsi+r9*8]
lea r11, [rbp+24]
sub r11, rsi
sar r11, 3
bt r8, 0
jnc .9
; if odd the do next two
add r11, 2
mov r8, [rbp+rdx*8]
mov r9, [rbp+rdx*8+8]
rcr rbx, 2
adc r8,0
adc r9, 0
adc rbx, rbx
sbb r8, [rcx+rdx*8]
sbb r9, [rcx+rdx*8+8]
rcr rbx, 2
adc [rbp+24], r8
adc [rbp+32], r9
rcl rbx, 3
; Now add in any accummulated carries and/or borrows
;
; NOTE: We can't propagate individual borrows or carries from the second
; and third quarter blocks into the fourth quater block by simply waiting
; for carry (or borrow) propagation to end. This is because a carry into
; the fourth quarter block when it contains only maximum integers or a
; borrow when it contains all zero integers will incorrectly propagate
; beyond the end of the top quarter block.
.9: lea rdx, [rdi+rdx*8]
sub rdx, rsi
sar rdx, 3
; carries/borrrow from second to third quarter quarter block
; rax{2} is the carry in (B + C)
; rax{1} is the carry in (B + C) + A
; rax{0} is the borrow in (B + C + A) - E
mov rcx, rdx
bt rax, 0
.10: sbb qword[rsi+rcx*8], 0
add_one rcx
jrcxz .11
jc .10
.11 mov rcx, rdx
bt rax, 1
.12: adc qword[rsi+rcx*8], 0
add_one rcx
jrcxz .13
jc .12
.13 mov rcx, rdx
bt rax, 2
.14: adc qword[rsi+rcx*8], 0
add_one rcx
jrcxz .15
jc .14
; carries/borrrow from third to fourth quarter quarter block
; rbx{2} is the carry in (B + C)
; rbx{1} is the carry in (B + C) + D
; rbx{0} is the borrow in (B + C + D) - F
.15: mov rcx, r11
bt rbx, 0
.16: sbb qword[rsi+rcx*8], 0
add_one rcx
jrcxz .17
jc .16
.17: mov rcx, r11
bt rbx, 1
.18: adc qword[rsi+rcx*8], 0
add_one rcx
jrcxz .19
jc .18
.19: mov rcx, r11
bt rbx, 2
.20: adc qword[rsi+rcx*8], 0
add_one rcx
jrcxz .21
jc .20
.21:
END_PROC reg_save_list
end
|
; A195605: a(n) = (4*n*(n+2)+(-1)^n+1)/2 + 1.
; 2,7,18,31,50,71,98,127,162,199,242,287,338,391,450,511,578,647,722,799,882,967,1058,1151,1250,1351,1458,1567,1682,1799,1922,2047,2178,2311,2450,2591,2738,2887,3042,3199,3362,3527,3698,3871,4050,4231,4418,4607,4802,4999,5202,5407,5618,5831,6050,6271,6498,6727,6962,7199,7442,7687,7938,8191,8450,8711,8978,9247,9522,9799,10082,10367,10658,10951,11250,11551,11858,12167,12482,12799,13122,13447,13778,14111,14450,14791,15138,15487,15842,16199,16562,16927,17298,17671,18050,18431,18818,19207,19602,19999,20402,20807,21218,21631,22050,22471,22898,23327,23762,24199,24642,25087,25538,25991,26450,26911,27378,27847,28322,28799,29282,29767,30258,30751,31250,31751,32258,32767,33282,33799,34322,34847,35378,35911,36450,36991,37538,38087,38642,39199,39762,40327,40898,41471,42050,42631,43218,43807,44402,44999,45602,46207,46818,47431,48050,48671,49298,49927,50562,51199,51842,52487,53138,53791,54450,55111,55778,56447,57122,57799,58482,59167,59858,60551,61250,61951,62658,63367,64082,64799,65522,66247,66978,67711,68450,69191,69938,70687,71442,72199,72962,73727,74498,75271,76050,76831,77618,78407,79202,79999,80802,81607,82418,83231,84050,84871,85698,86527,87362,88199,89042,89887,90738,91591,92450,93311,94178,95047,95922,96799,97682,98567,99458,100351,101250,102151,103058,103967,104882,105799,106722,107647,108578,109511,110450,111391,112338,113287,114242,115199,116162,117127,118098,119071,120050,121031,122018,123007,124002,124999
mov $1,$0
gcd $0,2
add $1,1
pow $1,2
mul $1,2
mov $2,$0
sub $2,2
add $1,$2
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r14
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0xe947, %r11
nop
nop
nop
add $57064, %r10
movb (%r11), %cl
add %rcx, %rcx
lea addresses_WT_ht+0x2854, %r10
nop
add %r9, %r9
movb (%r10), %r8b
cmp %rdi, %rdi
lea addresses_UC_ht+0x728f, %r10
nop
nop
nop
nop
nop
and $43705, %r11
mov (%r10), %r8d
nop
nop
nop
nop
and $23034, %rdi
lea addresses_D_ht+0x1c40f, %rsi
lea addresses_normal_ht+0x147cb, %rdi
clflush (%rsi)
nop
add $48535, %r14
mov $47, %rcx
rep movsq
cmp %r11, %r11
lea addresses_D_ht+0x1b02f, %rsi
lea addresses_D_ht+0xebcf, %rdi
nop
nop
nop
nop
nop
dec %r10
mov $85, %rcx
rep movsw
nop
nop
nop
nop
inc %rcx
lea addresses_A_ht+0x1bd4f, %rsi
lea addresses_UC_ht+0x1b1cf, %rdi
nop
nop
nop
and $32304, %r14
mov $21, %rcx
rep movsw
nop
nop
nop
nop
xor $58227, %rsi
lea addresses_A_ht+0x14dcf, %rsi
lea addresses_D_ht+0x14f0f, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
sub %r11, %r11
mov $9, %rcx
rep movsb
nop
nop
xor %rdi, %rdi
lea addresses_WT_ht+0x95b8, %rcx
nop
nop
nop
nop
cmp $50558, %rdi
movl $0x61626364, (%rcx)
nop
nop
and %r10, %r10
lea addresses_WT_ht+0xf277, %rdi
xor %r8, %r8
movb (%rdi), %r11b
nop
nop
nop
sub $25567, %rcx
lea addresses_UC_ht+0x15dcf, %rsi
nop
dec %r8
mov $0x6162636465666768, %r9
movq %r9, (%rsi)
nop
nop
cmp %r11, %r11
lea addresses_WT_ht+0xf90d, %rsi
lea addresses_UC_ht+0x9a7f, %rdi
clflush (%rdi)
nop
nop
nop
nop
add %r9, %r9
mov $36, %rcx
rep movsq
nop
and $27623, %rsi
lea addresses_A_ht+0x1913f, %rsi
lea addresses_WC_ht+0x163cf, %rdi
add $47417, %r14
mov $122, %rcx
rep movsq
and $15768, %r10
lea addresses_A_ht+0x1e4cf, %rdi
nop
nop
nop
nop
nop
xor $13574, %r14
mov $0x6162636465666768, %r9
movq %r9, %xmm0
movups %xmm0, (%rdi)
nop
nop
xor %r9, %r9
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r14
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r14
push %r15
push %r8
push %r9
push %rdi
// Store
lea addresses_US+0xc1cf, %r14
nop
nop
add %r9, %r9
movl $0x51525354, (%r14)
nop
nop
nop
nop
nop
and $7661, %r14
// Load
lea addresses_WT+0x1d04f, %r12
nop
nop
nop
nop
and $63745, %r10
mov (%r12), %r8
// Exception!!!
nop
mov (0), %r15
and %r12, %r12
// Faulty Load
lea addresses_US+0x11bcf, %r8
nop
nop
nop
xor $46222, %r12
vmovups (%r8), %ymm5
vextracti128 $1, %ymm5, %xmm5
vpextrq $1, %xmm5, %r14
lea oracles, %r12
and $0xff, %r14
shlq $12, %r14
mov (%r12,%r14,1), %r14
pop %rdi
pop %r9
pop %r8
pop %r15
pop %r14
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_US'}}
{'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': True, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}}
{'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
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x111ba, %r15
nop
add $12613, %r10
movups (%r15), %xmm0
vpextrq $0, %xmm0, %rsi
nop
nop
nop
nop
cmp $59231, %r13
lea addresses_A_ht+0x27ba, %rsi
lea addresses_D_ht+0x38ca, %rdi
nop
and $62343, %r15
mov $124, %rcx
rep movsb
nop
nop
nop
xor $49836, %r15
pop %rsi
pop %rdi
pop %rcx
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
// Faulty Load
lea addresses_US+0x133ba, %rcx
nop
nop
nop
and $35246, %rsi
mov (%rcx), %r8
lea oracles, %rdx
and $0xff, %r8
shlq $12, %r8
mov (%rdx,%r8,1), %r8
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': True, 'type': 'addresses_US'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}}
{'45': 13480, '3c': 5013, 'de': 961, '80': 46, 'b0': 90, '79': 10, 'ff': 2030, '00': 19, 'b6': 1, 'e9': 88, 'e0': 89, '90': 2}
45 3c de de ff ff 45 45 45 3c 3c 45 45 de 45 45 de 45 45 45 45 45 45 ff ff 45 3c 3c 45 45 3c 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 de 45 45 45 80 3c 45 45 de 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 3c ff b0 3c b0 3c 45 45 45 45 3c 3c ff 45 3c 3c 3c 3c ff 45 45 3c 45 3c 3c 3c 3c 3c 45 3c 45 45 45 3c 3c 3c 45 ff 45 45 45 de 45 45 45 45 45 45 45 45 3c 45 45 3c 45 45 ff 45 45 45 45 45 45 45 45 45 45 45 45 45 45 3c 45 ff 45 45 45 45 45 45 45 45 45 45 de 45 45 45 45 45 3c 45 b0 45 45 45 45 45 45 45 45 45 45 45 45 b0 45 45 45 3c 3c 3c 45 45 45 de 3c 45 45 45 45 45 45 3c 45 45 45 45 45 45 e9 45 45 45 45 3c 3c 45 45 45 45 45 ff de 3c ff 45 3c 45 45 45 45 45 45 45 de 45 45 45 45 45 45 45 45 ff 3c 45 45 de de ff 3c 45 45 ff 45 45 45 45 ff 3c 3c 45 ff 45 45 e9 45 45 ff 45 45 3c 45 45 45 45 45 45 de 45 3c 45 3c 45 45 45 45 ff 3c 3c 45 45 45 3c 45 45 45 45 45 3c 3c ff 80 3c 45 45 3c 45 45 45 45 45 45 45 45 3c 45 3c 3c 3c 3c 45 45 3c 45 ff 3c ff 45 45 e9 45 45 3c ff 3c ff 45 45 3c 3c 45 3c 45 3c 45 45 3c 45 45 45 45 45 e0 3c 3c 3c 45 45 45 45 45 45 45 45 ff 3c 3c ff 45 45 45 45 45 45 45 45 45 3c 45 45 45 45 ff ff 3c ff 3c 45 ff 45 45 3c 3c ff de 45 45 45 3c 45 45 45 3c 45 45 45 3c 45 45 45 ff 3c e9 45 3c ff ff 3c de 3c 80 ff 45 3c 3c 45 45 45 45 45 45 45 45 3c 45 45 45 45 de 3c ff 45 45 45 45 45 45 45 45 3c 3c 3c 45 45 45 de 45 ff 45 45 45 45 45 45 3c 45 45 45 3c ff 3c 3c 3c 3c 45 45 de 3c 45 45 45 3c ff 45 3c 3c 45 45 ff 45 3c ff ff 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 3c 3c 3c 45 de 45 45 45 3c 3c ff de 45 45 45 45 79 3c 45 3c 45 3c 45 45 45 45 45 ff de de 45 45 45 45 3c 45 45 3c 45 45 ff 45 45 45 e0 3c ff 3c 45 45 45 45 45 45 45 de 45 45 45 45 3c 45 45 45 45 45 45 45 45 3c 45 de ff 3c 45 3c 45 45 45 45 45 45 3c 3c 45 45 3c 45 45 3c 3c 45 45 45 45 45 45 45 45 45 45 45 3c ff 3c 45 3c 3c 45 45 45 45 45 3c 45 45 45 45 45 45 3c 45 45 3c 45 45 3c 45 3c 45 45 45 45 45 de 45 45 ff 45 45 3c 45 45 45 45 45 45 45 45 ff ff ff 3c 3c 45 45 45 ff ff 3c de 3c 45 3c ff 45 45 45 3c 45 45 ff 3c 45 45 b0 3c 45 45 45 45 b0 3c 3c 3c 3c ff 45 45 45 45 45 45 45 de ff 45 45 45 45 45 45 b0 3c 45 45 45 45 45 45 45 de 3c 3c 45 45 de 45 45 45 45 45 45 de 3c 45 45 45 3c ff 45 45 45 3c 45 3c 45 45 45 45 e0 3c 3c 45 45 45 45 3c 3c ff ff 45 45 45 3c 45 45 45 3c 3c 45 45 45 3c 45 45 45 45 45 45 3c 45 45 45 45 45 45 3c 45 3c ff ff 45 ff 45 45 3c 3c 3c 45 45 45 45 3c 45 45 3c 45 45 45 45 3c 45 45 45 45 45 3c ff 45 45 45 3c 45 45 45 3c 3c 45 45 45 de 3c 3c ff 45 45 3c 3c ff de 45 3c 3c 45 45 45 45 3c 45 45 45 e9 45 45 3c 3c 45 45 45 de 45 3c ff 3c 45 45 45 e9 ff 3c 45 45 45 45 3c 3c 3c ff 45 45 45 45 ff 3c 45 45 45 3c 45 45 3c 45 45 3c 45 45 45 45 45 3c 3c ff 45 45 3c 45 3c 45 45 45 3c de 45 45 45 45 45 3c 3c 3c 45 de 3c 45 45 3c 3c 45 e9 45 3c ff 45 45 3c 3c 45 3c ff 45 3c 45 3c 3c 45 45 45 3c 3c de 45 45 45 de 45 e9 45 45 45 45 45 3c 3c 45 45 45 de ff de 45 3c ff 3c 3c 45 3c 45 3c 3c 45 3c 45 3c 45 45 3c 3c 45 e9 45 45 45 45 45 de 45 ff 3c 3c 3c 45 45 45 de ff 45
*/
|
Map_22544E: dc.w Frame_225460-Map_22544E ; ...
dc.w Frame_225468-Map_22544E
dc.w Frame_225476-Map_22544E
dc.w Frame_225490-Map_22544E
dc.w Frame_2254B6-Map_22544E
dc.w Frame_2254DC-Map_22544E
dc.w Frame_225502-Map_22544E
dc.w Frame_225528-Map_22544E
dc.w Frame_225542-Map_22544E
Frame_225460: dc.w 1
dc.b $F0, $F, 8,$3B,$FF,$F0
Frame_225468: dc.w 2
dc.b $FC, 4, 0,$4B,$FF,$D0
dc.b $FC, 4, 0,$4D,$FF,$E0
Frame_225476: dc.w 4
dc.b $FC, 4, 0,$4D,$FF,$D0
dc.b $FC, 4, 0,$4F,$FF,$E0
dc.b $FC, 4, 0,$51,$FF,$F0
dc.b $F8, 5, 0,$57, 0, 0
Frame_225490: dc.w 6
dc.b $FC, 4, 0,$4B,$FF,$D0
dc.b $FC, 4, 0,$4D,$FF,$E0
dc.b $FC, 4, 0,$4F,$FF,$F0
dc.b $FC, 4, 0,$51, 0, 0
dc.b $F8, 5, 0,$53, 0,$10
dc.b $F8, 5, 0,$57, 0,$20
Frame_2254B6: dc.w 6
dc.b $FC, 4,$10,$4B,$FF,$D0
dc.b $FC, 4,$10,$4D,$FF,$E0
dc.b $FC, 4,$10,$4F,$FF,$F0
dc.b $FC, 4,$10,$51, 0, 0
dc.b $F8, 5,$10,$53, 0,$10
dc.b $F8, 5,$10,$57, 0,$20
Frame_2254DC: dc.w 6
dc.b $FC, 4, 0,$4D,$FF,$D0
dc.b $FC, 4, 0,$4F,$FF,$E0
dc.b $FC, 4, 0,$51,$FF,$F0
dc.b $F8, 5, 0,$53, 0, 0
dc.b $F8, 5,$18,$53, 0,$10
dc.b $F8, 5, 0,$5B, 0,$20
Frame_225502: dc.w 6
dc.b $FC, 4,$10,$4D,$FF,$D0
dc.b $FC, 4,$10,$4F,$FF,$E0
dc.b $FC, 4,$10,$51,$FF,$F0
dc.b $F8, 5,$10,$53, 0, 0
dc.b $F8, 5, 8,$53, 0,$10
dc.b $F8, 5,$10,$5B, 0,$20
Frame_225528: dc.w 4
dc.b $FC, 4, 0,$4B,$FF,$F0
dc.b $FC, 4, 0,$4D, 0, 0
dc.b $FC, 4, 0,$4F, 0,$10
dc.b $F8, 5, 0,$5B, 0,$20
Frame_225542: dc.w 2
dc.b $FC, 4, 0,$4B, 0,$10
dc.b $FC, 4, 0,$5F, 0,$20
|
// The IYFEngine
//
// Copyright (C) 2015-2018, Manvydas Šliamka
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
// WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "assets/AssetManager.hpp"
#include "assets/loaders/MeshLoader.hpp"
#include "assets/metadata/AnimationMetadata.hpp"
#include "assets/metadata/MeshMetadata.hpp"
#include "assets/metadata/TextureMetadata.hpp"
#include "assets/metadata/FontMetadata.hpp"
#include "assets/metadata/AudioMetadata.hpp"
#include "assets/metadata/VideoMetadata.hpp"
#include "assets/metadata/ScriptMetadata.hpp"
#include "assets/metadata/ShaderMetadata.hpp"
#include "assets/metadata/StringMetadata.hpp"
#include "assets/metadata/CustomMetadata.hpp"
#include "assets/metadata/MaterialTemplateMetadata.hpp"
#include "assets/metadata/MaterialInstanceMetadata.hpp"
#include "graphics/MeshComponent.hpp"
#include "core/Constants.hpp"
#include "core/filesystem/VirtualFileSystem.hpp"
#include "logging/Logger.hpp"
#include "core/Platform.hpp"
#include "core/Engine.hpp"
#include "io/serialization/FileSerializer.hpp"
#include "io/FileSystem.hpp"
#include "io/serialization/FileSerializer.hpp"
#include "io/interfaces/TextSerializable.hpp"
#include "assets/typeManagers/TypeManager.hpp"
#include "assets/typeManagers/FontTypeManager.hpp"
#include "assets/typeManagers/MeshTypeManager.hpp"
#include "assets/typeManagers/ShaderTypeManager.hpp"
#include "assets/typeManagers/TextureTypeManager.hpp"
#include "utilities/DataSizes.hpp"
#include "utilities/FileInDir.hpp"
#include "rapidjson/prettywriter.h"
#include "rapidjson/document.h"
#include <climits>
namespace iyf {
namespace con {
const std::chrono::milliseconds MinAsyncLoadWindow = std::chrono::milliseconds(2);
const std::chrono::milliseconds MaxAsyncLoadWindow = std::chrono::milliseconds(60);
}
using namespace iyf::literals;
AssetManager::AssetManager(Engine* engine) : engine(engine), asyncLoadWindow(con::MinAsyncLoadWindow), isInit(false) {
if (std::atomic<std::uint32_t>::is_always_lock_free) {
LOG_V("std::uint32_t is lock free on this system");
} else {
LOG_W("std::uint32_t is NOT lock free on this system");
}
AssetType biggestAssetMetadata = AssetType::COUNT;
std::size_t maxSize = 0;
std::stringstream ss;
ss << "Metadata type sizes: ";
for (std::uint64_t i = 0; i < static_cast<std::uint64_t>(AssetType::COUNT); ++i) {
const AssetType type = static_cast<AssetType>(i);
const std::size_t size = Metadata::GetAssetMetadataSize(type);
ss << "\n\t" << con::AssetTypeToTranslationString(type) << " " << size;
if (size > maxSize) {
maxSize = size;
biggestAssetMetadata = type;
}
}
ss << "\n\tBIGGEST METADATA OBJECT: " << con::AssetTypeToTranslationString(biggestAssetMetadata) << ", " << maxSize << " bytes.";
LOG_D("{}", ss.str())
editorMode = engine->isEditorMode();
}
AssetManager::~AssetManager() { }
AssetType AssetManager::GetAssetTypeFromExtension(const Path& pathToFile) {
static const std::unordered_map<std::string, AssetType> ExtensionToType = {
{".ttf", AssetType::Font},
{".otf", AssetType::Font},
{".bmp", AssetType::Texture},
{".psd", AssetType::Texture},
{".png", AssetType::Texture},
{".gif", AssetType::Texture},
{".tga", AssetType::Texture},
{".jpg", AssetType::Texture},
{".jpeg", AssetType::Texture},
{".hdr", AssetType::Texture},
{".pic", AssetType::Texture},
{".ppm", AssetType::Texture},
{".pgm", AssetType::Texture},
// TODO. Test and enable more formats. We're using Assimp. It suports MANY different mesh formats, however, I've only done extensive testing with Blender exported fbx and dae files.
{".fbx", AssetType::Mesh},
{".dae", AssetType::Mesh},
// {".3ds", AssetType::Mesh},
// {".blend", AssetType::Mesh},
// TODO. support (some of?) these. Currently, the engine isn't able to convert anything and, to be honest, I don't know much about audio format patents and licences.
// I know that MP3 is patent protected and that you need to pay for a licence if you use it. I also know that ogg is just a container and that, while it was designed to
// be used with free codecs, it's possible to squeeze in things like mp3s into it.
// I don't know if you need to get a the license if you only convert mp3 to vorbis (opus?). I do know that converting from one compressed format to another is a bad idea because quality
// suffers, so I should at least try to add support free uncompressed formats (e.g., FLAC).
// And seriously, what about opus? Should I use it instead of vorbis?
// {".opus", AssetType::Audio},
// {".flac", AssetType::Audio},
// {".mp3", AssetType::Audio}, // Probably not.
// {".waw", AssetType::Audio},
// {".ogg", AssetType::Audio},
{".vert", AssetType::Shader},
{".tesc", AssetType::Shader},
{".tese", AssetType::Shader},
{".geom", AssetType::Shader},
{".frag", AssetType::Shader},
{".comp", AssetType::Shader},
{".csv", AssetType::Strings},
{con::MaterialTemplateFormatExtension(), AssetType::MaterialTemplate},
{con::MaterialInstanceFormatExtension(), AssetType::MaterialInstance},
};
std::string extension = pathToFile.extension().getGenericString();
if (extension.empty()) {
return AssetType::Custom;
}
// TODO can extensions be not ASCII? Can we mess something up here?
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
const auto it = ExtensionToType.find(extension);
if (it == ExtensionToType.end()) {
return AssetType::Custom;
} else {
return it->second;
}
}
void AssetManager::initialize() {
if (isInit) {
return;
}
//LOG_D(sizeof(MeshMetadata) << " " << sizeof(TextureMetadata) << " " << sizeof(Metadata) << " " << sizeof(ManifestElement) << " l " << sizeof(MeshVertex))
//LOG_D("MAH_MESH" << sizeof(Mesh) << " " << sizeof(std::size_t))
BufferRangeSet brs(Bytes(64));
brs.getFreeRange(Bytes(8), Bytes(2));
auto fr = brs.getFreeRange(Bytes(10), Bytes(5));
LOG_D("Ranges {} {} {}", fr.completeRange.offset.count(), fr.completeRange.size.count(), fr.startPadding)
typeManagers[static_cast<std::size_t>(AssetType::Mesh)] = std::unique_ptr<MeshTypeManager>(new MeshTypeManager(this, 2_MiB, 1_MiB));
typeManagers[static_cast<std::size_t>(AssetType::Shader)] = std::unique_ptr<ShaderTypeManager>(new ShaderTypeManager(this));
typeManagers[static_cast<std::size_t>(AssetType::Texture)] = std::unique_ptr<TextureTypeManager>(new TextureTypeManager(this));
typeManagers[static_cast<std::size_t>(AssetType::Font)] = std::unique_ptr<FontTypeManager>(new FontTypeManager(this));
//AssetHandle<Mesh> r = load<Mesh>(HS("nano"));
buildManifestFromFilesystem();
loadSystemAssets();
for (auto& tm : typeManagers) {
if (tm != nullptr) {
tm->initMissingAssetHandle();
}
}
isInit = true;
}
void AssetManager::dispose() {
for (auto& tm : typeManagers) {
if (tm != nullptr) {
tm->collectGarbage(GarbageCollectionRunPolicy::FullCollectionDuringDestruction);
tm = nullptr;
}
}
isInit = false;
}
/// A helper class used when building the manifest.
struct FileDiscoveryResults {
enum class Field {
FilePath,
TextMetadataPath,
BinaryMetadataPath
};
inline FileDiscoveryResults() : nameHash(0) {}
inline FileDiscoveryResults(StringHash nameHash) : nameHash(nameHash) {}
inline bool isComplete() const {
return (!filePath.empty()) && wasMetadataFound();
}
inline bool wasMetadataFound() const {
// We need a metadata file of ONE type. If no metadata files were found, we can't add the asset to the manifest.
// If both types of metadata files are found, we don't know which one is valid.
return (textMetadataPath.empty() && !binaryMetadataPath.empty()) || (!textMetadataPath.empty() && binaryMetadataPath.empty());
}
StringHash nameHash;
Path filePath;
Path textMetadataPath;
Path binaryMetadataPath;
};
inline void findAndSetFileDiscoveryResults(std::unordered_map<StringHash, FileDiscoveryResults>& results, StringHash nameHash, FileDiscoveryResults::Field field, const Path& path) {
auto result = results.find(nameHash);
if (result == results.end()) {
FileDiscoveryResults fdr(nameHash);
switch (field) {
case FileDiscoveryResults::Field::FilePath:
fdr.filePath = path;
break;
case FileDiscoveryResults::Field::TextMetadataPath:
fdr.textMetadataPath = path;
break;
case FileDiscoveryResults::Field::BinaryMetadataPath:
fdr.binaryMetadataPath = path;
break;
}
results[nameHash] = std::move(fdr);
} else {
assert(result->second.nameHash == nameHash);
switch (field) {
case FileDiscoveryResults::Field::FilePath:
result->second.filePath = path;
break;
case FileDiscoveryResults::Field::TextMetadataPath:
result->second.textMetadataPath = path;
break;
case FileDiscoveryResults::Field::BinaryMetadataPath:
result->second.binaryMetadataPath = path;
break;
}
}
}
/// Checks if the name of the asset or metadata file is valid
inline bool isFileNameValid(const std::string& name) {
if (name.empty()) {
return false;
}
for (char c : name) {
if (c < 48 || c > 57) {
return false;
}
}
return true;
}
template <typename T>
inline T loadMetadata(const Path& path, bool isJSON) {
T metadata;
if (isJSON) {
auto jsonFile = VirtualFileSystem::Instance().openFile(path, FileOpenMode::Read);
const auto wholeFile = jsonFile->readWholeFile();
rj::Document document;
document.Parse(wholeFile.first.get(), wholeFile.second);
metadata.deserializeJSON(document);
} else {
FileSerializer file(VirtualFileSystem::Instance(), path, FileOpenMode::Read);
metadata.deserialize(file);
}
assert(metadata.isComplete());
return metadata;
}
/// Loads the metadata and creates a AssetManager::ManifestElement from it
inline AssetManager::ManifestElement buildManifestElement(AssetType type, bool isJSON, const Path& metadataPath, const Path& filePath) {
AssetManager::ManifestElement me;
me.type = type;
me.path = filePath;
switch (type) {
case AssetType::Animation:
me.metadata = loadMetadata<AnimationMetadata>(metadataPath, isJSON);
break;
case AssetType::Mesh:
me.metadata = loadMetadata<MeshMetadata>(metadataPath, isJSON);
break;
case AssetType::Texture:
me.metadata = loadMetadata<TextureMetadata>(metadataPath, isJSON);
break;
case AssetType::Font:
me.metadata = loadMetadata<FontMetadata>(metadataPath, isJSON);
break;
case AssetType::Audio:
me.metadata = loadMetadata<AudioMetadata>(metadataPath, isJSON);
break;
case AssetType::Video:
me.metadata = loadMetadata<VideoMetadata>(metadataPath, isJSON);
break;
case AssetType::Script:
me.metadata = loadMetadata<ScriptMetadata>(metadataPath, isJSON);
break;
case AssetType::Shader:
me.metadata = loadMetadata<ShaderMetadata>(metadataPath, isJSON);
break;
case AssetType::Strings:
me.metadata = loadMetadata<StringMetadata>(metadataPath, isJSON);
break;
case AssetType::Custom:
me.metadata = loadMetadata<CustomMetadata>(metadataPath, isJSON);
break;
case AssetType::MaterialTemplate:
me.metadata = loadMetadata<MaterialTemplateMetadata>(metadataPath, isJSON);
break;
case AssetType::MaterialInstance:
me.metadata = loadMetadata<MaterialInstanceMetadata>(metadataPath, isJSON);
break;
case AssetType::COUNT:
throw std::runtime_error("COUNT is not an asset type");
}
me.systemAsset = me.metadata.getBase().isSystemAsset();
return me;
}
/// Adds all assets of the specified type to the provided manifest
///
/// \warning Make sure this is always protected by a mutex
inline void addFilesToManifest(FileSystem* filesystem, AssetType type, std::unordered_map<StringHash, AssetManager::ManifestElement>& manifest) {
const Path& baseDir = con::AssetTypeToPath(type);
LOG_V("Examining contents of \"{}\"", baseDir.getGenericString());
const auto contents = filesystem->getDirectoryContents(baseDir);
// Used to detect errors.
// TODO Return this as well. It may be useful for debugging
std::unordered_map<StringHash, FileDiscoveryResults> results;
for (const auto& p : contents) {
const Path fullPath = baseDir / p;
const std::string stem = fullPath.stem().getGenericString();
const bool validName = isFileNameValid(stem);
if (!validName) {
LOG_W("Found a file with a non-numeric name: {}. Skipping it.", fullPath);
continue;
}
const char* stemPtr = stem.c_str();
char* end;
const std::uint64_t parsedNumber = std::strtoull(stemPtr, &end, 10);
if (stemPtr == end) {
LOG_W("strtoull encountered an error when processing {}. Skipping it.", fullPath);
}
if (errno == ERANGE) {
LOG_W("strtoull encountered an error when processing {}. Skipping it.", fullPath);
errno = 0;
continue;
}
StringHash nameHash(parsedNumber);
//LOG_V("FOUND file: " << parsedNumber << " " << fullPath);
// We found an asset file, however, we only care about the metadata at the moment.
if (fullPath.extension().empty()) {
findAndSetFileDiscoveryResults(results, nameHash, FileDiscoveryResults::Field::FilePath, fullPath);
} else if (fullPath.extension() == con::MetadataExtension()) {
findAndSetFileDiscoveryResults(results, nameHash, FileDiscoveryResults::Field::BinaryMetadataPath, fullPath);
} else if (fullPath.extension() == con::TextMetadataExtension()) {
findAndSetFileDiscoveryResults(results, nameHash, FileDiscoveryResults::Field::TextMetadataPath, fullPath);
} else {
LOG_W("Found a file with an unexpected extension: {}. Skipping it.", fullPath);
}
}
std::size_t count = 0;
for (const auto& result : results) {
const bool hasFile = !result.second.filePath.empty();
const bool hasTextMetadata = !result.second.textMetadataPath.empty();
const bool hasBinaryMetadata = !result.second.binaryMetadataPath.empty();
if (!result.second.isComplete()) {
LOG_W("Couldn't add an item to the manifest. File + ONE type of metadata required, found this instead:\n\t"
"\n\tFile: {}"
"\n\tText metadata: {}"
"\n\tBinary metadata: {}",
(hasFile ? result.second.filePath : "NOT FOUND"),
(hasTextMetadata ? result.second.textMetadataPath : "NOT FOUND"),
(hasBinaryMetadata ? result.second.binaryMetadataPath : "NOT FOUND"));
}
const bool isJSON = hasTextMetadata;
const Path metadataPath = isJSON ? result.second.textMetadataPath : result.second.binaryMetadataPath;
auto me = buildManifestElement(type, isJSON, metadataPath, result.second.filePath);
auto manifestItem = manifest.find(result.second.nameHash);
if (manifestItem != manifest.end() && !manifestItem->second.systemAsset) {
throw std::runtime_error("A non-system asset hasn't been cleaned up.");
}
manifest[result.second.nameHash] = std::move(me);
count++;
}
LOG_V("Added {} {} file(s) to the manifest.\n\tIt now stores metadata of {} file(s).", count, con::AssetTypeToTranslationString(type), manifest.size());
}
void AssetManager::buildManifestFromFilesystem() {
VirtualFileSystem* filesystem = engine->getFileSystem();
LOG_V("Building the manifest using the following search path:\n\t{}", filesystem->logSearchPath("\n\t"));
// TODO automatically convert or delete items that were added or removed while the engine was off (e.g. thanks
// to version control).
std::lock_guard<std::mutex> manifestLock(manifestMutex);
for (std::size_t i = 0; i < static_cast<std::size_t>(AssetType::COUNT); ++i) {
addFilesToManifest(filesystem, static_cast<AssetType>(i), manifest);
}
}
bool AssetManager::serializeMetadata(StringHash nameHash, Serializer& file) {
std::lock_guard<std::mutex> manifestLock(manifestMutex);
auto result = manifest.find(nameHash);
if (result == manifest.end()) {
return false;
}
const Metadata& meta = (*result).second.metadata;
meta.getBase().serialize(file);
return true;
}
void AssetManager::collectGarbage() {
for (auto& tm : typeManagers) {
if (tm != nullptr) {
tm->collectGarbage(GarbageCollectionRunPolicy::FullCollection);
}
}
}
void AssetManager::enableLoadedAssets() {
const std::chrono::nanoseconds window = asyncLoadWindow;
const auto start = std::chrono::steady_clock::now();
auto now = start;
for (auto& tm : typeManagers) {
if (tm != nullptr) {
const bool canBatch = tm->canBatchAsyncLoadedAssets();
if (canBatch) {
while ((tm->hasAssetsToEnable() == AssetsToEnableResult::HasAssetsToEnable) &&
((now + tm->estimateBatchOperationDuration()) - start < window)) {
tm->enableAsyncLoadedAsset(true);
now = std::chrono::steady_clock::now();
}
} else {
while ((tm->hasAssetsToEnable() == AssetsToEnableResult::HasAssetsToEnable) &&
(now - start < window)) {
tm->enableAsyncLoadedAsset(false);
now = std::chrono::steady_clock::now();
}
}
if (canBatch) {
// This should always happen. If nothing was added, the TypeManager should avoid any expensive
// operations.
tm->executeBatchOperations();
now = std::chrono::steady_clock::now();
}
}
}
// TODO should I sleep or something to avoid inconsistent frame rates?
}
void AssetManager::setAsyncLoadWindow(std::chrono::milliseconds loadWindow) {
asyncLoadWindow = std::clamp(loadWindow, con::MinAsyncLoadWindow, con::MaxAsyncLoadWindow);
}
std::chrono::milliseconds AssetManager::getAsyncLoadWindow() const {
return asyncLoadWindow;
}
void AssetManager::loadSystemAssets() {
//
// std::vector<int> v;
// v.push_back(42);
// TODO FIXME
LOG_W("SYSTEM ASSETS NOT PRELOADED");
}
static inline Path MakeMetadataPathName(const Path& filePath, bool binary) {
Path result = filePath;
if (binary) {
result += con::MetadataExtension();
} else {
result += con::TextMetadataExtension();
}
return result;
}
static inline std::optional<StringHash> ValidateAndHashPath(const FileSystem* fs, const Path& path) {
if (path.empty()) {
LOG_W("Couldn't process the file because an empty path was provided.");
return std::nullopt;
}
if (!path.extension().empty()) {
LOG_W("Couldn't process \"{}\". A numeric filename without extension is required.", path);
return std::nullopt;
}
const std::string stem = path.stem().getGenericString();
const bool validName = isFileNameValid(stem);
if (!validName) {
LOG_W("Couldn't process \"{}\". It has a non-numeric name.", path);
return std::nullopt;
}
if (!fs->exists(path)) {
LOG_W("Couldn't process \"{}\". File does not exist.", path);
return std::nullopt;
}
const char* stemPtr = stem.c_str();
char* end;
const std::uint64_t parsedNumber = std::strtoull(stemPtr, &end, 10);
if (stemPtr == end) {
LOG_W("strtoull encountered an error when processing {}. Skipping it.", path);
}
if (errno == ERANGE) {
LOG_W("When parsed the filename {} does not fit in std::uint64_t. Skipping it.", path);
errno = 0;
return std::nullopt;
}
return StringHash(parsedNumber);
}
void AssetManager::requestAssetRefresh(AssetType type, const Path& path) {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
const VirtualFileSystem* fs = engine->getFileSystem();
auto validationResult = ValidateAndHashPath(fs, path);
if (!validationResult) {
return;
}
const StringHash nameHash = *validationResult;
const Path binaryMetadataPath = MakeMetadataPathName(path, true);
const Path textMetadataPath = MakeMetadataPathName(path, false);
// Don't move these file operations to any other thread. Editor APIs are kept synchronous on purpose
// to avoid race conditions.
bool binaryMetadataExists = fs->exists(binaryMetadataPath);
bool textMetadataExists = fs->exists(textMetadataPath);
if (!(binaryMetadataExists || textMetadataExists)) {
LOG_W("Couldn't add \"{}\" to the manifest. No metadata exists for it.", path);
return;
}
if (binaryMetadataExists && textMetadataExists) {
LOG_W("Couldn't add \"{}\" to the manifest. It has both text and binary metadata and it's impossible to know which one is valid.", path);
return;
}
AssetManager::ManifestElement me = buildManifestElement(type, textMetadataExists, textMetadataExists ? textMetadataPath : binaryMetadataPath, path);
//manifest[nameHash] = std::move(me);
auto manifestElement = manifest.insert_or_assign(nameHash, std::move(me));
if (manifestElement.second) {
LOG_V("Inserted a new element into the manifest");
} else {
LOG_V("Updated an existing element of the manifest");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
std::lock_guard<std::mutex> assetLock(loadedAssetListMutex);
const auto& loadedAsset = loadedAssets.find(nameHash);
if (loadedAsset != loadedAssets.end()) {
const AssetType type = loadedAsset->second.first;
const std::uint32_t id = loadedAsset->second.second;
const Metadata& metadata = manifestElement.first->second.metadata;
typeManagers[static_cast<std::size_t>(type)]->refresh(nameHash, path, metadata, id);
}
}
void AssetManager::requestAssetDeletion(const Path& path, [[maybe_unused]] bool isDir) {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
std::lock_guard<std::mutex> assetLock(loadedAssetListMutex);
const VirtualFileSystem* fs = engine->getFileSystem();
if (isDir) {
#ifndef NDEBUG
// TODO at least so far (on Linux) I get all file deletion events from inotify BEFORE I get the directory deletion
// event. Unfortunately, I have to store all events I receive in a map because I need to track if a file is still being
// modified by an external program. That is, for my purposes, a file's STATE is more important than the event order.
//
// Since using a map screws up the order, it is possible that a directory deletion event arrives BEFORE file deletion events,
// which renders the following check useless. However, since directories are NOT assets in my engine, this SHOULDN'T matter, for
// as long as all file deletion events arrive eventually.
//
// What I want you to do future me (or my helper) is to make sure the events ALWAYS arrive on all platforms.
// for (const auto& me : manifest) {
// Path src;
// bool inDir = std::visit([&path, &src](auto&& meta) {
// src = meta.getSourceAssetPath();
// return util::FileInDir(path, src);
// }, me.second.metadata);
//
// if (inDir) {
// LOG_V("File " << src << " not removed from the " << path << " directory before its deletion.");
// }
// }
#endif // NDEBUG
} else {
auto validationResult = ValidateAndHashPath(fs, path);
if (!validationResult) {
return;
}
const StringHash nameHash = *validationResult;
const auto& loadedAsset = loadedAssets.find(nameHash);
if (loadedAsset != loadedAssets.end()) {
LOG_W("The file ({}) that was removed had live references. If you don't find "
"and fix them, they will be replaced with missing assets next time you start the editor.", path);
}
// All metadata operations are synchronous in editor mode
const Path binaryMetadataPath = MakeMetadataPathName(path, true);
const Path textMetadataPath = MakeMetadataPathName(path, false);
bool binaryMetadataExists = fs->exists(binaryMetadataPath);
if (binaryMetadataExists) {
fs->remove(binaryMetadataPath);
}
bool textMetadataExists = fs->exists(textMetadataPath);
if (textMetadataExists) {
fs->remove(textMetadataPath);
}
fs->remove(path);
}
}
void AssetManager::requestAssetMove(const Path& sourcePath, const Path& destinationPath, [[maybe_unused]] bool isDir) {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
std::lock_guard<std::mutex> assetLock(loadedAssetListMutex);
LOG_D("Beginning asset data move for {}. Moving from {} to {}", (isDir ? "directory" : "file"), sourcePath, destinationPath);
// Can't change the key immediately. It would mess up the iteration order.
std::vector<std::pair<StringHash, StringHash>> fileMoves;
fileMoves.reserve(64);
for (auto& me : manifest) {
MetadataBase& meta = me.second.metadata.getBase();
assert(meta.getMetadataSource() == MetadataSource::JSON);
const Path currentSourceAssetPath = meta.getSourceAssetPath();
const bool inDir = util::FileInDir(sourcePath, currentSourceAssetPath);
const std::string currentSourceAssetPathString = currentSourceAssetPath.getGenericString();
const std::string sourceDirectoryString = sourcePath.getGenericString();
if (inDir) {
assert(currentSourceAssetPathString.compare(0, sourceDirectoryString.length(), sourceDirectoryString) == 0);
const VirtualFileSystem* fs = engine->getFileSystem();
const Path fullNewPath = destinationPath / Path(currentSourceAssetPathString.substr(sourceDirectoryString.length()));
const StringHash currentSourceHash = ComputeNameHash(currentSourceAssetPath);
const StringHash newPathHash = ComputeNameHash(fullNewPath);
assert(currentSourceHash == me.first);
Path postMoveAssetPath(me.second.path.parentPath());
postMoveAssetPath /= std::to_string(newPathHash.value());
if (checkForHashCollisionImpl(newPathHash, fullNewPath)) {
LOG_W("Couldn't move {} (a.k.a. {}) to {} (a.k.a.{}). A hash collision has occured. You'll need "
"to rename and re-import the file. Moreover, references to this file won't be updated.", currentSourceAssetPathString, me.second.path, fullNewPath, postMoveAssetPath);
continue;
}
if (!fs->exists(me.second.path)) {
LOG_W("Couldn't move {} (a.k.a. {}) to {} (a.k.a. {}. File does not exist.", currentSourceAssetPathString, me.second.path, fullNewPath, postMoveAssetPath);
continue;
}
// The paths in the virtual filesystem are used to retrieve and serialize metadata
const Path moveSourceVirtualFS = me.second.path;
Path moveDestinationVirtualFS = moveSourceVirtualFS.parentPath();
moveDestinationVirtualFS /= std::to_string(newPathHash.value());
// The paths in the real filesystem are used for actual file moves.
const Path fullMoveSource = fs->getRealDirectory(moveSourceVirtualFS);
assert(!fullMoveSource.empty());
Path fullMoveDestination = fullMoveSource.parentPath();
fullMoveDestination /= std::to_string(newPathHash.value());
fs->rename(fullMoveSource, fullMoveDestination);
// Retrieve metadata
const Path binaryMetadataPath = MakeMetadataPathName(moveSourceVirtualFS, true);
const Path textMetadataPath = MakeMetadataPathName(moveSourceVirtualFS, false);
// LOG_D(currentSourceAssetPathString << "\n\t" << fullNewPath.getGenericString() << "\n\t" <<
// me.second.path << "\n\t" << postMoveAssetPath << "\n\t" <<
// binaryMetadataPath << "\n\t" << textMetadataPath);
bool binaryMetadataExists = fs->exists(binaryMetadataPath);
if (binaryMetadataExists) {
FileSystemResult removalResult = fs->remove(binaryMetadataPath);
if (removalResult != FileSystemResult::Success) {
LOG_E("Failed to remove a binary metadata file: {}", binaryMetadataPath);
throw std::logic_error("Failed to remove a metadata file. Check log.");
}
}
bool textMetadataExists = fs->exists(textMetadataPath);
if (textMetadataExists) {
FileSystemResult removalResult = fs->remove(textMetadataPath);
if (removalResult != FileSystemResult::Success) {
LOG_E("Failed to remove a text metadata file: {}", textMetadataPath);
throw std::logic_error("Failed to remove a metadata file. Check log.");
}
}
// Update the paths stored in the metadata object
me.second.path = postMoveAssetPath;
meta.sourceAsset = fullNewPath;
// Save the updated metadata
if (textMetadataExists || (!textMetadataExists && !binaryMetadataExists)) {
const std::string jsonString = meta.getJSONString();
const Path newMetadataPath = MakeMetadataPathName(moveDestinationVirtualFS, false);
auto metadataOutput = VirtualFileSystem::Instance().openFile(newMetadataPath, FileOpenMode::Write);
metadataOutput->writeString(jsonString);
} else {
const Path newMetadataPath = MakeMetadataPathName(moveDestinationVirtualFS, true);
FileSerializer serializer(VirtualFileSystem::Instance(), newMetadataPath, FileOpenMode::Write);
meta.serialize(serializer);
}
auto loadedAsset = loadedAssets.find(currentSourceHash);
if (loadedAsset != loadedAssets.end()) {
std::uint32_t loadedAssetID = loadedAsset->second.second;
auto node = loadedAssets.extract(currentSourceHash);
assert(!node.empty());
node.key() = newPathHash;
loadedAssets.insert(std::move(node));
typeManagers[static_cast<std::size_t>(me.second.type)]->notifyMove(loadedAssetID, currentSourceHash, newPathHash);
}
fileMoves.emplace_back(std::make_pair(currentSourceHash, newPathHash));
}
}
for (const auto& fm : fileMoves) {
auto node = manifest.extract(fm.first);
assert(!node.empty());
node.key() = fm.second;
manifest.insert(std::move(node));
}
}
void AssetManager::appendAssetToManifest(StringHash nameHash, const Path& path, const Metadata& metadata) {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
manifest[nameHash] = {path, metadata.getAssetType(), false, metadata};
}
void AssetManager::removeAssetFromManifest(StringHash nameHash) {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
std::lock_guard<std::mutex> assetLock(loadedAssetListMutex);
std::size_t elementsRemoved = manifest.erase(nameHash);
const auto& loadedAsset = loadedAssets.find(nameHash);
if (elementsRemoved > 0 && loadedAsset != loadedAssets.end()) {
// TODO implement
throw std::runtime_error("Removal of hot assets not yet implemented");
}
}
void AssetManager::removeNonSystemAssetsFromManifest() {
if (!editorMode) {
throw std::logic_error("This method can't be used when the engine is running in game mode.");
}
std::lock_guard<std::mutex> manifestLock(manifestMutex);
std::lock_guard<std::mutex> assetLock(loadedAssetListMutex);
// C++14 allows to erase individual elements when iterating through the container:
// http://en.cppreference.com/w/cpp/container/unordered_map/erase
for (auto it = manifest.begin(); it != manifest.end(); ) {
const auto& loadedAsset = loadedAssets.find(it->first);
if (it->second.systemAsset) {
++it;
} else {
if (loadedAsset != loadedAssets.end()) {
// TODO implement
throw std::runtime_error("Removal of hot assets not yet implemented");
}
it = manifest.erase(it);
}
}
}
std::optional<Path> AssetManager::checkForHashCollision(StringHash nameHash, const Path& checkPath) const {
if (!editorMode) {
throw std::logic_error("This method can only be used when the engine is running in editor mode.");
}
std::unique_lock<std::mutex> lock(manifestMutex);
return checkForHashCollisionImpl(nameHash, checkPath);
}
std::optional<Path> AssetManager::checkForHashCollisionImpl(StringHash nameHash, const Path& checkPath) const {
auto result = manifest.find(nameHash);
if (result != manifest.end()) {
const Path foundPath = result->second.metadata.getBase().getSourceAssetPath();
if (foundPath != checkPath) {
return foundPath;
}
}
return std::nullopt;
}
}
|
/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbWrapperApplicationFactory.h"
#include "otbWrapperCompositeApplication.h"
namespace otb
{
namespace Wrapper
{
class BundleToPerfectSensor : public CompositeApplication
{
public:
/** Standard class typedefs. */
typedef BundleToPerfectSensor Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(BundleToPerfectSensor, otb::Wrapper::CompositeApplication);
private:
void DoInit() override
{
SetName("BundleToPerfectSensor");
SetDescription("Perform P+XS pansharpening");
// Documentation
SetDocLongDescription("This application performs P+XS pansharpening. The default mode use Pan and XS sensor models to estimate the transformation to superimpose XS over Pan before the fusion (\"default mode\"). The application provides also a PHR mode for Pleiades images which does not use sensor models as Pan and XS products are already coregistered but only estimate an affine transformation to superimpose XS over the Pan.Note that this option is automatically activated in case Pleiades images are detected as input.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Geometry);
AddDocTag(Tags::Pansharpening);
ClearApplications();
AddApplication("Superimpose", "superimpose", "Reproject XS onto Pan");
AddApplication("Pansharpening", "pansharp", "Fusion of XS and Pan");
ShareParameter("inp","superimpose.inr","Input PAN Image","Input panchromatic image.");
ShareParameter("inxs","superimpose.inm","Input XS Image","Input XS image.");
ShareParameter("out","pansharp.out");
ShareParameter("elev","superimpose.elev");
ShareParameter("mode","superimpose.mode");
ShareParameter("method","pansharp.method");
ShareParameter("lms","superimpose.lms",
"Spacing of the deformation field",
"Spacing of the deformation field. Default is 10 times the PAN image spacing.");
ShareParameter("interpolator","superimpose.interpolator");
ShareParameter("fv","superimpose.fv");
ShareParameter("ram","superimpose.ram");
Connect("pansharp.inp","superimpose.inr");
Connect("pansharp.ram","superimpose.ram");
// Doc example parameter settings
SetDocExampleParameterValue("inp", "QB_Toulouse_Ortho_PAN.tif");
SetDocExampleParameterValue("inxs", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "BundleToPerfectSensor.png uchar");
SetOfficialDocLink();
}
void DoUpdateParameters() override
{
UpdateInternalParameters("superimpose");
}
void DoExecute() override
{
ExecuteInternal("superimpose");
GetInternalApplication("pansharp")->SetParameterInputImage("inxs",
GetInternalApplication("superimpose")->GetParameterOutputImage("out"));
ExecuteInternal("pansharp");
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::BundleToPerfectSensor)
|
/**
* \file TransverseMercatorExact.cpp
* \brief Implementation for geographic_lib::TransverseMercatorExact class
*
* Copyright (c) Charles Karney (2008-2017) <charles@karney.com> and licensed
* under the MIT/X11 License. For more information, see
* https://geographiclib.sourceforge.io/
*
* The relevant section of Lee's paper is part V, pp 67--101,
* <a href="https://doi.org/10.3138/X687-1574-4325-WM62">Conformal
* Projections Based On Jacobian Elliptic Functions</a>.
*
* The method entails using the Thompson Transverse Mercator as an
* intermediate projection. The projections from the intermediate
* coordinates to [\e phi, \e lam] and [\e x, \e y] are given by elliptic
* functions. The inverse of these projections are found by Newton's method
* with a suitable starting guess.
*
* This implementation and notation closely follows Lee, with the following
* exceptions:
* <center><table>
* <tr><th>Lee <th>here <th>Description
* <tr><td>x/a <td>xi <td>Northing (unit Earth)
* <tr><td>y/a <td>eta <td>Easting (unit Earth)
* <tr><td>s/a <td>sigma <td>xi + i * eta
* <tr><td>y <td>x <td>Easting
* <tr><td>x <td>y <td>Northing
* <tr><td>k <td>e <td>eccentricity
* <tr><td>k^2 <td>mu <td>elliptic function parameter
* <tr><td>k'^2 <td>mv <td>elliptic function complementary parameter
* <tr><td>m <td>k <td>scale
* <tr><td>zeta <td>zeta <td>complex longitude = Mercator = chi in paper
* <tr><td>s <td>sigma <td>complex GK = zeta in paper
* </table></center>
*
* Minor alterations have been made in some of Lee's expressions in an
* attempt to control round-off. For example atanh(sin(phi)) is replaced by
* asinh(tan(phi)) which maintains accuracy near phi = pi/2. Such changes
* are noted in the code.
**********************************************************************/
#include <geographic_lib/TransverseMercatorExact.hpp>
#if defined(_MSC_VER)
// Squelch warnings about constant conditional expressions
# pragma warning (disable: 4127)
#endif
namespace geographic_lib {
using namespace std;
TransverseMercatorExact::TransverseMercatorExact(real a, real f, real k0,
bool extendp)
: tol_(numeric_limits<real>::epsilon())
, tol2_(real(0.1) * tol_)
, taytol_(pow(tol_, real(0.6)))
, _a(a)
, _f(f)
, _k0(k0)
, _mu(_f * (2 - _f)) // e^2
, _mv(1 - _mu) // 1 - e^2
, _e(sqrt(_mu))
, _extendp(extendp)
, _Eu(_mu)
, _Ev(_mv)
{
if (!(Math::isfinite(_a) && _a > 0))
throw GeographicErr("Equatorial radius is not positive");
if (!(_f > 0))
throw GeographicErr("Flattening is not positive");
if (!(_f < 1))
throw GeographicErr("Polar semi-axis is not positive");
if (!(Math::isfinite(_k0) && _k0 > 0))
throw GeographicErr("Scale is not positive");
}
const TransverseMercatorExact& TransverseMercatorExact::UTM() {
static const TransverseMercatorExact utm(Constants::WGS84_a(),
Constants::WGS84_f(),
Constants::UTM_k0());
return utm;
}
void TransverseMercatorExact::zeta(real /*u*/, real snu, real cnu, real dnu,
real /*v*/, real snv, real cnv, real dnv,
real& taup, real& lam) const {
// Lee 54.17 but write
// atanh(snu * dnv) = asinh(snu * dnv / sqrt(cnu^2 + _mv * snu^2 * snv^2))
// atanh(_e * snu / dnv) =
// asinh(_e * snu / sqrt(_mu * cnu^2 + _mv * cnv^2))
// Overflow value s.t. atan(overflow) = pi/2
static const real
overflow = 1 / Math::sq(std::numeric_limits<real>::epsilon());
real
d1 = sqrt(Math::sq(cnu) + _mv * Math::sq(snu * snv)),
d2 = sqrt(_mu * Math::sq(cnu) + _mv * Math::sq(cnv)),
t1 = (d1 != 0 ? snu * dnv / d1 : (snu < 0 ? -overflow : overflow)),
t2 = (d2 != 0 ? sinh( _e * Math::asinh(_e * snu / d2) ) :
(snu < 0 ? -overflow : overflow));
// psi = asinh(t1) - asinh(t2)
// taup = sinh(psi)
taup = t1 * Math::hypot(real(1), t2) - t2 * Math::hypot(real(1), t1);
lam = (d1 != 0 && d2 != 0) ?
atan2(dnu * snv, cnu * cnv) - _e * atan2(_e * cnu * snv, dnu * cnv) :
0;
}
void TransverseMercatorExact::dwdzeta(real /*u*/,
real snu, real cnu, real dnu,
real /*v*/,
real snv, real cnv, real dnv,
real& du, real& dv) const {
// Lee 54.21 but write (1 - dnu^2 * snv^2) = (cnv^2 + _mu * snu^2 * snv^2)
// (see A+S 16.21.4)
real d = _mv * Math::sq(Math::sq(cnv) + _mu * Math::sq(snu * snv));
du = cnu * dnu * dnv * (Math::sq(cnv) - _mu * Math::sq(snu * snv)) / d;
dv = -snu * snv * cnv * (Math::sq(dnu * dnv) + _mu * Math::sq(cnu)) / d;
}
// Starting point for zetainv
bool TransverseMercatorExact::zetainv0(real psi, real lam,
real& u, real& v) const {
bool retval = false;
if (psi < -_e * Math::pi()/4 &&
lam > (1 - 2 * _e) * Math::pi()/2 &&
psi < lam - (1 - _e) * Math::pi()/2) {
// N.B. this branch is normally not taken because psi < 0 is converted
// psi > 0 by Forward.
//
// There's a log singularity at w = w0 = Eu.K() + i * Ev.K(),
// corresponding to the south pole, where we have, approximately
//
// psi = _e + i * pi/2 - _e * atanh(cos(i * (w - w0)/(1 + _mu/2)))
//
// Inverting this gives:
real
psix = 1 - psi / _e,
lamx = (Math::pi()/2 - lam) / _e;
u = Math::asinh(sin(lamx) / Math::hypot(cos(lamx), sinh(psix))) *
(1 + _mu/2);
v = atan2(cos(lamx), sinh(psix)) * (1 + _mu/2);
u = _Eu.K() - u;
v = _Ev.K() - v;
} else if (psi < _e * Math::pi()/2 &&
lam > (1 - 2 * _e) * Math::pi()/2) {
// At w = w0 = i * Ev.K(), we have
//
// zeta = zeta0 = i * (1 - _e) * pi/2
// zeta' = zeta'' = 0
//
// including the next term in the Taylor series gives:
//
// zeta = zeta0 - (_mv * _e) / 3 * (w - w0)^3
//
// When inverting this, we map arg(w - w0) = [-90, 0] to
// arg(zeta - zeta0) = [-90, 180]
real
dlam = lam - (1 - _e) * Math::pi()/2,
rad = Math::hypot(psi, dlam),
// atan2(dlam-psi, psi+dlam) + 45d gives arg(zeta - zeta0) in range
// [-135, 225). Subtracting 180 (since multiplier is negative) makes
// range [-315, 45). Multiplying by 1/3 (for cube root) gives range
// [-105, 15). In particular the range [-90, 180] in zeta space maps
// to [-90, 0] in w space as required.
ang = atan2(dlam-psi, psi+dlam) - real(0.75) * Math::pi();
// Error using this guess is about 0.21 * (rad/e)^(5/3)
retval = rad < _e * taytol_;
rad = Math::cbrt(3 / (_mv * _e) * rad);
ang /= 3;
u = rad * cos(ang);
v = rad * sin(ang) + _Ev.K();
} else {
// Use spherical TM, Lee 12.6 -- writing atanh(sin(lam) / cosh(psi)) =
// asinh(sin(lam) / hypot(cos(lam), sinh(psi))). This takes care of the
// log singularity at zeta = Eu.K() (corresponding to the north pole)
v = Math::asinh(sin(lam) / Math::hypot(cos(lam), sinh(psi)));
u = atan2(sinh(psi), cos(lam));
// But scale to put 90,0 on the right place
u *= _Eu.K() / (Math::pi()/2);
v *= _Eu.K() / (Math::pi()/2);
}
return retval;
}
// Invert zeta using Newton's method
void TransverseMercatorExact::zetainv(real taup, real lam,
real& u, real& v) const {
real
psi = Math::asinh(taup),
scal = 1/Math::hypot(real(1), taup);
if (zetainv0(psi, lam, u, v))
return;
real stol2 = tol2_ / Math::sq(max(psi, real(1)));
// min iterations = 2, max iterations = 6; mean = 4.0
for (int i = 0, trip = 0; i < numit_ || GEOGRAPHICLIB_PANIC; ++i) {
real snu, cnu, dnu, snv, cnv, dnv;
_Eu.sncndn(u, snu, cnu, dnu);
_Ev.sncndn(v, snv, cnv, dnv);
real tau1, lam1, du1, dv1;
zeta(u, snu, cnu, dnu, v, snv, cnv, dnv, tau1, lam1);
dwdzeta(u, snu, cnu, dnu, v, snv, cnv, dnv, du1, dv1);
tau1 -= taup;
lam1 -= lam;
tau1 *= scal;
real
delu = tau1 * du1 - lam1 * dv1,
delv = tau1 * dv1 + lam1 * du1;
u -= delu;
v -= delv;
if (trip)
break;
real delw2 = Math::sq(delu) + Math::sq(delv);
if (!(delw2 >= stol2))
++trip;
}
}
void TransverseMercatorExact::sigma(real /*u*/, real snu, real cnu, real dnu,
real v, real snv, real cnv, real dnv,
real& xi, real& eta) const {
// Lee 55.4 writing
// dnu^2 + dnv^2 - 1 = _mu * cnu^2 + _mv * cnv^2
real d = _mu * Math::sq(cnu) + _mv * Math::sq(cnv);
xi = _Eu.E(snu, cnu, dnu) - _mu * snu * cnu * dnu / d;
eta = v - _Ev.E(snv, cnv, dnv) + _mv * snv * cnv * dnv / d;
}
void TransverseMercatorExact::dwdsigma(real /*u*/,
real snu, real cnu, real dnu,
real /*v*/,
real snv, real cnv, real dnv,
real& du, real& dv) const {
// Reciprocal of 55.9: dw/ds = dn(w)^2/_mv, expanding complex dn(w) using
// A+S 16.21.4
real d = _mv * Math::sq(Math::sq(cnv) + _mu * Math::sq(snu * snv));
real
dnr = dnu * cnv * dnv,
dni = - _mu * snu * cnu * snv;
du = (Math::sq(dnr) - Math::sq(dni)) / d;
dv = 2 * dnr * dni / d;
}
// Starting point for sigmainv
bool TransverseMercatorExact::sigmainv0(real xi, real eta,
real& u, real& v) const {
bool retval = false;
if (eta > real(1.25) * _Ev.KE() ||
(xi < -real(0.25) * _Eu.E() && xi < eta - _Ev.KE())) {
// sigma as a simple pole at w = w0 = Eu.K() + i * Ev.K() and sigma is
// approximated by
//
// sigma = (Eu.E() + i * Ev.KE()) + 1/(w - w0)
real
x = xi - _Eu.E(),
y = eta - _Ev.KE(),
r2 = Math::sq(x) + Math::sq(y);
u = _Eu.K() + x/r2;
v = _Ev.K() - y/r2;
} else if ((eta > real(0.75) * _Ev.KE() && xi < real(0.25) * _Eu.E())
|| eta > _Ev.KE()) {
// At w = w0 = i * Ev.K(), we have
//
// sigma = sigma0 = i * Ev.KE()
// sigma' = sigma'' = 0
//
// including the next term in the Taylor series gives:
//
// sigma = sigma0 - _mv / 3 * (w - w0)^3
//
// When inverting this, we map arg(w - w0) = [-pi/2, -pi/6] to
// arg(sigma - sigma0) = [-pi/2, pi/2]
// mapping arg = [-pi/2, -pi/6] to [-pi/2, pi/2]
real
deta = eta - _Ev.KE(),
rad = Math::hypot(xi, deta),
// Map the range [-90, 180] in sigma space to [-90, 0] in w space. See
// discussion in zetainv0 on the cut for ang.
ang = atan2(deta-xi, xi+deta) - real(0.75) * Math::pi();
// Error using this guess is about 0.068 * rad^(5/3)
retval = rad < 2 * taytol_;
rad = Math::cbrt(3 / _mv * rad);
ang /= 3;
u = rad * cos(ang);
v = rad * sin(ang) + _Ev.K();
} else {
// Else use w = sigma * Eu.K/Eu.E (which is correct in the limit _e -> 0)
u = xi * _Eu.K()/_Eu.E();
v = eta * _Eu.K()/_Eu.E();
}
return retval;
}
// Invert sigma using Newton's method
void TransverseMercatorExact::sigmainv(real xi, real eta,
real& u, real& v) const {
if (sigmainv0(xi, eta, u, v))
return;
// min iterations = 2, max iterations = 7; mean = 3.9
for (int i = 0, trip = 0; i < numit_ || GEOGRAPHICLIB_PANIC; ++i) {
real snu, cnu, dnu, snv, cnv, dnv;
_Eu.sncndn(u, snu, cnu, dnu);
_Ev.sncndn(v, snv, cnv, dnv);
real xi1, eta1, du1, dv1;
sigma(u, snu, cnu, dnu, v, snv, cnv, dnv, xi1, eta1);
dwdsigma(u, snu, cnu, dnu, v, snv, cnv, dnv, du1, dv1);
xi1 -= xi;
eta1 -= eta;
real
delu = xi1 * du1 - eta1 * dv1,
delv = xi1 * dv1 + eta1 * du1;
u -= delu;
v -= delv;
if (trip)
break;
real delw2 = Math::sq(delu) + Math::sq(delv);
if (!(delw2 >= tol2_))
++trip;
}
}
void TransverseMercatorExact::Scale(real tau, real /*lam*/,
real snu, real cnu, real dnu,
real snv, real cnv, real dnv,
real& gamma, real& k) const {
real sec2 = 1 + Math::sq(tau); // sec(phi)^2
// Lee 55.12 -- negated for our sign convention. gamma gives the bearing
// (clockwise from true north) of grid north
gamma = atan2(_mv * snu * snv * cnv, cnu * dnu * dnv);
// Lee 55.13 with nu given by Lee 9.1 -- in sqrt change the numerator
// from
//
// (1 - snu^2 * dnv^2) to (_mv * snv^2 + cnu^2 * dnv^2)
//
// to maintain accuracy near phi = 90 and change the denomintor from
//
// (dnu^2 + dnv^2 - 1) to (_mu * cnu^2 + _mv * cnv^2)
//
// to maintain accuracy near phi = 0, lam = 90 * (1 - e). Similarly
// rewrite sqrt term in 9.1 as
//
// _mv + _mu * c^2 instead of 1 - _mu * sin(phi)^2
k = sqrt(_mv + _mu / sec2) * sqrt(sec2) *
sqrt( (_mv * Math::sq(snv) + Math::sq(cnu * dnv)) /
(_mu * Math::sq(cnu) + _mv * Math::sq(cnv)) );
}
void TransverseMercatorExact::Forward(real lon0, real lat, real lon,
real& x, real& y,
real& gamma, real& k) const {
lat = Math::LatFix(lat);
lon = Math::AngDiff(lon0, lon);
// Explicitly enforce the parity
int
latsign = (!_extendp && lat < 0) ? -1 : 1,
lonsign = (!_extendp && lon < 0) ? -1 : 1;
lon *= lonsign;
lat *= latsign;
bool backside = !_extendp && lon > 90;
if (backside) {
if (lat == 0)
latsign = -1;
lon = 180 - lon;
}
real
lam = lon * Math::degree(),
tau = Math::tand(lat);
// u,v = coordinates for the Thompson TM, Lee 54
real u, v;
if (lat == 90) {
u = _Eu.K();
v = 0;
} else if (lat == 0 && lon == 90 * (1 - _e)) {
u = 0;
v = _Ev.K();
} else
// tau = tan(phi), taup = sinh(psi)
zetainv(Math::taupf(tau, _e), lam, u, v);
real snu, cnu, dnu, snv, cnv, dnv;
_Eu.sncndn(u, snu, cnu, dnu);
_Ev.sncndn(v, snv, cnv, dnv);
real xi, eta;
sigma(u, snu, cnu, dnu, v, snv, cnv, dnv, xi, eta);
if (backside)
xi = 2 * _Eu.E() - xi;
y = xi * _a * _k0 * latsign;
x = eta * _a * _k0 * lonsign;
if (lat == 90) {
gamma = lon;
k = 1;
} else {
// Recompute (tau, lam) from (u, v) to improve accuracy of Scale
zeta(u, snu, cnu, dnu, v, snv, cnv, dnv, tau, lam);
tau = Math::tauf(tau, _e);
Scale(tau, lam, snu, cnu, dnu, snv, cnv, dnv, gamma, k);
gamma /= Math::degree();
}
if (backside)
gamma = 180 - gamma;
gamma *= latsign * lonsign;
k *= _k0;
}
void TransverseMercatorExact::Reverse(real lon0, real x, real y,
real& lat, real& lon,
real& gamma, real& k) const {
// This undoes the steps in Forward.
real
xi = y / (_a * _k0),
eta = x / (_a * _k0);
// Explicitly enforce the parity
int
latsign = !_extendp && y < 0 ? -1 : 1,
lonsign = !_extendp && x < 0 ? -1 : 1;
xi *= latsign;
eta *= lonsign;
bool backside = !_extendp && xi > _Eu.E();
if (backside)
xi = 2 * _Eu.E()- xi;
// u,v = coordinates for the Thompson TM, Lee 54
real u, v;
if (xi == 0 && eta == _Ev.KE()) {
u = 0;
v = _Ev.K();
} else
sigmainv(xi, eta, u, v);
real snu, cnu, dnu, snv, cnv, dnv;
_Eu.sncndn(u, snu, cnu, dnu);
_Ev.sncndn(v, snv, cnv, dnv);
real phi, lam, tau;
if (v != 0 || u != _Eu.K()) {
zeta(u, snu, cnu, dnu, v, snv, cnv, dnv, tau, lam);
tau = Math::tauf(tau, _e);
phi = atan(tau);
lat = phi / Math::degree();
lon = lam / Math::degree();
Scale(tau, lam, snu, cnu, dnu, snv, cnv, dnv, gamma, k);
gamma /= Math::degree();
} else {
lat = 90;
lon = lam = gamma = 0;
k = 1;
}
if (backside)
lon = 180 - lon;
lon *= lonsign;
lon = Math::AngNormalize(lon + Math::AngNormalize(lon0));
lat *= latsign;
if (backside)
gamma = 180 - gamma;
gamma *= latsign * lonsign;
k *= _k0;
}
} // namespace geographic_lib
|
COMMENT @----------------------------------------------------------------------
Copyright (c) GeoWorks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Hello (Sample PC GEOS application)
FILE: hello.asm
REVISION HISTORY:
Name Date Description
---- ---- -----------
Eric 11/90 Initial version
Eric 3/91 Simplified by removing text color changes.
DESCRIPTION:
This file source code for the Hello application. This code will
be assembled by ESP, and then linked by the GLUE linker to produce
a runnable .geo application file.
RCS STAMP:
$Id: hello2.asm,v 1.1 97/04/04 16:33:31 newdeal Exp $
------------------------------------------------------------------------------@
;------------------------------------------------------------------------------
; Include files
;------------------------------------------------------------------------------
include geos.def
include heap.def
include geode.def
include resource.def
include ec.def
include object.def
include graphics.def
include Objects/winC.def
;------------------------------------------------------------------------------
; Libraries used
;------------------------------------------------------------------------------
UseLib ui.def
UseLib Objects/vTextC.def
;------------------------------------------------------------------------------
; Class & Method Definitions
;------------------------------------------------------------------------------
;Here we define "HelloProcessClass" as a subclass of the system provided
;"GenProcessClass". As this application is launched, an instance of this class
;will be created, and will handle all application-related events (messages).
;The application thread will be responsible for running this object,
;meaning that whenever this object handles a method, we will be executing
;in the application thread.
HelloProcessClass class GenProcessClass
;define messages for this class here.
MSG_DRAW_NEW_TEXT message
HelloProcessClass endc ;end of class definition
;This class definition must be stored in memory at runtime, so that
;the PC/GEOS messaging system can examine it. We will place it in this
;application's idata (initialized data) area, which is part of
;the "DGroup" resource.
idata segment
HelloProcessClass mask CLASSF_NEVER_SAVED
;this flag necessary because ProcessClass
;objects are hybrid objects.
winHandle hptr.Window 0
textToDraw byte "Text to start with",0
idata ends
;------------------------------------------------------------------------------
; Resources
;------------------------------------------------------------------------------
;The "hello.ui" file, which contains user-interface descriptions for this
;application, is written in a language called Espire. That file gets compiled
;by UIC, and the resulting assembly statements are written into the
;hello2.rdef file. We include that file here, so that these descriptions
;can be assembled into our application.
;
;Precisely, we are assembling .byte and .word statements which comprise the
;exact instance data for each generic object in the .ui file. When this
;application is launched, these resources (such as MenuResource) will be loaded
;into the Global Heap. The objects in the resource can very quickly become
;usable, as they are pre-instantiated.
include hello2.rdef ;include compiled UI definitions
;------------------------------------------------------------------------------
; Code for HelloProcessClass
;------------------------------------------------------------------------------
CommonCode segment resource ;start of code resource
COMMENT @----------------------------------------------------------------------
FUNCTION: MSG_META_EXPOSED handler.
DESCRIPTION: This method is sent by the Windowing System when we must
redraw a portion of the document in the View area.
PASS: ds = dgroup
cx = handle of window which we must draw to.
RETURN: ds = same
CAN DESTROY: bx, si, di, ds, es
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Eric 11/90 initial version
------------------------------------------------------------------------------@
HelloExposed method HelloProcessClass, MSG_META_EXPOSED
mov ds:[winHandle], cx ; save handle for later
mov di, cx ;set ^hdi = window handle
call GrCreateState ;Get a default graphics state that we
;can use while drawing.
;first, start a window update. This tells the windowing system that
;we are in the process of drawing to this window.
call GrBeginUpdate
;if we had background graphics to draw, we would call the
;apropriate graphics routines now.
;draw the text into the window (pass ^hdi = GState)
call HelloDrawText
;now free the GState, and indicate that we are done drawing to the
;window.
call GrEndUpdate
call GrDestroyState
ret
HelloExposed endm
COMMENT @----------------------------------------------------------------------
FUNCTION: HelloDrawText
DESCRIPTION: This procedure will draw a simple line of text onto the
document.
CALLED BY: HelloExposed
PASS: ds = dgroup
di = handle of GState to draw with (the GState structure
contains the handle of the window to draw into.)
RETURN: ds, di = same
DESTROYED: ?
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Eric 11/90 initial version
------------------------------------------------------------------------------@
;These constants are used in the code below:
TEXT_POINT_SIZE equ 48 ;point size
TEXT_ROTATION equ 360-15 ;angle of rotation, in degrees
TEXT_X_POSITION equ 30 ;x position, in document coords.
TEXT_Y_POSITION equ 0 ;y position, in document coords.
HelloDrawText proc near
; White out the background first
mov ah, CF_INDEX
mov al, C_WHITE
call GrSetAreaColor
clr ax
clr bx
mov cx,500
mov dx,500
call GrFillRect
;first change some of the default GState values, such as font
mov cx, FID_DTC_URW_ROMAN ;font (URW Roman)
mov dx, TEXT_POINT_SIZE ;point size (integer)
clr ah ;point size (fraction) = 0
call GrSetFont ;change the GState
;set the text color according to our textColor variable
mov ah, CF_INDEX ;indicate we are using a pre-defined
;color, not an RGB value.
mov al, C_LIGHT_BLUE ;set text color value
call GrSetTextColor ;set text color in GState
;apply a rotation to the transformation matrix, so the text
;will be drawn at an angle.
mov dx, TEXT_ROTATION ;set rotation (integer) for text
clr cx ;zero fractional degrees.
call GrApplyRotation
;draw some text onto the document
mov ax, TEXT_X_POSITION ;set (ax, bx) = top-left document
mov bx, TEXT_Y_POSITION ; coordinate for text.
mov si, offset textToDraw
clr cx ;indicate is null-terminated string
call GrDrawText ;draw text into window
ret
HelloDrawText endp
COMMENT @----------------------------------------------------------------------
FUNCTION: HelloDrawNewText
DESCRIPTION: This procedure will draw a simple line of text onto the
document.
CALLED BY: MSG_DRAW_NEW_TEXT (when user selects button)
PASS: ds = dgroup
di = handle of GState to draw with (the GState structure
contains the handle of the window to draw into.)
RETURN: ds, di = same
DESTROYED: ?
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Eric 11/90 initial version
------------------------------------------------------------------------------@
HelloDrawNewText method HelloProcessClass, MSG_DRAW_NEW_TEXT
; Start by reading in the text from the TextEdit object
;
GetResourceHandleNS BoxResource,bx
mov si, offset EnterText
mov ax, MSG_VIS_TEXT_GET_ALL_PTR
mov dx, ds ; copy into our buffer
mov bp, offset textToDraw
mov di, mask MF_CALL
call ObjMessage
mov di, ds:[winHandle] ; create a GState to draw with
call GrCreateState
call HelloDrawText ; draw the new text
call GrDestroyState ;
ret
HelloDrawNewText endm
CommonCode ends ;end of CommonCode resource
|
#include <ros.h>
#include <std_msgs/String.h>
#include <motor_control/motor_Values.h>
#include <sensor_msgs/BatteryState.h>
#include <std_msgs/Bool.h>
#include <Arduino.h>
#include <Servo.h>
#define LIMITER 250
#define ESC_MAX_F_VALUE 2000-LIMITER
#define ESC_MIN_F_VALUE 1528 //1528
#define ESC_MAX_R_VALUE 1000+LIMITER
#define ESC_MIN_R_VALUE 1480 //1478
//hall effect connected to A0
bool flag = true;
bool motor_enabled = true;
ros::NodeHandle nh;
motor_control::motor_Values motor_values_msg;
std_msgs::Bool bool_msg;
ros::Publisher motor_enabler("motor_enabled", &bool_msg);
Servo svfl;
Servo svfr;
Servo svbl;
Servo svbr;
Servo shfl;
Servo shfr;
Servo shbl;
Servo shbr;
int motor_map(int value) {
value = value * -1;
if (value > 0) {
return map(value, 0, 100, ESC_MIN_F_VALUE, ESC_MAX_F_VALUE);
}
else if (value < 0) {
return map(value, 0, -100, ESC_MIN_R_VALUE, ESC_MAX_R_VALUE);
}
else {
return 1500;
}
}
void motor_Cb(const motor_control::motor_Values& data) {
if (motor_enabled == true) {
svfl.writeMicroseconds(motor_map(data.vlf));
svfr.writeMicroseconds(motor_map(data.vrf));
svbl.writeMicroseconds(motor_map(data.vlb));
svbr.writeMicroseconds(motor_map(data.vrb));
shfl.writeMicroseconds(motor_map(data.hlf));
shfr.writeMicroseconds(motor_map(data.hrf));
shbl.writeMicroseconds(motor_map(data.hlb));
shbr.writeMicroseconds(motor_map(data.hrb));
}
else {
svfl.writeMicroseconds(1500);
svfr.writeMicroseconds(1500);
svbl.writeMicroseconds(1500);
svbr.writeMicroseconds(1500);
shfl.writeMicroseconds(1500);
shfr.writeMicroseconds(1500);
shbl.writeMicroseconds(1500);
shbr.writeMicroseconds(1500);
}
}
ros::Subscriber<motor_control::motor_Values> sub("/thruster_values", &motor_Cb );
void setup() {
nh.initNode();
nh.subscribe(sub);
nh.advertise(motor_enabler);
svfl.attach(6);
svfr.attach(4);
svbl.attach(8);
svbr.attach(3);
shfl.attach(7);
shfr.attach(5);
shbl.attach(9);
shbr.attach(2);
svfl.writeMicroseconds(1500);
svfr.writeMicroseconds(1500);
svbl.writeMicroseconds(1500);
svbr.writeMicroseconds(1500);
shfl.writeMicroseconds(1500);
shfr.writeMicroseconds(1500);
shbl.writeMicroseconds(1500);
shbr.writeMicroseconds(1500);
delay(100);
}
void loop()
{
int detectValue = abs(analogRead(A0)-515);
if (detectValue > 50) {
if (flag == false) {
motor_enabled = true;
bool_msg.data = motor_enabled;
motor_enabler.publish(&bool_msg);
flag = true;
}
}
else {
if (flag == true) {
motor_enabled = false;
svfl.writeMicroseconds(1500);
svfr.writeMicroseconds(1500);
svbl.writeMicroseconds(1500);
svbr.writeMicroseconds(1500);
shfl.writeMicroseconds(1500);
shfr.writeMicroseconds(1500);
shbl.writeMicroseconds(1500);
shbr.writeMicroseconds(1500);
bool_msg.data = motor_enabled;
motor_enabler.publish(&bool_msg);
flag = false;
}
}
nh.spinOnce();
delay(1);
}
|
SECTION code_clib
PUBLIC w_plotpixel
defc NEEDplot = 1
.w_plotpixel
INCLUDE "w_pixel.inc"
|
map_header MtMoon1F, MT_MOON_1F, CAVERN, 0
end_map_header
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r9
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x4219, %rsi
lea addresses_normal_ht+0xf419, %rdi
nop
cmp %r12, %r12
mov $118, %rcx
rep movsb
nop
nop
nop
inc %r11
lea addresses_normal_ht+0xf59f, %rax
nop
nop
nop
nop
nop
sub $6436, %r9
mov $0x6162636465666768, %r11
movq %r11, %xmm4
and $0xffffffffffffffc0, %rax
vmovntdq %ymm4, (%rax)
nop
nop
nop
nop
nop
and $8389, %rcx
lea addresses_WC_ht+0x1d7bb, %rcx
nop
xor $63822, %r9
movl $0x61626364, (%rcx)
nop
nop
nop
nop
inc %rax
lea addresses_A_ht+0x13a81, %rdi
nop
xor %r9, %r9
mov $0x6162636465666768, %rax
movq %rax, %xmm4
and $0xffffffffffffffc0, %rdi
movntdq %xmm4, (%rdi)
nop
nop
nop
add $45186, %rcx
lea addresses_A_ht+0xab19, %rax
nop
sub $49491, %rdi
vmovups (%rax), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $0, %xmm1, %r12
nop
nop
nop
nop
nop
xor %r9, %r9
lea addresses_normal_ht+0x4181, %rsi
lea addresses_WT_ht+0xd259, %rdi
nop
nop
nop
cmp %rbp, %rbp
mov $113, %rcx
rep movsw
nop
nop
nop
nop
xor $52256, %rax
lea addresses_UC_ht+0x3af9, %rsi
lea addresses_D_ht+0x11619, %rdi
nop
nop
nop
nop
nop
dec %r11
mov $67, %rcx
rep movsq
nop
cmp %r12, %r12
lea addresses_UC_ht+0xd619, %rsi
lea addresses_WC_ht+0x15819, %rdi
clflush (%rdi)
nop
nop
and $54399, %rbp
mov $100, %rcx
rep movsw
nop
nop
nop
nop
nop
sub $45997, %rdi
lea addresses_D_ht+0x9e29, %rsi
lea addresses_normal_ht+0xf619, %rdi
xor %r9, %r9
mov $126, %rcx
rep movsw
nop
xor %rdi, %rdi
lea addresses_D_ht+0xd41f, %rsi
lea addresses_D_ht+0xe419, %rdi
cmp %rbp, %rbp
mov $89, %rcx
rep movsw
nop
nop
nop
nop
cmp %r11, %r11
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r9
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r15
push %r8
push %rdi
push %rdx
push %rsi
// Faulty Load
lea addresses_RW+0xb619, %rdx
sub $3077, %rdi
movups (%rdx), %xmm6
vpextrq $1, %xmm6, %r14
lea oracles, %rdx
and $0xff, %r14
shlq $12, %r14
mov (%rdx,%r14,1), %r14
pop %rsi
pop %rdx
pop %rdi
pop %r8
pop %r15
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 1, 'size': 32, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 16, 'same': False, 'NT': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
module SYSTEM
;------------------------------------
run:
ld sp,#8000
call SOUND_PLAYER.SET_SOUND.mute
xor a
ld hl,varsStart
ld de,varsStart + 1
ld bc,tablesEnd - varsStart - 1
ld (hl),a
ldir
; inc a ; remove later
out (254),a
; The main loop of the program.
; The main loop calls the required system by identifier.
; The index and address of the execution of the required system are stored in a pre-created table.
ld bc,$
; A - system ID
rlca
add a,low systemMap
ld l,a
adc a,high systemMap
sub l
ld h,a
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
exx
call SOUND_PLAYER.play
exx
BORDER 0
call int
push bc
jp (hl)
;------------------------------------
int:
ld iy,#5C3A
ei
halt
di
ret
;------------------------------------
systemMap:
; system indices and addresses
TITLE: equ 0
dw TITLE_2.run
MAIN_MENU_INIT: equ 1
dw MAIN_MENU.init
MAIN_MENU_UPDATE: equ 2
dw MAIN_MENU.update
GAME_INIT: equ 3
dw GAME.init
GAME_UPDATE: equ 4
dw GAME.update
INFO_INIT: equ 5
dw 0
INFO_UPDATE: equ 6
dw 0
PASS_INIT: equ 7
dw PASS.init
PASS_UPDATE: equ 8
dw PASS.update
SHOP_INIT: equ 9
dw SHOP.init
SHOP_UPDATE: equ 10
dw SHOP.update
;------------------------------------
endmodule
|
;--------------------------------------------------------------
; ZX81 HRG library for the Memotech expansion
; by Stefano Bodrato, Feb. 2010
;--------------------------------------------------------------
;
; $Id: mt_pixladdr.asm,v 1.5 2016-07-14 17:44:17 pauloscustodio Exp $
;
SECTION code_clib
PUBLIC pixeladdress
;;EXTERN base_graphics
; ******************************************************************
;
; Get absolute pixel address in map of virtual (x,y) coordinate.
;
; in: hl = (x,y) coordinate of pixel (h,l)
;
; out: de = address of pixel byte
; a = bit number of byte where pixel is to be placed
; fz = 1 if bit number is 0 of pixel position
;
; registers changed after return:
; ......hl/ixiy same
; afbcde../.... different
;
.pixeladdress
; add y-times the nuber of bytes per line (33)
ld a,h
ld b,a
ld h,0
ld d,h
ld e,l
add hl,hl
add hl,hl
add hl,hl
add hl,hl
add hl,hl
add hl,de
inc hl
inc hl
ld de,($407B)
;;ld de,(base_graphics)
add hl,de
; add x divided by 8
;or a
rra
srl a
srl a
ld e,a
ld d,0
add hl,de
ld d,h
ld e,l
ld a,b
and 7
xor 7
ret
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.