text stringlengths 1 1.05M |
|---|
// projects/08/ProgramFlow/BasicLoop/BasicLoop.vm
@0
D=A
@SP
A=M
M=D
@SP
AM=M+1
@0
D=A
@LCL
AD=D+M
@R13
M=D
@SP
AM=M-1
D=M
@R13
A=M
M=D
(LOOP_START)
@0
D=A
@ARG
AD=D+M
D=M
@SP
A=M
M=D
@SP
AM=M+1
@0
D=A
@LCL
AD=D+M
D=M
@SP
A=M
M=D
@SP
AM=M+1
@SP
AM=M-1
D=M
@SP
AM=M-1
M=D+M
@SP
AM=M+1
@0
D=A
@LCL
AD=D+M
@R13
M=D
@SP
AM=M-1
D=M
@R13
A=M
M=D
@0
D=A
@ARG
AD=D+M
D=M
@SP
A=M
M=D
@SP
AM=M+1
@1
D=A
@SP
A=M
M=D
@SP
AM=M+1
@SP
AM=M-1
D=M
@SP
AM=M-1
M=M-D
@SP
AM=M+1
@0
D=A
@ARG
AD=D+M
@R13
M=D
@SP
AM=M-1
D=M
@R13
A=M
M=D
@0
D=A
@ARG
AD=D+M
D=M
@SP
A=M
M=D
@SP
AM=M+1
@SP
AM=M-1
D=M
@LOOP_START
D;JNE
@0
D=A
@LCL
AD=D+M
D=M
@SP
A=M
M=D
@SP
AM=M+1
(END)
@END
0;JMP
|
; A013728: a(n) = 23^(2*n + 1).
; 23,12167,6436343,3404825447,1801152661463,952809757913927,504036361936467383,266635235464391245607,141050039560662968926103,74615470927590710561908487,39471584120695485887249589623,20880467999847912034355032910567,11045767571919545466173812409689943,5843211045545439551605946764725979847,3091058643093537522799545838540043339063,1635170022196481349560959748587682926364327,865004941741938633917747707002884268046728983,457587614181485537342488537004525777796719632007
mul $0,2
mov $1,23
pow $1,$0
mul $1,23
mov $0,$1
|
// Copyright (c) by respective owners including Yahoo!, Microsoft, and
// individual contributors. All rights reserved. Released under a BSD (revised)
// license as described in the file LICENSE.
#include <cfloat>
#include <cmath>
#include <cstdio>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <algorithm>
#include <queue>
#include "reductions.h"
#include "vw.h"
using namespace VW::LEARNER;
using namespace VW::config;
namespace plt_ns
{
struct node
{
uint32_t n; // node number
float p; // node probability
bool operator<(const node& r) const { return p < r.p; }
};
struct plt
{
vw* all;
// tree structure
uint32_t k; // number of labels
uint32_t t; // number of tree nodes
uint32_t ti; // number of internal nodes
uint32_t kary; // kary tree
// for training
v_array<float> nodes_time; // in case of sgd, this stores individual t for each node
std::unordered_set<uint32_t> positive_nodes; // container for positive nodes
std::unordered_set<uint32_t> negative_nodes; // container for negative nodes
// for prediction
float threshold;
uint32_t top_k;
v_array<polyprediction> node_preds; // for storing results of base.multipredict
std::vector<node> node_queue; // container for queue used for both types of predictions
// for measuring predictive performance
std::unordered_set<uint32_t> true_labels;
v_array<uint32_t> tp_at; // true positives at (for precision and recall at)
uint32_t tp;
uint32_t fp;
uint32_t fn;
uint32_t true_count; // number of all true labels (for recall at)
uint32_t ec_count; // number of examples
plt()
{
nodes_time = v_init<float>();
node_preds = v_init<polyprediction>();
tp_at = v_init<uint32_t>();
tp = 0;
fp = 0;
fn = 0;
ec_count = 0;
true_count = 0;
}
~plt()
{
nodes_time.delete_v();
node_preds.delete_v();
tp_at.delete_v();
}
};
inline void learn_node(plt& p, uint32_t n, single_learner& base, example& ec)
{
if (!p.all->weights.adaptive)
{
p.all->sd->t = p.nodes_time[n];
p.nodes_time[n] += ec.weight;
}
base.learn(ec, n);
}
void learn(plt& p, single_learner& base, example& ec)
{
MULTILABEL::labels multilabels = std::move(ec.l.multilabels);
MULTILABEL::labels preds = std::move(ec.pred.multilabels);
double t = p.all->sd->t;
double weighted_holdout_examples = p.all->sd->weighted_holdout_examples;
p.all->sd->weighted_holdout_examples = 0;
p.positive_nodes.clear();
p.negative_nodes.clear();
if (multilabels.label_v.size() > 0)
{
for (auto label : multilabels.label_v)
{
uint32_t tn = label + p.ti;
if (tn < p.t)
{
p.positive_nodes.insert(tn);
while (tn > 0)
{
tn = static_cast<uint32_t>(floor(static_cast<float>(tn - 1) / p.kary));
p.positive_nodes.insert(tn);
}
}
}
if (multilabels.label_v.back() >= p.k)
std::cout << "label " << multilabels.label_v.back() << " is not in {0," << p.k - 1 << "} This won't work right."
<< std::endl;
for (auto& n : p.positive_nodes)
{
if (n < p.ti)
{
for (uint32_t i = 1; i <= p.kary; ++i)
{
uint32_t n_child = p.kary * n + i;
if (n_child < p.t && p.positive_nodes.find(n_child) == p.positive_nodes.end())
p.negative_nodes.insert(n_child);
}
}
}
}
else
p.negative_nodes.insert(0);
ec.l.simple = {1.f, 1.f, 0.f};
for (auto& n : p.positive_nodes) learn_node(p, n, base, ec);
ec.l.simple.label = -1.f;
for (auto& n : p.negative_nodes) learn_node(p, n, base, ec);
p.all->sd->t = t;
p.all->sd->weighted_holdout_examples = weighted_holdout_examples;
ec.pred.multilabels = std::move(preds);
ec.l.multilabels = std::move(multilabels);
}
inline float predict_node(uint32_t n, single_learner& base, example& ec)
{
ec.l.simple = {FLT_MAX, 1.f, 0.f};
base.predict(ec, n);
return 1.0f / (1.0f + exp(-ec.partial_prediction));
}
template <bool threshold>
void predict(plt& p, single_learner& base, example& ec)
{
MULTILABEL::labels multilabels = std::move(ec.l.multilabels);
MULTILABEL::labels preds = std::move(ec.pred.multilabels);
preds.label_v.clear();
// split labels into true and skip (those > max. label num)
p.true_labels.clear();
for (auto label : multilabels.label_v)
{
if (label < p.k)
p.true_labels.insert(label);
else
std::cout << "label " << label << " is not in {0," << p.k - 1 << "} Model can't predict it." << std::endl;
}
p.node_queue.clear(); // clear node queue
// prediction with threshold
if (threshold)
{
float cp_root = predict_node(0, base, ec);
if (cp_root > p.threshold) p.node_queue.push_back({0, cp_root}); // here queue is used for dfs search
while (!p.node_queue.empty())
{
node node = p.node_queue.back(); // current node
p.node_queue.pop_back();
uint32_t n_child = p.kary * node.n + 1;
ec.l.simple = {FLT_MAX, 1.f, 0.f};
base.multipredict(ec, n_child, p.kary, p.node_preds.begin(), false);
for (uint32_t i = 0; i < p.kary; ++i, ++n_child)
{
float cp_child = node.p * (1.f / (1.f + exp(-p.node_preds[i].scalar)));
if (cp_child > p.threshold)
{
if (n_child < p.ti)
p.node_queue.push_back({n_child, cp_child});
else
{
uint32_t l = n_child - p.ti;
preds.label_v.push_back(l);
}
}
}
}
if (p.true_labels.size() > 0)
{
uint32_t tp = 0;
for (auto pred_label : preds.label_v)
{
if (p.true_labels.count(pred_label)) ++tp;
}
p.tp += tp;
p.fp += static_cast<uint32_t>(preds.label_v.size()) - tp;
p.fn += static_cast<uint32_t>(p.true_labels.size()) - tp;
++p.ec_count;
}
}
// top-k prediction
else
{
p.node_queue.push_back({0, predict_node(0, base, ec)}); // here queue is used as priority queue
std::push_heap(p.node_queue.begin(), p.node_queue.end());
while (!p.node_queue.empty())
{
std::pop_heap(p.node_queue.begin(), p.node_queue.end());
node node = p.node_queue.back();
p.node_queue.pop_back();
if (node.n < p.ti)
{
uint32_t n_child = p.kary * node.n + 1;
ec.l.simple = {FLT_MAX, 1.f, 0.f};
base.multipredict(ec, n_child, p.kary, p.node_preds.begin(), false);
for (uint32_t i = 0; i < p.kary; ++i, ++n_child)
{
float cp_child = node.p * (1.0f / (1.0f + exp(-p.node_preds[i].scalar)));
p.node_queue.push_back({n_child, cp_child});
std::push_heap(p.node_queue.begin(), p.node_queue.end());
}
}
else
{
uint32_t l = node.n - p.ti;
preds.label_v.push_back(l);
if (preds.label_v.size() >= p.top_k) break;
}
}
// calculate p@
if (p.true_labels.size() > 0)
{
for (size_t i = 0; i < p.top_k; ++i)
{
if (p.true_labels.count(preds.label_v[i])) ++p.tp_at[i];
}
++p.ec_count;
p.true_count += static_cast<uint32_t>(p.true_labels.size());
}
}
p.node_queue.clear();
ec.pred.multilabels = std::move(preds);
ec.l.multilabels = std::move(multilabels);
}
void finish_example(vw& all, plt& /*p*/, example& ec)
{
MULTILABEL::output_example(all, ec);
VW::finish_example(all, ec);
}
void finish(plt& p)
{
// print results in test mode
if (!p.all->training && p.ec_count > 0)
{
// top-k predictions
if (p.top_k > 0)
{
double correct = 0;
for (size_t i = 0; i < p.top_k; ++i)
{
correct += p.tp_at[i];
std::cerr << "p@" << i + 1 << " = " << correct / (p.ec_count * (i + 1)) << std::endl;
std::cerr << "r@" << i + 1 << " = " << correct / p.true_count << std::endl;
}
}
else if (p.threshold > 0)
{
std::cerr << "hamming loss = " << static_cast<double>(p.fp + p.fn) / p.ec_count << std::endl;
std::cerr << "precision = " << static_cast<double>(p.tp) / (p.tp + p.fp) << std::endl;
std::cerr << "recall = " << static_cast<double>(p.tp) / (p.tp + p.fn) << std::endl;
}
}
}
void save_load_tree(plt& p, io_buf& model_file, bool read, bool text)
{
if (model_file.num_files() > 0)
{
bool resume = p.all->save_resume;
std::stringstream msg;
msg << ":" << resume << "\n";
bin_text_read_write_fixed(model_file, (char*)&resume, sizeof(resume), "", read, msg, text);
if (resume && !p.all->weights.adaptive)
{
for (size_t i = 0; i < p.t; ++i)
bin_text_read_write_fixed(model_file, (char*)&p.nodes_time[i], sizeof(p.nodes_time[0]), "", read, msg, text);
}
}
}
} // namespace plt_ns
using namespace plt_ns;
base_learner* plt_setup(options_i& options, vw& all)
{
auto tree = scoped_calloc_or_throw<plt>();
option_group_definition new_options("Probabilistic Label Tree ");
new_options.add(make_option("plt", tree->k).keep().necessary().help("Probabilistic Label Tree with <k> labels"))
.add(make_option("kary_tree", tree->kary).keep().default_value(2).help("use <k>-ary tree"))
.add(make_option("threshold", tree->threshold)
.default_value(0.5)
.help("predict labels with conditional marginal probability greater than <thr> threshold"))
.add(make_option("top_k", tree->top_k)
.default_value(0)
.help("predict top-<k> labels instead of labels above threshold"));
if (!options.add_parse_and_check_necessary(new_options)) return nullptr;
tree->all = &all;
// calculate number of tree nodes
const double a = std::pow(tree->kary, std::floor(std::log(tree->k) / std::log(tree->kary)));
const double b = tree->k - a;
const double c = std::ceil(b / (tree->kary - 1.0));
const double d = (tree->kary * a - 1.0) / (tree->kary - 1.0);
const double e = tree->k - (a - c);
tree->t = static_cast<uint32_t>(e + d);
tree->ti = tree->t - tree->k;
if (!all.logger.quiet)
{
*(all.trace_message) << "PLT k = " << tree->k << "\nkary_tree = " << tree->kary << std::endl;
if (!all.training)
{
if (tree->top_k > 0) { *(all.trace_message) << "top_k = " << tree->top_k << std::endl; }
else
{
*(all.trace_message) << "threshold = " << tree->threshold << std::endl;
}
}
}
// resize v_arrays
tree->nodes_time.resize(tree->t);
std::fill(tree->nodes_time.begin(), tree->nodes_time.end(), all.initial_t);
tree->node_preds.resize(tree->kary);
if (tree->top_k > 0) tree->tp_at.resize(tree->top_k);
learner<plt, example>* l;
if (tree->top_k > 0)
l = &init_learner(tree, as_singleline(setup_base(options, all)), learn, predict<false>, tree->t,
prediction_type_t::multilabels, all.get_setupfn_name(plt_setup) + "-top_k");
else
l = &init_learner(tree, as_singleline(setup_base(options, all)), learn, predict<true>, tree->t,
prediction_type_t::multilabels, all.get_setupfn_name(plt_setup));
all.example_parser->lbl_parser = MULTILABEL::multilabel;
all.delete_prediction = MULTILABEL::delete_prediction;
// force logistic loss for base classifiers
all.loss = getLossFunction(all, "logistic");
l->set_finish_example(finish_example);
l->set_finish(finish);
l->set_save_load(save_load_tree);
return make_base(*l);
}
|
;
; savexmm.asm
;
; Copyright (c) Microsoft Corporation. Licensed under the MIT license.
;
; Routines for saving and restoring XMM registers.
;
TITLE savexmm.asm
.686
.xmm
_TEXT SEGMENT PARA PUBLIC USE32 'CODE'
ASSUME CS:_TEXT, DS:FLAT, SS:FLAT
PUBLIC @SymCryptEnvUmSaveXmmRegistersAsm@4
PUBLIC @SymCryptEnvUmRestoreXmmRegistersAsm@4
PUBLIC @SymCryptEnvUmSaveYmmRegistersAsm@4
PUBLIC @SymCryptEnvUmRestoreYmmRegistersAsm@4
;VOID SYMCRYPT_CALL SymCryptEnvUmSaveXmmRegistersAsm( __m128i * buffer );
;VOID SYMCRYPT_CALL SymCryptEnvUmRestoreXmmRegistersAsm( __m128i * buffer );
;VOID SYMCRYPT_CALL SymCryptEnvUmSaveYmmRegistersAsm( __m256i * buffer );
;VOID SYMCRYPT_CALL SymCryptEnvUmRestoreYmmRegistersAsm( __m256i * buffer );
@SymCryptEnvUmSaveXmmRegistersAsm@4 PROC
;
; The .FPO provides debugging information for stack frames that do not use
; ebp as a base pointer.
; This stuff not well documented,
; but here is the information I've gathered about the arguments to .FPO
;
; In order:
; cdwLocals: Size of local variables, in DWords
; cdwParams: Size of parameters, in DWords. Given that this is all about
; stack stuff, I'm assuming this is only about parameters passed
; on the stack.
; cbProlog : Number of bytes in the prolog code. We sometimes interleaved the
; prolog code with work for better performance. Most uses of
; .FPO seem to set this value to 0.
; The debugger seems to work if the prolog defined by this value
; contains all the stack adjustments.
; cbRegs : # registers saved in the prolog. 4 in our case
; fUseBP : 0 if EBP is not used as base pointer, 1 if EBP is used as base pointer
; cbFrame : Type of frame.
; 0 = FPO frame (no frame pointer)
; 1 = Trap frame (result of a CPU trap event)
; 2 = TSS frame
;
; Having looked at various occurrences of .FPO in the Windows code it
; seems to be used fairly sloppy, with lots of arguments left 0 even when
; they probably shouldn't be according to the spec.
;
.FPO(0,0,0,0,0,0)
; ecx = buffer
;
; First we align ecx to the next multiple of 16. The buffer is defined to have 16*9 bytes so we have enough room
;
add ecx, 15
and ecx, NOT 15
movaps [ecx ], xmm0
movaps [ecx+ 16], xmm1
movaps [ecx+ 32], xmm2
movaps [ecx+ 48], xmm3
movaps [ecx+ 64], xmm4
movaps [ecx+ 80], xmm5
movaps [ecx+ 96], xmm6
movaps [ecx+112], xmm7
ret
@SymCryptEnvUmSaveXmmRegistersAsm@4 ENDP
@SymCryptEnvUmRestoreXmmRegistersAsm@4 PROC
; ecx = buffer
;
; First we align ecx to the next multiple of 16. The buffer is defined to have 16*9 bytes so we have enough room
;
add ecx, 15
and ecx, NOT 15
movaps xmm0, [ecx ]
movaps xmm1, [ecx+ 16]
movaps xmm2, [ecx+ 32]
movaps xmm3, [ecx+ 48]
movaps xmm4, [ecx+ 64]
movaps xmm5, [ecx+ 80]
movaps xmm6, [ecx+ 96]
movaps xmm7, [ecx+112]
ret
@SymCryptEnvUmRestoreXmmRegistersAsm@4 ENDP
@SymCryptEnvUmSaveYmmRegistersAsm@4 PROC
;
; The .FPO provides debugging information for stack frames that do not use
; ebp as a base pointer.
; This stuff not well documented,
; but here is the information I've gathered about the arguments to .FPO
;
; In order:
; cdwLocals: Size of local variables, in DWords
; cdwParams: Size of parameters, in DWords. Given that this is all about
; stack stuff, I'm assuming this is only about parameters passed
; on the stack.
; cbProlog : Number of bytes in the prolog code. We sometimes interleaved the
; prolog code with work for better performance. Most uses of
; .FPO seem to set this value to 0.
; The debugger seems to work if the prolog defined by this value
; contains all the stack adjustments.
; cbRegs : # registers saved in the prolog. 4 in our case
; fUseBP : 0 if EBP is not used as base pointer, 1 if EBP is used as base pointer
; cbFrame : Type of frame.
; 0 = FPO frame (no frame pointer)
; 1 = Trap frame (result of a CPU trap event)
; 2 = TSS frame
;
; Having looked at various occurrences of .FPO in the Windows code it
; seems to be used fairly sloppy, with lots of arguments left 0 even when
; they probably shouldn't be according to the spec.
;
.FPO(0,0,0,0,0,0)
; ecx = buffer
;
; First we align ecx to the next multiple of 16. The buffer is defined to have 16*9 bytes so we have enough room
;
add ecx, 31
and ecx, NOT 31
vmovaps [ecx+ 0 * 32 ], ymm0
vmovaps [ecx+ 1 * 32 ], ymm1
vmovaps [ecx+ 2 * 32 ], ymm2
vmovaps [ecx+ 3 * 32 ], ymm3
vmovaps [ecx+ 4 * 32 ], ymm4
vmovaps [ecx+ 5 * 32 ], ymm5
vmovaps [ecx+ 6 * 32 ], ymm6
vmovaps [ecx+ 7 * 32 ], ymm7
ret
@SymCryptEnvUmSaveYmmRegistersAsm@4 ENDP
@SymCryptEnvUmRestoreYmmRegistersAsm@4 PROC
; ecx = buffer
;
; First we align ecx to the next multiple of 16. The buffer is defined to have 16*9 bytes so we have enough room
;
add ecx, 31
and ecx, NOT 31
vmovaps ymm0, [ecx + 0 * 32 ]
vmovaps ymm1, [ecx + 1 * 32 ]
vmovaps ymm2, [ecx + 2 * 32 ]
vmovaps ymm3, [ecx + 3 * 32 ]
vmovaps ymm4, [ecx + 4 * 32 ]
vmovaps ymm5, [ecx + 5 * 32 ]
vmovaps ymm6, [ecx + 6 * 32 ]
vmovaps ymm7, [ecx + 7 * 32 ]
ret
@SymCryptEnvUmRestoreYmmRegistersAsm@4 ENDP
_TEXT ENDS
END
|
;; $Header:
;;
;; IDT/IRQ Channeler/Helper
;; By EKS - Dave Poirier
;; Distributed under the BSD License
;;
;; known limitations:
;;-------------------
;; - Maximum of 255 clients per IRQ channel
;; - GDT descriptor created are always with privilege level 0
;; - Doesn't remove a client from an IRQ channel due to an incomplete
;; ics.remove_client implementation
;; - In case the PIC was only partly initialized by a 3rd party, no detection
;; will be made of that case when writing to the PIC
;; - No check is done to see if GDT is still at the allocated address
;; - Initialization will freeze with an error code on screen if it can't
;; properly allocate memory to create either GDT or IDT
;;
;; special notable requirement:
;;-----------------------------
;; - A stack must already be setup to at least allow 64 bytes, ss must be set
;; a priori to use a 4GB r/w segment or one that is at least aligned with
;; physical addresses.
;;
;; special initialization behaviour:
;;----------------------------------
;; - During initialization, both the IDT and the GDT will be reloaded with the
;; defaults one. CS = 0x0008, DS=ES=FS=GS=SS = 0x0010. Both descriptor will
;; be base address 0, size = 4GB. Data segment is r/w, Code segment is r/x
;;
section .c_info
;version
db 0,0,1,'a' ;0.0.1 alpha
dd str_cellname
dd str_author
dd str_copyright
str_cellname: db "Potassium - IRQ Dispatcher",0
str_author: db "Dave Poirier",0
str_copyright: db "Distributed under BSD License",0
section .text
;==============================================================================
%define _PROVIDE_NMI_FUNCTIONS_
%define MAX_GDT_SIZE 128
%define FIRST_FREE_GDT_ENTRY 3
%define IDT_ENTRY_COUNT 0x30
%define FIRST_KNOWN_INT_HANDLER 0x20
%define KNOWN_INT_HANDLER_COUNT 0x10
%define PORT_PIC_MASTER_COMMAND 0x20
%define PORT_PIC_SLAVE_COMMAND 0xA0
%define GDTFF_OFF (FIRST_FREE_GDT_ENTRY*8)
%define IDT_SIZE (IDT_ENTRY_COUNT*8)
%define SEG_CODE 0x0008
%define SEG_DATA 0x0010
struc gdt_null_desc
.signature resb 4
.first_free resd 1
endstruc
section .c_init
;------------------------------------------------------------------------------
init:
pushad ; backup all regs, we mustn't destroy!
;
; Allocate memory for GDT
;------------------------
mov ecx, MAX_GDT_SIZE ; Max GDT Size
externfunc mem.alloc ; allocate memory for it
mov edx, 0xEE010001 ; failure code
jc short init_failed ; display error if any
;
; Initialize GDT manipulation data
;---------------------------------
mov [gdt.offset], edi ; save pointer to GDT
mov [edi], dword 'GDTM' ; mark it as valid GDT
lea esi, [byte edi + GDTFF_OFF] ; get first free entry pointer
mov [byte edi + 04], esi ; set first free entry pointer
;
; Initialize Code Segment
;------------------------
mov [byte edi + 08], dword 0x0000FFFF ; set base/limit
mov [byte edi + 12], dword 0x00CF9B00 ; set base/limit/type
;
; Initialize Data Segment
;------------------------
mov [byte edi + 16], dword 0x0000FFFF ; set base/limit
mov [byte edi + 20], dword 0x00CF9300 ; set base/limit/type
;
; Link up free entries
;---------------------
mov ecx, ((MAX_GDT_SIZE-GDTFF_OFF)/8) ; number of free entries
add edi, byte GDTFF_OFF ; move pointer to first free entry
.linking_gdt_entries: ;
lea esi, [edi + 8] ; get pointer to next free entry
mov [edi], esi ; set pointer to next free entry
dec ecx ; decrement free entry count
mov edi, esi ; move pointer to next free entry
jnz short .linking_gdt_entries ; continue if any free entry left
;
mov [byte edi - 8], dword ecx ; null terminate last entry
;
; Reload Pointer to GDT
;----------------------
lgdt [gdt] ; set cpu gdtr
;
; Activate new code segment, part i
;----------------------------------
jmp dword SEG_CODE:reload_cs ; far jump to re-entry code
;
; Error handler in case of failure
init_failed: ;---------------------------------
mov edi, 0xB8000+(0xA0*25)-0x10 ; Memory offset to send error code
push byte 8 ; Error code length
pop ecx ; set it in ecx for loop control
mov ah, 0x04 ; color code to use
.processing_error_code: ;
shr edx, 4 ; switch digit to display
mov al, dl ; get digit code
and al, 0x0F ; mask off useless bits
cmp al, 0x0A ; differentiate digit/alpha
sbb al, 0x69 ; convert to ascii, part i
das ; convert to ascii, part ii
stosw ; send digit to memory
loop .processing_error_code ; process next digit
jmp short $ ; lock everything up
;
; PIC 82C59A Initialization Sequence
pic.sequence.master: ;-----------------------------------
db 0x11, 0x20, 0x04, 0x1D, 0xFB ; Master PIC
;
pic.sequence.slave: ;
db 0x11, 0x28, 0x02, 0x19, 0xFF ; Slave PIC
;
send_pic_sequence: ;
lodsb ; load icw0
out dx, al ; send icw0 to pic address+0
inc edx ; select pic address+1
lodsb ; load icw1
out dx, al ; send icw1 to pic address+1
lodsb ; load icw2
out dx, al ; send icw2 to pic address+1
lodsb ; load icw3
out dx, al ; send icw3 to pic address+1
lodsb ; load irq mask
out dx, al ; send irq mask to pic address+1
retn ;
; Activate new code segment, part ii
;-----------------------------------
reload_cs: ; reentry point
;
; Activate new data segment
;--------------------------
push byte SEG_DATA ; segment selector to use
pop eax ; get it in eax so we can work with it
mov ds, eax ; initialize ds
mov es, eax ; initialize es
mov fs, eax ; initialize fs
mov gs, eax ; initialize gs
mov ss, eax ; initialize ss
;
; Acquiring memory for IDT
;-------------------------
mov ecx, IDT_SIZE ; size of the IDT to initialize
externfunc mem.alloc ; allocate memory
mov edx, 0xEE010002 ; error code in case of failure
jc short init_failed ; handle error if any
;
; Activate IDT
;-------------
dec eax ; decrement size of GDT by 1
push edi ; save gdt location
o16 push ax ; save size of GDT-1
lidt [esp] ; set cpu IDTR
o16 pop ax ; clear off gdt size
pop dword [idt.offset] ; set internal pointer to idt location
;
; Initialize unhandled INTs
;-------------------------
push byte FIRST_KNOWN_INT_HANDLER ; number of int to setup
mov esi, _default_int_handler ; set our default handler
pop ecx ; set number of unhandled interrupts
xor eax, eax ; start with interrupt 0
.registering_unhandled_int: ;
push eax ; back it up, it will be destroyed
call int.hook ; hook it up
pop eax ; restore eax
inc eax ; go to next interrupt
dec ecx ; decrement interrupt count
jnz short .registering_unhandled_int ; go process any interrupt left
;
; Initialize known IDT entries
;-----------------------------
; assuming al = FIRST_KNOWN_INT_HANDLER
;
push byte KNOWN_INT_HANDLER_COUNT ; number of int to setup
mov esi, _irq_0 ; pointer to int information
pop ecx ; set int count in ecx
.registering_idt_entries: ;
push eax ; backup interrupt number
push esi ; backup int handler offset
call int.hook ; interrupt hooking function
externfunc ics.create_channel ; create associated ICS channel
pop esi ; restore int handler offset
pop eax ; restore int handler offset
mov [esi + 1], edi ; save ICS channel in int handler
inc eax ; select next idt entry
add esi, byte 8 ; move to the next int handler
dec ecx ; decrement int handler count
jnz short .registering_idt_entries ; if any left, process them
;
; Send 82C59A Initialization Sequences
;-------------------------------------
mov esi, pic.sequence.master ; select initialization sequence
mov edx, PORT_PIC_MASTER_COMMAND ; select master PIC
call send_pic_sequence ; send sequence
mov edx, PORT_PIC_SLAVE_COMMAND ; select slave PIC
call send_pic_sequence ; send sequence
;
sti ;
;
popad ; restore all regs, we mustn't destroy!
;------------------------------------------------------------------------------
section .data
;==============================================================================
gdt:
.size: dw MAX_GDT_SIZE - 1
.offset: dd 0
idt:
.offset: dd 0
.default_handler: dd -1
.fatal_error: db 0
strings:
.unhandled_interrupt: db "Unhandled interrupt catched! Locking up.",0
;==============================================================================
section .text
;==============================================================================
%ifdef _PROVIDE_NMI_FUNCTIONS_
globalfunc int.enable_nmi
;------------------------------------------------------------------------------
;>
;; Enable Non-Maskable Interrupt
;;
;; parameters:
;;------------
;; none
;;
;; returns:
;;---------
;; registers as usual
;; no error check
;<
;------------------------------------------------------------------------------
in byte al, byte 0x70 ; Read CMOS RAM Index register
and byte al, byte 0x7F ; Unmask NMI bit
out byte 0x70, byte al ; Write modified CMOS RAM Index reg
retn ;
;------------------------------------------------------------------------------
globalfunc int.disable_nmi
;------------------------------------------------------------------------------
;>
;; Disable Non-Maskable Interrupt
;;
;; parameters:
;;------------
;; none
;;
;; returns:
;;---------
;; registers as usual
;; no error check
;<
;------------------------------------------------------------------------------
in byte al, byte 0x70 ; Read CMOS RAM Index register
or byte al, byte 0x80 ; Mask NMI bit
out byte 0x70, byte al ; Write modified CMOS RAM Index reg
retn ;
;------------------------------------------------------------------------------
%endif
globalfunc int.hook_irq
;------------------------------------------------------------------------------
;>
;; Hook a client to an irq channel
;;
;; note that the client must be ICS compatible, see the ICS documentation for
;; more detail.
;;
;; parameters:
;;------------
;; al = irq number (0 to 15)
;; esi = pointer to client to hook
;;
;; returned values:
;;-----------------
;; error and registers as usual
;<
;------------------------------------------------------------------------------
pushad ; backup all regs
;
; Test irq number validity
;-------------------------
test al, 0xF0 ; make sure requested irq is valid
stc ; prepare error flag in case
jnz short .exit ; if invalid, exit
;
; Add client to ics irq channel
;------------------------------
movzx eax, al ; expand irq number to 32bit
mov edi, [eax * 8 + _irq_0 + 1] ; get irq channel number
push eax ; backup requested irq number
externfunc ics.add_client ; add client to the ics irq channel
pop eax ; restore requested irq number
jc short .exit ; in case of any error, exit
;
; IRQ mask/unmask control
;------------------------
inc byte [eax * 8 + _irq_0 + 7] ; increment client count for this irq
clc ; clear error in case we leave early
jnz short .exit ; client already present? don't unmask
;
call int.unmask_irq ; unmask irq
;
; Exit point
.exit: ;-----------
popad ; restore all registers
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc int.unhook_irq
;------------------------------------------------------------------------------
;>
;; Unhook a client from an irq channel
;;
;; Parameters:
;;------------
;; al = irq number
;; esi = pointer to client
;;
;; Returned values:
;;-----------------
;; error and registers as usual
;<
;------------------------------------------------------------------------------
pushad ; backing up all registers
;
; Test irq number validity
;-------------------------
test al, 0xF0 ; must be between 0 and 15
stc ; set error flag in case
jnz short .exit ; exit if invalid
;
; IRQ mask/unmask control
;------------------------
movzx eax, al ; expand irq number to 32bit
dec byte [eax * 8 + _irq_0 + 7] ; decrement client count
jns short .unhook_client ; if client count is above -1..
; don't mask yet
;
call int.mask_irq ; mask irq, no more client left
;
; Unhook client from irq channel
.unhook_client: ;-------------------------------
; externfunc ics.remove_client ; XXX TODO: as soon as it is available
; uncomment and test!
;
; Exit point
.exit: ;-----------
popad ; restore all registers
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc int.mask_irq
;------------------------------------------------------------------------------
;>
;; Mask an irq, in either the slave or master pic
;;
;; parameters:
;;------------
;; al = irq number (only the lowest 4 bits are used)
;;
;; returned values:
;;-----------------
;; CL = irq number as provided in AL
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
test al, 0xF0 ; test irq number validity
mov cl, al ; prepare rotating mask count
stc ; set error flag in case
mov ah, 0x01 ; mask to 'or' with, only 1 bit cleared
jnz short int.unmask_irq.exit ; if irq number is above range, exit
rol ah, cl ; rotate mask to fit selected irq
test al, 0x08 ; determine slave/master based on bit 3
jnz .slave_pic ; seems it slave, go do it
;
; Master PIC irq mask
;--------------------
in al, 0x21 ; get current master pic irq mask
or al, ah ; set the irq mask for selected irq
out 0x21, al ; send new irq mask to master pic
clc ; clear any error flag
retn ; return to caller
;
; Slave PIC irq mask
.slave_pic: ;-------------------
in al, 0xA1 ; get current slave pic irq mask
or al, ah ; set the irq mask for selected irq
out 0xA1, al ; send new irq mask to slave pic
clc ; clear any error flag
retn ; get back to caller
;------------------------------------------------------------------------------
globalfunc int.unmask_irq
;------------------------------------------------------------------------------
;>
;; Unmask an irq, in either the slave or master pic
;;
;; parameters:
;;------------
;; al = irq number
;;
;; returned values:
;;-----------------
;; cl = irq number as requested in al
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
test al, 0xF0 ; test irq number validity
mov cl, al ; prepare rotating mask count
stc ; set error flag in case
mov ah, 0xFE ; mask to 'and' with, only 1 bit cleared
jnz short .exit ; if irq number is above range, exit
rol ah, cl ; rotate mask to fit selected irq
test al, 0x08 ; was it a slave or master pic's irq?
jnz .slave_pic ; seems it slave, go do it
;
; Master PIC irq unmask
;----------------------
in al, 0x21 ; get current master pic irq mask
and al, ah ; clear the irq mask for selected irq
out 0x21, al ; send new irq mask to master pic
clc ; clear any error flag
retn ;
;
; Exit point, invalid param
.exit: ;--------------------------
mov eax, __ERROR_INVALID_PARAMETERS__ ;
retn ; get back to caller
;
; Slave PIC irq unmask
.slave_pic: ;---------------------
in al, 0xA1 ; get current slave pic irq mask
and al, ah ; clear the irq mask for selected irq
out 0xA1, al ; send new irq mask to slave pic
clc ; clear any error flag
retn ; get back to caller
;------------------------------------------------------------------------------
globalfunc int.get_irq_mask
;------------------------------------------------------------------------------
;>
;; Get both master and slave pic irq mask
;;
;; parameters:
;;------------
;; none
;;
;; returned values:
;;-----------------
;; al = master pic irq mask
;; ah = slave pic irq mask
;<
; no error returned,
;------------------------------------------------------------------------------
in al, 0xA1 ; get slave pic irq mask
mov ah, al ; put it up in ah
in al, 0x21 ; get master pic irq mask
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc int.set_irq_mask
;------------------------------------------------------------------------------
;>
;; Set both master and slave pic irq mask
;;
;; parameters:
;;------------
;; al = master pic irq mask
;; ah = slave pic irq mask
;;
;; returned values:
;;-----------------
;; none, eax destroyed
;<
;------------------------------------------------------------------------------
out 0x21, al ; send irq mask to master pic
mov al, ah ; load up irq mask of slave pic
out 0xA1, al ; send irq mask to slave pic
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc gdt.create_descriptor
;------------------------------------------------------------------------------
;>
;; Create a GDT descriptor
;;
;; parameters:
;;------------
;; esi = base address of segment to create
;; ecx = size of segment
;; dh = type of segment
;; dl = default operation/address size 0=16bits, 1=32bits
;;
;; returned values:
;;-----------------
;;
;; eax = gdt descriptor bits 0-31
;; ebx = gdt descriptor bits 32-63
;; esi = segment selector
;;
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
push edi ; backup it up!
;
; Get Pointer to first free GDT entry
;------------------------------------
mov edi, [gdt.offset] ; get pointer to GDT
mov ebx, [edi + gdt_null_desc.first_free]
test ebx, ebx ; verify that next free entry isn't nil
stc ; set error flag in case
mov eax, __ERROR_GDT_FULL__ ; prepare error code
jz short .exit ; in case its nil, exit
;
; Unlink GDT entry
;-----------------
mov eax, [ebx] ; get pointer to next free entry
push ebx ; save current gdt entry pointer
mov [edi + gdt_null_desc.first_free], eax ; set pointer to next free entry
;
; Create GDT descriptor
;----------------------
mov ebx, esi ; load base address
mov eax, esi ; load base address
and ebx, 0xFF000000 ; keep only highest 8 bites of address
rol eax, 16 ; rotate bits left by 16
; the original 16-23 bits will end up
; in bits 0-7; original bits 0-15 will
; end up in bits 16-31
test ecx, 0xFFF00000 ; check if segment size require BIG bit
mov bl, al ; load original address bits 16-23
jz short .small_seg ; if it isn't required.. bypass bit set
shr ecx, 12 ; divide size by 4KB
or ebx, 0x00800000 ; set the BIG bit
.small_seg: ;
mov ax, cx ; load size 0-15 in descriptor low part
pop esi ; restore pointer to gdt entry selected
neg edi ; negate gdt location to compute index
and ecx, 0x000F0000 ; keep only high part of segment size
test dl, dl ; test default operation size
mov bh, dh ; set segment type
jz short .16bits_seg ; if 16 bits, bypass bit set
or ebx, 0x00400000 ; set operation size bit
.16bits_seg: ;
or ebx, ecx ; include high part of segment size
mov [esi], eax ; write gdt descriptor low part
mov [esi + 4], ebx ; write gdt descriptor high part
add esi, edi ; compute gdt entry index (selector)
clc ; clear any error flag
.exit: ;
pop edi ; restore edi
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc gdt.destroy_descriptor
;------------------------------------------------------------------------------
;>
;; Destroy a GDT Descriptor
;;
;; parameters:
;;------------
;; EAX = Selector of the gdt entry to destroy
;;
;; returned values:
;;-----------------
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
push edi ; backup edi reg
cmp eax, [gdt.size] ; parameter sanity check
mov edi, [gdt.offset] ; load pointer to gdt
jnb short .above_gdt_limit ; index points above gdt? exit !
;
add eax, edi ; point to gdt entry
push dword [edi + gdt_null_desc.first_free] ; original first free
mov [edi + gdt_null_desc.first_free], eax ; new first free
pop dword [eax] ; link to original first free
clc ; clear any error flag
pop edi ; restore edi
retn ; return to caller
;
.above_gdt_limit: ;
pop edi ; restore edi
mov eax, __ERROR_INVALID_PARAMETERS__ ; set error code
stc ; set error flag
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc int.hook
;------------------------------------------------------------------------------
;>
;; Hook an Interrupt Handler directly in the IDT
;;
;; parameters:
;;------------
;; AL = Interrupt number
;; esi = pointer to interrupt handler
;;
;; returned values:
;;-----------------
;; ebx = original interrupt number requested
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
movzx ebx, al ; expand interrupt number to 32bit
mov eax, __ERROR_INVALID_PARAMETERS__ ; set error in case int > idt limit
cmp bl, IDT_ENTRY_COUNT ; original idt size created
jnb short .exit_with_error ; int > idt limit? exit!
;
; Acquire pointer to idt entry
;-----------------------------
push edi ; backup those up..
push esi ;
push ebx ;
;
mov edi, [idt.offset] ; get pointer to idt
lea edi, [ebx * 8 + edi] ; add in displacement to int entry
;
mov eax, esi ; load interrupt handler location
mov ebx, cs ; get code segment value
and esi, 0x0000FFFF ; keep only lowest 16 bits
shl ebx, 16 ; switch left 16 bits original cs
and eax, 0xFFFF0000 ; keep only highest 16 bits
or esi, ebx ; mask in code segment value
or eax, 0x00008E00 ; mask gate as 32bit, present, DPL=0
mov [edi], esi ; write low part of int descriptor
mov [edi + 4], eax ; write high part of int descriptor
pop ebx ; restore backed up registers
pop esi ;
pop edi ;
clc ; clear any error flag
retn ; return to caller
;
.exit_with_error: ;
stc ; set error flag
retn ; return to caller
;------------------------------------------------------------------------------
globalfunc int.unhook
;------------------------------------------------------------------------------
;>
;; Unhook an interrupt descriptor
;;
;; parameters:
;;------------
;; al = interrupt number
;;
;; returned values:
;;-----------------
;; errors and registers as usual
;<
;------------------------------------------------------------------------------
push esi
mov esi, _default_int_handler
call int.hook
pop esi
retn
;------------------------------------------------------------------------------
globalfunc int.set_default_handler
;------------------------------------------------------------------------------
;>
;; Set the default interrupt handler that will be called if an unhooked int
;; is generated.
;;
;; note: send -1 to restore potassium's default
;;
;; Parameters:
;;------------
;; esi = pointer to interrupt handler function
;;
;; Returned values:
;;-----------------
;; none, always successful
;<
;------------------------------------------------------------------------------
mov [idt.default_handler], esi
retn
;------------------------------------------------------------------------------
_default_int_handler:
;------------------------------------------------------------------------------
cmp dword [idt.default_handler], byte -1 ; check if default handler is
jz short .no_handler_hooked ; present, if not, deal with it
;
; Redirect to default handler
jmp [idt.default_handler] ;<---------------------------
;
; Default handler not present
.no_handler_hooked: ;----------------------------
;
; Extra check in case we have
; a double or tripple fault
;-----------------------------
inc byte [idt.fatal_error] ; inc fata error count
jnz short $ ; if not going from -1 to 0...
; we have a double fault at
; the least
;
; Disable Non-maskable int
call int.disable_nmi ;-------------------------
;
; Display unhandled
;------------------
mov esi, strings.unhandled_interrupt ; our error message
mov edi, 0xB8000 ; location to print it
mov ah, 0x40 ; color code
.writing_message: ;
lodsb ; load one char
stosw ; write char + color
test al, al ; test for end of string
jnz short .writing_message ; if char ain't null, continue
jmp short $ ; lock the comp.
;------------------------------------------------------------------------------
_irq_common:
;------------------------------------------------------------------------------
push eax
mov al, 0x20
out 0x20, al
pop eax
externfunc ics.send_confirmed_message
add esp, byte 4
iretd
;------------------------------------------------------------------------------
;------------------------------------------------------------------------------
align 8, db 0 ; align code on 8 bytes boundary for
; faster computations
; (see int.hook_irq and int.unhook_irq)
;
_irq_0: ;-----------: IRQ 0 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_1: ;-----------: IRQ 1 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_2: ;-----------: IRQ 2 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_3: ;-----------: IRQ 3 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_4: ;-----------: IRQ 4 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_5: ;-----------: IRQ 5 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_6: ;-----------: IRQ 6 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_7: ;-----------: IRQ 7 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_8: ;-----------: IRQ 8 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_9: ;-----------: IRQ 9 handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_A: ;-----------: IRQ A handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_B: ;-----------: IRQ B handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_C: ;-----------: IRQ C handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_D: ;-----------: IRQ D handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_E: ;-----------: IRQ E handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;
_irq_F: ;-----------: IRQ F handler
push dword 0 ; ICS channel, set at initialization
jmp short _irq_common_slave ; jump to common irq handling code
.count: db -1 ; number of client hooked on this irq
;------------------------------------------------------------------------------
_irq_common_slave:
;------------------------------------------------------------------------------
push eax
mov al, 0x20
out 0x20, al
out 0xA0, al
pop eax
externfunc ics.send_confirmed_message
add esp, byte 4
iretd
;------------------------------------------------------------------------------
|
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2020 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/iqcash-config.h"
#endif
#include "qt/iqcash/iqcashgui.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "intro.h"
#include "net.h"
#include "networkstyle.h"
#include "optionsmodel.h"
#include "qt/iqcash/splash.h"
#include "qt/iqcash/welcomecontentwidget.h"
#include "utilitydialog.h"
#include "winshutdownmonitor.h"
#ifdef ENABLE_WALLET
#include "paymentserver.h"
#include "walletmodel.h"
#endif
#include "masternodeconfig.h"
#include "fs.h"
#include "init.h"
#include "main.h"
#include "rpc/server.h"
#include "guiinterface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#endif
#include <stdint.h>
#include <boost/thread.hpp>
#include <QApplication>
#include <QDebug>
#include <QLibraryInfo>
#include <QLocale>
#include <QMessageBox>
#include <QProcess>
#include <QSettings>
#include <QThread>
#include <QTimer>
#include <QTranslator>
#if defined(QT_STATICPLUGIN)
#include <QtPlugin>
#if defined(QT_QPA_PLATFORM_XCB)
Q_IMPORT_PLUGIN(QXcbIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_WINDOWS)
Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin);
#elif defined(QT_QPA_PLATFORM_COCOA)
Q_IMPORT_PLUGIN(QCocoaIntegrationPlugin);
#endif
Q_IMPORT_PLUGIN(QSvgPlugin);
Q_IMPORT_PLUGIN(QSvgIconPlugin);
Q_IMPORT_PLUGIN(QGifPlugin);
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
Q_DECLARE_METATYPE(CAmount)
static void InitMessage(const std::string& message)
{
LogPrintf("init message: %s\n", message);
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("iqcash-core", psz).toStdString();
}
static QString GetLangTerritory(bool forceLangFromSetting = false)
{
QSettings settings;
// Get desired locale (e.g. "de_DE")
// 1) System default language
QString lang_territory = QLocale::system().name();
// 2) Language from QSettings
QString lang_territory_qsettings = settings.value("language", "").toString();
if (!lang_territory_qsettings.isEmpty())
lang_territory = lang_territory_qsettings;
// 3) -lang command line argument
lang_territory = QString::fromStdString(GetArg("-lang", lang_territory.toStdString()));
return (forceLangFromSetting) ? lang_territory_qsettings : lang_territory;
}
/** Set up translations */
static void initTranslations(QTranslator& qtTranslatorBase, QTranslator& qtTranslator, QTranslator& translatorBase, QTranslator& translator, bool forceLangFromSettings = false)
{
// Remove old translators
QApplication::removeTranslator(&qtTranslatorBase);
QApplication::removeTranslator(&qtTranslator);
QApplication::removeTranslator(&translatorBase);
QApplication::removeTranslator(&translator);
// Get desired locale (e.g. "de_DE")
// 1) System default language
QString lang_territory = GetLangTerritory(forceLangFromSettings);
// Convert to "de" only by truncating "_DE"
QString lang = lang_territory;
lang.truncate(lang_territory.lastIndexOf('_'));
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
QApplication::installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
QApplication::installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in iqcash.qrc)
if (translatorBase.load(lang, ":/translations/"))
QApplication::installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in iqcash.qrc)
if (translator.load(lang_territory, ":/translations/"))
QApplication::installTranslator(&translator);
}
/* qDebug() message handler --> debug.log */
void DebugMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(context);
if (type == QtDebugMsg) {
LogPrint(BCLog::QT, "GUI: %s\n", msg.toStdString());
} else {
LogPrintf("GUI: %s\n", msg.toStdString());
}
}
/** Class encapsulating IQCASH Core startup and shutdown.
* Allows running startup and shutdown in a different thread from the UI thread.
*/
class BitcoinCore : public QObject
{
Q_OBJECT
public:
explicit BitcoinCore();
public Q_SLOTS:
void initialize();
void shutdown();
void restart(QStringList args);
Q_SIGNALS:
void initializeResult(int retval);
void shutdownResult(int retval);
void runawayException(const QString& message);
private:
/// Flag indicating a restart
bool execute_restart;
/// Pass fatal exception message to UI thread
void handleRunawayException(const std::exception* e);
};
/** Main IQCASH application object */
class BitcoinApplication : public QApplication
{
Q_OBJECT
public:
explicit BitcoinApplication(int& argc, char** argv);
~BitcoinApplication();
#ifdef ENABLE_WALLET
/// Create payment server
void createPaymentServer();
#endif
/// parameter interaction/setup based on rules
void parameterSetup();
/// Create options model
void createOptionsModel();
/// Create main window
void createWindow(const NetworkStyle* networkStyle);
/// Create splash screen
void createSplashScreen(const NetworkStyle* networkStyle);
/// Create tutorial screen
bool createTutorialScreen();
/// Request core initialization
void requestInitialize();
/// Request core shutdown
void requestShutdown();
/// Get process return value
int getReturnValue() { return returnValue; }
/// Get window identifier of QMainWindow (IQCASHGUI)
WId getMainWinId() const;
public Q_SLOTS:
void initializeResult(int retval);
void shutdownResult(int retval);
/// Handle runaway exceptions. Shows a message box with the problem and quits the program.
void handleRunawayException(const QString& message);
void updateTranslation(bool forceLangFromSettings = false);
Q_SIGNALS:
void requestedInitialize();
void requestedRestart(QStringList args);
void requestedShutdown();
void stopThread();
void splashFinished(QWidget* window);
private:
QThread* coreThread;
OptionsModel* optionsModel;
ClientModel* clientModel;
IQCASHGUI* window;
QTimer* pollShutdownTimer;
#ifdef ENABLE_WALLET
PaymentServer* paymentServer;
WalletModel* walletModel;
#endif
int returnValue;
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
void startThread();
};
#include "iqcash.moc"
BitcoinCore::BitcoinCore() : QObject()
{
}
void BitcoinCore::handleRunawayException(const std::exception* e)
{
PrintExceptionContinue(e, "Runaway exception");
Q_EMIT runawayException(QString::fromStdString(strMiscWarning));
}
void BitcoinCore::initialize()
{
execute_restart = true;
try {
qDebug() << __func__ << ": Running AppInit2 in thread";
int rv = AppInit2();
Q_EMIT initializeResult(rv);
} catch (const std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
void BitcoinCore::restart(QStringList args)
{
if (execute_restart) { // Only restart 1x, no matter how often a user clicks on a restart-button
execute_restart = false;
try {
qDebug() << __func__ << ": Running Restart in thread";
Interrupt();
PrepareShutdown();
qDebug() << __func__ << ": Shutdown finished";
Q_EMIT shutdownResult(1);
CExplicitNetCleanup::callCleanup();
QProcess::startDetached(QApplication::applicationFilePath(), args);
qDebug() << __func__ << ": Restart initiated...";
QApplication::quit();
} catch (const std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
}
void BitcoinCore::shutdown()
{
try {
qDebug() << __func__ << ": Running Shutdown in thread";
Interrupt();
Shutdown();
qDebug() << __func__ << ": Shutdown finished";
Q_EMIT shutdownResult(1);
} catch (const std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
}
BitcoinApplication::BitcoinApplication(int& argc, char** argv) : QApplication(argc, argv),
coreThread(0),
optionsModel(0),
clientModel(0),
window(0),
pollShutdownTimer(0),
#ifdef ENABLE_WALLET
paymentServer(0),
walletModel(0),
#endif
returnValue(0)
{
setQuitOnLastWindowClosed(false);
}
BitcoinApplication::~BitcoinApplication()
{
if (coreThread) {
qDebug() << __func__ << ": Stopping thread";
Q_EMIT stopThread();
coreThread->wait();
qDebug() << __func__ << ": Stopped thread";
}
delete window;
window = 0;
#ifdef ENABLE_WALLET
delete paymentServer;
paymentServer = 0;
#endif
// Delete Qt-settings if user clicked on "Reset Options"
QSettings settings;
if (optionsModel && optionsModel->resetSettings) {
settings.clear();
settings.sync();
}
delete optionsModel;
optionsModel = 0;
}
#ifdef ENABLE_WALLET
void BitcoinApplication::createPaymentServer()
{
paymentServer = new PaymentServer(this);
}
#endif
void BitcoinApplication::createOptionsModel()
{
optionsModel = new OptionsModel();
}
void BitcoinApplication::createWindow(const NetworkStyle* networkStyle)
{
window = new IQCASHGUI(networkStyle, 0);
pollShutdownTimer = new QTimer(window);
connect(pollShutdownTimer, &QTimer::timeout, window, &IQCASHGUI::detectShutdown);
pollShutdownTimer->start(200);
}
void BitcoinApplication::createSplashScreen(const NetworkStyle* networkStyle)
{
Splash* splash = new Splash(0, networkStyle);
// We don't hold a direct pointer to the splash screen after creation, so use
// Qt::WA_DeleteOnClose to make sure that the window will be deleted eventually.
splash->setAttribute(Qt::WA_DeleteOnClose);
splash->show();
connect(this, &BitcoinApplication::splashFinished, splash, &Splash::slotFinish);
connect(this, &BitcoinApplication::requestedShutdown, splash, &QWidget::close);
}
bool BitcoinApplication::createTutorialScreen()
{
WelcomeContentWidget* widget = new WelcomeContentWidget();
connect(widget, &WelcomeContentWidget::onLanguageSelected, [this](){
updateTranslation(true);
});
widget->exec();
bool ret = widget->isOk;
widget->deleteLater();
return ret;
}
void BitcoinApplication::updateTranslation(bool forceLangFromSettings){
// Re-initialize translations after change them
initTranslations(this->qtTranslatorBase, this->qtTranslator, this->translatorBase, this->translator, forceLangFromSettings);
}
void BitcoinApplication::startThread()
{
if (coreThread)
return;
coreThread = new QThread(this);
BitcoinCore* executor = new BitcoinCore();
executor->moveToThread(coreThread);
/* communication to and from thread */
connect(executor, &BitcoinCore::initializeResult, this, &BitcoinApplication::initializeResult);
connect(executor, &BitcoinCore::shutdownResult, this, &BitcoinApplication::shutdownResult);
connect(executor, &BitcoinCore::runawayException, this, &BitcoinApplication::handleRunawayException);
connect(this, &BitcoinApplication::requestedInitialize, executor, &BitcoinCore::initialize);
connect(this, &BitcoinApplication::requestedShutdown, executor, &BitcoinCore::shutdown);
connect(window, &IQCASHGUI::requestedRestart, executor, &BitcoinCore::restart);
/* make sure executor object is deleted in its own thread */
connect(this, &BitcoinApplication::stopThread, executor, &QObject::deleteLater);
connect(this, &BitcoinApplication::stopThread, coreThread, &QThread::quit);
coreThread->start();
}
void BitcoinApplication::parameterSetup()
{
// Default printtoconsole to false for the GUI. GUI programs should not
// print to the console unnecessarily.
SoftSetBoolArg("-printtoconsole", false);
InitLogging();
InitParameterInteraction();
}
void BitcoinApplication::requestInitialize()
{
qDebug() << __func__ << ": Requesting initialize";
startThread();
Q_EMIT requestedInitialize();
}
void BitcoinApplication::requestShutdown()
{
qDebug() << __func__ << ": Requesting shutdown";
startThread();
window->hide();
window->setClientModel(0);
pollShutdownTimer->stop();
#ifdef ENABLE_WALLET
window->removeAllWallets();
delete walletModel;
walletModel = 0;
#endif
delete clientModel;
clientModel = 0;
// Show a simple window indicating shutdown status
ShutdownWindow::showShutdownWindow(window);
// Request shutdown from core thread
Q_EMIT requestedShutdown();
}
void BitcoinApplication::initializeResult(int retval)
{
qDebug() << __func__ << ": Initialization result: " << retval;
// Set exit result: 0 if successful, 1 if failure
returnValue = retval ? 0 : 1;
if (retval) {
#ifdef ENABLE_WALLET
PaymentServer::LoadRootCAs();
paymentServer->setOptionsModel(optionsModel);
#endif
clientModel = new ClientModel(optionsModel);
window->setClientModel(clientModel);
#ifdef ENABLE_WALLET
if (pwalletMain) {
walletModel = new WalletModel(pwalletMain, optionsModel);
window->addWallet(IQCASHGUI::DEFAULT_WALLET, walletModel);
window->setCurrentWallet(IQCASHGUI::DEFAULT_WALLET);
connect(walletModel, &WalletModel::coinsSent,
paymentServer, &PaymentServer::fetchPaymentACK);
}
#endif
// If -min option passed, start window minimized.
if (GetBoolArg("-min", false)) {
window->showMinimized();
} else {
window->show();
}
Q_EMIT splashFinished(window);
#ifdef ENABLE_WALLET
// Now that initialization/startup is done, process any command-line
// IQCASH: URIs or payment requests:
//connect(paymentServer, &PaymentServer::receivedPaymentRequest, window, &IQCASHGUI::handlePaymentRequest);
connect(window, &IQCASHGUI::receivedURI, paymentServer, &PaymentServer::handleURIOrFile);
connect(paymentServer, &PaymentServer::message, [this](const QString& title, const QString& message, unsigned int style) {
window->message(title, message, style);
});
QTimer::singleShot(100, paymentServer, &PaymentServer::uiReady);
#endif
} else {
quit(); // Exit main loop
}
}
void BitcoinApplication::shutdownResult(int retval)
{
qDebug() << __func__ << ": Shutdown result: " << retval;
quit(); // Exit main loop after shutdown finished
}
void BitcoinApplication::handleRunawayException(const QString& message)
{
QMessageBox::critical(0, "Runaway exception", QObject::tr("A fatal error occurred. IQCASH can no longer continue safely and will quit.") + QString("\n\n") + message);
::exit(1);
}
WId BitcoinApplication::getMainWinId() const
{
if (!window)
return 0;
return window->winId();
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char* argv[])
{
SetupEnvironment();
/// 1. Parse command-line options. These take precedence over anything else.
// Command-line options take precedence:
ParseParameters(argc, argv);
// Do not refer to data directory yet, this can be overridden by Intro::pickDataDirectory
/// 2. Basic Qt initialization (not dependent on parameters or configuration)
Q_INIT_RESOURCE(iqcash_locale);
Q_INIT_RESOURCE(iqcash);
// Generate high-dpi pixmaps
QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
#if QT_VERSION >= 0x050600
QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
#ifdef Q_OS_MAC
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
BitcoinApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType<bool*>();
// Need to pass name here as CAmount is a typedef (see http://qt-project.org/doc/qt-5/qmetatype.html#qRegisterMetaType)
// IMPORTANT if it is no longer a typedef use the normal variant above
qRegisterMetaType<CAmount>("CAmount");
/// 3. Application identification
// must be set before OptionsModel is initialized or translations are loaded,
// as it is used to locate QSettings
QApplication::setOrganizationName(QAPP_ORG_NAME);
QApplication::setOrganizationDomain(QAPP_ORG_DOMAIN);
QApplication::setApplicationName(QAPP_APP_NAME_DEFAULT);
GUIUtil::SubstituteFonts(GetLangTerritory());
/// 4. Initialization of translations, so that intro dialog is in user's language
// Now that QSettings are accessible, initialize translations
//initTranslations(qtTranslatorBase, qtTranslator, translatorBase, translator);
app.updateTranslation();
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) {
HelpMessageDialog help(NULL, mapArgs.count("-version"));
help.showOrPrint();
return 1;
}
/// 5. Now that settings and translations are available, ask user for data directory
// User language is set up: pick a data directory
if (!Intro::pickDataDirectory())
return 0;
/// 6. Determine availability of data directory and parse iqcash.conf
/// - Do not call GetDataDir(true) before this step finishes
if (!fs::is_directory(GetDataDir(false))) {
QMessageBox::critical(0, QObject::tr("IQCASH Core"),
QObject::tr("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (const std::exception& e) {
QMessageBox::critical(0, QObject::tr("IQCASH Core"),
QObject::tr("Error: Cannot parse configuration file: %1. Only use key=value syntax.").arg(e.what()));
return 0;
}
/// 7. Determine network (and switch to network specific options)
// - Do not call Params() before this step
// - Do this after parsing the configuration file, as the network can be switched there
// - QSettings() will use the new application name after this, resulting in network-specific settings
// - Needs to be done before createOptionsModel
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
QMessageBox::critical(0, QObject::tr("IQCASH Core"), QObject::tr("Error: Invalid combination of -regtest and -testnet."));
return 1;
}
#ifdef ENABLE_WALLET
// Parse URIs on command line -- this can affect Params()
PaymentServer::ipcParseCommandLine(argc, argv);
#endif
QScopedPointer<const NetworkStyle> networkStyle(NetworkStyle::instantiate(QString::fromStdString(Params().NetworkIDString())));
assert(!networkStyle.isNull());
// Allow for separate UI settings for testnets
QApplication::setApplicationName(networkStyle->getAppName());
// Re-initialize translations after changing application name (language in network-specific settings can be different)
app.updateTranslation();
#ifdef ENABLE_WALLET
/// 7a. parse masternode.conf
std::string strErr;
if (!masternodeConfig.read(strErr)) {
QMessageBox::critical(0, QObject::tr("IQCASH Core"),
QObject::tr("Error reading masternode configuration file: %1").arg(strErr.c_str()));
return 0;
}
/// 8. URI IPC sending
// - Do this early as we don't want to bother initializing if we are just calling IPC
// - Do this *after* setting up the data directory, as the data directory hash is used in the name
// of the server.
// - Do this after creating app and setting up translations, so errors are
// translated properly.
if (PaymentServer::ipcSendCommandLine())
exit(0);
// Start up the payment server early, too, so impatient users that click on
// iqcash: links repeatedly have their payment requests routed to this process:
app.createPaymentServer();
#endif
/// 9. Main GUI initialization
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
#if defined(Q_OS_WIN)
// Install global event filter for processing Windows session related Windows messages (WM_QUERYENDSESSION and WM_ENDSESSION)
qApp->installNativeEventFilter(new WinShutdownMonitor());
#endif
// Install qDebug() message handler to route to debug.log
qInstallMessageHandler(DebugMessageHandler);
// Allow parameter interaction before we create the options model
app.parameterSetup();
// Load GUI settings from QSettings
app.createOptionsModel();
// Subscribe to global signals from core
uiInterface.InitMessage.connect(InitMessage);
bool ret = true;
#ifdef ENABLE_WALLET
// Check if the wallet exists or need to be created
std::string strWalletFile = GetArg("-wallet", "wallet.dat");
std::string strDataDir = GetDataDir().string();
// Wallet file must be a plain filename without a directory
fs::path wallet_file_path(strWalletFile);
if (strWalletFile != wallet_file_path.filename().string()) {
throw std::runtime_error(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
}
fs::path pathBootstrap = GetDataDir() / strWalletFile;
if (!fs::exists(pathBootstrap)) {
// wallet doesn't exist, popup tutorial screen.
ret = app.createTutorialScreen();
}
#endif
if(!ret){
// wallet not loaded.
return 0;
}
if (GetBoolArg("-splash", true) && !GetBoolArg("-min", false))
app.createSplashScreen(networkStyle.data());
try {
app.createWindow(networkStyle.data());
app.requestInitialize();
#if defined(Q_OS_WIN)
WinShutdownMonitor::registerShutdownBlockReason(QObject::tr("IQCASH Core didn't yet exit safely..."), (HWND)app.getMainWinId());
#endif
app.exec();
app.requestShutdown();
app.exec();
} catch (const std::exception& e) {
PrintExceptionContinue(&e, "Runaway exception");
app.handleRunawayException(QString::fromStdString(strMiscWarning));
} catch (...) {
PrintExceptionContinue(NULL, "Runaway exception");
app.handleRunawayException(QString::fromStdString(strMiscWarning));
}
return app.getReturnValue();
}
#endif // BITCOIN_QT_TEST
|
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/builtins/builtins-utils-gen.h"
#include "src/builtins/builtins.h"
#include "src/code-stub-assembler.h"
#include "src/ic/handler-compiler.h"
#include "src/ic/ic.h"
#include "src/ic/keyed-store-generic.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
TF_BUILTIN(KeyedLoadIC_IndexedString, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* index = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
Label miss(this);
Node* index_intptr = TryToIntptr(index, &miss);
Node* length = SmiUntag(LoadStringLength(receiver));
GotoIf(UintPtrGreaterThanOrEqual(index_intptr, length), &miss);
Node* code = StringCharCodeAt(receiver, index_intptr, INTPTR_PARAMETERS);
Node* result = StringFromCharCode(code);
Return(result);
Bind(&miss);
TailCallRuntime(Runtime::kKeyedLoadIC_Miss, context, receiver, index, slot,
vector);
}
TF_BUILTIN(KeyedLoadIC_Miss, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kKeyedLoadIC_Miss, context, receiver, name, slot,
vector);
}
TF_BUILTIN(KeyedLoadIC_Slow, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kKeyedGetProperty, context, receiver, name);
}
void Builtins::Generate_KeyedStoreIC_Megamorphic(
compiler::CodeAssemblerState* state) {
KeyedStoreGenericGenerator::Generate(state, SLOPPY);
}
void Builtins::Generate_KeyedStoreIC_Megamorphic_Strict(
compiler::CodeAssemblerState* state) {
KeyedStoreGenericGenerator::Generate(state, STRICT);
}
void Builtins::Generate_StoreIC_Uninitialized(
compiler::CodeAssemblerState* state) {
StoreICUninitializedGenerator::Generate(state, SLOPPY);
}
void Builtins::Generate_StoreICStrict_Uninitialized(
compiler::CodeAssemblerState* state) {
StoreICUninitializedGenerator::Generate(state, STRICT);
}
TF_BUILTIN(KeyedStoreIC_Miss, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* value = Parameter(Descriptor::kValue);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kKeyedStoreIC_Miss, context, value, slot, vector,
receiver, name);
}
TF_BUILTIN(KeyedStoreIC_Slow, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* value = Parameter(Descriptor::kValue);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
// The slow case calls into the runtime to complete the store without causing
// an IC miss that would otherwise cause a transition to the generic stub.
TailCallRuntime(Runtime::kKeyedStoreIC_Slow, context, value, slot, vector,
receiver, name);
}
TF_BUILTIN(LoadGlobalIC_Miss, CodeStubAssembler) {
Node* name = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kLoadGlobalIC_Miss, context, name, slot, vector);
}
TF_BUILTIN(LoadGlobalIC_Slow, CodeStubAssembler) {
Node* name = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kLoadGlobalIC_Slow, context, name, slot, vector);
}
void Builtins::Generate_LoadIC_Getter_ForDeopt(MacroAssembler* masm) {
NamedLoadHandlerCompiler::GenerateLoadViaGetterForDeopt(masm);
}
TF_BUILTIN(LoadIC_FunctionPrototype, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
Label miss(this);
Node* proto_or_map =
LoadObjectField(receiver, JSFunction::kPrototypeOrInitialMapOffset);
GotoIf(IsTheHole(proto_or_map), &miss);
Variable var_result(this, MachineRepresentation::kTagged, proto_or_map);
Label done(this, &var_result);
GotoIfNot(IsMap(proto_or_map), &done);
var_result.Bind(LoadMapPrototype(proto_or_map));
Goto(&done);
Bind(&done);
Return(var_result.value());
Bind(&miss);
TailCallRuntime(Runtime::kLoadIC_Miss, context, receiver, name, slot, vector);
}
TF_BUILTIN(LoadIC_Miss, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kLoadIC_Miss, context, receiver, name, slot, vector);
}
TF_BUILTIN(LoadIC_Slow, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kGetProperty, context, receiver, name);
}
TF_BUILTIN(StoreIC_Miss, CodeStubAssembler) {
Node* receiver = Parameter(Descriptor::kReceiver);
Node* name = Parameter(Descriptor::kName);
Node* value = Parameter(Descriptor::kValue);
Node* slot = Parameter(Descriptor::kSlot);
Node* vector = Parameter(Descriptor::kVector);
Node* context = Parameter(Descriptor::kContext);
TailCallRuntime(Runtime::kStoreIC_Miss, context, value, slot, vector,
receiver, name);
}
void Builtins::Generate_StoreIC_Setter_ForDeopt(MacroAssembler* masm) {
NamedStoreHandlerCompiler::GenerateStoreViaSetterForDeopt(masm);
}
} // namespace internal
} // namespace v8
|
/******************************************************************************
* Copyright (c) Intel Corporation - All rights reserved. *
* This file is part of the LIBXSMM library. *
* *
* For information on the license, see the LICENSE file. *
* Further information: https://github.com/hfp/libxsmm/ *
* SPDX-License-Identifier: BSD-3-Clause *
******************************************************************************/
/* Narendra Chaudhary, Dhiraj Kalamkar (Intel Corp.)
******************************************************************************/
#include<immintrin.h>
// #include<x86intrin.h>
#include<iostream>
#include<stdio.h>
// #include<stdlib.h>
#include<torch/extension.h>
#include<tuple>
#include<omp.h>
#include<libxsmm.h>
#include<libxsmm_intrinsics_x86.h>
// #include <torch/csrc/autograd/record_function.h>
#include <ATen/record_function.h>
#define PCL_ASSERT(cond, x...) do { if(!(cond)) { printf(x); fflush(stdout); exit(1); } } while(0)
#define XS_TILE_FORWARD 64
#define XS_TILE_DBACKWARD 64
#define XS_TILE_WBACKWARD 64 // 256 for peak performance
at::Tensor Conv1dOpti_forward_bf16_libxsmm(at::Tensor& input, at::Tensor& weight, int dilation){
// RECORD_FUNCTION("Conv1dOpti_forward_bf16", std::vector<c10::IValue>({input, weight})); // For recording time
int64_t N_t = input.size(0); // Batch
int64_t C_t = input.size(1); // Channel
int64_t Win_t = input.size(2); // input width
int64_t F_t = weight.size(0); // Number of filters
int64_t WW_t = weight.size(2); // filter width
int64_t dial = dilation; // dilation parameter
int64_t pad_size = ((WW_t- 1))*dial; // Total padding size
int64_t W_t = Win_t - pad_size; // output width
auto Y = input.new_empty({N_t,F_t,W_t}); // New tensor for output
libxsmm_bfloat16* input_a = (libxsmm_bfloat16*) input.data_ptr<at::BFloat16>(); // Get BFloat16 data pointers for accessing tensors
libxsmm_bfloat16* weight_a = (libxsmm_bfloat16*) weight.data_ptr<at::BFloat16>();
libxsmm_bfloat16* Y_a = (libxsmm_bfloat16*) Y.data_ptr<at::BFloat16>();
auto flip_weight = weight.new_empty({WW_t,F_t,C_t}); // Weight tensor with permuted dimension (width, filters, channels)
libxsmm_bfloat16* flip_weight_a = (libxsmm_bfloat16*) flip_weight.data_ptr<at::BFloat16>(); // Get BFloat16 data pointers for accessing the tensor
/* jited tranpose to permute the array dimensions
Overall convert (F_t, C_t, WW_t) -----> (WW_t, F_t, C_t)*/
libxsmm_blasint per_m = WW_t;
libxsmm_blasint per_n = F_t*C_t;
libxsmm_blasint per_ldi = WW_t;
libxsmm_blasint per_ldo = F_t*C_t;
libxsmm_meltwfunction_unary trans_permute_kernel = libxsmm_dispatch_meltw_unary(per_m, per_n, &per_ldi, &per_ldo, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_kernel == NULL) {
fprintf( stderr, "JIT unary TPP for NORM_TO_NORMT. Bailing...!\n");
exit(-1);
}
libxsmm_meltw_unary_param trans_permute_param;
trans_permute_param.in.primary = weight_a;
trans_permute_param.out.primary = flip_weight_a;
trans_permute_kernel( &trans_permute_param);
int lda = C_t; // Input channels (16)
int ldb = Win_t; // Input width (60400)
int ldc = W_t; // Output width (60000)
unsigned long long l_br = WW_t; // Number of batches in brGEMM (= width of kernel = 51)
int tile_multiple = (W_t/XS_TILE_FORWARD)*XS_TILE_FORWARD; // Number of blocks/Tiles in the output width
int short_width = ((XS_TILE_FORWARD + (WW_t-1)*dial)/XS_TILE_FORWARD + 1)*XS_TILE_FORWARD; // width of short buffer
auto input_shortvnni = input.new_empty({N_t,C_t,short_width}); // VNNI transformed array of the short buffer
libxsmm_bfloat16* input_a_shortvnni = (libxsmm_bfloat16*) input_shortvnni.data_ptr<at::BFloat16>(); // Get pointer
int edge_width = (((W_t - tile_multiple) + (WW_t-1)*dial)/XS_TILE_FORWARD + 1)*XS_TILE_FORWARD; // width of buffer in the edge case (last block)
auto input_edgevnni = input.new_empty({N_t,C_t,edge_width}); // VNNI VNNI transformed array of the edge buffer
libxsmm_bfloat16* input_a_edgevnni = (libxsmm_bfloat16*) input_edgevnni.data_ptr<at::BFloat16>(); // Get pointer
/* Dispatch brGEMM kernels for the normal case and the edge case*/
libxsmm_bmmfunction_reducebatch_strd bmmshortkernel = libxsmm_bmmdispatch_reducebatch_strd(XS_TILE_FORWARD, F_t, C_t, dial*2*sizeof(libxsmm_bfloat16), F_t*C_t*sizeof(libxsmm_bfloat16), &short_width, &lda, &ldc, NULL, NULL, NULL, NULL);
libxsmm_bmmfunction_reducebatch_strd bmmedgekernel2 = libxsmm_bmmdispatch_reducebatch_strd(W_t - tile_multiple, F_t, C_t, dial*2*sizeof(libxsmm_bfloat16), F_t*C_t*sizeof(libxsmm_bfloat16), &edge_width, &lda, &ldc, NULL, NULL, NULL, NULL);
/* JIT eltwise TPPs for initialization ... */
libxsmm_blasint tpp_m1 = XS_TILE_FORWARD; // columns
libxsmm_blasint tpp_m2 = W_t - tile_multiple; // columns
libxsmm_blasint tpp_n = F_t; // rows
libxsmm_blasint ld_zero = W_t;
libxsmm_meltwfunction_unary copy_kernel_1 = libxsmm_dispatch_meltw_unary(tpp_m1, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
libxsmm_meltwfunction_unary copy_kernel_2 = libxsmm_dispatch_meltw_unary(tpp_m2, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( copy_kernel_1 == NULL || copy_kernel_2 == NULL) {
fprintf( stderr, "JIT for initialization by unary copy kernel failed. Bailing...!\n");
exit(-1);
}
/* use jited VNNI */
libxsmm_blasint ldi = Win_t;
libxsmm_blasint ldo_short = short_width;
libxsmm_blasint ldo_edge = edge_width;
libxsmm_meltw_unary_type trans_vnni_type;
if ( C_t % 2 == 1 ) {
trans_vnni_type = LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI_PAD;
} else {
trans_vnni_type = LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI;
}
tpp_m1 = (XS_TILE_FORWARD + dial*(WW_t-1));
tpp_m2 = (W_t - tile_multiple + dial*(WW_t-1));
libxsmm_meltwfunction_unary trans_shortvnni_kernel = libxsmm_dispatch_meltw_unary(tpp_m1, C_t, &ldi, &ldo_short, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, trans_vnni_type);
libxsmm_meltwfunction_unary trans_edgevnni_kernel = libxsmm_dispatch_meltw_unary(tpp_m2, C_t, &ldi, &ldo_edge, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, trans_vnni_type);
if ( trans_shortvnni_kernel == NULL | trans_edgevnni_kernel == NULL) {
fprintf( stderr, "JIT for NORM_TO_VNNI TPP. Bailing...!\n");
exit(-1);
}
// Main compute loop
#pragma omp parallel for
for(int n = 0; n < N_t; n++) { // Loop for batches
int last_block = 0;
libxsmm_meltw_unary_param copy_params_1; // Copy parameter variable for holding the pointer
libxsmm_meltw_unary_param copy_params_2;
libxsmm_meltw_unary_param trans_param_short;
libxsmm_meltw_unary_param trans_param_edge;
for(int wb = 0; wb < W_t - XS_TILE_FORWARD + 1; wb += XS_TILE_FORWARD) { // width blocking loop (Normal case)
copy_params_1.out.primary = &Y_a[n*F_t*W_t + wb]; /* Initialization of output array */
copy_kernel_1(©_params_1);
// VNNI transform
trans_param_short.in.primary = &input_a[n*C_t*Win_t + 0*Win_t + wb];
trans_param_short.out.primary = &input_a_shortvnni[n*C_t*short_width];
trans_shortvnni_kernel( &trans_param_short );
// brGEMM
bmmshortkernel(&input_a_shortvnni[n*C_t*short_width], &flip_weight_a[0], &Y_a[n*F_t*W_t + 0*W_t + wb], &l_br);
last_block = wb; // Store value for last block
}
if (W_t % XS_TILE_FORWARD != 0){ // Edge case
copy_params_2.out.primary = &Y_a[n*F_t*W_t + last_block + XS_TILE_FORWARD]; /* Initialization of output array */
copy_kernel_2(©_params_2);
// VNNI transform
trans_param_edge.in.primary = &input_a[n*C_t*Win_t + 0*Win_t + (last_block + XS_TILE_FORWARD)];
trans_param_edge.out.primary = &input_a_edgevnni[n*C_t*edge_width];
trans_edgevnni_kernel( &trans_param_edge );
// brGEMM
bmmedgekernel2(&input_a_edgevnni[n*C_t*edge_width], &flip_weight_a[0], &Y_a[n*F_t*W_t + 0*W_t + (last_block + XS_TILE_FORWARD)], &l_br);
}
}
return Y; // Return output tensorcd
}
std::tuple<at::Tensor, at::Tensor> Conv1dOpti_backward_bf16_libxsmm(at::Tensor& grad, at::Tensor& input, at::Tensor& weight, int dilation){
// RECORD_FUNCTION("Conv1dOpti_backward_bf16", std::vector<c10::IValue>({grad, input, weight})); // For recording time
int64_t N_t = input.size(0); // Batch
int64_t C_t = input.size(1); // Channel
int64_t Win_t = input.size(2); // input width
int64_t F_t = weight.size(0); // Number of filters
int64_t WW_t = weight.size(2); // filter width
int64_t dial = dilation; // dilation parameter
int64_t pad_size = ((WW_t- 1))*dial; // Total padding size
int64_t W_t = Win_t - pad_size; // output width
auto d_input = input.new_empty({N_t,C_t,Win_t}); // declare data gradiant tensor
auto d_weight = weight.new_empty({F_t,C_t,WW_t}); // declare weight gradiant tensor
libxsmm_bfloat16* input_a = (libxsmm_bfloat16*) input.data_ptr<at::BFloat16>(); // Get BFloat16 data pointers for accessing tensors
libxsmm_bfloat16* weight_a = (libxsmm_bfloat16*) weight.data_ptr<at::BFloat16>();
libxsmm_bfloat16* grad_a = (libxsmm_bfloat16*) grad.data_ptr<at::BFloat16>();
libxsmm_bfloat16* d_input_a = (libxsmm_bfloat16*) d_input.data_ptr<at::BFloat16>();
libxsmm_bfloat16* d_weight_a = (libxsmm_bfloat16*) d_weight.data_ptr<at::BFloat16>();
/* Backward Data part of the code */
auto flip_weight_tensor = weight.new_empty({WW_t,C_t,F_t}); // Weight tensor with permuted dimension (width, channels, filters)
libxsmm_bfloat16* flip_weight_a = (libxsmm_bfloat16*) flip_weight_tensor.data_ptr<at::BFloat16>(); // Get pointer
auto weight_buffer = weight.new_empty({F_t,C_t,WW_t}); // Tensor weight buffer
libxsmm_bfloat16* weight_buffer_a = (libxsmm_bfloat16*) weight_buffer.data_ptr<at::BFloat16>();
#pragma omp parallel for
for(int i = 0; i < F_t*C_t; i++){
for(int kw = 0; kw < WW_t; kw++){ // reverse copy
flip_weight_a[i*WW_t + kw] = weight_a[i*WW_t + WW_t - kw - 1];
}
}
/* jited tranpose to permute the array dimensions
Overall convert (F_t, C_t, WW_t) -----> (WW_t, C_t, F_t)*/
libxsmm_blasint flip_m1 = WW_t;
libxsmm_blasint flip_n1 = F_t*C_t;
libxsmm_blasint flip_ldi_1 = WW_t;
libxsmm_blasint flip_ldo_1 = F_t*C_t;
libxsmm_meltwfunction_unary trans_flip_1 = libxsmm_dispatch_meltw_unary(flip_m1, flip_n1, &flip_ldi_1, &flip_ldo_1, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_flip_1 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (F_t, C_t, WW_t) -----> (WW_t, F_t, C_t)
libxsmm_meltw_unary_param trans_param_flip_1;
trans_param_flip_1.in.primary = flip_weight_a;
trans_param_flip_1.out.primary = weight_buffer_a;
trans_flip_1( &trans_param_flip_1 );
libxsmm_blasint flip_m2 = C_t;
libxsmm_blasint flip_n2 = F_t;
libxsmm_blasint flip_ldi_2 = C_t;
libxsmm_blasint flip_ldo_2 = F_t;
libxsmm_meltwfunction_unary trans_flip_2 = libxsmm_dispatch_meltw_unary(flip_m2, flip_n2, &flip_ldi_2, &flip_ldo_2, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_flip_2 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, F_t, C_t) -----> (F_t, C_t, WW_t)
#pragma omp parallel for
for(int kw = 0; kw < WW_t; kw++){ // permute last two dimensions
libxsmm_meltw_unary_param trans_param_flip_2;
trans_param_flip_2.in.primary = &weight_buffer_a[kw*C_t*F_t];
trans_param_flip_2.out.primary = &flip_weight_a[kw*C_t*F_t];
trans_flip_2( &trans_param_flip_2 );
}
int64_t Wpad_t = W_t + 2*(WW_t - 1)*dial; // For padding gradiant on both sides
int64_t tile_multiple = (Win_t/XS_TILE_DBACKWARD)*XS_TILE_DBACKWARD; // Number of blocks/tiles in Input
int lda = F_t; // Number of Filters (16)
int ldb_orig = W_t; // Output width (60000)
int ldb = Wpad_t; // Extra padded grad input case 60800
int ldc = Win_t; // Input width (60400)
unsigned long long l_br = WW_t; // Number of batches in brGEMM (= width of kernel = 51)
int pad_tile_multiple = 2 * (((WW_t - 1)*dial)/XS_TILE_DBACKWARD + 1) * XS_TILE_DBACKWARD; // Padded block/tile (896)
int ldb_shortpad = 2*pad_tile_multiple; // grad padded short buffer (1792)
auto grad_shortpad_tensor = grad.new_empty({N_t,F_t,2*pad_tile_multiple});
libxsmm_bfloat16* grad_a_shortpad = (libxsmm_bfloat16*) grad_shortpad_tensor.data_ptr<at::BFloat16>(); // short buffer for padded gradiant
// #ifdef USE_TPP
// Virtual copy kernels
libxsmm_blasint virtual_m1 = pad_tile_multiple - ((WW_t - 1)*dial); // columns
libxsmm_blasint virtual_m2 = ((WW_t - 1)*dial); // columns
libxsmm_blasint virtual_n = F_t; // rows
libxsmm_blasint ldi_virtual = W_t;
libxsmm_blasint ldo_virtual = 2*pad_tile_multiple;
if (ldi_virtual < virtual_m1){ // corner case when width's are very small
virtual_m1 = ldi_virtual;
libxsmm_meltwfunction_unary all_zero = libxsmm_dispatch_meltw_unary(ldo_virtual, virtual_n, NULL, &ldo_virtual, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( all_zero == NULL) {
fprintf( stderr, "JIT for initialization by unary virtual all zero kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++){
libxsmm_meltw_unary_param all_zero_params;
all_zero_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual]; // Initialize the entire array when widths are small
all_zero(&all_zero_params);
}
}
libxsmm_meltwfunction_unary virtual_copy = libxsmm_dispatch_meltw_unary(virtual_m1, virtual_n, &ldi_virtual, &ldo_virtual, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY);
libxsmm_meltwfunction_unary virtual_copy_zero = libxsmm_dispatch_meltw_unary(virtual_m2, virtual_n, NULL, &ldo_virtual, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( virtual_copy == NULL || virtual_copy_zero == NULL) {
fprintf( stderr, "JIT for initialization by unary virtual copy kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++){ // Loops for storing the edge portion of gradinant array into grad_a_shortpad
libxsmm_meltw_unary_param vcopy_params; // Copy parameter variable for holding the pointer
libxsmm_meltw_unary_param vcopy_params_zero;
vcopy_params_zero.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual]; // copy zeros
virtual_copy_zero(&vcopy_params_zero);
vcopy_params.in.primary = &grad_a[n*F_t*W_t]; // copy after zeros from start of the grad array
vcopy_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ((WW_t - 1)*dial)];
virtual_copy(&vcopy_params);
vcopy_params.in.primary = &grad_a[n*F_t*W_t + W_t - virtual_m1]; // copy from the end of the grad array
vcopy_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ldo_virtual - virtual_m1 - ((WW_t - 1)*dial)];
virtual_copy(&vcopy_params);
vcopy_params_zero.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ldo_virtual - ((WW_t - 1)*dial)]; // copy zeros
virtual_copy_zero(&vcopy_params_zero);
}
// #else
// #pragma omp parallel for
// for(int n = 0; n < N_t; n++){ // loop to store the edges for gradiant array into grad_a_shortpad buffer
// for(int filter=0; filter < F_t; filter++){
// for(int w = 0; w < pad_tile_multiple; w++){
// // initialize start of array
// if (w >= ((WW_t - 1)*dial) && w < (W_t + (WW_t - 1)*dial)){
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w] = grad_a[n*F_t*W_t + filter*W_t + w - (WW_t - 1)*dial];
// }
// else{
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w] = 0.0f;
// }
// }
// for(int w = Wpad_t - pad_tile_multiple; w < Wpad_t ; w++){
// // initialize end of array
// if (w >= ((WW_t - 1)*dial) && w < (W_t + (WW_t - 1)*dial)){
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w - Wpad_t + 2*pad_tile_multiple] = grad_a[n*F_t*W_t + filter*W_t + w - (WW_t - 1)*dial];
// }
// else{
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w - Wpad_t + 2*pad_tile_multiple] = 0.0f;
// }
// }
// }
// }
// #endif
int short_width = ((XS_TILE_DBACKWARD + (WW_t-1)*dial)/XS_TILE_DBACKWARD + 1)*XS_TILE_DBACKWARD; // Width of buffer (512)
auto grad_shortvnni_tensor = grad.new_empty({N_t,F_t,short_width}); // Buffer for storing VNNI transform
libxsmm_bfloat16* grad_a_shortvnni = (libxsmm_bfloat16*) grad_shortvnni_tensor.data_ptr<at::BFloat16>();
/* Dispatch brGEMM kernels for the normal case and the edge case*/
libxsmm_bmmfunction_reducebatch_strd bmmshortkernel = libxsmm_bmmdispatch_reducebatch_strd(XS_TILE_DBACKWARD, C_t, F_t, 2*dial*sizeof(libxsmm_bfloat16), C_t*F_t*sizeof(libxsmm_bfloat16), &short_width, &lda, &ldc, NULL, NULL, NULL, NULL);
libxsmm_bmmfunction_reducebatch_strd bmmshortkernel2 = libxsmm_bmmdispatch_reducebatch_strd(Win_t - tile_multiple, C_t, F_t, 2*dial*sizeof(libxsmm_bfloat16), C_t*F_t*sizeof(libxsmm_bfloat16), &short_width, &lda, &ldc, NULL, NULL, NULL, NULL);
if ( bmmshortkernel == NULL || bmmshortkernel2 == NULL) {
fprintf( stderr, "JIT for bmm kernel failed. Bailing...!\n");
exit(-1);
}
/* JIT eltwise TPPs for initialization ... */
libxsmm_blasint tpp_m1 = XS_TILE_DBACKWARD; // columns
libxsmm_blasint tpp_m2 = Win_t - tile_multiple; // columns
libxsmm_blasint tpp_n = C_t; // rows
libxsmm_blasint ld_zero = Win_t;
libxsmm_meltwfunction_unary copy_kernel_1 = libxsmm_dispatch_meltw_unary(tpp_m1, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
libxsmm_meltwfunction_unary copy_kernel_2 = libxsmm_dispatch_meltw_unary(tpp_m2, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( copy_kernel_1 == NULL || copy_kernel_2 == NULL) {
fprintf( stderr, "JIT for initialization by unary copy kernel failed. Bailing...!\n");
exit(-1);
}
/* use jited VNNI */
libxsmm_blasint ldi_1 = W_t;
libxsmm_blasint ldi_2 = ldb_shortpad; // (1792)
libxsmm_blasint ldo = short_width; // (512)
libxsmm_meltw_unary_type trans_vnni_type;
if ( F_t % 2 == 1 ) {
trans_vnni_type = LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI_PAD;
} else {
trans_vnni_type = LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_VNNI;
}
tpp_m1 = (XS_TILE_DBACKWARD + dial*(WW_t-1));
tpp_m2 = (XS_TILE_DBACKWARD + dial*(WW_t-1));
libxsmm_meltwfunction_unary trans_shortvnni_kernel_1 = libxsmm_dispatch_meltw_unary(tpp_m1, F_t, &ldi_1, &ldo, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, trans_vnni_type);
libxsmm_meltwfunction_unary trans_shortvnni_kernel_2 = libxsmm_dispatch_meltw_unary(tpp_m2, F_t, &ldi_2, &ldo, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, trans_vnni_type);
if ( trans_shortvnni_kernel_1 == NULL | trans_shortvnni_kernel_2 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_VNNI TPP. Bailing...!\n");
exit(-1);
}
// Main computation loop
#pragma omp parallel for
for(int n = 0; n < N_t; n++) {
int last_block=0;
libxsmm_meltw_unary_param copy_params_1; // Copy parameter variable for holding the pointer
libxsmm_meltw_unary_param copy_params_2;
libxsmm_meltw_unary_param trans_param_1;
libxsmm_meltw_unary_param trans_param_2;
for(int wb = 0; wb < Win_t - XS_TILE_DBACKWARD + 1; wb += XS_TILE_DBACKWARD) {
copy_params_1.out.primary = &d_input_a[n*C_t*Win_t + wb]; // Initialization
copy_kernel_1(©_params_1);
if (wb >= (WW_t-1)*dial && wb < Win_t - (WW_t-1)*dial - XS_TILE_DBACKWARD){
// Normal case (Take VNNI transform of a portion of grad_a array )
// VNNI transform
trans_param_1.in.primary = &grad_a[n*F_t*W_t + 0*W_t + wb - (WW_t-1)*dial];
trans_param_1.out.primary = &grad_a_shortvnni[n*F_t*short_width];
trans_shortvnni_kernel_1( &trans_param_1 );
// brGEMM
bmmshortkernel(&grad_a_shortvnni[n*F_t*short_width], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + 0*Win_t + wb], &l_br);
}
else if (wb < (WW_t-1)*dial){
// Right side case (Take VNNI transform of grad_a_shortpad array)
// VNNI transform
trans_param_2.in.primary = &grad_a_shortpad[n*F_t*2*pad_tile_multiple + wb];
trans_param_2.out.primary = &grad_a_shortvnni[n*F_t*short_width];
trans_shortvnni_kernel_2( &trans_param_2 );
// brGEMM
bmmshortkernel(&grad_a_shortvnni[n*F_t*short_width], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + 0*Win_t + wb], &l_br);
}
else{
// Left side case (Take VNNI transform of grad_a_shortpad array)
// VNNI transform
trans_param_2.in.primary = &grad_a_shortpad[n*F_t*2*pad_tile_multiple + wb - Wpad_t + 2*pad_tile_multiple];
trans_param_2.out.primary = &grad_a_shortvnni[n*F_t*short_width];
trans_shortvnni_kernel_2( &trans_param_2 );
// brGEMM
bmmshortkernel(&grad_a_shortvnni[n*F_t*short_width], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + 0*Win_t + wb], &l_br);
}
last_block = wb;
}
if (Win_t % XS_TILE_DBACKWARD != 0){ // Edge case
// Right side case (Take VNNI transform of grad_a_shortpad array)
copy_params_2.out.primary = &d_input_a[n*C_t*Win_t + last_block + XS_TILE_DBACKWARD]; // Initialization
copy_kernel_2(©_params_2);
// VNNI transform
trans_param_2.in.primary = &grad_a_shortpad[n*F_t*2*pad_tile_multiple + last_block + XS_TILE_DBACKWARD - Wpad_t + 2*pad_tile_multiple];
trans_param_2.out.primary = &grad_a_shortvnni[n*F_t*short_width];
trans_shortvnni_kernel_2( &trans_param_2 );
// brGEMM
bmmshortkernel2(&grad_a_shortvnni[n*F_t*short_width], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + last_block + XS_TILE_DBACKWARD], &l_br);
}
}
/* Backward Weight part of the code */
float* flip_d_weight_a = (float*) libxsmm_aligned_malloc( F_t*C_t*WW_t*sizeof(float), 64 ); // Array for permuted weight gradiant
for(int w = 0; w < F_t*C_t*WW_t; w++){ // Initialize array
flip_d_weight_a[w] = 0.0f;
}
// lda = W_t; // Already defined variables
// ldb = Win_t;
// ldc = C_t;
l_br = WW_t; // Number of batches in brGEMM (= width of kernel = 51)
tile_multiple = (W_t/XS_TILE_WBACKWARD)*XS_TILE_WBACKWARD;
// Blocking on grad_a
int lda_g = Win_t;
int ldb_trans_g = F_t;
int ldc_g = F_t;
libxsmm_blasint M_g = W_t/2;
libxsmm_blasint N_g = F_t;
libxsmm_blasint short_W_t = XS_TILE_WBACKWARD;
libxsmm_blasint edge_W_t = W_t - tile_multiple;
auto grad_shortvnni_tensor2 = grad.new_empty({N_t,F_t,short_W_t}); // Short buffer for storing VNNI transform
libxsmm_bfloat16* grad_shortvnni = (libxsmm_bfloat16*) grad_shortvnni_tensor2.data_ptr<at::BFloat16>();
auto grad_edgevnni_tensor2 = grad.new_empty({N_t,F_t,edge_W_t}); // Short buffer for storing VNNI transform in edge case
libxsmm_bfloat16* grad_edgevnni = (libxsmm_bfloat16*) grad_edgevnni_tensor2.data_ptr<at::BFloat16>();
/* use jited tranpose */
libxsmm_meltwfunction_unary trans_shortkernel_grad = libxsmm_dispatch_meltw_unary(short_W_t/2, N_g, &M_g, &N_g, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
libxsmm_meltwfunction_unary trans_edgekernel_grad = libxsmm_dispatch_meltw_unary(edge_W_t/2, N_g, &M_g, &N_g, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_shortkernel_grad == NULL | trans_edgekernel_grad == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
/* Dispatch brGEMM kernels for the normal case and the edge case*/
libxsmm_bsmmfunction bsmmkernel5 = libxsmm_bsmmdispatch(F_t, C_t, XS_TILE_WBACKWARD, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
libxsmm_bsmmfunction bsmmkernel6 = libxsmm_bsmmdispatch(F_t, C_t, W_t - tile_multiple, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
if ( bsmmkernel5 == NULL | bsmmkernel6 == NULL) {
fprintf( stderr, "JIT for bsmm kernel. Bailing...!\n");
exit(-1);
}
// Main compute loop
#pragma omp parallel for reduction(+: flip_d_weight_a[:F_t*C_t*WW_t])
for(int n = 0; n < N_t; n++) {
int last_block = 0;
libxsmm_meltw_unary_param trans_param_short;
libxsmm_meltw_unary_param trans_param_edge;
for(int wb = 0; wb < W_t - XS_TILE_WBACKWARD + 1; wb += XS_TILE_WBACKWARD) { // Normal Case
/* Take transpose assumping FP32 (This will do both transpose and VNNI transform for BF16) */
trans_param_short.in.primary = &grad_a[n*F_t*W_t + wb];
trans_param_short.out.primary = &grad_shortvnni[n*F_t*short_W_t];
trans_shortkernel_grad( &trans_param_short );
for(int kw = 0; kw < WW_t; kw++) {
// libxsmm_bsmmfunction bsmmkernel5 = libxsmm_bsmmdispatch(F_t, C_t, XS_TILE_WBACKWARD, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
bsmmkernel5(&grad_shortvnni[n*F_t*short_W_t], &input_a[n*C_t*Win_t + wb + kw*dial], &flip_d_weight_a[kw*C_t*F_t]);
}
last_block = wb;
}
if (W_t % XS_TILE_WBACKWARD != 0){ // Edge Case
trans_param_edge.in.primary = &grad_a[n*F_t*W_t + last_block + XS_TILE_WBACKWARD];
trans_param_edge.out.primary = &grad_edgevnni[n*F_t*edge_W_t];
trans_edgekernel_grad( &trans_param_edge );
for(int kw = 0; kw < WW_t; kw++) {
// libxsmm_bsmmfunction bsmmkernel6 = libxsmm_bsmmdispatch(F_t, C_t, W_t - tile_multiple, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
bsmmkernel6(&grad_edgevnni[n*F_t*edge_W_t], &input_a[n*C_t*Win_t + (last_block + XS_TILE_WBACKWARD) + kw*dial], &flip_d_weight_a[kw*F_t*C_t]);
}
}
}
auto flip_d_weight_tensor = weight.new_empty({WW_t,C_t,F_t});
libxsmm_bfloat16* flip_d_weight_bf16 = (libxsmm_bfloat16*) flip_d_weight_tensor.data_ptr<at::BFloat16>();
/* JIT eltwise TPPs for FP32 to BF16 conversion... */
libxsmm_blasint cvt_m = 1;
libxsmm_blasint cvt_n = F_t*C_t*WW_t;
libxsmm_meltwfunction_unary eltwise_kernel = libxsmm_dispatch_meltw_unary(cvt_m, cvt_n, NULL, NULL, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY);
if ( eltwise_kernel == NULL ) {
fprintf( stderr, "JIT for TPP convert FP32 to BF16 failed. Bailing...!\n");
exit(-1);
}
libxsmm_meltw_unary_param eltwise_params;
eltwise_params.in.primary = flip_d_weight_a;
eltwise_params.out.primary = flip_d_weight_bf16;
eltwise_kernel(&eltwise_params);
/* jited tranpose to permute the array dimensions
Overall Convert (WW_t, C_t, F_t) -----> (F_t, C_t, WW_t)*/
libxsmm_blasint per_m1 = F_t;
libxsmm_blasint per_n1 = C_t;
libxsmm_blasint ldi_per_1 = F_t;
libxsmm_blasint ldo_per_1 = C_t;
libxsmm_meltwfunction_unary trans_permute_1 = libxsmm_dispatch_meltw_unary(per_m1, per_n1, &ldi_per_1, &ldo_per_1, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_1 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, C_t, F_t) -----> (WW_t, F_t, C_t)
#pragma omp parallel for
for(int kw = 0; kw < WW_t; kw++){ // permute last two dimensions
libxsmm_meltw_unary_param trans_param_permute_1;
trans_param_permute_1.in.primary = &flip_d_weight_bf16[kw*C_t*F_t];
trans_param_permute_1.out.primary = &flip_weight_a[kw*C_t*F_t];
trans_permute_1( &trans_param_permute_1 );
}
libxsmm_blasint per_m2 = F_t*C_t;
libxsmm_blasint per_n2 = WW_t;
libxsmm_blasint ldi_per_2 = F_t*C_t;
libxsmm_blasint ldo_per_2 = WW_t;
libxsmm_meltwfunction_unary trans_permute_2 = libxsmm_dispatch_meltw_unary(per_m2, per_n2, &ldi_per_2, &ldo_per_2, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_2 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, F_t, C_t) -----> (F_t, C_t, WW_t)
libxsmm_meltw_unary_param trans_param_permute_2;
trans_param_permute_2.in.primary = flip_weight_a;
trans_param_permute_2.out.primary = d_weight_a;
trans_permute_2( &trans_param_permute_2 );
libxsmm_free(flip_d_weight_a);
return {d_input, d_weight};
}
at::Tensor Conv1dOpti_forward_libxsmm(at::Tensor& input, at::Tensor& weight, int dilation){
// RECORD_FUNCTION("Conv1dOpti_forward_libxsmm", std::vector<c10::IValue>({input, weight})); // For recording time
int64_t N_t = input.size(0); // Batch
int64_t C_t = input.size(1); // Channel
int64_t Win_t = input.size(2); // input width
int64_t F_t = weight.size(0); // Number of filters
int64_t WW_t = weight.size(2); // filter width
int64_t dial = dilation; // dilation parameter
int64_t pad_size = ((WW_t- 1))*dial; // Total padding size
int64_t W_t = Win_t - pad_size; // output width
auto Y = input.new_empty({N_t,F_t,W_t}); // New tensor for output
float* input_a = input.data_ptr<float>(); // Get pointers for accessing the tensors
float* weight_a = weight.data_ptr<float>();
float* Y_a = Y.data_ptr<float>();
auto flip_weight = weight.new_empty({WW_t,F_t,C_t}); // Array to store permuted weight tensor (width, filters, channels)
float* flip_weight_a = flip_weight.data_ptr<float>();
/* jited tranpose to permute the array dimensions
Overall convert (F_t, C_t, WW_t) -----> (WW_t, F_t, C_t)*/
libxsmm_blasint per_m = WW_t;
libxsmm_blasint per_n = F_t*C_t;
libxsmm_blasint per_ldi = WW_t;
libxsmm_blasint per_ldo = F_t*C_t;
libxsmm_meltwfunction_unary trans_permute_kernel = libxsmm_dispatch_meltw_unary(per_m, per_n, &per_ldi, &per_ldo, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_kernel == NULL) {
fprintf( stderr, "JIT unary TPP for NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
libxsmm_meltw_unary_param trans_permute_param;
trans_permute_param.in.primary = weight_a;
trans_permute_param.out.primary = flip_weight_a;
trans_permute_kernel( &trans_permute_param);
int lda = C_t; // Input channels (15)
int ldb = Win_t; // Input width (60400)
int ldc = W_t; // Output width (60000)
unsigned long long l_br = WW_t;
int tile_multiple = (W_t/XS_TILE_FORWARD)*XS_TILE_FORWARD;
/* Dispatch brGEMM kernels for the normal case and the edge case*/
libxsmm_smmfunction_reducebatch_strd kernel = libxsmm_smmdispatch_reducebatch_strd(XS_TILE_FORWARD, F_t, C_t, dial*sizeof(float), F_t*C_t*sizeof(float), &ldb, &lda, &ldc, NULL, NULL, NULL, NULL);
libxsmm_smmfunction_reducebatch_strd kernel2 = libxsmm_smmdispatch_reducebatch_strd(W_t - tile_multiple, F_t, C_t, dial*sizeof(float), F_t*C_t*sizeof(float), &ldb, &lda, &ldc, NULL, NULL, NULL, NULL);
/* JIT eltwise TPPs for initialization... */
libxsmm_blasint tpp_m1 = XS_TILE_FORWARD; // columns
libxsmm_blasint tpp_m2 = W_t - tile_multiple; // columns
libxsmm_blasint tpp_n = F_t; // rows
libxsmm_blasint ld_zero = W_t;
libxsmm_meltw_unary_type unary_type;
unary_type = LIBXSMM_MELTW_TYPE_UNARY_XOR;
libxsmm_meltw_unary_flags unary_flags;
unary_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE;
libxsmm_meltwfunction_unary unary_kernel_1 = libxsmm_dispatch_meltw_unary(tpp_m1, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, unary_type);
libxsmm_meltwfunction_unary unary_kernel_2 = libxsmm_dispatch_meltw_unary(tpp_m2, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, unary_flags, unary_type);
if ( unary_kernel_1 == NULL || unary_kernel_2 == NULL) {
fprintf( stderr, "JIT for copy UNARY kernel. Bailing...!\n");
exit(-1);
}
// Main compute loop
#pragma omp parallel for
for(int n = 0; n < N_t; n++) { // Loop for batches
int last_block = 0;
libxsmm_meltw_unary_param unary_param_1;
libxsmm_meltw_unary_param unary_param_2;
for(int wb = 0; wb < W_t - XS_TILE_FORWARD + 1; wb += XS_TILE_FORWARD) { // width blocking loop (Normal case)
unary_param_1.out.primary = &Y_a[n*F_t*W_t + wb]; // Initialization
unary_kernel_1( &unary_param_1 );
kernel(&input_a[n*C_t*Win_t + 0*Win_t + wb], &flip_weight_a[0], &Y_a[n*F_t*W_t + 0*W_t + wb], &l_br);
last_block = wb;
}
if (W_t % XS_TILE_FORWARD != 0){ // Edge Case
unary_param_2.out.primary = &Y_a[n*F_t*W_t + last_block + XS_TILE_FORWARD]; // Initialization
unary_kernel_2( &unary_param_2 );
kernel2(&input_a[n*C_t*Win_t + 0*Win_t + last_block + XS_TILE_FORWARD], &flip_weight_a[0], &Y_a[n*F_t*W_t + 0*W_t + last_block + XS_TILE_FORWARD], &l_br);
}
}
return Y; // Return output array
}
std::tuple<at::Tensor, at::Tensor>
Conv1dOpti_backward_libxsmm(at::Tensor& grad, at::Tensor& input, at::Tensor& weight, int dilation){
// RECORD_FUNCTION("Conv1dOpti_backward_libxsmm", std::vector<c10::IValue>({grad, input, weight}));
int64_t N_t = input.size(0); // Batch
int64_t C_t = input.size(1); // Channel
int64_t Win_t = input.size(2); // input width
int64_t F_t = weight.size(0); // Number of filters
int64_t WW_t = weight.size(2); // filter width
int64_t dial = dilation; // dilation parameter
int64_t pad_size = ((WW_t- 1))*dial; // Total padding size
int64_t W_t = Win_t - pad_size; // output width
auto d_input = input.new_empty({N_t,C_t,Win_t}); // declare data gradiant tensor
auto d_weight = weight.new_empty({F_t,C_t,WW_t}); // declare weight gradiant tensor
float* input_a = input.data_ptr<float>(); // Get data pointers for accessing tensors
float* weight_a = weight.data_ptr<float>();
float* grad_a = grad.data_ptr<float>();
float* d_input_a = d_input.data_ptr<float>();
float* d_weight_a = d_weight.data_ptr<float>();
/* Backward data part of the code */
auto flip_weight = weight.new_empty({WW_t,C_t,F_t}); // Tensor for permuted weights (width, channels, filters)
float* flip_weight_a = flip_weight.data_ptr<float>();
auto weight_buffer = weight.new_empty({F_t,C_t,WW_t}); // Tensor weight buffer
float* weight_buffer_a = weight_buffer.data_ptr<float>();
#pragma omp parallel for
for(int i = 0; i < F_t*C_t; i++){
for(int kw = 0; kw < WW_t; kw++){ // reverse copy
flip_weight_a[i*WW_t + kw] = weight_a[i*WW_t + WW_t - kw - 1];
}
}
/* jited tranpose to permute the array dimensions
Overall convert (F_t, C_t, WW_t) -----> (WW_t, C_t, F_t)*/
libxsmm_blasint flip_m1 = WW_t;
libxsmm_blasint flip_n1 = F_t*C_t;
libxsmm_blasint flip_ldi_1 = WW_t;
libxsmm_blasint flip_ldo_1 = F_t*C_t;
libxsmm_meltwfunction_unary trans_unary_flip_1 = libxsmm_dispatch_meltw_unary(flip_m1, flip_n1, &flip_ldi_1, &flip_ldo_1, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_unary_flip_1 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (F_t, C_t, WW_t) -----> (WW_t, F_t, C_t)
libxsmm_meltw_unary_param trans_unary_param_flip_1;
trans_unary_param_flip_1.in.primary = flip_weight_a;
trans_unary_param_flip_1.out.primary = weight_buffer_a;
trans_unary_flip_1( &trans_unary_param_flip_1 );
libxsmm_blasint flip_m2 = C_t;
libxsmm_blasint flip_n2 = F_t;
libxsmm_blasint flip_ldi_2 = C_t;
libxsmm_blasint flip_ldo_2 = F_t;
libxsmm_meltwfunction_unary trans_unary_flip_2 = libxsmm_dispatch_meltw_unary(flip_m2, flip_n2, &flip_ldi_2, &flip_ldo_2, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_unary_flip_2 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, F_t, C_t) -----> (F_t, C_t, WW_t)
#pragma omp parallel for
for(int kw = 0; kw < WW_t; kw++){ // permute last two dimensions
libxsmm_meltw_unary_param trans_unary_param_flip_2;
trans_unary_param_flip_2.in.primary = &weight_buffer_a[kw*C_t*F_t];
trans_unary_param_flip_2.out.primary = &flip_weight_a[kw*C_t*F_t];
trans_unary_flip_2( &trans_unary_param_flip_2 );
}
int64_t Wpad_t = W_t + 2*(WW_t - 1)*dial;
int64_t tile_multiple = (Win_t/XS_TILE_DBACKWARD)*XS_TILE_DBACKWARD;
int lda = F_t; // Filters (15)
int ldb_orig = W_t; // grad width 60000
int ldb = Wpad_t; // Extra padded grad input case 60800
int ldc = Win_t; // Input width (60400)
unsigned long long l_br = WW_t; // Number of batches for brGEMM (51)
libxsmm_smmfunction_reducebatch_strd kernel = libxsmm_smmdispatch_reducebatch_strd(XS_TILE_DBACKWARD, C_t, F_t, dial*sizeof(float), C_t*F_t*sizeof(float), &ldb_orig, &lda, &ldc, NULL, NULL, NULL, NULL);
int pad_tile_multiple = 2 * (((WW_t - 1)*dial)/XS_TILE_DBACKWARD + 1) * XS_TILE_DBACKWARD; // 896
auto grad_shortpad_tensor = grad.new_empty({N_t,F_t,2*pad_tile_multiple});
float* grad_a_shortpad = grad_shortpad_tensor.data_ptr<float>();
int ldb_shortpad = 2*pad_tile_multiple; // grad pad 1792
/* Dispatch kernels for normal and edge cases*/
libxsmm_smmfunction_reducebatch_strd kernel4 = libxsmm_smmdispatch_reducebatch_strd(XS_TILE_DBACKWARD, C_t, F_t, dial*sizeof(float), C_t*F_t*sizeof(float), &ldb_shortpad, &lda, &ldc, NULL, NULL, NULL, NULL);
libxsmm_smmfunction_reducebatch_strd kernel5 = libxsmm_smmdispatch_reducebatch_strd(Win_t - tile_multiple, C_t, F_t, dial*sizeof(float), C_t*F_t*sizeof(float), &ldb_shortpad, &lda, &ldc, NULL, NULL, NULL, NULL);
// #ifdef USE_TPP
// Virtual copy kernels
libxsmm_blasint virtual_m1 = pad_tile_multiple - ((WW_t - 1)*dial); // columns
libxsmm_blasint virtual_m2 = ((WW_t - 1)*dial); // columns
libxsmm_blasint virtual_n = F_t; // rows
libxsmm_blasint ldi_virtual = W_t;
libxsmm_blasint ldo_virtual = 2*pad_tile_multiple;
if (ldi_virtual < virtual_m1){ // corner case when width's are very small
virtual_m1 = ldi_virtual;
libxsmm_meltwfunction_unary all_zero = libxsmm_dispatch_meltw_unary(ldo_virtual, virtual_n, NULL, &ldo_virtual, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( all_zero == NULL) {
fprintf( stderr, "JIT for initialization by unary all zero copy kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++){
libxsmm_meltw_unary_param all_zero_params;
all_zero_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual]; // Initialize the entire array when widths are small
all_zero(&all_zero_params);
}
}
libxsmm_meltwfunction_unary virtual_copy = libxsmm_dispatch_meltw_unary(virtual_m1, virtual_n, &ldi_virtual, &ldo_virtual, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_IDENTITY);
libxsmm_meltwfunction_unary virtual_copy_zero = libxsmm_dispatch_meltw_unary(virtual_m2, virtual_n, NULL, &ldo_virtual, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( virtual_copy == NULL || virtual_copy_zero == NULL) {
fprintf( stderr, "JIT for initialization by unary copy kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++){ // Loops for storing the edge portion of gradinant array into grad_a_shortpad
libxsmm_meltw_unary_param vcopy_params; // Copy parameter variable for holding the pointer
libxsmm_meltw_unary_param vcopy_params_zero;
vcopy_params_zero.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual]; // copy zeros
virtual_copy_zero(&vcopy_params_zero);
vcopy_params.in.primary = &grad_a[n*F_t*W_t]; // copy after zeros from start of the grad array
vcopy_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ((WW_t - 1)*dial)];
virtual_copy(&vcopy_params);
vcopy_params.in.primary = &grad_a[n*F_t*W_t + W_t - virtual_m1]; // copy from the end of the grad array
vcopy_params.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ldo_virtual - virtual_m1 - ((WW_t - 1)*dial)];
virtual_copy(&vcopy_params);
vcopy_params_zero.out.primary = &grad_a_shortpad[n*F_t*ldo_virtual + ldo_virtual - ((WW_t - 1)*dial)]; // copy zeros
virtual_copy_zero(&vcopy_params_zero);
}
// #else
// #pragma omp parallel for
// for(int n = 0; n < N_t; n++){ // Loops for storing the edge portion of gradinant array into grad_a_shortpad
// for(int filter=0; filter < F_t; filter++){
// for(int w = 0; w < pad_tile_multiple; w++){
// // initialize start of array
// if (w >= ((WW_t - 1)*dial) && w < (W_t + (WW_t - 1)*dial)){
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w] = grad_a[n*F_t*W_t + filter*W_t + w - (WW_t - 1)*dial];
// }
// else{
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w] = 0.0f;
// }
// }
// for(int w = Wpad_t - pad_tile_multiple; w < Wpad_t ; w++){
// // initialize end of array
// if (w >= ((WW_t - 1)*dial) && w < (W_t + (WW_t - 1)*dial)){
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w - Wpad_t + 2*pad_tile_multiple] = grad_a[n*F_t*W_t + filter*W_t + w - (WW_t - 1)*dial];
// }
// else{
// grad_a_shortpad[n*F_t*2*pad_tile_multiple + filter*2*pad_tile_multiple + w - Wpad_t + 2*pad_tile_multiple] = 0.0f;
// }
// }
// }
// }
// #endif
/* JIT eltwise TPPs for initialization... */
libxsmm_blasint tpp_m1 = XS_TILE_DBACKWARD; // columns
libxsmm_blasint tpp_m2 = Win_t - tile_multiple; // columns
libxsmm_blasint tpp_n = C_t; // rows
libxsmm_blasint ld_zero = Win_t;
libxsmm_meltwfunction_unary copy_kernel_1 = libxsmm_dispatch_meltw_unary(tpp_m1, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
libxsmm_meltwfunction_unary copy_kernel_2 = libxsmm_dispatch_meltw_unary(tpp_m2, tpp_n, NULL, &ld_zero, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_XOR);
if ( copy_kernel_1 == NULL || copy_kernel_2 == NULL) {
fprintf( stderr, "JIT for initialization by TPP copy kernel failed. Bailing...!\n");
exit(-1);
}
// Main compute kernel
#pragma omp parallel for
for(int n = 0; n < N_t; n++) {
int last_block=0;
libxsmm_meltw_unary_param copy_params_1;
libxsmm_meltw_unary_param copy_params_2;
for(int wb = 0; wb < Win_t - XS_TILE_DBACKWARD + 1; wb += XS_TILE_DBACKWARD) {
copy_params_1.out.primary = &d_input_a[n*C_t*Win_t + wb]; // Initialization
copy_kernel_1(©_params_1);
if (wb >= (WW_t-1)*dial && wb < Win_t - (WW_t-1)*dial - XS_TILE_DBACKWARD) // Normal case
kernel(&grad_a[n*F_t*W_t + 0*W_t + wb - (WW_t-1)*dial], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + 0*Win_t + wb], &l_br);
else if (wb < (WW_t-1)*dial) // Right side case
kernel4(&grad_a_shortpad[n*F_t*2*pad_tile_multiple + wb], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + wb], &l_br);
else // left side case
kernel4(&grad_a_shortpad[n*F_t*2*pad_tile_multiple + wb - Wpad_t + 2*pad_tile_multiple], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + wb], &l_br);
last_block = wb; // store position for last block
}
if (Win_t % XS_TILE_DBACKWARD != 0){ // Edge case
copy_params_2.out.primary = &d_input_a[n*C_t*Win_t + last_block + XS_TILE_DBACKWARD]; // Initialization
copy_kernel_2(©_params_2);
kernel5(&grad_a_shortpad[n*F_t*2*pad_tile_multiple + last_block + XS_TILE_DBACKWARD - Wpad_t + 2*pad_tile_multiple], &flip_weight_a[0], &d_input_a[n*C_t*Win_t + last_block + XS_TILE_DBACKWARD], &l_br);
}
}
/* Backward weight part of the code */
auto flip_d_weight = weight.new_empty({WW_t,C_t,F_t}); // Tensor for storing permuted weight gradiant
float* flip_d_weight_a = flip_d_weight.data_ptr<float>();
for(int w = 0; w < F_t*C_t*WW_t; w++){
flip_d_weight_a[w] = 0.0f;
}
// lda = W_t;
// ldb = Win_t;
// int ldb_trans = C_t;
// ldc = C_t;
l_br = WW_t;
tile_multiple = (W_t/XS_TILE_WBACKWARD)*XS_TILE_WBACKWARD;
// Blocking on grad_a
int lda_g = Win_t;
// int ldb_g = W_t;
int ldb_trans_g = F_t;
int ldc_g = F_t;
libxsmm_blasint short_W_t = XS_TILE_WBACKWARD;
libxsmm_blasint edge_W_t = W_t - tile_multiple;
libxsmm_blasint M_g = W_t;
libxsmm_blasint N_g = F_t;
auto grad_shorttrans_tensor = grad.new_empty({N_t,F_t,short_W_t}); // Tensor for storing transposed short buffer
float* grad_shorttrans = grad_shorttrans_tensor.data_ptr<float>();
auto grad_edgetrans_tensor = grad.new_empty({N_t,F_t,edge_W_t}); // Tensor for storing transposed short buffer in edge case
float* grad_edgetrans = grad_edgetrans_tensor.data_ptr<float>();
/* use jited tranpose */
libxsmm_meltwfunction_unary trans_shortkernel_grad = libxsmm_dispatch_meltw_unary(short_W_t, N_g, &M_g, &N_g, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
libxsmm_meltwfunction_unary trans_edgekernel_grad = libxsmm_dispatch_meltw_unary(edge_W_t, N_g, &M_g, &N_g, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_shortkernel_grad == NULL | trans_edgekernel_grad == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
/* Dispatch brGEMM kernel for normal and edge cases*/
libxsmm_smmfunction kernel_w5 = libxsmm_smmdispatch(F_t, C_t, XS_TILE_WBACKWARD, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
libxsmm_smmfunction kernel_w6 = libxsmm_smmdispatch(F_t, C_t, W_t - tile_multiple, &ldb_trans_g, &lda_g, &ldc_g, NULL, NULL, NULL, NULL);
// Main compute loop
#pragma omp parallel for reduction(+: flip_d_weight_a[:F_t*C_t*WW_t]) // Distribute the weight array
for(int n = 0; n < N_t; n++) {
int last_block = 0;
libxsmm_meltw_unary_param trans_param_short; // Pointer to hold trans short
libxsmm_meltw_unary_param trans_param_edge; // Pointer to hold trans edge
for(int wb = 0; wb < W_t - XS_TILE_WBACKWARD + 1; wb += XS_TILE_WBACKWARD) { // Normal case
trans_param_short.in.primary = &grad_a[n*F_t*W_t + wb];
trans_param_short.out.primary = &grad_shorttrans[n*F_t*short_W_t];
trans_shortkernel_grad( &trans_param_short );
for(int kw = 0; kw < WW_t; kw++) {
kernel_w5(&grad_shorttrans[n*F_t*short_W_t], &input_a[n*C_t*Win_t + wb + kw*dial], &flip_d_weight_a[kw*C_t*F_t]);
}
last_block = wb;
}
if (W_t % XS_TILE_WBACKWARD != 0){
trans_param_edge.in.primary = &grad_a[n*F_t*W_t + last_block + XS_TILE_WBACKWARD];
trans_param_edge.out.primary = &grad_edgetrans[n*F_t*edge_W_t];
trans_edgekernel_grad( &trans_param_edge );
for(int kw = 0; kw < WW_t; kw++) {
kernel_w6(&grad_edgetrans[n*F_t*edge_W_t], &input_a[n*C_t*Win_t + (last_block + XS_TILE_WBACKWARD) + kw*dial], &flip_d_weight_a[kw*F_t*C_t]);
}
}
}
/* jited tranpose to permute the array dimensions
Overall Convert (WW_t, C_t, F_t) -----> (F_t, C_t, WW_t)*/
libxsmm_blasint per_m1 = F_t;
libxsmm_blasint per_n1 = C_t;
libxsmm_blasint ldi_1 = F_t;
libxsmm_blasint ldo_1 = C_t;
libxsmm_meltwfunction_unary trans_permute_1 = libxsmm_dispatch_meltw_unary(per_m1, per_n1, &ldi_1, &ldo_1, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_1 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, C_t, F_t) -----> (WW_t, F_t, C_t)
#pragma omp parallel for
for(int kw = 0; kw < WW_t; kw++){ // permute last two dimensions
libxsmm_meltw_unary_param trans_param_permute_1;
trans_param_permute_1.in.primary = &flip_d_weight_a[kw*C_t*F_t];
trans_param_permute_1.out.primary = &flip_weight_a[kw*C_t*F_t];
trans_permute_1( &trans_param_permute_1 );
}
libxsmm_blasint per_m2 = F_t*C_t;
libxsmm_blasint per_n2 = WW_t;
libxsmm_blasint ldi_2 = F_t*C_t;
libxsmm_blasint ldo_2 = WW_t;
libxsmm_meltwfunction_unary trans_permute_2 = libxsmm_dispatch_meltw_unary(per_m2, per_n2, &ldi_2, &ldo_2, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_DATATYPE_F32, LIBXSMM_MELTW_FLAG_UNARY_NONE, LIBXSMM_MELTW_TYPE_UNARY_TRANSFORM_NORM_TO_NORMT);
if ( trans_permute_2 == NULL) {
fprintf( stderr, "JIT for unary NORM_TO_NORMT TPP. Bailing...!\n");
exit(-1);
}
// Convert (WW_t, F_t, C_t) -----> (F_t, C_t, WW_t)
libxsmm_meltw_unary_param trans_param_permute_2;
trans_param_permute_2.in.primary = flip_weight_a;
trans_param_permute_2.out.primary = d_weight_a;
trans_permute_2( &trans_param_permute_2 );
return {d_input, d_weight}; // return data gradiant and weight gradiant
}
at::Tensor relu_forward_bf16(at::Tensor& input){
// RECORD_FUNCTION("ReLU_forward_bf16", std::vector<c10::IValue>({input})); // For recording time
int64_t N_t = input.size(0); // Batch
int64_t C_t = input.size(1); // Channel
int64_t W_t = input.size(2); // input width
libxsmm_bfloat16* input_a = (libxsmm_bfloat16*) input.data_ptr<at::BFloat16>();
libxsmm_blasint tpp_m = W_t; // columns
libxsmm_blasint tpp_n = C_t; // rows
libxsmm_blasint ld = W_t;
libxsmm_meltw_unary_type unary_type;
unary_type = LIBXSMM_MELTW_TYPE_UNARY_RELU;
libxsmm_meltw_unary_flags unary_flags;
unary_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE;
libxsmm_meltwfunction_unary relu_fwd_kernel = libxsmm_dispatch_meltw_unary(tpp_m, tpp_n, &ld, &ld, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, unary_flags, unary_type);
if ( relu_fwd_kernel == NULL ) {
fprintf( stderr, "JIT for TPP relu_fwd_kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++) {
libxsmm_meltw_unary_param relu_params;
relu_params.in.primary = &input_a[n*C_t*W_t];
relu_params.out.primary = &input_a[n*C_t*W_t];
relu_params.out.secondary = NULL;
relu_fwd_kernel(&relu_params);
}
return input;
}
at::Tensor relu_backward_bf16(at::Tensor& grad, at::Tensor& output){
// RECORD_FUNCTION("ReLU_backward_bf16", std::vector<c10::IValue>({grad, output})); // For recording time
int64_t N_t = grad.size(0); // Batch
int64_t C_t = grad.size(1); // Channel
int64_t W_t = grad.size(2); // input width
unsigned short* output_a = (unsigned short*) output.data_ptr<at::BFloat16>();
libxsmm_bfloat16* grad_a = (libxsmm_bfloat16*) grad.data_ptr<at::BFloat16>();
libxsmm_blasint tpp_m = W_t; // columns
libxsmm_blasint tpp_n = C_t; // rows
libxsmm_blasint ld = W_t;
libxsmm_meltw_unary_type unary_type;
unary_type = LIBXSMM_MELTW_TYPE_UNARY_RELU_INV;
libxsmm_meltw_unary_flags unary_flags;
unary_flags = LIBXSMM_MELTW_FLAG_UNARY_NONE;
libxsmm_meltwfunction_unary relu_bwd_kernel = libxsmm_dispatch_meltw_unary(tpp_m, tpp_n, &ld, &ld, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, LIBXSMM_DATATYPE_BF16, unary_flags, unary_type);
if ( relu_bwd_kernel == NULL ) {
fprintf( stderr, "JIT for TPP relu_bwd_kernel failed. Bailing...!\n");
exit(-1);
}
#pragma omp parallel for
for(int n = 0; n < N_t; n++) {
libxsmm_meltw_unary_param relu_params;
relu_params.in.primary = &grad_a[n*C_t*W_t];
relu_params.out.primary = &grad_a[n*C_t*W_t];
relu_params.in.secondary = &output_a[n*C_t*W_t];
relu_bwd_kernel(&relu_params);
}
return grad;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("forward", &Conv1dOpti_forward_libxsmm, "Conv1dOpti lib forward");
m.def("backward", &Conv1dOpti_backward_libxsmm, "Conv1dOpti lib backward");
m.def("forward_bf16", &Conv1dOpti_forward_bf16_libxsmm, "Conv1dOpti bf16 forward");
m.def("backward_bf16", &Conv1dOpti_backward_bf16_libxsmm, "Conv1dOpti bf16 backward");
m.def("relu_forward_bf16", &relu_forward_bf16, "ReLU bf16 forward");
m.def("relu_backward_bf16", &relu_backward_bf16, "ReLU bf16 backward");
}
|
/*
* test_IF.cpp
*
* Created on: 2019-3-30
* Author: fasiondog
*/
#include "doctest/doctest.h"
#include <fstream>
#include <hikyuu/StockManager.h>
#include <hikyuu/indicator/crt/KDATA.h>
#include <hikyuu/indicator/crt/CVAL.h>
using namespace hku;
/**
* @defgroup test_indicator_IF test_indicator_IF
* @ingroup test_hikyuu_indicator_suite
* @{
*/
/** @par 检测点 */
TEST_CASE("test_IF") {
KData kdata = getStock("SH600000").getKData(KQuery(-10));
/** @arg 三个参数均为 indicator */
Indicator x = IF(CLOSE() > OPEN(), CVAL(1), CVAL(0));
x.setContext(kdata);
Indicator c = CLOSE(kdata);
Indicator o = OPEN(kdata);
for (int i = 0; i < x.size(); i++) {
if (c[i] > o[i]) {
CHECK_EQ(x[i], 1);
} else {
CHECK_EQ(x[i], 0);
}
}
/** @arg 参数其中之一为数字 */
x = IF(CLOSE() > OPEN(), 1, CVAL(0));
x.setContext(kdata);
for (int i = 0; i < x.size(); i++) {
if (c[i] > o[i]) {
CHECK_EQ(x[i], 1);
} else {
CHECK_EQ(x[i], 0);
}
}
x = IF(CLOSE() > OPEN(), CVAL(1), 0);
x.setContext(kdata);
for (int i = 0; i < x.size(); i++) {
if (c[i] > o[i]) {
CHECK_EQ(x[i], 1);
} else {
CHECK_EQ(x[i], 0);
}
}
/** @arg 两个参数为数字 */
x = IF(CLOSE() > OPEN(), 1, 0);
x.setContext(kdata);
for (int i = 0; i < x.size(); i++) {
if (c[i] > o[i]) {
CHECK_EQ(x[i], 1);
} else {
CHECK_EQ(x[i], 0);
}
}
}
//-----------------------------------------------------------------------------
// test export
//-----------------------------------------------------------------------------
#if HKU_SUPPORT_SERIALIZATION
/** @par 检测点 */
TEST_CASE("test_IF_export") {
StockManager& sm = StockManager::instance();
string filename(sm.tmpdir());
filename += "/IF.xml";
KData kdata = getStock("SH600000").getKData(KQuery(-10));
Indicator x1 = IF(CLOSE() > OPEN(), CVAL(1), CVAL(0));
x1.setContext(kdata);
{
std::ofstream ofs(filename);
boost::archive::xml_oarchive oa(ofs);
oa << BOOST_SERIALIZATION_NVP(x1);
}
Indicator x2;
{
std::ifstream ifs(filename);
boost::archive::xml_iarchive ia(ifs);
ia >> BOOST_SERIALIZATION_NVP(x2);
}
CHECK_EQ(x1.size(), x2.size());
CHECK_EQ(x1.discard(), x2.discard());
CHECK_EQ(x1.getResultNumber(), x2.getResultNumber());
for (size_t i = 0; i < x1.size(); ++i) {
CHECK_EQ(x1[i], doctest::Approx(x2[i]));
}
}
#endif /* #if HKU_SUPPORT_SERIALIZATION */
/** @} */
|
org 100h
L1: MOV AL, 0FH
MOV BH, AL
MOV CL, 08H
MOV DL, 00H
MOV BL, 02H
LOOP: MOV AL, DL
MUL BL
MOV DL, AL
RCR BH, 01H
JC CR
DEC CL
JNZ LOOP
JMP L2
CR: INC DL
DEC CL
JNZ LOOP
L2: CMP BH, DL
JZ PALINDROME
NOTPALINDROME: MOV AH, 02
MOV DL, 'N'
INT 21H
JMP L3
PALINDROME: MOV AH, 02
MOV DL, 'P'
INT 21H
L3: HLT
ret |
; A308709: Start with 3, divide by 3, multiply by 2, multiply by 3, multiply by 2, repeat.
; Submitted by Simon Strandgaard
; 3,1,2,6,12,4,8,24,48,16,32,96,192,64,128,384,768,256,512,1536,3072,1024,2048,6144,12288,4096,8192,24576,49152,16384,32768,98304,196608,65536,131072,393216,786432,262144,524288,1572864,3145728,1048576
mov $1,$0
mod $0,4
gcd $0,3
lpb $1
mul $0,2
sub $1,2
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r14
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x86a7, %r12
sub $38574, %r14
movups (%r12), %xmm2
vpextrq $0, %xmm2, %rax
add %rcx, %rcx
lea addresses_normal_ht+0x9278, %rsi
lea addresses_D_ht+0xfda7, %rdi
nop
nop
nop
nop
add $18522, %rbp
mov $123, %rcx
rep movsq
nop
nop
nop
nop
dec %rbp
lea addresses_WC_ht+0x18a7, %rsi
lea addresses_A_ht+0x29a7, %rdi
nop
nop
nop
sub $44211, %rbx
mov $1, %rcx
rep movsw
nop
nop
nop
nop
xor %rax, %rax
lea addresses_D_ht+0x26a7, %rsi
lea addresses_UC_ht+0xb007, %rdi
nop
nop
and $46857, %rax
mov $15, %rcx
rep movsb
nop
nop
sub $28241, %rdi
lea addresses_A_ht+0x11017, %rbp
nop
and $62458, %rcx
mov (%rbp), %rsi
nop
nop
nop
and $889, %rbp
lea addresses_normal_ht+0x1b7, %rax
sub $32173, %r14
and $0xffffffffffffffc0, %rax
movntdqa (%rax), %xmm4
vpextrq $1, %xmm4, %rdi
sub $36701, %r12
lea addresses_UC_ht+0x123bf, %rdi
add %rax, %rax
movl $0x61626364, (%rdi)
nop
nop
dec %r14
lea addresses_normal_ht+0x305f, %rsi
lea addresses_D_ht+0x2b7b, %rdi
clflush (%rsi)
cmp %r12, %r12
mov $118, %rcx
rep movsb
nop
sub $2999, %rdi
lea addresses_D_ht+0x10e67, %rax
inc %r14
mov (%rax), %edi
nop
nop
nop
nop
add $9787, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r14
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r8
push %r9
push %rbx
push %rcx
push %rdi
// Store
lea addresses_US+0xce67, %rcx
nop
nop
nop
nop
nop
cmp %rbx, %rbx
movb $0x51, (%rcx)
nop
cmp $19108, %rcx
// Load
lea addresses_normal+0xa6a6, %rcx
dec %r13
movb (%rcx), %r9b
nop
nop
nop
inc %rdi
// Store
lea addresses_WT+0x4ea7, %r8
nop
nop
nop
nop
nop
xor %rbx, %rbx
movl $0x51525354, (%r8)
nop
nop
nop
sub $62008, %r9
// Load
lea addresses_US+0x6d43, %rcx
cmp %r10, %r10
mov (%rcx), %r13
nop
cmp %rcx, %rcx
// Faulty Load
lea addresses_normal+0x9aa7, %r10
nop
nop
nop
and $7303, %r13
movb (%r10), %r9b
lea oracles, %rbx
and $0xff, %r9
shlq $12, %r9
mov (%rbx,%r9,1), %r9
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r8
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 9, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 2, 'size': 8, 'same': False, 'NT': True}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 4, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 8, 'same': True, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 4, 'size': 16, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 3, 'size': 4, 'same': True, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 4, 'size': 4, 'same': False, 'NT': False}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2019 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Asher Elmquist
// =============================================================================
//
// Container class for an GPS sensor
//
// =============================================================================
#include "chrono_sensor/ChGPSSensor.h"
// #include "chrono_sensor/filters/ChFilterGPSUpdate.h"
namespace chrono {
namespace sensor {
CH_SENSOR_API ChGPSSensor::ChGPSSensor(std::shared_ptr<chrono::ChBody> parent,
float updateRate,
chrono::ChFrame<double> offsetPose,
ChVector<double> gps_reference,
std::shared_ptr<ChGPSNoiseModel> noise_model)
: ChSensor(parent, updateRate, offsetPose) {
m_filters.push_front(chrono_types::make_shared<ChFilterGPSUpdate>(gps_reference, noise_model));
}
CH_SENSOR_API ChGPSSensor::~ChGPSSensor() {}
} // namespace sensor
} // namespace chrono
|
_rm: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "stat.h"
#include "user.h"
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
7: ff 71 fc pushl -0x4(%ecx)
a: 55 push %ebp
b: 89 e5 mov %esp,%ebp
d: 57 push %edi
e: 56 push %esi
f: 53 push %ebx
10: 51 push %ecx
11: bf 01 00 00 00 mov $0x1,%edi
16: 83 ec 08 sub $0x8,%esp
19: 8b 31 mov (%ecx),%esi
1b: 8b 59 04 mov 0x4(%ecx),%ebx
1e: 83 c3 04 add $0x4,%ebx
int i;
if(argc < 2){
21: 83 fe 01 cmp $0x1,%esi
24: 7e 3e jle 64 <main+0x64>
26: 8d 76 00 lea 0x0(%esi),%esi
29: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
printf(2, "Usage: rm files...\n");
exit();
}
for(i = 1; i < argc; i++){
if(unlink(argv[i]) < 0){
30: 83 ec 0c sub $0xc,%esp
33: ff 33 pushl (%ebx)
35: e8 e8 02 00 00 call 322 <unlink>
3a: 83 c4 10 add $0x10,%esp
3d: 85 c0 test %eax,%eax
3f: 78 0f js 50 <main+0x50>
for(i = 1; i < argc; i++){
41: 83 c7 01 add $0x1,%edi
44: 83 c3 04 add $0x4,%ebx
47: 39 fe cmp %edi,%esi
49: 75 e5 jne 30 <main+0x30>
printf(2, "rm: %s failed to delete\n", argv[i]);
break;
}
}
exit();
4b: e8 82 02 00 00 call 2d2 <exit>
printf(2, "rm: %s failed to delete\n", argv[i]);
50: 50 push %eax
51: ff 33 pushl (%ebx)
53: 68 9c 07 00 00 push $0x79c
58: 6a 02 push $0x2
5a: e8 d1 03 00 00 call 430 <printf>
break;
5f: 83 c4 10 add $0x10,%esp
62: eb e7 jmp 4b <main+0x4b>
printf(2, "Usage: rm files...\n");
64: 52 push %edx
65: 52 push %edx
66: 68 88 07 00 00 push $0x788
6b: 6a 02 push $0x2
6d: e8 be 03 00 00 call 430 <printf>
exit();
72: e8 5b 02 00 00 call 2d2 <exit>
77: 66 90 xchg %ax,%ax
79: 66 90 xchg %ax,%ax
7b: 66 90 xchg %ax,%ax
7d: 66 90 xchg %ax,%ax
7f: 90 nop
00000080 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, const char *t)
{
80: 55 push %ebp
81: 89 e5 mov %esp,%ebp
83: 53 push %ebx
84: 8b 45 08 mov 0x8(%ebp),%eax
87: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
8a: 89 c2 mov %eax,%edx
8c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
90: 83 c1 01 add $0x1,%ecx
93: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
97: 83 c2 01 add $0x1,%edx
9a: 84 db test %bl,%bl
9c: 88 5a ff mov %bl,-0x1(%edx)
9f: 75 ef jne 90 <strcpy+0x10>
;
return os;
}
a1: 5b pop %ebx
a2: 5d pop %ebp
a3: c3 ret
a4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
aa: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000000b0 <strcmp>:
int
strcmp(const char *p, const char *q)
{
b0: 55 push %ebp
b1: 89 e5 mov %esp,%ebp
b3: 53 push %ebx
b4: 8b 55 08 mov 0x8(%ebp),%edx
b7: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
ba: 0f b6 02 movzbl (%edx),%eax
bd: 0f b6 19 movzbl (%ecx),%ebx
c0: 84 c0 test %al,%al
c2: 75 1c jne e0 <strcmp+0x30>
c4: eb 2a jmp f0 <strcmp+0x40>
c6: 8d 76 00 lea 0x0(%esi),%esi
c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
d0: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
d3: 0f b6 02 movzbl (%edx),%eax
p++, q++;
d6: 83 c1 01 add $0x1,%ecx
d9: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
dc: 84 c0 test %al,%al
de: 74 10 je f0 <strcmp+0x40>
e0: 38 d8 cmp %bl,%al
e2: 74 ec je d0 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
e4: 29 d8 sub %ebx,%eax
}
e6: 5b pop %ebx
e7: 5d pop %ebp
e8: c3 ret
e9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
f0: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
f2: 29 d8 sub %ebx,%eax
}
f4: 5b pop %ebx
f5: 5d pop %ebp
f6: c3 ret
f7: 89 f6 mov %esi,%esi
f9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000100 <strlen>:
uint
strlen(const char *s)
{
100: 55 push %ebp
101: 89 e5 mov %esp,%ebp
103: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
106: 80 39 00 cmpb $0x0,(%ecx)
109: 74 15 je 120 <strlen+0x20>
10b: 31 d2 xor %edx,%edx
10d: 8d 76 00 lea 0x0(%esi),%esi
110: 83 c2 01 add $0x1,%edx
113: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
117: 89 d0 mov %edx,%eax
119: 75 f5 jne 110 <strlen+0x10>
;
return n;
}
11b: 5d pop %ebp
11c: c3 ret
11d: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
120: 31 c0 xor %eax,%eax
}
122: 5d pop %ebp
123: c3 ret
124: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
12a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000130 <memset>:
void*
memset(void *dst, int c, uint n)
{
130: 55 push %ebp
131: 89 e5 mov %esp,%ebp
133: 57 push %edi
134: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
137: 8b 4d 10 mov 0x10(%ebp),%ecx
13a: 8b 45 0c mov 0xc(%ebp),%eax
13d: 89 d7 mov %edx,%edi
13f: fc cld
140: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
142: 89 d0 mov %edx,%eax
144: 5f pop %edi
145: 5d pop %ebp
146: c3 ret
147: 89 f6 mov %esi,%esi
149: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000150 <strchr>:
char*
strchr(const char *s, char c)
{
150: 55 push %ebp
151: 89 e5 mov %esp,%ebp
153: 53 push %ebx
154: 8b 45 08 mov 0x8(%ebp),%eax
157: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
15a: 0f b6 10 movzbl (%eax),%edx
15d: 84 d2 test %dl,%dl
15f: 74 1d je 17e <strchr+0x2e>
if(*s == c)
161: 38 d3 cmp %dl,%bl
163: 89 d9 mov %ebx,%ecx
165: 75 0d jne 174 <strchr+0x24>
167: eb 17 jmp 180 <strchr+0x30>
169: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
170: 38 ca cmp %cl,%dl
172: 74 0c je 180 <strchr+0x30>
for(; *s; s++)
174: 83 c0 01 add $0x1,%eax
177: 0f b6 10 movzbl (%eax),%edx
17a: 84 d2 test %dl,%dl
17c: 75 f2 jne 170 <strchr+0x20>
return (char*)s;
return 0;
17e: 31 c0 xor %eax,%eax
}
180: 5b pop %ebx
181: 5d pop %ebp
182: c3 ret
183: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000190 <gets>:
char*
gets(char *buf, int max)
{
190: 55 push %ebp
191: 89 e5 mov %esp,%ebp
193: 57 push %edi
194: 56 push %esi
195: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
196: 31 f6 xor %esi,%esi
198: 89 f3 mov %esi,%ebx
{
19a: 83 ec 1c sub $0x1c,%esp
19d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
1a0: eb 2f jmp 1d1 <gets+0x41>
1a2: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
1a8: 8d 45 e7 lea -0x19(%ebp),%eax
1ab: 83 ec 04 sub $0x4,%esp
1ae: 6a 01 push $0x1
1b0: 50 push %eax
1b1: 6a 00 push $0x0
1b3: e8 32 01 00 00 call 2ea <read>
if(cc < 1)
1b8: 83 c4 10 add $0x10,%esp
1bb: 85 c0 test %eax,%eax
1bd: 7e 1c jle 1db <gets+0x4b>
break;
buf[i++] = c;
1bf: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
1c3: 83 c7 01 add $0x1,%edi
1c6: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
1c9: 3c 0a cmp $0xa,%al
1cb: 74 23 je 1f0 <gets+0x60>
1cd: 3c 0d cmp $0xd,%al
1cf: 74 1f je 1f0 <gets+0x60>
for(i=0; i+1 < max; ){
1d1: 83 c3 01 add $0x1,%ebx
1d4: 3b 5d 0c cmp 0xc(%ebp),%ebx
1d7: 89 fe mov %edi,%esi
1d9: 7c cd jl 1a8 <gets+0x18>
1db: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
1dd: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
1e0: c6 03 00 movb $0x0,(%ebx)
}
1e3: 8d 65 f4 lea -0xc(%ebp),%esp
1e6: 5b pop %ebx
1e7: 5e pop %esi
1e8: 5f pop %edi
1e9: 5d pop %ebp
1ea: c3 ret
1eb: 90 nop
1ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
1f0: 8b 75 08 mov 0x8(%ebp),%esi
1f3: 8b 45 08 mov 0x8(%ebp),%eax
1f6: 01 de add %ebx,%esi
1f8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
1fa: c6 03 00 movb $0x0,(%ebx)
}
1fd: 8d 65 f4 lea -0xc(%ebp),%esp
200: 5b pop %ebx
201: 5e pop %esi
202: 5f pop %edi
203: 5d pop %ebp
204: c3 ret
205: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000210 <stat>:
int
stat(const char *n, struct stat *st)
{
210: 55 push %ebp
211: 89 e5 mov %esp,%ebp
213: 56 push %esi
214: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
215: 83 ec 08 sub $0x8,%esp
218: 6a 00 push $0x0
21a: ff 75 08 pushl 0x8(%ebp)
21d: e8 f0 00 00 00 call 312 <open>
if(fd < 0)
222: 83 c4 10 add $0x10,%esp
225: 85 c0 test %eax,%eax
227: 78 27 js 250 <stat+0x40>
return -1;
r = fstat(fd, st);
229: 83 ec 08 sub $0x8,%esp
22c: ff 75 0c pushl 0xc(%ebp)
22f: 89 c3 mov %eax,%ebx
231: 50 push %eax
232: e8 f3 00 00 00 call 32a <fstat>
close(fd);
237: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
23a: 89 c6 mov %eax,%esi
close(fd);
23c: e8 b9 00 00 00 call 2fa <close>
return r;
241: 83 c4 10 add $0x10,%esp
}
244: 8d 65 f8 lea -0x8(%ebp),%esp
247: 89 f0 mov %esi,%eax
249: 5b pop %ebx
24a: 5e pop %esi
24b: 5d pop %ebp
24c: c3 ret
24d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
250: be ff ff ff ff mov $0xffffffff,%esi
255: eb ed jmp 244 <stat+0x34>
257: 89 f6 mov %esi,%esi
259: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000260 <atoi>:
int
atoi(const char *s)
{
260: 55 push %ebp
261: 89 e5 mov %esp,%ebp
263: 53 push %ebx
264: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
267: 0f be 11 movsbl (%ecx),%edx
26a: 8d 42 d0 lea -0x30(%edx),%eax
26d: 3c 09 cmp $0x9,%al
n = 0;
26f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
274: 77 1f ja 295 <atoi+0x35>
276: 8d 76 00 lea 0x0(%esi),%esi
279: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
280: 8d 04 80 lea (%eax,%eax,4),%eax
283: 83 c1 01 add $0x1,%ecx
286: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
28a: 0f be 11 movsbl (%ecx),%edx
28d: 8d 5a d0 lea -0x30(%edx),%ebx
290: 80 fb 09 cmp $0x9,%bl
293: 76 eb jbe 280 <atoi+0x20>
return n;
}
295: 5b pop %ebx
296: 5d pop %ebp
297: c3 ret
298: 90 nop
299: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
000002a0 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
2a0: 55 push %ebp
2a1: 89 e5 mov %esp,%ebp
2a3: 56 push %esi
2a4: 53 push %ebx
2a5: 8b 5d 10 mov 0x10(%ebp),%ebx
2a8: 8b 45 08 mov 0x8(%ebp),%eax
2ab: 8b 75 0c mov 0xc(%ebp),%esi
char *dst;
const char *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
2ae: 85 db test %ebx,%ebx
2b0: 7e 14 jle 2c6 <memmove+0x26>
2b2: 31 d2 xor %edx,%edx
2b4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
2b8: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
2bc: 88 0c 10 mov %cl,(%eax,%edx,1)
2bf: 83 c2 01 add $0x1,%edx
while(n-- > 0)
2c2: 39 d3 cmp %edx,%ebx
2c4: 75 f2 jne 2b8 <memmove+0x18>
return vdst;
}
2c6: 5b pop %ebx
2c7: 5e pop %esi
2c8: 5d pop %ebp
2c9: c3 ret
000002ca <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
2ca: b8 01 00 00 00 mov $0x1,%eax
2cf: cd 40 int $0x40
2d1: c3 ret
000002d2 <exit>:
SYSCALL(exit)
2d2: b8 02 00 00 00 mov $0x2,%eax
2d7: cd 40 int $0x40
2d9: c3 ret
000002da <wait>:
SYSCALL(wait)
2da: b8 03 00 00 00 mov $0x3,%eax
2df: cd 40 int $0x40
2e1: c3 ret
000002e2 <pipe>:
SYSCALL(pipe)
2e2: b8 04 00 00 00 mov $0x4,%eax
2e7: cd 40 int $0x40
2e9: c3 ret
000002ea <read>:
SYSCALL(read)
2ea: b8 05 00 00 00 mov $0x5,%eax
2ef: cd 40 int $0x40
2f1: c3 ret
000002f2 <write>:
SYSCALL(write)
2f2: b8 10 00 00 00 mov $0x10,%eax
2f7: cd 40 int $0x40
2f9: c3 ret
000002fa <close>:
SYSCALL(close)
2fa: b8 15 00 00 00 mov $0x15,%eax
2ff: cd 40 int $0x40
301: c3 ret
00000302 <kill>:
SYSCALL(kill)
302: b8 06 00 00 00 mov $0x6,%eax
307: cd 40 int $0x40
309: c3 ret
0000030a <exec>:
SYSCALL(exec)
30a: b8 07 00 00 00 mov $0x7,%eax
30f: cd 40 int $0x40
311: c3 ret
00000312 <open>:
SYSCALL(open)
312: b8 0f 00 00 00 mov $0xf,%eax
317: cd 40 int $0x40
319: c3 ret
0000031a <mknod>:
SYSCALL(mknod)
31a: b8 11 00 00 00 mov $0x11,%eax
31f: cd 40 int $0x40
321: c3 ret
00000322 <unlink>:
SYSCALL(unlink)
322: b8 12 00 00 00 mov $0x12,%eax
327: cd 40 int $0x40
329: c3 ret
0000032a <fstat>:
SYSCALL(fstat)
32a: b8 08 00 00 00 mov $0x8,%eax
32f: cd 40 int $0x40
331: c3 ret
00000332 <link>:
SYSCALL(link)
332: b8 13 00 00 00 mov $0x13,%eax
337: cd 40 int $0x40
339: c3 ret
0000033a <mkdir>:
SYSCALL(mkdir)
33a: b8 14 00 00 00 mov $0x14,%eax
33f: cd 40 int $0x40
341: c3 ret
00000342 <chdir>:
SYSCALL(chdir)
342: b8 09 00 00 00 mov $0x9,%eax
347: cd 40 int $0x40
349: c3 ret
0000034a <dup>:
SYSCALL(dup)
34a: b8 0a 00 00 00 mov $0xa,%eax
34f: cd 40 int $0x40
351: c3 ret
00000352 <getpid>:
SYSCALL(getpid)
352: b8 0b 00 00 00 mov $0xb,%eax
357: cd 40 int $0x40
359: c3 ret
0000035a <sbrk>:
SYSCALL(sbrk)
35a: b8 0c 00 00 00 mov $0xc,%eax
35f: cd 40 int $0x40
361: c3 ret
00000362 <sleep>:
SYSCALL(sleep)
362: b8 0d 00 00 00 mov $0xd,%eax
367: cd 40 int $0x40
369: c3 ret
0000036a <uptime>:
SYSCALL(uptime)
36a: b8 0e 00 00 00 mov $0xe,%eax
36f: cd 40 int $0x40
371: c3 ret
00000372 <ticketLockInit>:
SYSCALL(ticketLockInit)
372: b8 16 00 00 00 mov $0x16,%eax
377: cd 40 int $0x40
379: c3 ret
0000037a <ticketLockTest>:
SYSCALL(ticketLockTest)
37a: b8 17 00 00 00 mov $0x17,%eax
37f: cd 40 int $0x40
381: c3 ret
382: 66 90 xchg %ax,%ax
384: 66 90 xchg %ax,%ax
386: 66 90 xchg %ax,%ax
388: 66 90 xchg %ax,%ax
38a: 66 90 xchg %ax,%ax
38c: 66 90 xchg %ax,%ax
38e: 66 90 xchg %ax,%ax
00000390 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
390: 55 push %ebp
391: 89 e5 mov %esp,%ebp
393: 57 push %edi
394: 56 push %esi
395: 53 push %ebx
396: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
399: 85 d2 test %edx,%edx
{
39b: 89 45 c0 mov %eax,-0x40(%ebp)
neg = 1;
x = -xx;
39e: 89 d0 mov %edx,%eax
if(sgn && xx < 0){
3a0: 79 76 jns 418 <printint+0x88>
3a2: f6 45 08 01 testb $0x1,0x8(%ebp)
3a6: 74 70 je 418 <printint+0x88>
x = -xx;
3a8: f7 d8 neg %eax
neg = 1;
3aa: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
} else {
x = xx;
}
i = 0;
3b1: 31 f6 xor %esi,%esi
3b3: 8d 5d d7 lea -0x29(%ebp),%ebx
3b6: eb 0a jmp 3c2 <printint+0x32>
3b8: 90 nop
3b9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
do{
buf[i++] = digits[x % base];
3c0: 89 fe mov %edi,%esi
3c2: 31 d2 xor %edx,%edx
3c4: 8d 7e 01 lea 0x1(%esi),%edi
3c7: f7 f1 div %ecx
3c9: 0f b6 92 bc 07 00 00 movzbl 0x7bc(%edx),%edx
}while((x /= base) != 0);
3d0: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
3d2: 88 14 3b mov %dl,(%ebx,%edi,1)
}while((x /= base) != 0);
3d5: 75 e9 jne 3c0 <printint+0x30>
if(neg)
3d7: 8b 45 c4 mov -0x3c(%ebp),%eax
3da: 85 c0 test %eax,%eax
3dc: 74 08 je 3e6 <printint+0x56>
buf[i++] = '-';
3de: c6 44 3d d8 2d movb $0x2d,-0x28(%ebp,%edi,1)
3e3: 8d 7e 02 lea 0x2(%esi),%edi
3e6: 8d 74 3d d7 lea -0x29(%ebp,%edi,1),%esi
3ea: 8b 7d c0 mov -0x40(%ebp),%edi
3ed: 8d 76 00 lea 0x0(%esi),%esi
3f0: 0f b6 06 movzbl (%esi),%eax
write(fd, &c, 1);
3f3: 83 ec 04 sub $0x4,%esp
3f6: 83 ee 01 sub $0x1,%esi
3f9: 6a 01 push $0x1
3fb: 53 push %ebx
3fc: 57 push %edi
3fd: 88 45 d7 mov %al,-0x29(%ebp)
400: e8 ed fe ff ff call 2f2 <write>
while(--i >= 0)
405: 83 c4 10 add $0x10,%esp
408: 39 de cmp %ebx,%esi
40a: 75 e4 jne 3f0 <printint+0x60>
putc(fd, buf[i]);
}
40c: 8d 65 f4 lea -0xc(%ebp),%esp
40f: 5b pop %ebx
410: 5e pop %esi
411: 5f pop %edi
412: 5d pop %ebp
413: c3 ret
414: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
neg = 0;
418: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
41f: eb 90 jmp 3b1 <printint+0x21>
421: eb 0d jmp 430 <printf>
423: 90 nop
424: 90 nop
425: 90 nop
426: 90 nop
427: 90 nop
428: 90 nop
429: 90 nop
42a: 90 nop
42b: 90 nop
42c: 90 nop
42d: 90 nop
42e: 90 nop
42f: 90 nop
00000430 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, const char *fmt, ...)
{
430: 55 push %ebp
431: 89 e5 mov %esp,%ebp
433: 57 push %edi
434: 56 push %esi
435: 53 push %ebx
436: 83 ec 2c sub $0x2c,%esp
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
439: 8b 75 0c mov 0xc(%ebp),%esi
43c: 0f b6 1e movzbl (%esi),%ebx
43f: 84 db test %bl,%bl
441: 0f 84 b3 00 00 00 je 4fa <printf+0xca>
ap = (uint*)(void*)&fmt + 1;
447: 8d 45 10 lea 0x10(%ebp),%eax
44a: 83 c6 01 add $0x1,%esi
state = 0;
44d: 31 ff xor %edi,%edi
ap = (uint*)(void*)&fmt + 1;
44f: 89 45 d4 mov %eax,-0x2c(%ebp)
452: eb 2f jmp 483 <printf+0x53>
454: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
458: 83 f8 25 cmp $0x25,%eax
45b: 0f 84 a7 00 00 00 je 508 <printf+0xd8>
write(fd, &c, 1);
461: 8d 45 e2 lea -0x1e(%ebp),%eax
464: 83 ec 04 sub $0x4,%esp
467: 88 5d e2 mov %bl,-0x1e(%ebp)
46a: 6a 01 push $0x1
46c: 50 push %eax
46d: ff 75 08 pushl 0x8(%ebp)
470: e8 7d fe ff ff call 2f2 <write>
475: 83 c4 10 add $0x10,%esp
478: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
47b: 0f b6 5e ff movzbl -0x1(%esi),%ebx
47f: 84 db test %bl,%bl
481: 74 77 je 4fa <printf+0xca>
if(state == 0){
483: 85 ff test %edi,%edi
c = fmt[i] & 0xff;
485: 0f be cb movsbl %bl,%ecx
488: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
48b: 74 cb je 458 <printf+0x28>
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
48d: 83 ff 25 cmp $0x25,%edi
490: 75 e6 jne 478 <printf+0x48>
if(c == 'd'){
492: 83 f8 64 cmp $0x64,%eax
495: 0f 84 05 01 00 00 je 5a0 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
49b: 81 e1 f7 00 00 00 and $0xf7,%ecx
4a1: 83 f9 70 cmp $0x70,%ecx
4a4: 74 72 je 518 <printf+0xe8>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
4a6: 83 f8 73 cmp $0x73,%eax
4a9: 0f 84 99 00 00 00 je 548 <printf+0x118>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
4af: 83 f8 63 cmp $0x63,%eax
4b2: 0f 84 08 01 00 00 je 5c0 <printf+0x190>
putc(fd, *ap);
ap++;
} else if(c == '%'){
4b8: 83 f8 25 cmp $0x25,%eax
4bb: 0f 84 ef 00 00 00 je 5b0 <printf+0x180>
write(fd, &c, 1);
4c1: 8d 45 e7 lea -0x19(%ebp),%eax
4c4: 83 ec 04 sub $0x4,%esp
4c7: c6 45 e7 25 movb $0x25,-0x19(%ebp)
4cb: 6a 01 push $0x1
4cd: 50 push %eax
4ce: ff 75 08 pushl 0x8(%ebp)
4d1: e8 1c fe ff ff call 2f2 <write>
4d6: 83 c4 0c add $0xc,%esp
4d9: 8d 45 e6 lea -0x1a(%ebp),%eax
4dc: 88 5d e6 mov %bl,-0x1a(%ebp)
4df: 6a 01 push $0x1
4e1: 50 push %eax
4e2: ff 75 08 pushl 0x8(%ebp)
4e5: 83 c6 01 add $0x1,%esi
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
4e8: 31 ff xor %edi,%edi
write(fd, &c, 1);
4ea: e8 03 fe ff ff call 2f2 <write>
for(i = 0; fmt[i]; i++){
4ef: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
4f3: 83 c4 10 add $0x10,%esp
for(i = 0; fmt[i]; i++){
4f6: 84 db test %bl,%bl
4f8: 75 89 jne 483 <printf+0x53>
}
}
}
4fa: 8d 65 f4 lea -0xc(%ebp),%esp
4fd: 5b pop %ebx
4fe: 5e pop %esi
4ff: 5f pop %edi
500: 5d pop %ebp
501: c3 ret
502: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
state = '%';
508: bf 25 00 00 00 mov $0x25,%edi
50d: e9 66 ff ff ff jmp 478 <printf+0x48>
512: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
printint(fd, *ap, 16, 0);
518: 83 ec 0c sub $0xc,%esp
51b: b9 10 00 00 00 mov $0x10,%ecx
520: 6a 00 push $0x0
522: 8b 7d d4 mov -0x2c(%ebp),%edi
525: 8b 45 08 mov 0x8(%ebp),%eax
528: 8b 17 mov (%edi),%edx
52a: e8 61 fe ff ff call 390 <printint>
ap++;
52f: 89 f8 mov %edi,%eax
531: 83 c4 10 add $0x10,%esp
state = 0;
534: 31 ff xor %edi,%edi
ap++;
536: 83 c0 04 add $0x4,%eax
539: 89 45 d4 mov %eax,-0x2c(%ebp)
53c: e9 37 ff ff ff jmp 478 <printf+0x48>
541: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
548: 8b 45 d4 mov -0x2c(%ebp),%eax
54b: 8b 08 mov (%eax),%ecx
ap++;
54d: 83 c0 04 add $0x4,%eax
550: 89 45 d4 mov %eax,-0x2c(%ebp)
if(s == 0)
553: 85 c9 test %ecx,%ecx
555: 0f 84 8e 00 00 00 je 5e9 <printf+0x1b9>
while(*s != 0){
55b: 0f b6 01 movzbl (%ecx),%eax
state = 0;
55e: 31 ff xor %edi,%edi
s = (char*)*ap;
560: 89 cb mov %ecx,%ebx
while(*s != 0){
562: 84 c0 test %al,%al
564: 0f 84 0e ff ff ff je 478 <printf+0x48>
56a: 89 75 d0 mov %esi,-0x30(%ebp)
56d: 89 de mov %ebx,%esi
56f: 8b 5d 08 mov 0x8(%ebp),%ebx
572: 8d 7d e3 lea -0x1d(%ebp),%edi
575: 8d 76 00 lea 0x0(%esi),%esi
write(fd, &c, 1);
578: 83 ec 04 sub $0x4,%esp
s++;
57b: 83 c6 01 add $0x1,%esi
57e: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
581: 6a 01 push $0x1
583: 57 push %edi
584: 53 push %ebx
585: e8 68 fd ff ff call 2f2 <write>
while(*s != 0){
58a: 0f b6 06 movzbl (%esi),%eax
58d: 83 c4 10 add $0x10,%esp
590: 84 c0 test %al,%al
592: 75 e4 jne 578 <printf+0x148>
594: 8b 75 d0 mov -0x30(%ebp),%esi
state = 0;
597: 31 ff xor %edi,%edi
599: e9 da fe ff ff jmp 478 <printf+0x48>
59e: 66 90 xchg %ax,%ax
printint(fd, *ap, 10, 1);
5a0: 83 ec 0c sub $0xc,%esp
5a3: b9 0a 00 00 00 mov $0xa,%ecx
5a8: 6a 01 push $0x1
5aa: e9 73 ff ff ff jmp 522 <printf+0xf2>
5af: 90 nop
write(fd, &c, 1);
5b0: 83 ec 04 sub $0x4,%esp
5b3: 88 5d e5 mov %bl,-0x1b(%ebp)
5b6: 8d 45 e5 lea -0x1b(%ebp),%eax
5b9: 6a 01 push $0x1
5bb: e9 21 ff ff ff jmp 4e1 <printf+0xb1>
putc(fd, *ap);
5c0: 8b 7d d4 mov -0x2c(%ebp),%edi
write(fd, &c, 1);
5c3: 83 ec 04 sub $0x4,%esp
putc(fd, *ap);
5c6: 8b 07 mov (%edi),%eax
write(fd, &c, 1);
5c8: 6a 01 push $0x1
ap++;
5ca: 83 c7 04 add $0x4,%edi
putc(fd, *ap);
5cd: 88 45 e4 mov %al,-0x1c(%ebp)
write(fd, &c, 1);
5d0: 8d 45 e4 lea -0x1c(%ebp),%eax
5d3: 50 push %eax
5d4: ff 75 08 pushl 0x8(%ebp)
5d7: e8 16 fd ff ff call 2f2 <write>
ap++;
5dc: 89 7d d4 mov %edi,-0x2c(%ebp)
5df: 83 c4 10 add $0x10,%esp
state = 0;
5e2: 31 ff xor %edi,%edi
5e4: e9 8f fe ff ff jmp 478 <printf+0x48>
s = "(null)";
5e9: bb b5 07 00 00 mov $0x7b5,%ebx
while(*s != 0){
5ee: b8 28 00 00 00 mov $0x28,%eax
5f3: e9 72 ff ff ff jmp 56a <printf+0x13a>
5f8: 66 90 xchg %ax,%ax
5fa: 66 90 xchg %ax,%ax
5fc: 66 90 xchg %ax,%ax
5fe: 66 90 xchg %ax,%ax
00000600 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
600: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
601: a1 6c 0a 00 00 mov 0xa6c,%eax
{
606: 89 e5 mov %esp,%ebp
608: 57 push %edi
609: 56 push %esi
60a: 53 push %ebx
60b: 8b 5d 08 mov 0x8(%ebp),%ebx
bp = (Header*)ap - 1;
60e: 8d 4b f8 lea -0x8(%ebx),%ecx
611: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
618: 39 c8 cmp %ecx,%eax
61a: 8b 10 mov (%eax),%edx
61c: 73 32 jae 650 <free+0x50>
61e: 39 d1 cmp %edx,%ecx
620: 72 04 jb 626 <free+0x26>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
622: 39 d0 cmp %edx,%eax
624: 72 32 jb 658 <free+0x58>
break;
if(bp + bp->s.size == p->s.ptr){
626: 8b 73 fc mov -0x4(%ebx),%esi
629: 8d 3c f1 lea (%ecx,%esi,8),%edi
62c: 39 fa cmp %edi,%edx
62e: 74 30 je 660 <free+0x60>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
630: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
633: 8b 50 04 mov 0x4(%eax),%edx
636: 8d 34 d0 lea (%eax,%edx,8),%esi
639: 39 f1 cmp %esi,%ecx
63b: 74 3a je 677 <free+0x77>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
63d: 89 08 mov %ecx,(%eax)
freep = p;
63f: a3 6c 0a 00 00 mov %eax,0xa6c
}
644: 5b pop %ebx
645: 5e pop %esi
646: 5f pop %edi
647: 5d pop %ebp
648: c3 ret
649: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
650: 39 d0 cmp %edx,%eax
652: 72 04 jb 658 <free+0x58>
654: 39 d1 cmp %edx,%ecx
656: 72 ce jb 626 <free+0x26>
{
658: 89 d0 mov %edx,%eax
65a: eb bc jmp 618 <free+0x18>
65c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
bp->s.size += p->s.ptr->s.size;
660: 03 72 04 add 0x4(%edx),%esi
663: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
666: 8b 10 mov (%eax),%edx
668: 8b 12 mov (%edx),%edx
66a: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
66d: 8b 50 04 mov 0x4(%eax),%edx
670: 8d 34 d0 lea (%eax,%edx,8),%esi
673: 39 f1 cmp %esi,%ecx
675: 75 c6 jne 63d <free+0x3d>
p->s.size += bp->s.size;
677: 03 53 fc add -0x4(%ebx),%edx
freep = p;
67a: a3 6c 0a 00 00 mov %eax,0xa6c
p->s.size += bp->s.size;
67f: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
682: 8b 53 f8 mov -0x8(%ebx),%edx
685: 89 10 mov %edx,(%eax)
}
687: 5b pop %ebx
688: 5e pop %esi
689: 5f pop %edi
68a: 5d pop %ebp
68b: c3 ret
68c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
00000690 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
690: 55 push %ebp
691: 89 e5 mov %esp,%ebp
693: 57 push %edi
694: 56 push %esi
695: 53 push %ebx
696: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
699: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
69c: 8b 15 6c 0a 00 00 mov 0xa6c,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
6a2: 8d 78 07 lea 0x7(%eax),%edi
6a5: c1 ef 03 shr $0x3,%edi
6a8: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
6ab: 85 d2 test %edx,%edx
6ad: 0f 84 9d 00 00 00 je 750 <malloc+0xc0>
6b3: 8b 02 mov (%edx),%eax
6b5: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
6b8: 39 cf cmp %ecx,%edi
6ba: 76 6c jbe 728 <malloc+0x98>
6bc: 81 ff 00 10 00 00 cmp $0x1000,%edi
6c2: bb 00 10 00 00 mov $0x1000,%ebx
6c7: 0f 43 df cmovae %edi,%ebx
p = sbrk(nu * sizeof(Header));
6ca: 8d 34 dd 00 00 00 00 lea 0x0(,%ebx,8),%esi
6d1: eb 0e jmp 6e1 <malloc+0x51>
6d3: 90 nop
6d4: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
6d8: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
6da: 8b 48 04 mov 0x4(%eax),%ecx
6dd: 39 f9 cmp %edi,%ecx
6df: 73 47 jae 728 <malloc+0x98>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
6e1: 39 05 6c 0a 00 00 cmp %eax,0xa6c
6e7: 89 c2 mov %eax,%edx
6e9: 75 ed jne 6d8 <malloc+0x48>
p = sbrk(nu * sizeof(Header));
6eb: 83 ec 0c sub $0xc,%esp
6ee: 56 push %esi
6ef: e8 66 fc ff ff call 35a <sbrk>
if(p == (char*)-1)
6f4: 83 c4 10 add $0x10,%esp
6f7: 83 f8 ff cmp $0xffffffff,%eax
6fa: 74 1c je 718 <malloc+0x88>
hp->s.size = nu;
6fc: 89 58 04 mov %ebx,0x4(%eax)
free((void*)(hp + 1));
6ff: 83 ec 0c sub $0xc,%esp
702: 83 c0 08 add $0x8,%eax
705: 50 push %eax
706: e8 f5 fe ff ff call 600 <free>
return freep;
70b: 8b 15 6c 0a 00 00 mov 0xa6c,%edx
if((p = morecore(nunits)) == 0)
711: 83 c4 10 add $0x10,%esp
714: 85 d2 test %edx,%edx
716: 75 c0 jne 6d8 <malloc+0x48>
return 0;
}
}
718: 8d 65 f4 lea -0xc(%ebp),%esp
return 0;
71b: 31 c0 xor %eax,%eax
}
71d: 5b pop %ebx
71e: 5e pop %esi
71f: 5f pop %edi
720: 5d pop %ebp
721: c3 ret
722: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
if(p->s.size == nunits)
728: 39 cf cmp %ecx,%edi
72a: 74 54 je 780 <malloc+0xf0>
p->s.size -= nunits;
72c: 29 f9 sub %edi,%ecx
72e: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
731: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
734: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
737: 89 15 6c 0a 00 00 mov %edx,0xa6c
}
73d: 8d 65 f4 lea -0xc(%ebp),%esp
return (void*)(p + 1);
740: 83 c0 08 add $0x8,%eax
}
743: 5b pop %ebx
744: 5e pop %esi
745: 5f pop %edi
746: 5d pop %ebp
747: c3 ret
748: 90 nop
749: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
base.s.ptr = freep = prevp = &base;
750: c7 05 6c 0a 00 00 70 movl $0xa70,0xa6c
757: 0a 00 00
75a: c7 05 70 0a 00 00 70 movl $0xa70,0xa70
761: 0a 00 00
base.s.size = 0;
764: b8 70 0a 00 00 mov $0xa70,%eax
769: c7 05 74 0a 00 00 00 movl $0x0,0xa74
770: 00 00 00
773: e9 44 ff ff ff jmp 6bc <malloc+0x2c>
778: 90 nop
779: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
prevp->s.ptr = p->s.ptr;
780: 8b 08 mov (%eax),%ecx
782: 89 0a mov %ecx,(%edx)
784: eb b1 jmp 737 <malloc+0xa7>
|
; -*- fundamental -*- (asm-mode sucks)
; ****************************************************************************
;
; isolinux.asm
;
; A program to boot Linux kernels off a CD-ROM using the El Torito
; boot standard in "no emulation" mode, making the entire filesystem
; available. It is based on the SYSLINUX boot loader for MS-DOS
; floppies.
;
; Copyright 1994-2009 H. Peter Anvin - All Rights Reserved
; Copyright 2009 Intel Corporation; author: H. Peter Anvin
;
; This program is free software; you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, Inc., 53 Temple Place Ste 330,
; Boston MA 02111-1307, USA; either version 2 of the License, or
; (at your option) any later version; incorporated herein by reference.
;
; ****************************************************************************
%define IS_ISOLINUX 1
%include "head.inc"
;
; Some semi-configurable constants... change on your own risk.
;
my_id equ isolinux_id
NULLFILE equ 0 ; Zero byte == null file name
NULLOFFSET equ 0 ; Position in which to look
retry_count equ 6 ; How patient are we with the BIOS?
%assign HIGHMEM_SLOP 128*1024 ; Avoid this much memory near the top
SECTOR_SHIFT equ 11 ; 2048 bytes/sector (El Torito requirement)
SECTOR_SIZE equ (1 << SECTOR_SHIFT)
ROOT_DIR_WORD equ 0x002F
; ---------------------------------------------------------------------------
; BEGIN CODE
; ---------------------------------------------------------------------------
;
; Memory below this point is reserved for the BIOS and the MBR
;
section .earlybss
global trackbuf
trackbufsize equ 8192
trackbuf resb trackbufsize ; Track buffer goes here
; ends at 2800h
; Some of these are touched before the whole image
; is loaded. DO NOT move this to .bss16/.uibss.
section .earlybss
global BIOSName
alignb 4
FirstSecSum resd 1 ; Checksum of bytes 64-2048
ImageDwords resd 1 ; isolinux.bin size, dwords
InitStack resd 1 ; Initial stack pointer (SS:SP)
DiskSys resw 1 ; Last INT 13h call
ImageSectors resw 1 ; isolinux.bin size, sectors
; These following two are accessed as a single dword...
GetlinsecPtr resw 1 ; The sector-read pointer
BIOSName resw 1 ; Display string for BIOS type
%define HAVE_BIOSNAME 1
global BIOSType
BIOSType resw 1
DiskError resb 1 ; Error code for disk I/O
global DriveNumber
DriveNumber resb 1 ; CD-ROM BIOS drive number
ISOFlags resb 1 ; Flags for ISO directory search
RetryCount resb 1 ; Used for disk access retries
alignb 8
global Hidden
Hidden resq 1 ; Used in hybrid mode
bsSecPerTrack resw 1 ; Used in hybrid mode
bsHeads resw 1 ; Used in hybrid mode
;
; El Torito spec packet
;
alignb 8
_spec_start equ $
global spec_packet
spec_packet: resb 1 ; Size of packet
sp_media: resb 1 ; Media type
sp_drive: resb 1 ; Drive number
sp_controller: resb 1 ; Controller index
sp_lba: resd 1 ; LBA for emulated disk image
sp_devspec: resw 1 ; IDE/SCSI information
sp_buffer: resw 1 ; User-provided buffer
sp_loadseg: resw 1 ; Load segment
sp_sectors: resw 1 ; Sector count
sp_chs: resb 3 ; Simulated CHS geometry
sp_dummy: resb 1 ; Scratch, safe to overwrite
;
; EBIOS drive parameter packet
;
alignb 8
drive_params: resw 1 ; Buffer size
dp_flags: resw 1 ; Information flags
dp_cyl: resd 1 ; Physical cylinders
dp_head: resd 1 ; Physical heads
dp_sec: resd 1 ; Physical sectors/track
dp_totalsec: resd 2 ; Total sectors
dp_secsize: resw 1 ; Bytes per sector
dp_dpte: resd 1 ; Device Parameter Table
dp_dpi_key: resw 1 ; 0BEDDh if rest valid
dp_dpi_len: resb 1 ; DPI len
resb 1
resw 1
dp_bus: resb 4 ; Host bus type
dp_interface: resb 8 ; Interface type
db_i_path: resd 2 ; Interface path
db_d_path: resd 2 ; Device path
resb 1
db_dpi_csum: resb 1 ; Checksum for DPI info
;
; EBIOS disk address packet
;
alignb 8
dapa: resw 1 ; Packet size
.count: resw 1 ; Block count
.off: resw 1 ; Offset of buffer
.seg: resw 1 ; Segment of buffer
.lba: resd 2 ; LBA (LSW, MSW)
;
; Spec packet for disk image emulation
;
alignb 8
dspec_packet: resb 1 ; Size of packet
dsp_media: resb 1 ; Media type
dsp_drive: resb 1 ; Drive number
dsp_controller: resb 1 ; Controller index
dsp_lba: resd 1 ; LBA for emulated disk image
dsp_devspec: resw 1 ; IDE/SCSI information
dsp_buffer: resw 1 ; User-provided buffer
dsp_loadseg: resw 1 ; Load segment
dsp_sectors: resw 1 ; Sector count
dsp_chs: resb 3 ; Simulated CHS geometry
dsp_dummy: resb 1 ; Scratch, safe to overwrite
alignb 4
_spec_end equ $
_spec_len equ _spec_end - _spec_start
section .init
;;
;; Primary entry point. Because BIOSes are buggy, we only load the first
;; CD-ROM sector (2K) of the file, so the number one priority is actually
;; loading the rest.
;;
global StackBuf
StackBuf equ STACK_TOP-44 ; 44 bytes needed for
; the bootsector chainloading
; code!
global OrigESDI
OrigESDI equ StackBuf-4 ; The high dword on the stack
StackHome equ OrigESDI
bootsec equ $
_start: ; Far jump makes sure we canonicalize the address
cli
jmp 0:_start1
times 8-($-$$) nop ; Pad to file offset 8
; This table hopefully gets filled in by mkisofs using the
; -boot-info-table option. If not, the values in this
; table are default values that we can use to get us what
; we need, at least under a certain set of assumptions.
global iso_boot_info
iso_boot_info:
bi_pvd: dd 16 ; LBA of primary volume descriptor
bi_file: dd 0 ; LBA of boot file
bi_length: dd 0xdeadbeef ; Length of boot file
bi_csum: dd 0xdeadbeef ; Checksum of boot file
bi_reserved: times 10 dd 0xdeadbeef ; Reserved
bi_end:
; Custom entry point for the hybrid-mode disk.
; The following values will have been pushed onto the
; entry stack:
; - partition offset (qword)
; - ES
; - DI
; - DX (including drive number)
; - CBIOS Heads
; - CBIOS Sectors
; - EBIOS flag
; (top of stack)
;
; If we had an old isohybrid, the partition offset will
; be missing; we can check for that with sp >= 0x7c00.
; Serious hack alert.
%ifndef DEBUG_MESSAGES
_hybrid_signature:
dd 0x7078c0fb ; An arbitrary number...
_start_hybrid:
pop cx ; EBIOS flag
pop word [cs:bsSecPerTrack]
pop word [cs:bsHeads]
pop dx
pop di
pop es
xor eax,eax
xor ebx,ebx
cmp sp,7C00h
jae .nooffset
pop eax
pop ebx
.nooffset:
mov si,bios_cbios
jcxz _start_common
mov si,bios_ebios
jmp _start_common
%endif
_start1:
mov si,bios_cdrom
xor eax,eax
xor ebx,ebx
_start_common:
mov [cs:InitStack],sp ; Save initial stack pointer
mov [cs:InitStack+2],ss
xor cx,cx
mov ss,cx
mov sp,StackBuf ; Set up stack
push es ; Save initial ES:DI -> $PnP pointer
push di
mov ds,cx
mov es,cx
mov fs,cx
mov gs,cx
sti
cld
mov [Hidden],eax
mov [Hidden+4],ebx
mov [BIOSType],si
mov eax,[si]
mov [GetlinsecPtr],eax
; Show signs of life
mov si,syslinux_banner
call writestr_early
%ifdef DEBUG_MESSAGES
mov si,copyright_str
%else
mov si,[BIOSName]
%endif
call writestr_early
;
; Before modifying any memory, get the checksum of bytes
; 64-2048
;
initial_csum: xor edi,edi
mov si,bi_end
mov cx,(SECTOR_SIZE-64) >> 2
.loop: lodsd
add edi,eax
loop .loop
mov [FirstSecSum],edi
mov [DriveNumber],dl
%ifdef DEBUG_MESSAGES
mov si,startup_msg
call writemsg
mov al,dl
call writehex2
call crlf_early
%endif
;
; Initialize spec packet buffers
;
mov di,_spec_start
mov cx,_spec_len >> 2
xor eax,eax
rep stosd
; Initialize length field of the various packets
mov byte [spec_packet],13h
mov byte [drive_params],30
mov byte [dapa],16
mov byte [dspec_packet],13h
; Other nonzero fields
inc word [dsp_sectors]
; Are we just pretending to be a CD-ROM?
cmp word [BIOSType],bios_cdrom
jne found_drive ; If so, no spec packet...
; Now figure out what we're actually doing
; Note: use passed-in DL value rather than 7Fh because
; at least some BIOSes will get the wrong value otherwise
mov ax,4B01h ; Get disk emulation status
mov dl,[DriveNumber]
mov si,spec_packet
call int13
jc award_hack ; changed for BrokenAwardHack
mov dl,[DriveNumber]
cmp [sp_drive],dl ; Should contain the drive number
jne spec_query_failed
%ifdef DEBUG_MESSAGES
mov si,spec_ok_msg
call writemsg
mov al,byte [sp_drive]
call writehex2
call crlf_early
%endif
found_drive:
; Alright, we have found the drive. Now, try to find the
; boot file itself. If we have a boot info table, life is
; good; if not, we have to make some assumptions, and try
; to figure things out ourselves. In particular, the
; assumptions we have to make are:
; - single session only
; - only one boot entry (no menu or other alternatives)
cmp dword [bi_file],0 ; Address of code to load
jne found_file ; Boot info table present :)
%ifdef DEBUG_MESSAGES
mov si,noinfotable_msg
call writemsg
%endif
; No such luck. See if the spec packet contained one.
mov eax,[sp_lba]
and eax,eax
jz set_file ; Good enough
%ifdef DEBUG_MESSAGES
mov si,noinfoinspec_msg
call writemsg
%endif
; No such luck. Get the Boot Record Volume, assuming single
; session disk, and that we're the first entry in the chain.
mov eax,17 ; Assumed address of BRV
mov bx,trackbuf
call getonesec
mov eax,[trackbuf+47h] ; Get boot catalog address
mov bx,trackbuf
call getonesec ; Get boot catalog
mov eax,[trackbuf+28h] ; First boot entry
; And hope and pray this is us...
; Some BIOSes apparently have limitations on the size
; that may be loaded (despite the El Torito spec being very
; clear on the fact that it must all be loaded.) Therefore,
; we load it ourselves, and *bleep* the BIOS.
set_file:
mov [bi_file],eax
found_file:
; Set up boot file sizes
mov eax,[bi_length]
sub eax,SECTOR_SIZE-3 ; ... minus sector loaded
shr eax,2 ; bytes->dwords
mov [ImageDwords],eax ; boot file dwords
add eax,((SECTOR_SIZE-1) >> 2)
shr eax,SECTOR_SHIFT-2 ; dwords->sectors
mov [ImageSectors],ax ; boot file sectors
mov eax,[bi_file] ; Address of code to load
inc eax ; Don't reload bootstrap code
%ifdef DEBUG_MESSAGES
mov si,offset_msg
call writemsg
call writehex8
call crlf_early
%endif
; Load the rest of the file. However, just in case there
; are still BIOSes with 64K wraparound problems, we have to
; take some extra precautions. Since the normal load
; address (TEXT_START) is *not* 2K-sector-aligned, we round
; the target address upward to a sector boundary,
; and then move the entire thing down as a unit.
MaxLMA equ 384*1024 ; Reasonable limit (384K)
mov bx,((TEXT_START+2*SECTOR_SIZE-1) & ~(SECTOR_SIZE-1)) >> 4
mov bp,[ImageSectors]
push bx ; Load segment address
.more:
push bx ; Segment address
push bp ; Sector count
mov es,bx
mov cx,0xfff
and bx,cx
inc cx
sub cx,bx
shr cx,SECTOR_SHIFT - 4
jnz .notaligned
mov cx,0x10000 >> SECTOR_SHIFT ; Full 64K segment possible
.notaligned:
cmp bp,cx
jbe .ok
mov bp,cx
.ok:
xor bx,bx
push bp
push eax
call getlinsec
pop eax
pop cx
movzx edx,cx
pop bp
pop bx
shl cx,SECTOR_SHIFT - 4
add bx,cx
add eax,edx
sub bp,dx
jnz .more
; Move the image into place, and also verify the
; checksum
pop ax ; Load segment address
mov bx,(TEXT_START + SECTOR_SIZE) >> 4
mov ecx,[ImageDwords]
mov edi,[FirstSecSum] ; First sector checksum
xor si,si
move_verify_image:
.setseg:
mov ds,ax
mov es,bx
.loop:
mov edx,[si]
add edi,edx
dec ecx
mov [es:si],edx
jz .done
add si,4
jnz .loop
add ax,1000h
add bx,1000h
jmp .setseg
.done:
mov ax,cs
mov ds,ax
mov es,ax
; Verify the checksum on the loaded image.
cmp [bi_csum],edi
je integrity_ok
mov si,checkerr_msg
call writemsg
jmp kaboom
integrity_ok:
%ifdef DEBUG_MESSAGES
mov si,allread_msg
call writemsg
%endif
jmp all_read ; Jump to main code
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Start of BrokenAwardHack --- 10-nov-2002 Knut_Petersen@t-online.de
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; There is a problem with certain versions of the AWARD BIOS ...
;; the boot sector will be loaded and executed correctly, but, because the
;; int 13 vector points to the wrong code in the BIOS, every attempt to
;; load the spec packet will fail. We scan for the equivalent of
;;
;; mov ax,0201h
;; mov bx,7c00h
;; mov cx,0006h
;; mov dx,0180h
;; pushf
;; call <direct far>
;;
;; and use <direct far> as the new vector for int 13. The code above is
;; used to load the boot code into ram, and there should be no reason
;; for anybody to change it now or in the future. There are no opcodes
;; that use encodings relativ to IP, so scanning is easy. If we find the
;; code above in the BIOS code we can be pretty sure to run on a machine
;; with an broken AWARD BIOS ...
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
%ifdef DEBUG_MESSAGES ;;
;;
award_notice db "Trying BrokenAwardHack first ...",CR,LF,0 ;;
award_not_orig db "BAH: Original Int 13 vector : ",0 ;;
award_not_new db "BAH: Int 13 vector changed to : ",0 ;;
award_not_succ db "BAH: SUCCESS",CR,LF,0 ;;
award_not_fail db "BAH: FAILURE" ;;
award_not_crlf db CR,LF,0 ;;
;;
%endif ;;
;;
award_oldint13 dd 0 ;;
award_string db 0b8h,1,2,0bbh,0,7ch,0b9h,6,0,0bah,80h,1,09ch,09ah ;;
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
award_hack: mov si,spec_err_msg ; Moved to this place from
call writemsg ; spec_query_failed
;
%ifdef DEBUG_MESSAGES ;
;
mov si,award_notice ; display our plan
call writemsg ;
mov si,award_not_orig ; display original int 13
call writemsg ; vector
%endif ;
mov eax,[13h*4] ;
mov [award_oldint13],eax ;
;
%ifdef DEBUG_MESSAGES ;
;
call writehex8 ;
mov si,award_not_crlf ;
call writestr_early ;
%endif ;
push es ; save ES
mov ax,0f000h ; ES = BIOS Seg
mov es,ax ;
cld ;
xor di,di ; start at ES:DI = f000:0
award_loop: push di ; save DI
mov si,award_string ; scan for award_string
mov cx,7 ; length of award_string = 7dw
repz cmpsw ; compare
pop di ; restore DI
jcxz award_found ; jmp if found
inc di ; not found, inc di
jno award_loop ;
;
award_failed: pop es ; No, not this way :-((
award_fail2: ;
;
%ifdef DEBUG_MESSAGES ;
;
mov si,award_not_fail ; display failure ...
call writemsg ;
%endif ;
mov eax,[award_oldint13] ; restore the original int
or eax,eax ; 13 vector if there is one
jz spec_query_failed ; and try other workarounds
mov [13h*4],eax ;
jmp spec_query_failed ;
;
award_found: mov eax,[es:di+0eh] ; load possible int 13 addr
pop es ; restore ES
;
cmp eax,[award_oldint13] ; give up if this is the
jz award_failed ; active int 13 vector,
mov [13h*4],eax ; otherwise change 0:13h*4
;
;
%ifdef DEBUG_MESSAGES ;
;
push eax ; display message and
mov si,award_not_new ; new vector address
call writemsg ;
pop eax ;
call writehex8 ;
mov si,award_not_crlf ;
call writestr_early ;
%endif ;
mov ax,4B01h ; try to read the spec packet
mov dl,[DriveNumber] ; now ... it should not fail
mov si,spec_packet ; any longer
int 13h ;
jc award_fail2 ;
;
%ifdef DEBUG_MESSAGES ;
;
mov si,award_not_succ ; display our SUCCESS
call writemsg ;
%endif ;
jmp found_drive ; and leave error recovery code
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; End of BrokenAwardHack ---- 10-nov-2002 Knut_Petersen@t-online.de
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; INT 13h, AX=4B01h, DL=<passed in value> failed.
; Try to scan the entire 80h-FFh from the end.
spec_query_failed:
; some code moved to BrokenAwardHack
mov dl,0FFh
.test_loop: pusha
mov ax,4B01h
mov si,spec_packet
mov byte [si],13h ; Size of buffer
call int13
popa
jc .still_broken
mov si,maybe_msg
call writemsg
mov al,dl
call writehex2
call crlf_early
cmp byte [sp_drive],dl
jne .maybe_broken
; Okay, good enough...
mov si,alright_msg
call writemsg
.found_drive0: mov [DriveNumber],dl
.found_drive: jmp found_drive
; Award BIOS 4.51 apparently passes garbage in sp_drive,
; but if this was the drive number originally passed in
; DL then consider it "good enough"
.maybe_broken:
mov al,[DriveNumber]
cmp al,dl
je .found_drive
; Intel Classic R+ computer with Adaptec 1542CP BIOS 1.02
; passes garbage in sp_drive, and the drive number originally
; passed in DL does not have 80h bit set.
or al,80h
cmp al,dl
je .found_drive0
.still_broken: dec dx
cmp dl, 80h
jnb .test_loop
; No spec packet anywhere. Some particularly pathetic
; BIOSes apparently don't even implement function
; 4B01h, so we can't query a spec packet no matter
; what. If we got a drive number in DL, then try to
; use it, and if it works, then well...
mov dl,[DriveNumber]
cmp dl,81h ; Should be 81-FF at least
jb fatal_error ; If not, it's hopeless
; Write a warning to indicate we're on *very* thin ice now
mov si,nospec_msg
call writemsg
mov al,dl
call writehex2
call crlf_early
mov si,trysbm_msg
call writemsg
jmp .found_drive ; Pray that this works...
fatal_error:
mov si,nothing_msg
call writemsg
.norge: jmp short .norge
; Information message (DS:SI) output
; Prefix with "isolinux: "
;
writemsg: push ax
push si
mov si,isolinux_str
call writestr_early
pop si
call writestr_early
pop ax
ret
writestr_early:
pushfd
pushad
.top: lodsb
and al,al
jz .end
call writechr
jmp short .top
.end: popad
popfd
ret
crlf_early: push ax
mov al,CR
call writechr
mov al,LF
call writechr
pop ax
ret
;
; Write a character to the screen. There is a more "sophisticated"
; version of this in the subsequent code, so we patch the pointer
; when appropriate.
;
writechr:
.simple:
pushfd
pushad
mov ah,0Eh
xor bx,bx
int 10h
popad
popfd
ret
;
; int13: save all the segment registers and call INT 13h.
; Some CD-ROM BIOSes have been found to corrupt segment registers
; and/or disable interrupts.
;
int13:
pushf
push bp
push ds
push es
push fs
push gs
int 13h
mov bp,sp
setc [bp+10] ; Propagate CF to the caller
pop gs
pop fs
pop es
pop ds
pop bp
popf
ret
;
; Get one sector. Convenience entry point.
;
getonesec:
mov bp,1
; Fall through to getlinsec
;
; Get linear sectors - EBIOS LBA addressing, 2048-byte sectors.
;
; Input:
; EAX - Linear sector number
; ES:BX - Target buffer
; BP - Sector count
;
global getlinsec
getlinsec: jmp word [cs:GetlinsecPtr]
%ifndef DEBUG_MESSAGES
;
; First, the variants that we use when actually loading off a disk
; (hybrid mode.) These are adapted versions of the equivalent routines
; in ldlinux.asm.
;
;
; getlinsec_ebios:
;
; getlinsec implementation for floppy/HDD EBIOS (EDD)
;
getlinsec_ebios:
xor edx,edx
shld edx,eax,2
shl eax,2 ; Convert to HDD sectors
add eax,[Hidden]
adc edx,[Hidden+4]
shl bp,2
.loop:
push bp ; Sectors left
.retry2:
call maxtrans ; Enforce maximum transfer size
movzx edi,bp ; Sectors we are about to read
mov cx,retry_count
.retry:
; Form DAPA on stack
push edx
push eax
push es
push bx
push di
push word 16
mov si,sp
pushad
mov dl,[DriveNumber]
push ds
push ss
pop ds ; DS <- SS
mov ah,42h ; Extended Read
call int13
pop ds
popad
lea sp,[si+16] ; Remove DAPA
jc .error
pop bp
add eax,edi ; Advance sector pointer
adc edx,0
sub bp,di ; Sectors left
shl di,9 ; 512-byte sectors
add bx,di ; Advance buffer pointer
and bp,bp
jnz .loop
ret
.error:
; Some systems seem to get "stuck" in an error state when
; using EBIOS. Doesn't happen when using CBIOS, which is
; good, since some other systems get timeout failures
; waiting for the floppy disk to spin up.
pushad ; Try resetting the device
xor ax,ax
mov dl,[DriveNumber]
call int13
popad
loop .retry ; CX-- and jump if not zero
;shr word [MaxTransfer],1 ; Reduce the transfer size
;jnz .retry2
; Total failure. Try falling back to CBIOS.
mov word [GetlinsecPtr], getlinsec_cbios
;mov byte [MaxTransfer],63 ; Max possibe CBIOS transfer
pop bp
jmp getlinsec_cbios.loop
;
; getlinsec_cbios:
;
; getlinsec implementation for legacy CBIOS
;
getlinsec_cbios:
xor edx,edx
shl eax,2 ; Convert to HDD sectors
add eax,[Hidden]
shl bp,2
.loop:
push edx
push eax
push bp
push bx
movzx esi,word [bsSecPerTrack]
movzx edi,word [bsHeads]
;
; Dividing by sectors to get (track,sector): we may have
; up to 2^18 tracks, so we need to use 32-bit arithmetric.
;
div esi
xor cx,cx
xchg cx,dx ; CX <- sector index (0-based)
; EDX <- 0
; eax = track #
div edi ; Convert track to head/cyl
; We should test this, but it doesn't fit...
; cmp eax,1023
; ja .error
;
; Now we have AX = cyl, DX = head, CX = sector (0-based),
; BP = sectors to transfer, SI = bsSecPerTrack,
; ES:BX = data target
;
call maxtrans ; Enforce maximum transfer size
; Must not cross track boundaries, so BP <= SI-CX
sub si,cx
cmp bp,si
jna .bp_ok
mov bp,si
.bp_ok:
shl ah,6 ; Because IBM was STOOPID
; and thought 8 bits were enough
; then thought 10 bits were enough...
inc cx ; Sector numbers are 1-based, sigh
or cl,ah
mov ch,al
mov dh,dl
mov dl,[DriveNumber]
xchg ax,bp ; Sector to transfer count
mov ah,02h ; Read sectors
mov bp,retry_count
.retry:
pushad
call int13
popad
jc .error
.resume:
movzx ecx,al ; ECX <- sectors transferred
shl ax,9 ; Convert sectors in AL to bytes in AX
pop bx
add bx,ax
pop bp
pop eax
pop edx
add eax,ecx
sub bp,cx
jnz .loop
ret
.error:
dec bp
jnz .retry
xchg ax,bp ; Sectors transferred <- 0
shr word [MaxTransfer],1
jnz .resume
jmp disk_error
;
; Truncate BP to MaxTransfer
;
maxtrans:
cmp bp,[MaxTransfer]
jna .ok
mov bp,[MaxTransfer]
.ok: ret
%endif
;
; This is the variant we use for real CD-ROMs:
; LBA, 2K sectors, some special error handling.
;
getlinsec_cdrom:
mov si,dapa ; Load up the DAPA
mov [si+4],bx
mov [si+6],es
mov [si+8],eax
.loop:
push bp ; Sectors left
cmp bp,[MaxTransferCD]
jbe .bp_ok
mov bp,[MaxTransferCD]
.bp_ok:
mov [si+2],bp
push si
mov dl,[DriveNumber]
mov ah,42h ; Extended Read
call xint13
pop si
pop bp
movzx eax,word [si+2] ; Sectors we read
add [si+8],eax ; Advance sector pointer
sub bp,ax ; Sectors left
shl ax,SECTOR_SHIFT-4 ; 2048-byte sectors -> segment
add [si+6],ax ; Advance buffer pointer
and bp,bp
jnz .loop
mov eax,[si+8] ; Next sector
ret
; INT 13h with retry
xint13: mov byte [RetryCount],retry_count
.try: pushad
call int13
jc .error
add sp,byte 8*4 ; Clean up stack
ret
.error:
mov [DiskError],ah ; Save error code
popad
mov [DiskSys],ax ; Save system call number
dec byte [RetryCount]
jz .real_error
push ax
mov al,[RetryCount]
mov ah,[dapa+2] ; Sector transfer count
cmp al,2 ; Only 2 attempts left
ja .nodanger
mov ah,1 ; Drop transfer size to 1
jmp short .setsize
.nodanger:
cmp al,retry_count-2
ja .again ; First time, just try again
shr ah,1 ; Otherwise, try to reduce
adc ah,0 ; the max transfer size, but not to 0
.setsize:
mov [MaxTransferCD],ah
mov [dapa+2],ah
.again:
pop ax
jmp .try
.real_error: mov si,diskerr_msg
call writemsg
mov al,[DiskError]
call writehex2
mov si,oncall_str
call writestr_early
mov ax,[DiskSys]
call writehex4
mov si,ondrive_str
call writestr_early
mov al,dl
call writehex2
call crlf_early
; Fall through to kaboom
;
; kaboom: write a message and bail out. Wait for a user keypress,
; then do a hard reboot.
;
global kaboom
disk_error:
kaboom:
RESET_STACK_AND_SEGS AX
mov si,bailmsg
pm_call pm_writestr
pm_call pm_getchar
cli
mov word [BIOS_magic],0 ; Cold reboot
jmp 0F000h:0FFF0h ; Reset vector address
; -----------------------------------------------------------------------------
; Common modules needed in the first sector
; -----------------------------------------------------------------------------
%include "writehex.inc" ; Hexadecimal output
; -----------------------------------------------------------------------------
; Data that needs to be in the first sector
; -----------------------------------------------------------------------------
global syslinux_banner, copyright_str
syslinux_banner db CR, LF, MY_NAME, ' ', VERSION_STR, ' ', DATE_STR, ' ', 0
copyright_str db ' Copyright (C) 1994-'
asciidec YEAR
db ' H. Peter Anvin et al', CR, LF, 0
isolinux_str db 'isolinux: ', 0
%ifdef DEBUG_MESSAGES
startup_msg: db 'Starting up, DL = ', 0
spec_ok_msg: db 'Loaded spec packet OK, drive = ', 0
secsize_msg: db 'Sector size ', 0
offset_msg: db 'Main image LBA = ', 0
verify_msg: db 'Image csum verified.', CR, LF, 0
allread_msg db 'Image read, jumping to main code...', CR, LF, 0
%endif
noinfotable_msg db 'No boot info table, assuming single session disk...', CR, LF, 0
noinfoinspec_msg db 'Spec packet missing LBA information, trying to wing it...', CR, LF, 0
spec_err_msg: db 'Loading spec packet failed, trying to wing it...', CR, LF, 0
maybe_msg: db 'Found something at drive = ', 0
alright_msg: db 'Looks reasonable, continuing...', CR, LF, 0
nospec_msg db 'Extremely broken BIOS detected, last attempt with drive = ', 0
nothing_msg: db 'Failed to locate CD-ROM device; boot failed.', CR, LF
trysbm_msg db 'See http://syslinux.zytor.com/sbm for more information.', CR, LF, 0
diskerr_msg: db 'Disk error ', 0
oncall_str: db ', AX = ',0
ondrive_str: db ', drive ', 0
checkerr_msg: db 'Image checksum error, sorry...', CR, LF, 0
err_bootfailed db CR, LF, 'Boot failed: press a key to retry...'
bailmsg equ err_bootfailed
crlf_msg db CR, LF
null_msg db 0
bios_cdrom_str db 'ETCD', 0
%ifndef DEBUG_MESSAGES
bios_cbios_str db 'CHDD', 0
bios_ebios_str db 'EHDD' ,0
%endif
alignz 4
global bios_cdrom
bios_cdrom: dw getlinsec_cdrom, bios_cdrom_str
%ifndef DEBUG_MESSAGES
bios_cbios: dw getlinsec_cbios, bios_cbios_str
bios_ebios: dw getlinsec_ebios, bios_ebios_str
%endif
; Maximum transfer size
MaxTransfer dw 127 ; Hard disk modes
MaxTransferCD dw 32 ; CD mode
rl_checkpt equ $ ; Must be <= 800h
; This pads to the end of sector 0 and errors out on
; overflow.
times 2048-($-$$) db 0
; ----------------------------------------------------------------------------
; End of code and data that have to be in the first sector
; ----------------------------------------------------------------------------
section .text16
all_read:
; Test tracers
TRACER 'T'
TRACER '>'
;
; Common initialization code
;
%include "init.inc"
; Tell the user we got this far...
%ifndef DEBUG_MESSAGES ; Gets messy with debugging on
mov si,copyright_str
pm_call pm_writestr
%endif
;
; Now we're all set to start with our *real* business. First load the
; configuration file (if any) and parse it.
;
; In previous versions I avoided using 32-bit registers because of a
; rumour some BIOSes clobbered the upper half of 32-bit registers at
; random. I figure, though, that if there are any of those still left
; they probably won't be trying to install Linux on them...
;
; The code is still ripe with 16-bitisms, though. Not worth the hassle
; to take'm out. In fact, we may want to put them back if we're going
; to boot ELKS at some point.
;
;
; Now, we need to sniff out the actual filesystem data structures.
; mkisofs gave us a pointer to the primary volume descriptor
; (which will be at 16 only for a single-session disk!); from the PVD
; we should be able to find the rest of what we need to know.
;
init_fs:
pushad
mov eax,ROOT_FS_OPS
mov dl,[DriveNumber]
cmp word [BIOSType],bios_cdrom
sete dh ; 1 for cdrom, 0 for hybrid mode
jne .hybrid
movzx ebp,word [MaxTransferCD]
jmp .common
.hybrid:
movzx ebp,word [MaxTransfer]
.common:
mov ecx,[Hidden]
mov ebx,[Hidden+4]
mov si,[bsHeads]
mov di,[bsSecPerTrack]
pm_call pm_fs_init
pm_call load_env32
enter_command:
auto_boot:
jmp kaboom ; load_env32() should never return. If
; it does, then kaboom!
popad
section .rodata
alignz 4
ROOT_FS_OPS:
extern iso_fs_ops
dd iso_fs_ops
dd 0
section .text16
%ifdef DEBUG_TRACERS
;
; debug hack to print a character with minimal code impact
;
debug_tracer: pushad
pushfd
mov bp,sp
mov bx,[bp+9*4] ; Get return address
mov al,[cs:bx] ; Get data byte
inc word [bp+9*4] ; Return to after data byte
call writechr
popfd
popad
ret
%endif ; DEBUG_TRACERS
section .bss16
alignb 4
ThisKbdTo resd 1 ; Temporary holder for KbdTimeout
ThisTotalTo resd 1 ; Temporary holder for TotalTimeout
KernelExtPtr resw 1 ; During search, final null pointer
FuncFlag resb 1 ; Escape sequences received from keyboard
KernelType resb 1 ; Kernel type, from vkernel, if known
global KernelName
KernelName resb FILENAME_MAX ; Mangled name for kernel
section .text16
;
; COM32 vestigial data structure
;
%include "com32.inc"
;
; Common local boot code
;
%include "localboot.inc"
; -----------------------------------------------------------------------------
; Common modules
; -----------------------------------------------------------------------------
%include "common.inc" ; Universal modules
; -----------------------------------------------------------------------------
; Begin data section
; -----------------------------------------------------------------------------
section .data16
err_disk_image db 'Cannot load disk image (invalid file)?', CR, LF, 0
section .bss16
global OrigFDCTabPtr
OrigFDCTabPtr resd 1 ; Keep bios_cleanup_hardware() honest
|
extern m7_ippsTDESEncryptCTR:function
extern n8_ippsTDESEncryptCTR:function
extern y8_ippsTDESEncryptCTR:function
extern e9_ippsTDESEncryptCTR:function
extern l9_ippsTDESEncryptCTR:function
extern n0_ippsTDESEncryptCTR:function
extern k0_ippsTDESEncryptCTR:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsTDESEncryptCTR
.Larraddr_ippsTDESEncryptCTR:
dq m7_ippsTDESEncryptCTR
dq n8_ippsTDESEncryptCTR
dq y8_ippsTDESEncryptCTR
dq e9_ippsTDESEncryptCTR
dq l9_ippsTDESEncryptCTR
dq n0_ippsTDESEncryptCTR
dq k0_ippsTDESEncryptCTR
segment .text
global ippsTDESEncryptCTR:function (ippsTDESEncryptCTR.LEndippsTDESEncryptCTR - ippsTDESEncryptCTR)
.Lin_ippsTDESEncryptCTR:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsTDESEncryptCTR:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsTDESEncryptCTR]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsTDESEncryptCTR:
|
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors -analyzer-config c++-container-inlining=false -verify %s
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors -analyzer-config c++-container-inlining=true -DINLINE=1 -verify %s
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors -analyzer-config c++-container-inlining=false -DTEST_INLINABLE_ALLOCATORS -verify %s
// RUN: %clang_analyze_cc1 -std=c++11 -analyzer-checker=core,unix.Malloc,debug.ExprInspection -analyzer-config c++-inlining=destructors -analyzer-config c++-container-inlining=true -DTEST_INLINABLE_ALLOCATORS -DINLINE=1 -verify %s
#ifndef HEADER
void clang_analyzer_eval(bool);
void clang_analyzer_checkInlined(bool);
#define HEADER
#include "containers.cpp"
#undef HEADER
void test() {
MySet set(0);
clang_analyzer_eval(set.isEmpty());
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
clang_analyzer_eval(set.raw_begin() == set.raw_end());
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
clang_analyzer_eval(set.begin().impl == set.end().impl);
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
}
void testSubclass(MySetSubclass &sub) {
sub.useIterator(sub.begin());
MySetSubclass local;
}
void testWrappers(BeginOnlySet &w1, IteratorStructOnlySet &w2,
IteratorTypedefOnlySet &w3, IteratorUsingOnlySet &w4) {
BeginOnlySet local1;
IteratorStructOnlySet local2;
IteratorTypedefOnlySet local3;
IteratorUsingOnlySet local4;
clang_analyzer_eval(w1.begin().impl.impl == w1.begin().impl.impl);
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
clang_analyzer_eval(w2.start().impl == w2.start().impl);
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
clang_analyzer_eval(w3.start().impl == w3.start().impl);
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
clang_analyzer_eval(w4.start().impl == w4.start().impl);
#if INLINE
// expected-warning@-2 {{TRUE}}
#else
// expected-warning@-4 {{UNKNOWN}}
#endif
}
#else // HEADER
#include "../Inputs/system-header-simulator-cxx.h"
class MySet {
int *storage;
unsigned size;
public:
MySet() : storage(0), size(0) {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
MySet(unsigned n) : storage(new int[n]), size(n) {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
~MySet() { delete[] storage; }
bool isEmpty() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return size == 0;
}
struct iterator {
int *impl;
iterator(int *p) : impl(p) {}
};
iterator begin() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return iterator(storage);
}
iterator end() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return iterator(storage+size);
}
typedef int *raw_iterator;
raw_iterator raw_begin() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return storage;
}
raw_iterator raw_end() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return storage + size;
}
};
class MySetSubclass : public MySet {
public:
MySetSubclass() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
void useIterator(iterator i) {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
};
class BeginOnlySet {
MySet impl;
public:
struct IterImpl {
MySet::iterator impl;
typedef std::forward_iterator_tag iterator_category;
IterImpl(MySet::iterator i) : impl(i) {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
};
BeginOnlySet() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
typedef IterImpl wrapped_iterator;
wrapped_iterator begin() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return IterImpl(impl.begin());
}
};
class IteratorTypedefOnlySet {
MySet impl;
public:
IteratorTypedefOnlySet() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
typedef MySet::iterator iterator;
iterator start() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return impl.begin();
}
};
class IteratorUsingOnlySet {
MySet impl;
public:
IteratorUsingOnlySet() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
using iterator = MySet::iterator;
iterator start() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return impl.begin();
}
};
class IteratorStructOnlySet {
MySet impl;
public:
IteratorStructOnlySet() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
}
struct iterator {
int *impl;
};
iterator start() {
clang_analyzer_checkInlined(true);
#if INLINE
// expected-warning@-2 {{TRUE}}
#endif
return iterator{impl.begin().impl};
}
};
#endif // HEADER
|
#pragma once
#include <string>
namespace cmn { class cmdLine; }
namespace shlink {
class iSymbolIndex;
class layout;
class layoutProgress;
class iTarget {
public:
virtual ~iTarget() {}
virtual void readArguments(cmn::cmdLine& cl) = 0;
virtual iSymbolIndex *createIndex() = 0;
virtual void seedRequirements(layoutProgress& lProg) = 0;
virtual void write(const layout& l, iSymbolIndex& x) = 0;
};
class iSymbolIndex {
public:
virtual ~iSymbolIndex() {}
virtual void reportSymbolLocation(
const std::string& name, unsigned long finalOffset) = 0;
};
iTarget *createTarget(cmn::cmdLine& cl);
} // namespace shlink
|
; A007911: a(n) = (n-1)!! - (n-2)!!.
; Submitted by Jon Maiga
; 1,1,5,7,33,57,279,561,2895,6555,35685,89055,509985,1381905,8294895,24137505,151335135,468934515,3061162125,10033419375,68000295825,234484536825,1645756410375,5943863027025,43105900812975,162446292283275,1214871076343925,4761954230608575,36659590336994625,149048910271886625,1179297174137457375,4961463912662882625,40288002704636061375,175022432901300859875,1456700757237661060125,6522450679923530727375,55576271870507820056625,256053920369732059199625,2231251669352950693824375
add $0,2
mov $2,1
lpb $0
mul $1,$0
add $3,$0
sub $0,2
add $1,$2
sub $3,1
mul $2,$3
mov $3,1
trn $3,$1
lpe
mov $0,$1
|
; A123138: The n-th digit of a(n-1) gives the position of digit n in a(n), a(1)=263514.
; 263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642,263514,513642
mod $0,2
mul $0,250128
add $0,263514
|
/*****************************************************************************************************************
* ReelRobotix Inc. - Software License Agreement Copyright (c) 2018
* Authors: Pablo Inigo Blasco, Brett Aldrich
*
******************************************************************************************************************/
#include <smacc_odom_tracker/odom_tracker.h>
#include <smacc_odom_tracker/OdomTrackerAction.h>
#include <actionlib/server/simple_action_server.h>
#include <memory>
typedef actionlib::SimpleActionServer<smacc_odom_tracker::OdomTrackerAction> Server;
using namespace smacc_odom_tracker;
class OdomTrackerActionServer
{
public:
std::shared_ptr<Server> as_ ;
OdomTracker odomTracker;
OdomTrackerActionServer()
{
}
/**
******************************************************************************************************************
* execute()
******************************************************************************************************************
*/
void execute(const smacc_odom_tracker::OdomTrackerGoalConstPtr& goal) // Note: "Action" is not appended to DoDishes here
{
try
{
switch(goal->command)
{
case OdomTrackerGoal::RECORD_FORWARD_PATH:
odomTracker.setWorkingMode(WorkingMode::RECORD_PATH_FORWARD);
break;
case OdomTrackerGoal::CLEAR_PATH_BACKWARDS:
odomTracker.setWorkingMode(WorkingMode::CLEAR_PATH_BACKWARD);
break;
case OdomTrackerGoal::IDLE:
odomTracker.setWorkingMode(WorkingMode::IDLE);
break;
case OdomTrackerGoal::START_BROADCAST_PATH:
odomTracker.setPublishMessages(true);
break;
case OdomTrackerGoal::STOP_BROADCAST_PATH:
odomTracker.setPublishMessages(false);
break;
case OdomTrackerGoal::PUSH_PATH:
odomTracker.pushPath();
break;
case OdomTrackerGoal::POP_PATH:
odomTracker.popPath();
break;
default:
ROS_ERROR("Odom Tracker Node - Action Server execute error: incorrect command - %d", goal->command);
as_->setAborted();
}
// never reach succeded because were are interested in keeping the feedback alive
as_->setSucceeded();
}
catch(std::exception& ex)
{
ROS_ERROR("Odom Tracker Node - Action Server execute error: %s", ex.what());
as_->setAborted();
}
}
/**
******************************************************************************************************************
* run()
******************************************************************************************************************
*/
void run()
{
ros::NodeHandle n;
ROS_INFO("Creating odom tracker action server");
as_ = std::make_shared<Server>(n, "odom_tracker", boost::bind(&OdomTrackerActionServer::execute, this, _1), false);
ROS_INFO("Starting OdomTracker Action Server");
as_->start();
ros::spin();
}
};
int main(int argc, char**argv)
{
ros::init(argc,argv,"odom_tracker_node");
OdomTrackerActionServer as;
as.run();
} |
;;
;; Copyright (c) 2020-2021, 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.
;;
%define NUM_LANES 8
%define AES_CBC_ENC_X4 aes_cbc_enc_128_x8_sse
%define FLUSH_JOB_AES_ENC flush_job_aes128_enc_x8_sse
%include "sse/mb_mgr_aes_flush_sse.asm"
|
Name: Object.asm
Type: file
Size: 14117
Last-Modified: '1992-02-13T07:47:46Z'
SHA-1: 85CAD05A22F32966ECA32A5DF7EA231B28899B56
Description: null
|
; A093112: a(n) = (2^n-1)^2 - 2.
; -1,7,47,223,959,3967,16127,65023,261119,1046527,4190207,16769023,67092479,268402687,1073676287,4294836223,17179607039,68718952447,274876858367,1099509530623,4398042316799,17592177655807,70368727400447,281474943156223,1125899839733759,4503599493152767,18014398241046527,72057593501057023,288230375077969919,1152921502459363327,4611686014132420607,18446744065119617023,73786976277658337279,295147905144993087487,1180591620648691826687,4722366482732206260223,18889465931203702947839,75557863725364567605247,302231454902557782048767,1208925819612430151450623,4835703278454118652313599,19342813113825270702276607,77371252455318674995150847,309485009821309884352692223,1237940039285309906154946559,4951760157141380362108141567,19807040628565802923409276927,79228162514263774643590529023,316912650057056224474268958719,1267650600228227149696889520127,5070602400912913102387185451007,20282409603651661416747996545023,81129638414606663681390495662079,324518553658426690754359001612287,1298074214633706835075030044377087,5192296858534827484415308253364223,20769187434139310225891609165168639,83076749736557241480027188964098047,332306998946228967073030260463239167
mov $1,2
pow $1,$0
bin $1,2
mul $1,8
sub $1,1
mov $0,$1
|
;------------------------------------------------------------------------------ ;
; Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
; This program and the accompanying materials
; are licensed and made available under the terms and conditions of the BSD License
; which accompanies this distribution. The full text of the license may be found at
; http://opensource.org/licenses/bsd-license.php.
;
; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
;
; Module Name:
;
; CpuSleep.Asm
;
; Abstract:
;
; CpuSleep function
;
; Notes:
;
;------------------------------------------------------------------------------
DEFAULT REL
SECTION .text
;------------------------------------------------------------------------------
; VOID
; EFIAPI
; CpuSleep (
; VOID
; );
;------------------------------------------------------------------------------
global ASM_PFX(CpuSleep)
ASM_PFX(CpuSleep):
hlt
ret
|
// Copyright (c) 2014 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "crypto/rfc6979_hmac_sha256.h"
#include "crypto/ripemd160.h"
#include "crypto/sha1.h"
#include "crypto/sha256.h"
#include "crypto/sha512.h"
#include "crypto/hmac_sha256.h"
#include "crypto/hmac_sha512.h"
#include "random.h"
#include "utilstrencodings.h"
#include <vector>
#include <boost/assign/list_of.hpp>
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(crypto_tests)
template<typename Hasher, typename In, typename Out>
void TestVector(const Hasher &h, const In &in, const Out &out) {
Out hash;
BOOST_CHECK(out.size() == h.OUTPUT_SIZE);
hash.resize(out.size());
{
// Test that writing the whole input string at once works.
Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
for (int i=0; i<32; i++) {
// Test that writing the string broken up in random pieces works.
Hasher hasher(h);
size_t pos = 0;
while (pos < in.size()) {
size_t len = insecure_rand() % ((in.size() - pos + 1) / 2 + 1);
hasher.Write((unsigned char*)&in[pos], len);
pos += len;
if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) {
// Test that writing the rest at once to a copy of a hasher works.
Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
}
hasher.Finalize(&hash[0]);
BOOST_CHECK(hash == out);
}
}
void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));}
void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));}
void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));}
void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));}
void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) {
std::vector<unsigned char> key = ParseHex(hexkey);
TestVector(CHMAC_SHA256(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout));
}
void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) {
std::vector<unsigned char> key = ParseHex(hexkey);
TestVector(CHMAC_SHA512(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout));
}
std::string LongTestString(void) {
std::string ret;
for (int i=0; i<200000; i++) {
ret += (unsigned char)(i);
ret += (unsigned char)(i >> 4);
ret += (unsigned char)(i >> 8);
ret += (unsigned char)(i >> 12);
ret += (unsigned char)(i >> 16);
}
return ret;
}
const std::string test1 = LongTestString();
BOOST_AUTO_TEST_CASE(ripemd160_testvectors) {
TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31");
TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc");
TestRIPEMD160("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36");
TestRIPEMD160("secure hash algorithm", "20397528223b6a5f4cbc2808aba0464e645544f9");
TestRIPEMD160("RIPEMD160 is considered to be safe", "a7d78608c7af8a8e728778e81576870734122b66");
TestRIPEMD160("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"12a053384a9c0c88e405a06c27dcf49ada62eb2b");
TestRIPEMD160("For this sample, this 63-byte string will be used as input data",
"de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11");
TestRIPEMD160("This is exactly 64 bytes long, not counting the terminating byte",
"eda31d51d3a623b81e19eb02e24ff65d27d67b37");
TestRIPEMD160(std::string(1000000, 'a'), "52783243c1697bdbe16d37f97f68f08325dc1528");
TestRIPEMD160(test1, "464243587bd146ea835cdf57bdae582f25ec45f1");
}
BOOST_AUTO_TEST_CASE(sha1_testvectors) {
TestSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709");
TestSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d");
TestSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3");
TestSHA1("secure hash algorithm", "d4d6d2f0ebe317513bbd8d967d89bac5819c2f60");
TestSHA1("SHA1 is considered to be safe", "f2b6650569ad3a8720348dd6ea6c497dee3a842a");
TestSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"84983e441c3bd26ebaae4aa1f95129e5e54670f1");
TestSHA1("For this sample, this 63-byte string will be used as input data",
"4f0ea5cd0585a23d028abdc1a6684e5a8094dc49");
TestSHA1("This is exactly 64 bytes long, not counting the terminating byte",
"fb679f23e7d1ce053313e66e127ab1b444397057");
TestSHA1(std::string(1000000, 'a'), "34aa973cd4c4daa4f61eeb2bdbad27316534016f");
TestSHA1(test1, "b7755760681cbfd971451668f32af5774f4656b5");
}
BOOST_AUTO_TEST_CASE(sha256_testvectors) {
TestSHA256("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
TestSHA256("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
TestSHA256("message digest",
"f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650");
TestSHA256("secure hash algorithm",
"f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d");
TestSHA256("SHA256 is considered to be safe",
"6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630");
TestSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
TestSHA256("For this sample, this 63-byte string will be used as input data",
"f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342");
TestSHA256("This is exactly 64 bytes long, not counting the terminating byte",
"ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8");
TestSHA256("As Bitcoin relies on 80 byte header hashes, we want to have an example for that.",
"7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743");
TestSHA256(std::string(1000000, 'a'),
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");
TestSHA256(test1, "a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26");
}
BOOST_AUTO_TEST_CASE(sha512_testvectors) {
TestSHA512("",
"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce"
"47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e");
TestSHA512("abc",
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
TestSHA512("message digest",
"107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33"
"09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c");
TestSHA512("secure hash algorithm",
"7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3"
"d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e");
TestSHA512("SHA512 is considered to be safe",
"099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964"
"6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2");
TestSHA512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq",
"204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335"
"96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445");
TestSHA512("For this sample, this 63-byte string will be used as input data",
"b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e"
"6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766");
TestSHA512("This is exactly 64 bytes long, not counting the terminating byte",
"70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38"
"7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030");
TestSHA512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno"
"ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu",
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"
"501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
TestSHA512(std::string(1000000, 'a'),
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"
"de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b");
TestSHA512(test1,
"40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594"
"37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc");
}
BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) {
// test cases 1, 2, 3, 4, 6 and 7 of RFC 4231
TestHMACSHA256("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"4869205468657265",
"b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");
TestHMACSHA256("4a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddddddd",
"773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");
TestHMACSHA256("0102030405060708090a0b0c0d0e0f10111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
"82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729554b");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"
"65204b6579202d2048617368204b6579204669727374",
"60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54");
TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"5468697320697320612074657374207573696e672061206c6172676572207468"
"616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"
"68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"
"647320746f20626520686173686564206265666f7265206265696e6720757365"
"642062792074686520484d414320616c676f726974686d2e",
"9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2");
}
BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) {
// test cases 1, 2, 3, 4, 6 and 7 of RFC 4231
TestHMACSHA512("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b",
"4869205468657265",
"87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde"
"daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854");
TestHMACSHA512("4a656665",
"7768617420646f2079612077616e7420666f72206e6f7468696e673f",
"164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554"
"9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
"dddddddddddddddddddddddddddddddddddd",
"fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39"
"bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb");
TestHMACSHA512("0102030405060708090a0b0c0d0e0f10111213141516171819",
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"
"cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd",
"b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db"
"a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a"
"65204b6579202d2048617368204b6579204669727374",
"80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352"
"6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598");
TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaa",
"5468697320697320612074657374207573696e672061206c6172676572207468"
"616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074"
"68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565"
"647320746f20626520686173686564206265666f7265206265696e6720757365"
"642062792074686520484d414320616c676f726974686d2e",
"e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944"
"b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58");
}
void TestRFC6979(const std::string& hexkey, const std::string& hexmsg, const std::vector<std::string>& hexout)
{
std::vector<unsigned char> key = ParseHex(hexkey);
std::vector<unsigned char> msg = ParseHex(hexmsg);
RFC6979_HMAC_SHA256 rng(&key[0], key.size(), &msg[0], msg.size());
for (unsigned int i = 0; i < hexout.size(); i++) {
std::vector<unsigned char> out = ParseHex(hexout[i]);
std::vector<unsigned char> gen;
gen.resize(out.size());
rng.Generate(&gen[0], gen.size());
BOOST_CHECK(out == gen);
}
}
BOOST_AUTO_TEST_CASE(rfc6979_hmac_sha256)
{
TestRFC6979(
"0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f00",
"4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a",
boost::assign::list_of
("4fe29525b2086809159acdf0506efb86b0ec932c7ba44256ab321e421e67e9fb")
("2bf0fff1d3c378a22dc5de1d856522325c65b504491a0cbd01cb8f3aa67ffd4a")
("f528b410cb541f77000d7afb6c5b53c5c471eab43e466d9ac5190c39c82fd82e"));
TestRFC6979(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
boost::assign::list_of
("9c236c165b82ae0cd590659e100b6bab3036e7ba8b06749baf6981e16f1a2b95")
("df471061625bc0ea14b682feee2c9c02f235da04204c1d62a1536c6e17aed7a9")
("7597887cbd76321f32e30440679a22cf7f8d9d2eac390e581fea091ce202ba94"));
}
BOOST_AUTO_TEST_SUITE_END()
|
bits 32
global start
extern exit , printf
import exit msvcrt.dll
import printf msvcrt.dll
extern maxim
segment data use32 class=data
s dd 1234A678h , 12345678h , 1AC3B47Dh , 0FEDC9876h
len equ ($-s)/4
d times len db -1
mesaj_afisare db "Suma octetilor este : " , 0
format_farasemn db "%u " , 0
format_semn db "%d " , 0
segment code use32 class=code
start:
xor ecx , ecx
mov esi , s
mov edi , d
mov ecx , len
push dword ecx
call maxim
mov esi , d
mov ecx , len
xor edx , edx
parcurgere_rezultat:
xor eax , eax
lodsb
pushad
push dword eax
push dword format_farasemn
call [printf]
add esp , 4 * 2
popad
add edx , eax
loop parcurgere_rezultat
pushad
push dword mesaj_afisare
call [printf]
add esp , 4
popad
push dword edx
push dword format_semn
call [printf]
add esp , 4 * 2
push dword 0
call [exit]
|
TITLE sha512-586.asm
IF @Version LT 800
ECHO MASM version 8.00 or later is strongly recommended.
ENDIF
.686
.XMM
IF @Version LT 800
XMMWORD STRUCT 16
DQ 2 dup (?)
XMMWORD ENDS
ENDIF
.MODEL FLAT
OPTION DOTNAME
IF @Version LT 800
.text$ SEGMENT PAGE 'CODE'
ELSE
.text$ SEGMENT ALIGN(64) 'CODE'
ENDIF
;EXTERN _OPENSSL_ia32cap_P:NEAR
ALIGN 16
_sha512_block_data_order PROC PUBLIC
$L_sha512_block_data_order_begin::
push ebp
push ebx
push esi
push edi
mov esi,DWORD PTR 20[esp]
mov edi,DWORD PTR 24[esp]
mov eax,DWORD PTR 28[esp]
mov ebx,esp
call $L000pic_point
$L000pic_point:
pop ebp
lea ebp,DWORD PTR ($L001K512-$L000pic_point)[ebp]
sub esp,16
and esp,-64
shl eax,7
add eax,edi
mov DWORD PTR [esp],esi
mov DWORD PTR 4[esp],edi
mov DWORD PTR 8[esp],eax
mov DWORD PTR 12[esp],ebx
lea edx,DWORD PTR _OPENSSL_ia32cap_P
mov ecx,DWORD PTR [edx]
test ecx,67108864
jz $L002loop_x86
mov edx,DWORD PTR 4[edx]
movq mm0,QWORD PTR [esi]
and ecx,16777216
movq mm1,QWORD PTR 8[esi]
and edx,512
movq mm2,QWORD PTR 16[esi]
or ecx,edx
movq mm3,QWORD PTR 24[esi]
movq mm4,QWORD PTR 32[esi]
movq mm5,QWORD PTR 40[esi]
movq mm6,QWORD PTR 48[esi]
movq mm7,QWORD PTR 56[esi]
cmp ecx,16777728
je $L003SSSE3
sub esp,80
jmp $L004loop_sse2
ALIGN 16
$L004loop_sse2:
movq QWORD PTR 8[esp],mm1
movq QWORD PTR 16[esp],mm2
movq QWORD PTR 24[esp],mm3
movq QWORD PTR 40[esp],mm5
movq QWORD PTR 48[esp],mm6
pxor mm2,mm1
movq QWORD PTR 56[esp],mm7
movq mm3,mm0
mov eax,DWORD PTR [edi]
mov ebx,DWORD PTR 4[edi]
add edi,8
mov edx,15
bswap eax
bswap ebx
jmp $L00500_14_sse2
ALIGN 16
$L00500_14_sse2:
movd mm1,eax
mov eax,DWORD PTR [edi]
movd mm7,ebx
mov ebx,DWORD PTR 4[edi]
add edi,8
bswap eax
bswap ebx
punpckldq mm7,mm1
movq mm1,mm4
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
movq mm0,mm3
movq QWORD PTR 72[esp],mm7
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
paddq mm7,QWORD PTR [ebp]
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
sub esp,8
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 40[esp]
paddq mm3,mm2
movq mm2,mm0
add ebp,8
paddq mm3,mm6
movq mm6,QWORD PTR 48[esp]
dec edx
jnz $L00500_14_sse2
movd mm1,eax
movd mm7,ebx
punpckldq mm7,mm1
movq mm1,mm4
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
movq mm0,mm3
movq QWORD PTR 72[esp],mm7
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
paddq mm7,QWORD PTR [ebp]
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
sub esp,8
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm7,QWORD PTR 192[esp]
paddq mm3,mm2
movq mm2,mm0
add ebp,8
paddq mm3,mm6
pxor mm0,mm0
mov edx,32
jmp $L00616_79_sse2
ALIGN 16
$L00616_79_sse2:
movq mm5,QWORD PTR 88[esp]
movq mm1,mm7
psrlq mm7,1
movq mm6,mm5
psrlq mm5,6
psllq mm1,56
paddq mm0,mm3
movq mm3,mm7
psrlq mm7,6
pxor mm3,mm1
psllq mm1,7
pxor mm3,mm7
psrlq mm7,1
pxor mm3,mm1
movq mm1,mm5
psrlq mm5,13
pxor mm7,mm3
psllq mm6,3
pxor mm1,mm5
paddq mm7,QWORD PTR 200[esp]
pxor mm1,mm6
psrlq mm5,42
paddq mm7,QWORD PTR 128[esp]
pxor mm1,mm5
psllq mm6,42
movq mm5,QWORD PTR 40[esp]
pxor mm1,mm6
movq mm6,QWORD PTR 48[esp]
paddq mm7,mm1
movq mm1,mm4
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
movq QWORD PTR 72[esp],mm7
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
paddq mm7,QWORD PTR [ebp]
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
sub esp,8
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm7,QWORD PTR 192[esp]
paddq mm2,mm6
add ebp,8
movq mm5,QWORD PTR 88[esp]
movq mm1,mm7
psrlq mm7,1
movq mm6,mm5
psrlq mm5,6
psllq mm1,56
paddq mm2,mm3
movq mm3,mm7
psrlq mm7,6
pxor mm3,mm1
psllq mm1,7
pxor mm3,mm7
psrlq mm7,1
pxor mm3,mm1
movq mm1,mm5
psrlq mm5,13
pxor mm7,mm3
psllq mm6,3
pxor mm1,mm5
paddq mm7,QWORD PTR 200[esp]
pxor mm1,mm6
psrlq mm5,42
paddq mm7,QWORD PTR 128[esp]
pxor mm1,mm5
psllq mm6,42
movq mm5,QWORD PTR 40[esp]
pxor mm1,mm6
movq mm6,QWORD PTR 48[esp]
paddq mm7,mm1
movq mm1,mm4
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
movq QWORD PTR 72[esp],mm7
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
paddq mm7,QWORD PTR [ebp]
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
sub esp,8
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm7,QWORD PTR 192[esp]
paddq mm0,mm6
add ebp,8
dec edx
jnz $L00616_79_sse2
paddq mm0,mm3
movq mm1,QWORD PTR 8[esp]
movq mm3,QWORD PTR 24[esp]
movq mm5,QWORD PTR 40[esp]
movq mm6,QWORD PTR 48[esp]
movq mm7,QWORD PTR 56[esp]
pxor mm2,mm1
paddq mm0,QWORD PTR [esi]
paddq mm1,QWORD PTR 8[esi]
paddq mm2,QWORD PTR 16[esi]
paddq mm3,QWORD PTR 24[esi]
paddq mm4,QWORD PTR 32[esi]
paddq mm5,QWORD PTR 40[esi]
paddq mm6,QWORD PTR 48[esi]
paddq mm7,QWORD PTR 56[esi]
mov eax,640
movq QWORD PTR [esi],mm0
movq QWORD PTR 8[esi],mm1
movq QWORD PTR 16[esi],mm2
movq QWORD PTR 24[esi],mm3
movq QWORD PTR 32[esi],mm4
movq QWORD PTR 40[esi],mm5
movq QWORD PTR 48[esi],mm6
movq QWORD PTR 56[esi],mm7
lea esp,DWORD PTR [eax*1+esp]
sub ebp,eax
cmp edi,DWORD PTR 88[esp]
jb $L004loop_sse2
mov esp,DWORD PTR 92[esp]
emms
pop edi
pop esi
pop ebx
pop ebp
ret
ALIGN 32
$L003SSSE3:
lea edx,DWORD PTR [esp-64]
sub esp,256
movdqa xmm1,XMMWORD PTR 640[ebp]
movdqu xmm0,XMMWORD PTR [edi]
DB 102,15,56,0,193
movdqa xmm3,XMMWORD PTR [ebp]
movdqa xmm2,xmm1
movdqu xmm1,XMMWORD PTR 16[edi]
paddq xmm3,xmm0
DB 102,15,56,0,202
movdqa XMMWORD PTR [edx-128],xmm3
movdqa xmm4,XMMWORD PTR 16[ebp]
movdqa xmm3,xmm2
movdqu xmm2,XMMWORD PTR 32[edi]
paddq xmm4,xmm1
DB 102,15,56,0,211
movdqa XMMWORD PTR [edx-112],xmm4
movdqa xmm5,XMMWORD PTR 32[ebp]
movdqa xmm4,xmm3
movdqu xmm3,XMMWORD PTR 48[edi]
paddq xmm5,xmm2
DB 102,15,56,0,220
movdqa XMMWORD PTR [edx-96],xmm5
movdqa xmm6,XMMWORD PTR 48[ebp]
movdqa xmm5,xmm4
movdqu xmm4,XMMWORD PTR 64[edi]
paddq xmm6,xmm3
DB 102,15,56,0,229
movdqa XMMWORD PTR [edx-80],xmm6
movdqa xmm7,XMMWORD PTR 64[ebp]
movdqa xmm6,xmm5
movdqu xmm5,XMMWORD PTR 80[edi]
paddq xmm7,xmm4
DB 102,15,56,0,238
movdqa XMMWORD PTR [edx-64],xmm7
movdqa XMMWORD PTR [edx],xmm0
movdqa xmm0,XMMWORD PTR 80[ebp]
movdqa xmm7,xmm6
movdqu xmm6,XMMWORD PTR 96[edi]
paddq xmm0,xmm5
DB 102,15,56,0,247
movdqa XMMWORD PTR [edx-48],xmm0
movdqa XMMWORD PTR 16[edx],xmm1
movdqa xmm1,XMMWORD PTR 96[ebp]
movdqa xmm0,xmm7
movdqu xmm7,XMMWORD PTR 112[edi]
paddq xmm1,xmm6
DB 102,15,56,0,248
movdqa XMMWORD PTR [edx-32],xmm1
movdqa XMMWORD PTR 32[edx],xmm2
movdqa xmm2,XMMWORD PTR 112[ebp]
movdqa xmm0,XMMWORD PTR [edx]
paddq xmm2,xmm7
movdqa XMMWORD PTR [edx-16],xmm2
nop
ALIGN 32
$L007loop_ssse3:
movdqa xmm2,XMMWORD PTR 16[edx]
movdqa XMMWORD PTR 48[edx],xmm3
lea ebp,DWORD PTR 128[ebp]
movq QWORD PTR 8[esp],mm1
mov ebx,edi
movq QWORD PTR 16[esp],mm2
lea edi,DWORD PTR 128[edi]
movq QWORD PTR 24[esp],mm3
cmp edi,eax
movq QWORD PTR 40[esp],mm5
cmovb ebx,edi
movq QWORD PTR 48[esp],mm6
mov ecx,4
pxor mm2,mm1
movq QWORD PTR 56[esp],mm7
pxor mm3,mm3
jmp $L00800_47_ssse3
ALIGN 32
$L00800_47_ssse3:
movdqa xmm3,xmm5
movdqa xmm1,xmm2
DB 102,15,58,15,208,8
movdqa XMMWORD PTR [edx],xmm4
DB 102,15,58,15,220,8
movdqa xmm4,xmm2
psrlq xmm2,7
paddq xmm0,xmm3
movdqa xmm3,xmm4
psrlq xmm4,1
psllq xmm3,56
pxor xmm2,xmm4
psrlq xmm4,7
pxor xmm2,xmm3
psllq xmm3,7
pxor xmm2,xmm4
movdqa xmm4,xmm7
pxor xmm2,xmm3
movdqa xmm3,xmm7
psrlq xmm4,6
paddq xmm0,xmm2
movdqa xmm2,xmm7
psrlq xmm3,19
psllq xmm2,3
pxor xmm4,xmm3
psrlq xmm3,42
pxor xmm4,xmm2
psllq xmm2,42
pxor xmm4,xmm3
movdqa xmm3,XMMWORD PTR 32[edx]
pxor xmm4,xmm2
movdqa xmm2,XMMWORD PTR [ebp]
movq mm1,mm4
paddq xmm0,xmm4
movq mm7,QWORD PTR [edx-128]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
paddq xmm2,xmm0
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 32[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 40[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-120]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 24[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 56[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 48[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 16[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR [esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 24[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 32[esp]
movdqa XMMWORD PTR [edx-128],xmm2
movdqa xmm4,xmm6
movdqa xmm2,xmm3
DB 102,15,58,15,217,8
movdqa XMMWORD PTR 16[edx],xmm5
DB 102,15,58,15,229,8
movdqa xmm5,xmm3
psrlq xmm3,7
paddq xmm1,xmm4
movdqa xmm4,xmm5
psrlq xmm5,1
psllq xmm4,56
pxor xmm3,xmm5
psrlq xmm5,7
pxor xmm3,xmm4
psllq xmm4,7
pxor xmm3,xmm5
movdqa xmm5,xmm0
pxor xmm3,xmm4
movdqa xmm4,xmm0
psrlq xmm5,6
paddq xmm1,xmm3
movdqa xmm3,xmm0
psrlq xmm4,19
psllq xmm3,3
pxor xmm5,xmm4
psrlq xmm4,42
pxor xmm5,xmm3
psllq xmm3,42
pxor xmm5,xmm4
movdqa xmm4,XMMWORD PTR 48[edx]
pxor xmm5,xmm3
movdqa xmm3,XMMWORD PTR 16[ebp]
movq mm1,mm4
paddq xmm1,xmm5
movq mm7,QWORD PTR [edx-112]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 16[esp],mm4
paddq xmm3,xmm1
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 48[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 40[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 8[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 56[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 16[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 24[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-104]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 8[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 40[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 32[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR [esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 48[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 8[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 16[esp]
movdqa XMMWORD PTR [edx-112],xmm3
movdqa xmm5,xmm7
movdqa xmm3,xmm4
DB 102,15,58,15,226,8
movdqa XMMWORD PTR 32[edx],xmm6
DB 102,15,58,15,238,8
movdqa xmm6,xmm4
psrlq xmm4,7
paddq xmm2,xmm5
movdqa xmm5,xmm6
psrlq xmm6,1
psllq xmm5,56
pxor xmm4,xmm6
psrlq xmm6,7
pxor xmm4,xmm5
psllq xmm5,7
pxor xmm4,xmm6
movdqa xmm6,xmm1
pxor xmm4,xmm5
movdqa xmm5,xmm1
psrlq xmm6,6
paddq xmm2,xmm4
movdqa xmm4,xmm1
psrlq xmm5,19
psllq xmm4,3
pxor xmm6,xmm5
psrlq xmm5,42
pxor xmm6,xmm4
psllq xmm4,42
pxor xmm6,xmm5
movdqa xmm5,XMMWORD PTR [edx]
pxor xmm6,xmm4
movdqa xmm4,XMMWORD PTR 32[ebp]
movq mm1,mm4
paddq xmm2,xmm6
movq mm7,QWORD PTR [edx-96]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR [esp],mm4
paddq xmm4,xmm2
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 32[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 24[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 56[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 40[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR [esp]
paddq mm2,mm6
movq mm6,QWORD PTR 8[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-88]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 56[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 24[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 16[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 48[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 32[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 56[esp]
paddq mm0,mm6
movq mm6,QWORD PTR [esp]
movdqa XMMWORD PTR [edx-96],xmm4
movdqa xmm6,xmm0
movdqa xmm4,xmm5
DB 102,15,58,15,235,8
movdqa XMMWORD PTR 48[edx],xmm7
DB 102,15,58,15,247,8
movdqa xmm7,xmm5
psrlq xmm5,7
paddq xmm3,xmm6
movdqa xmm6,xmm7
psrlq xmm7,1
psllq xmm6,56
pxor xmm5,xmm7
psrlq xmm7,7
pxor xmm5,xmm6
psllq xmm6,7
pxor xmm5,xmm7
movdqa xmm7,xmm2
pxor xmm5,xmm6
movdqa xmm6,xmm2
psrlq xmm7,6
paddq xmm3,xmm5
movdqa xmm5,xmm2
psrlq xmm6,19
psllq xmm5,3
pxor xmm7,xmm6
psrlq xmm6,42
pxor xmm7,xmm5
psllq xmm5,42
pxor xmm7,xmm6
movdqa xmm6,XMMWORD PTR 16[edx]
pxor xmm7,xmm5
movdqa xmm5,XMMWORD PTR 48[ebp]
movq mm1,mm4
paddq xmm3,xmm7
movq mm7,QWORD PTR [edx-80]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 48[esp],mm4
paddq xmm5,xmm3
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 16[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 8[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 40[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 24[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 48[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 56[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-72]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 40[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 8[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR [esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 32[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 16[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 40[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 48[esp]
movdqa XMMWORD PTR [edx-80],xmm5
movdqa xmm7,xmm1
movdqa xmm5,xmm6
DB 102,15,58,15,244,8
movdqa XMMWORD PTR [edx],xmm0
DB 102,15,58,15,248,8
movdqa xmm0,xmm6
psrlq xmm6,7
paddq xmm4,xmm7
movdqa xmm7,xmm0
psrlq xmm0,1
psllq xmm7,56
pxor xmm6,xmm0
psrlq xmm0,7
pxor xmm6,xmm7
psllq xmm7,7
pxor xmm6,xmm0
movdqa xmm0,xmm3
pxor xmm6,xmm7
movdqa xmm7,xmm3
psrlq xmm0,6
paddq xmm4,xmm6
movdqa xmm6,xmm3
psrlq xmm7,19
psllq xmm6,3
pxor xmm0,xmm7
psrlq xmm7,42
pxor xmm0,xmm6
psllq xmm6,42
pxor xmm0,xmm7
movdqa xmm7,XMMWORD PTR 32[edx]
pxor xmm0,xmm6
movdqa xmm6,XMMWORD PTR 64[ebp]
movq mm1,mm4
paddq xmm4,xmm0
movq mm7,QWORD PTR [edx-64]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
paddq xmm6,xmm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 32[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 40[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-56]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 24[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 56[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 48[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 16[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR [esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 24[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 32[esp]
movdqa XMMWORD PTR [edx-64],xmm6
movdqa xmm0,xmm2
movdqa xmm6,xmm7
DB 102,15,58,15,253,8
movdqa XMMWORD PTR 16[edx],xmm1
DB 102,15,58,15,193,8
movdqa xmm1,xmm7
psrlq xmm7,7
paddq xmm5,xmm0
movdqa xmm0,xmm1
psrlq xmm1,1
psllq xmm0,56
pxor xmm7,xmm1
psrlq xmm1,7
pxor xmm7,xmm0
psllq xmm0,7
pxor xmm7,xmm1
movdqa xmm1,xmm4
pxor xmm7,xmm0
movdqa xmm0,xmm4
psrlq xmm1,6
paddq xmm5,xmm7
movdqa xmm7,xmm4
psrlq xmm0,19
psllq xmm7,3
pxor xmm1,xmm0
psrlq xmm0,42
pxor xmm1,xmm7
psllq xmm7,42
pxor xmm1,xmm0
movdqa xmm0,XMMWORD PTR 48[edx]
pxor xmm1,xmm7
movdqa xmm7,XMMWORD PTR 80[ebp]
movq mm1,mm4
paddq xmm5,xmm1
movq mm7,QWORD PTR [edx-48]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 16[esp],mm4
paddq xmm7,xmm5
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 48[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 40[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 8[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 56[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 16[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 24[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-40]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 8[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 40[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 32[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR [esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 48[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 8[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 16[esp]
movdqa XMMWORD PTR [edx-48],xmm7
movdqa xmm1,xmm3
movdqa xmm7,xmm0
DB 102,15,58,15,198,8
movdqa XMMWORD PTR 32[edx],xmm2
DB 102,15,58,15,202,8
movdqa xmm2,xmm0
psrlq xmm0,7
paddq xmm6,xmm1
movdqa xmm1,xmm2
psrlq xmm2,1
psllq xmm1,56
pxor xmm0,xmm2
psrlq xmm2,7
pxor xmm0,xmm1
psllq xmm1,7
pxor xmm0,xmm2
movdqa xmm2,xmm5
pxor xmm0,xmm1
movdqa xmm1,xmm5
psrlq xmm2,6
paddq xmm6,xmm0
movdqa xmm0,xmm5
psrlq xmm1,19
psllq xmm0,3
pxor xmm2,xmm1
psrlq xmm1,42
pxor xmm2,xmm0
psllq xmm0,42
pxor xmm2,xmm1
movdqa xmm1,XMMWORD PTR [edx]
pxor xmm2,xmm0
movdqa xmm0,XMMWORD PTR 96[ebp]
movq mm1,mm4
paddq xmm6,xmm2
movq mm7,QWORD PTR [edx-32]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR [esp],mm4
paddq xmm0,xmm6
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 32[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 24[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 56[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 40[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR [esp]
paddq mm2,mm6
movq mm6,QWORD PTR 8[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-24]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 56[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 24[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 16[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 48[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 32[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 56[esp]
paddq mm0,mm6
movq mm6,QWORD PTR [esp]
movdqa XMMWORD PTR [edx-32],xmm0
movdqa xmm2,xmm4
movdqa xmm0,xmm1
DB 102,15,58,15,207,8
movdqa XMMWORD PTR 48[edx],xmm3
DB 102,15,58,15,211,8
movdqa xmm3,xmm1
psrlq xmm1,7
paddq xmm7,xmm2
movdqa xmm2,xmm3
psrlq xmm3,1
psllq xmm2,56
pxor xmm1,xmm3
psrlq xmm3,7
pxor xmm1,xmm2
psllq xmm2,7
pxor xmm1,xmm3
movdqa xmm3,xmm6
pxor xmm1,xmm2
movdqa xmm2,xmm6
psrlq xmm3,6
paddq xmm7,xmm1
movdqa xmm1,xmm6
psrlq xmm2,19
psllq xmm1,3
pxor xmm3,xmm2
psrlq xmm2,42
pxor xmm3,xmm1
psllq xmm1,42
pxor xmm3,xmm2
movdqa xmm2,XMMWORD PTR 16[edx]
pxor xmm3,xmm1
movdqa xmm1,XMMWORD PTR 112[ebp]
movq mm1,mm4
paddq xmm7,xmm3
movq mm7,QWORD PTR [edx-16]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 48[esp],mm4
paddq xmm1,xmm7
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 16[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 8[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 40[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 24[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 48[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 56[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-8]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 40[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 8[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR [esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 32[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 16[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 40[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 48[esp]
movdqa XMMWORD PTR [edx-16],xmm1
lea ebp,DWORD PTR 128[ebp]
dec ecx
jnz $L00800_47_ssse3
movdqa xmm1,XMMWORD PTR [ebp]
lea ebp,DWORD PTR [ebp-640]
movdqu xmm0,XMMWORD PTR [ebx]
DB 102,15,56,0,193
movdqa xmm3,XMMWORD PTR [ebp]
movdqa xmm2,xmm1
movdqu xmm1,XMMWORD PTR 16[ebx]
paddq xmm3,xmm0
DB 102,15,56,0,202
movq mm1,mm4
movq mm7,QWORD PTR [edx-128]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 32[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 40[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-120]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 24[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 56[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 48[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 16[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR [esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 24[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 32[esp]
movdqa XMMWORD PTR [edx-128],xmm3
movdqa xmm4,XMMWORD PTR 16[ebp]
movdqa xmm3,xmm2
movdqu xmm2,XMMWORD PTR 32[ebx]
paddq xmm4,xmm1
DB 102,15,56,0,211
movq mm1,mm4
movq mm7,QWORD PTR [edx-112]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 16[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 48[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 40[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 8[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 56[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 16[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 24[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-104]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 8[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 40[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 32[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR [esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 48[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 8[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 16[esp]
movdqa XMMWORD PTR [edx-112],xmm4
movdqa xmm5,XMMWORD PTR 32[ebp]
movdqa xmm4,xmm3
movdqu xmm3,XMMWORD PTR 48[ebx]
paddq xmm5,xmm2
DB 102,15,56,0,220
movq mm1,mm4
movq mm7,QWORD PTR [edx-96]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR [esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 32[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 24[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 56[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 40[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR [esp]
paddq mm2,mm6
movq mm6,QWORD PTR 8[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-88]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 56[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 24[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 16[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 48[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 32[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 56[esp]
paddq mm0,mm6
movq mm6,QWORD PTR [esp]
movdqa XMMWORD PTR [edx-96],xmm5
movdqa xmm6,XMMWORD PTR 48[ebp]
movdqa xmm5,xmm4
movdqu xmm4,XMMWORD PTR 64[ebx]
paddq xmm6,xmm3
DB 102,15,56,0,229
movq mm1,mm4
movq mm7,QWORD PTR [edx-80]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 48[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 16[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 8[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 40[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 24[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 48[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 56[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-72]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 40[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 8[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR [esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 32[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 16[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 40[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 48[esp]
movdqa XMMWORD PTR [edx-80],xmm6
movdqa xmm7,XMMWORD PTR 64[ebp]
movdqa xmm6,xmm5
movdqu xmm5,XMMWORD PTR 80[ebx]
paddq xmm7,xmm4
DB 102,15,56,0,238
movq mm1,mm4
movq mm7,QWORD PTR [edx-64]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 32[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR [esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 56[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 24[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 8[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 32[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 40[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-56]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 24[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 56[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 48[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 16[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR [esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 24[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 32[esp]
movdqa XMMWORD PTR [edx-64],xmm7
movdqa XMMWORD PTR [edx],xmm0
movdqa xmm0,XMMWORD PTR 80[ebp]
movdqa xmm7,xmm6
movdqu xmm6,XMMWORD PTR 96[ebx]
paddq xmm0,xmm5
DB 102,15,56,0,247
movq mm1,mm4
movq mm7,QWORD PTR [edx-48]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 16[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 48[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 40[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 8[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 56[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 16[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 24[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-40]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 8[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 40[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 32[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR [esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 48[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 8[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 16[esp]
movdqa XMMWORD PTR [edx-48],xmm0
movdqa XMMWORD PTR 16[edx],xmm1
movdqa xmm1,XMMWORD PTR 96[ebp]
movdqa xmm0,xmm7
movdqu xmm7,XMMWORD PTR 112[ebx]
paddq xmm1,xmm6
DB 102,15,56,0,248
movq mm1,mm4
movq mm7,QWORD PTR [edx-32]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR [esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 32[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 24[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 56[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 40[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR [esp]
paddq mm2,mm6
movq mm6,QWORD PTR 8[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-24]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 56[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 24[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 16[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 48[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 32[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 56[esp]
paddq mm0,mm6
movq mm6,QWORD PTR [esp]
movdqa XMMWORD PTR [edx-32],xmm1
movdqa XMMWORD PTR 32[edx],xmm2
movdqa xmm2,XMMWORD PTR 112[ebp]
movdqa xmm0,XMMWORD PTR [edx]
paddq xmm2,xmm7
movq mm1,mm4
movq mm7,QWORD PTR [edx-16]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 48[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm0,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 16[esp],mm0
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR 8[esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 40[esp]
paddq mm3,mm7
movq mm5,mm0
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm0
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 24[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm0,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm2,mm0
psllq mm6,6
pxor mm7,mm5
pxor mm2,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 48[esp]
paddq mm2,mm6
movq mm6,QWORD PTR 56[esp]
movq mm1,mm4
movq mm7,QWORD PTR [edx-8]
pxor mm5,mm6
psrlq mm1,14
movq QWORD PTR 40[esp],mm4
pand mm5,mm4
psllq mm4,23
paddq mm2,mm3
movq mm3,mm1
psrlq mm1,4
pxor mm5,mm6
pxor mm3,mm4
psllq mm4,23
pxor mm3,mm1
movq QWORD PTR 8[esp],mm2
paddq mm7,mm5
pxor mm3,mm4
psrlq mm1,23
paddq mm7,QWORD PTR [esp]
pxor mm3,mm1
psllq mm4,4
pxor mm3,mm4
movq mm4,QWORD PTR 32[esp]
paddq mm3,mm7
movq mm5,mm2
psrlq mm5,28
paddq mm4,mm3
movq mm6,mm2
movq mm7,mm5
psllq mm6,25
movq mm1,QWORD PTR 16[esp]
psrlq mm5,6
pxor mm7,mm6
psllq mm6,5
pxor mm7,mm5
pxor mm2,mm1
psrlq mm5,5
pxor mm7,mm6
pand mm0,mm2
psllq mm6,6
pxor mm7,mm5
pxor mm0,mm1
pxor mm6,mm7
movq mm5,QWORD PTR 40[esp]
paddq mm0,mm6
movq mm6,QWORD PTR 48[esp]
movdqa XMMWORD PTR [edx-16],xmm2
movq mm1,QWORD PTR 8[esp]
paddq mm0,mm3
movq mm3,QWORD PTR 24[esp]
movq mm7,QWORD PTR 56[esp]
pxor mm2,mm1
paddq mm0,QWORD PTR [esi]
paddq mm1,QWORD PTR 8[esi]
paddq mm2,QWORD PTR 16[esi]
paddq mm3,QWORD PTR 24[esi]
paddq mm4,QWORD PTR 32[esi]
paddq mm5,QWORD PTR 40[esi]
paddq mm6,QWORD PTR 48[esi]
paddq mm7,QWORD PTR 56[esi]
movq QWORD PTR [esi],mm0
movq QWORD PTR 8[esi],mm1
movq QWORD PTR 16[esi],mm2
movq QWORD PTR 24[esi],mm3
movq QWORD PTR 32[esi],mm4
movq QWORD PTR 40[esi],mm5
movq QWORD PTR 48[esi],mm6
movq QWORD PTR 56[esi],mm7
cmp edi,eax
jb $L007loop_ssse3
mov esp,DWORD PTR 76[edx]
emms
pop edi
pop esi
pop ebx
pop ebp
ret
ALIGN 16
$L002loop_x86:
mov eax,DWORD PTR [edi]
mov ebx,DWORD PTR 4[edi]
mov ecx,DWORD PTR 8[edi]
mov edx,DWORD PTR 12[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 16[edi]
mov ebx,DWORD PTR 20[edi]
mov ecx,DWORD PTR 24[edi]
mov edx,DWORD PTR 28[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 32[edi]
mov ebx,DWORD PTR 36[edi]
mov ecx,DWORD PTR 40[edi]
mov edx,DWORD PTR 44[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 48[edi]
mov ebx,DWORD PTR 52[edi]
mov ecx,DWORD PTR 56[edi]
mov edx,DWORD PTR 60[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 64[edi]
mov ebx,DWORD PTR 68[edi]
mov ecx,DWORD PTR 72[edi]
mov edx,DWORD PTR 76[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 80[edi]
mov ebx,DWORD PTR 84[edi]
mov ecx,DWORD PTR 88[edi]
mov edx,DWORD PTR 92[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 96[edi]
mov ebx,DWORD PTR 100[edi]
mov ecx,DWORD PTR 104[edi]
mov edx,DWORD PTR 108[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
mov eax,DWORD PTR 112[edi]
mov ebx,DWORD PTR 116[edi]
mov ecx,DWORD PTR 120[edi]
mov edx,DWORD PTR 124[edi]
bswap eax
bswap ebx
bswap ecx
bswap edx
push eax
push ebx
push ecx
push edx
add edi,128
sub esp,72
mov DWORD PTR 204[esp],edi
lea edi,DWORD PTR 8[esp]
mov ecx,16
DD 2784229001
ALIGN 16
$L00900_15_x86:
mov ecx,DWORD PTR 40[esp]
mov edx,DWORD PTR 44[esp]
mov esi,ecx
shr ecx,9
mov edi,edx
shr edx,9
mov ebx,ecx
shl esi,14
mov eax,edx
shl edi,14
xor ebx,esi
shr ecx,5
xor eax,edi
shr edx,5
xor eax,ecx
shl esi,4
xor ebx,edx
shl edi,4
xor ebx,esi
shr ecx,4
xor eax,edi
shr edx,4
xor eax,ecx
shl esi,5
xor ebx,edx
shl edi,5
xor eax,esi
xor ebx,edi
mov ecx,DWORD PTR 48[esp]
mov edx,DWORD PTR 52[esp]
mov esi,DWORD PTR 56[esp]
mov edi,DWORD PTR 60[esp]
add eax,DWORD PTR 64[esp]
adc ebx,DWORD PTR 68[esp]
xor ecx,esi
xor edx,edi
and ecx,DWORD PTR 40[esp]
and edx,DWORD PTR 44[esp]
add eax,DWORD PTR 192[esp]
adc ebx,DWORD PTR 196[esp]
xor ecx,esi
xor edx,edi
mov esi,DWORD PTR [ebp]
mov edi,DWORD PTR 4[ebp]
add eax,ecx
adc ebx,edx
mov ecx,DWORD PTR 32[esp]
mov edx,DWORD PTR 36[esp]
add eax,esi
adc ebx,edi
mov DWORD PTR [esp],eax
mov DWORD PTR 4[esp],ebx
add eax,ecx
adc ebx,edx
mov ecx,DWORD PTR 8[esp]
mov edx,DWORD PTR 12[esp]
mov DWORD PTR 32[esp],eax
mov DWORD PTR 36[esp],ebx
mov esi,ecx
shr ecx,2
mov edi,edx
shr edx,2
mov ebx,ecx
shl esi,4
mov eax,edx
shl edi,4
xor ebx,esi
shr ecx,5
xor eax,edi
shr edx,5
xor ebx,ecx
shl esi,21
xor eax,edx
shl edi,21
xor eax,esi
shr ecx,21
xor ebx,edi
shr edx,21
xor eax,ecx
shl esi,5
xor ebx,edx
shl edi,5
xor eax,esi
xor ebx,edi
mov ecx,DWORD PTR 8[esp]
mov edx,DWORD PTR 12[esp]
mov esi,DWORD PTR 16[esp]
mov edi,DWORD PTR 20[esp]
add eax,DWORD PTR [esp]
adc ebx,DWORD PTR 4[esp]
or ecx,esi
or edx,edi
and ecx,DWORD PTR 24[esp]
and edx,DWORD PTR 28[esp]
and esi,DWORD PTR 8[esp]
and edi,DWORD PTR 12[esp]
or ecx,esi
or edx,edi
add eax,ecx
adc ebx,edx
mov DWORD PTR [esp],eax
mov DWORD PTR 4[esp],ebx
mov dl,BYTE PTR [ebp]
sub esp,8
lea ebp,DWORD PTR 8[ebp]
cmp dl,148
jne $L00900_15_x86
ALIGN 16
$L01016_79_x86:
mov ecx,DWORD PTR 312[esp]
mov edx,DWORD PTR 316[esp]
mov esi,ecx
shr ecx,1
mov edi,edx
shr edx,1
mov eax,ecx
shl esi,24
mov ebx,edx
shl edi,24
xor ebx,esi
shr ecx,6
xor eax,edi
shr edx,6
xor eax,ecx
shl esi,7
xor ebx,edx
shl edi,1
xor ebx,esi
shr ecx,1
xor eax,edi
shr edx,1
xor eax,ecx
shl edi,6
xor ebx,edx
xor eax,edi
mov DWORD PTR [esp],eax
mov DWORD PTR 4[esp],ebx
mov ecx,DWORD PTR 208[esp]
mov edx,DWORD PTR 212[esp]
mov esi,ecx
shr ecx,6
mov edi,edx
shr edx,6
mov eax,ecx
shl esi,3
mov ebx,edx
shl edi,3
xor eax,esi
shr ecx,13
xor ebx,edi
shr edx,13
xor eax,ecx
shl esi,10
xor ebx,edx
shl edi,10
xor ebx,esi
shr ecx,10
xor eax,edi
shr edx,10
xor ebx,ecx
shl edi,13
xor eax,edx
xor eax,edi
mov ecx,DWORD PTR 320[esp]
mov edx,DWORD PTR 324[esp]
add eax,DWORD PTR [esp]
adc ebx,DWORD PTR 4[esp]
mov esi,DWORD PTR 248[esp]
mov edi,DWORD PTR 252[esp]
add eax,ecx
adc ebx,edx
add eax,esi
adc ebx,edi
mov DWORD PTR 192[esp],eax
mov DWORD PTR 196[esp],ebx
mov ecx,DWORD PTR 40[esp]
mov edx,DWORD PTR 44[esp]
mov esi,ecx
shr ecx,9
mov edi,edx
shr edx,9
mov ebx,ecx
shl esi,14
mov eax,edx
shl edi,14
xor ebx,esi
shr ecx,5
xor eax,edi
shr edx,5
xor eax,ecx
shl esi,4
xor ebx,edx
shl edi,4
xor ebx,esi
shr ecx,4
xor eax,edi
shr edx,4
xor eax,ecx
shl esi,5
xor ebx,edx
shl edi,5
xor eax,esi
xor ebx,edi
mov ecx,DWORD PTR 48[esp]
mov edx,DWORD PTR 52[esp]
mov esi,DWORD PTR 56[esp]
mov edi,DWORD PTR 60[esp]
add eax,DWORD PTR 64[esp]
adc ebx,DWORD PTR 68[esp]
xor ecx,esi
xor edx,edi
and ecx,DWORD PTR 40[esp]
and edx,DWORD PTR 44[esp]
add eax,DWORD PTR 192[esp]
adc ebx,DWORD PTR 196[esp]
xor ecx,esi
xor edx,edi
mov esi,DWORD PTR [ebp]
mov edi,DWORD PTR 4[ebp]
add eax,ecx
adc ebx,edx
mov ecx,DWORD PTR 32[esp]
mov edx,DWORD PTR 36[esp]
add eax,esi
adc ebx,edi
mov DWORD PTR [esp],eax
mov DWORD PTR 4[esp],ebx
add eax,ecx
adc ebx,edx
mov ecx,DWORD PTR 8[esp]
mov edx,DWORD PTR 12[esp]
mov DWORD PTR 32[esp],eax
mov DWORD PTR 36[esp],ebx
mov esi,ecx
shr ecx,2
mov edi,edx
shr edx,2
mov ebx,ecx
shl esi,4
mov eax,edx
shl edi,4
xor ebx,esi
shr ecx,5
xor eax,edi
shr edx,5
xor ebx,ecx
shl esi,21
xor eax,edx
shl edi,21
xor eax,esi
shr ecx,21
xor ebx,edi
shr edx,21
xor eax,ecx
shl esi,5
xor ebx,edx
shl edi,5
xor eax,esi
xor ebx,edi
mov ecx,DWORD PTR 8[esp]
mov edx,DWORD PTR 12[esp]
mov esi,DWORD PTR 16[esp]
mov edi,DWORD PTR 20[esp]
add eax,DWORD PTR [esp]
adc ebx,DWORD PTR 4[esp]
or ecx,esi
or edx,edi
and ecx,DWORD PTR 24[esp]
and edx,DWORD PTR 28[esp]
and esi,DWORD PTR 8[esp]
and edi,DWORD PTR 12[esp]
or ecx,esi
or edx,edi
add eax,ecx
adc ebx,edx
mov DWORD PTR [esp],eax
mov DWORD PTR 4[esp],ebx
mov dl,BYTE PTR [ebp]
sub esp,8
lea ebp,DWORD PTR 8[ebp]
cmp dl,23
jne $L01016_79_x86
mov esi,DWORD PTR 840[esp]
mov edi,DWORD PTR 844[esp]
mov eax,DWORD PTR [esi]
mov ebx,DWORD PTR 4[esi]
mov ecx,DWORD PTR 8[esi]
mov edx,DWORD PTR 12[esi]
add eax,DWORD PTR 8[esp]
adc ebx,DWORD PTR 12[esp]
mov DWORD PTR [esi],eax
mov DWORD PTR 4[esi],ebx
add ecx,DWORD PTR 16[esp]
adc edx,DWORD PTR 20[esp]
mov DWORD PTR 8[esi],ecx
mov DWORD PTR 12[esi],edx
mov eax,DWORD PTR 16[esi]
mov ebx,DWORD PTR 20[esi]
mov ecx,DWORD PTR 24[esi]
mov edx,DWORD PTR 28[esi]
add eax,DWORD PTR 24[esp]
adc ebx,DWORD PTR 28[esp]
mov DWORD PTR 16[esi],eax
mov DWORD PTR 20[esi],ebx
add ecx,DWORD PTR 32[esp]
adc edx,DWORD PTR 36[esp]
mov DWORD PTR 24[esi],ecx
mov DWORD PTR 28[esi],edx
mov eax,DWORD PTR 32[esi]
mov ebx,DWORD PTR 36[esi]
mov ecx,DWORD PTR 40[esi]
mov edx,DWORD PTR 44[esi]
add eax,DWORD PTR 40[esp]
adc ebx,DWORD PTR 44[esp]
mov DWORD PTR 32[esi],eax
mov DWORD PTR 36[esi],ebx
add ecx,DWORD PTR 48[esp]
adc edx,DWORD PTR 52[esp]
mov DWORD PTR 40[esi],ecx
mov DWORD PTR 44[esi],edx
mov eax,DWORD PTR 48[esi]
mov ebx,DWORD PTR 52[esi]
mov ecx,DWORD PTR 56[esi]
mov edx,DWORD PTR 60[esi]
add eax,DWORD PTR 56[esp]
adc ebx,DWORD PTR 60[esp]
mov DWORD PTR 48[esi],eax
mov DWORD PTR 52[esi],ebx
add ecx,DWORD PTR 64[esp]
adc edx,DWORD PTR 68[esp]
mov DWORD PTR 56[esi],ecx
mov DWORD PTR 60[esi],edx
add esp,840
sub ebp,640
cmp edi,DWORD PTR 8[esp]
jb $L002loop_x86
mov esp,DWORD PTR 12[esp]
pop edi
pop esi
pop ebx
pop ebp
ret
ALIGN 64
$L001K512:
DD 3609767458,1116352408
DD 602891725,1899447441
DD 3964484399,3049323471
DD 2173295548,3921009573
DD 4081628472,961987163
DD 3053834265,1508970993
DD 2937671579,2453635748
DD 3664609560,2870763221
DD 2734883394,3624381080
DD 1164996542,310598401
DD 1323610764,607225278
DD 3590304994,1426881987
DD 4068182383,1925078388
DD 991336113,2162078206
DD 633803317,2614888103
DD 3479774868,3248222580
DD 2666613458,3835390401
DD 944711139,4022224774
DD 2341262773,264347078
DD 2007800933,604807628
DD 1495990901,770255983
DD 1856431235,1249150122
DD 3175218132,1555081692
DD 2198950837,1996064986
DD 3999719339,2554220882
DD 766784016,2821834349
DD 2566594879,2952996808
DD 3203337956,3210313671
DD 1034457026,3336571891
DD 2466948901,3584528711
DD 3758326383,113926993
DD 168717936,338241895
DD 1188179964,666307205
DD 1546045734,773529912
DD 1522805485,1294757372
DD 2643833823,1396182291
DD 2343527390,1695183700
DD 1014477480,1986661051
DD 1206759142,2177026350
DD 344077627,2456956037
DD 1290863460,2730485921
DD 3158454273,2820302411
DD 3505952657,3259730800
DD 106217008,3345764771
DD 3606008344,3516065817
DD 1432725776,3600352804
DD 1467031594,4094571909
DD 851169720,275423344
DD 3100823752,430227734
DD 1363258195,506948616
DD 3750685593,659060556
DD 3785050280,883997877
DD 3318307427,958139571
DD 3812723403,1322822218
DD 2003034995,1537002063
DD 3602036899,1747873779
DD 1575990012,1955562222
DD 1125592928,2024104815
DD 2716904306,2227730452
DD 442776044,2361852424
DD 593698344,2428436474
DD 3733110249,2756734187
DD 2999351573,3204031479
DD 3815920427,3329325298
DD 3928383900,3391569614
DD 566280711,3515267271
DD 3454069534,3940187606
DD 4000239992,4118630271
DD 1914138554,116418474
DD 2731055270,174292421
DD 3203993006,289380356
DD 320620315,460393269
DD 587496836,685471733
DD 1086792851,852142971
DD 365543100,1017036298
DD 2618297676,1126000580
DD 3409855158,1288033470
DD 4234509866,1501505948
DD 987167468,1607167915
DD 1246189591,1816402316
DD 67438087,66051
DD 202182159,134810123
_sha512_block_data_order ENDP
DB 83,72,65,53,49,50,32,98,108,111,99,107,32,116,114,97
DB 110,115,102,111,114,109,32,102,111,114,32,120,56,54,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
.text$ ENDS
.bss SEGMENT 'BSS'
COMM _OPENSSL_ia32cap_P:DWORD:4
.bss ENDS
END
|
; void __CALLEE__ *im2_CreateGenericISRLight_callee(uchar numhooks, void *addr)
; 10.2005 aralbrec
PUBLIC im2_CreateGenericISRLight_callee
PUBLIC ASMDISP_IM2_CREATEGENERICISRLIGHT_CALLEE
EXTERN IM2CreateCommon
.im2_CreateGenericISRLight_callee
pop hl
pop de
pop bc
push hl
ld a,c
.asmentry
; enter: a = maximum number of hooks
; de = RAM address to copy ISR to
; exit : hl = address just past ISR
; uses : af, bc, de, hl
.IM2CreateGenericISRLight
ld hl,GenericISRLight
jp IM2CreateCommon
.GenericISRLight
call pushreg
.position
ld bc,runhooks-position
add hl,bc
call runhooks
jp popreg
.runhooks
ld e,(hl)
inc hl
ld d,(hl)
inc hl
ld a,d
or e
ret z
push hl
ex de,hl
call JPHL
pop hl
ret c
jp runhooks
.popreg
pop de
pop bc
pop af
pop hl
ei
reti
.pushreg
ex (sp),hl
push af
push bc
push de
.JPHL
jp (hl)
DEFC ASMDISP_IM2_CREATEGENERICISRLIGHT_CALLEE = # asmentry - im2_CreateGenericISRLight_callee
|
; CALLER linkage for function pointers
PUBLIC fgetpos
EXTERN fgetpos_callee
EXTERN ASMDISP_FGETPOS_CALLEE
.fgetpos
pop de
pop hl
pop ix
push hl
push hl
push de
jp fgetpos_callee + ASMDISP_FGETPOS_CALLEE
|
; size_t w_vector_append_n(b_vector_t *v, size_t n, void *item)
SECTION code_clib
SECTION code_adt_w_vector
PUBLIC w_vector_append_n
EXTERN asm_w_vector_append_n
w_vector_append_n:
pop af
pop bc
pop de
pop hl
push hl
push de
push bc
push af
jp asm_w_vector_append_n
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC _w_vector_append_n
defc _w_vector_append_n = w_vector_append_n
ENDIF
|
;------------------------------------------------------------------------------
;
; Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.<BR>
; SPDX-License-Identifier: BSD-2-Clause-Patent
;
; Module Name:
;
; RdRand.nasm
;
; Abstract:
;
; Generates random number through CPU RdRand instruction under 32-bit platform.
;
; Notes:
;
;------------------------------------------------------------------------------
SECTION .text
;------------------------------------------------------------------------------
; Generates a 16 bit random number through RDRAND instruction.
; Return TRUE if Rand generated successfully, or FALSE if not.
;
; BOOLEAN EFIAPI InternalX86RdRand16 (UINT16 *Rand);
;------------------------------------------------------------------------------
global ASM_PFX(InternalX86RdRand16)
ASM_PFX(InternalX86RdRand16):
; rdrand ax ; generate a 16 bit RN into ax
; CF=1 if RN generated ok, otherwise CF=0
db 0xf, 0xc7, 0xf0 ; rdrand r16: "0f c7 /6 ModRM:r/m(w)"
jc rn16_ok ; jmp if CF=1
xor eax, eax ; reg=0 if CF=0
ret ; return with failure status
rn16_ok:
mov edx, dword [esp + 4]
mov [edx], ax
mov eax, 1
ret
;------------------------------------------------------------------------------
; Generates a 32 bit random number through RDRAND instruction.
; Return TRUE if Rand generated successfully, or FALSE if not.
;
; BOOLEAN EFIAPI InternalX86RdRand32 (UINT32 *Rand);
;------------------------------------------------------------------------------
global ASM_PFX(InternalX86RdRand32)
ASM_PFX(InternalX86RdRand32):
; rdrand eax ; generate a 32 bit RN into eax
; CF=1 if RN generated ok, otherwise CF=0
db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)"
jc rn32_ok ; jmp if CF=1
xor eax, eax ; reg=0 if CF=0
ret ; return with failure status
rn32_ok:
mov edx, dword [esp + 4]
mov [edx], eax
mov eax, 1
ret
;------------------------------------------------------------------------------
; Generates a 64 bit random number through RDRAND instruction.
; Return TRUE if Rand generated successfully, or FALSE if not.
;
; BOOLEAN EFIAPI InternalX86RdRand64 (UINT64 *Rand);
;------------------------------------------------------------------------------
global ASM_PFX(InternalX86RdRand64)
ASM_PFX(InternalX86RdRand64):
; rdrand eax ; generate a 32 bit RN into eax
; CF=1 if RN generated ok, otherwise CF=0
db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)"
jnc rn64_ret ; jmp if CF=0
mov edx, dword [esp + 4]
mov [edx], eax
db 0xf, 0xc7, 0xf0 ; generate another 32 bit RN
jnc rn64_ret ; jmp if CF=0
mov [edx + 4], eax
mov eax, 1
ret
rn64_ret:
xor eax, eax
ret ; return with failure status
|
BDP_OUT_BUFSIZE equ $30 ; Address of data size in buffer
BDP_OUT_BUFFER equ $32 ; Address of sub buffer
BDP_OUT_MAXSIZE equ $2E ; Max number of bytes in buffer
BDP_NEUTRALDATA set (CTH|CTL|CUP|CDOWN|CLEFT|CRIGHT)
BDP_NEUTRALCTRL set (CTHINT|CTR)
BDP_SENDDATA set (CTH|CTL|CTR|CUP|CDOWN|CLEFT|CRIGHT)
BDP_SENDCTRL set (CTL|CTR|CUP|CDOWN|CLEFT|CRIGHT)
; void bdp_write(char *data, int length);
_main_bdp_write
move.l 8(sp), d1 ; d1 = length
bne.b .data_present
rts
.data_present
move.l 4(sp), a0 ; a0 = source data
; Mask interrupts
move sr, d0
move.w d0, -(sp)
move #$2700, sr
; Setup port in output mode
move.b #BDP_SENDDATA, BDPDATA
move.b #BDP_SENDCTRL, BDPCTRL
; Compute packet size
bdp_send_packet
move.w d1, d0 ; d0 = packet size
cmpi.l #3, d1
ble.b .small
moveq #3, d0 ; Max 3 bytes per packet
.small
bdp_send_raw_packet ; Entry point to send one raw packet (d0 = low nybble of first byte, d1 = 3, a0 points to data)
; Send header byte
move.b #0|CTR, BDPDATA ; Send high nybble (always 0)
ori.b #CTL|CTR, d0 ; Precompute next nybble (packet size)
.head_msb
btst #CTH_BIT, BDPDATA ; Wait ack for high nybble
bne.b .head_msb
move.b d0, BDPDATA
moveq #2, d0 ; Always send 3 bytes per packet
bdp_send_byte
swap d0 ; Use other half of d0
; Wait until last byte was acknowledged
.wait_byte_ack
btst #CTH_BIT, BDPDATA
beq.b .wait_byte_ack
; Send high nybble
move.b (a0), d0
lsr.b #4, d0
ori.b #CTR, d0
move.b d0, BDPDATA ; Send high nybble of data
; Precompute low nybble
move.b (a0)+, d0
andi.b #$0F, d0
ori.b #CTL|CTR, d0
; Wait for high nybble ack
.byte_msb
btst #CTH_BIT, BDPDATA
bne.b .byte_msb
move.b d0, BDPDATA ; Send low nybble of data
swap d0 ; Restore byte count in d0
dbra d0, bdp_send_byte
; Packet sent
subq.l #3, d1 ; Compute remaining bytes to send
bgt.b bdp_send_packet
; Wait until ack line is released
.wait_last_ack
btst #CTH_BIT, BDPDATA
beq.b .wait_last_ack
bdp_write_finished
; Put port back to neutral state
move.b #BDP_NEUTRALDATA, BDPDATA
move.b #BDP_NEUTRALCTRL, BDPCTRL
; Unmask interrupts
move.w (sp)+, d0
move d0, sr
rts
if TARGET == TARGET_SCD1 || TARGET == TARGET_SCD2
; Poll sub cpu state
; void bdp_sub_check();
bdp_sub_check
if ..UNDEF BLS_NBDA
btst #6, GA_COMMFLAGS_SUB
beq.b .bda_check_end
ori.b #$C0, GA_COMMFLAGS_MAIN ; Ack the event
.wait_trap_ack btst #6, GA_COMMFLAGS_SUB
bne.b .wait_trap_ack
bclr #6, GA_COMMFLAGS_MAIN ; Clear ack
; mask interrupts
move sr, d0
move #$2700, sr
; setup port in output mode
move.b #BDP_SENDDATA, BDPDATA
move.b #BDP_SENDCTRL, BDPCTRL
; prepare raw packet parameters
moveq #3, d1
lea .sub_trap7 + 1, a0
pea .bda_check_end ; Tail call and return to .bda_check_end
move.w d0, -(sp) ; bdp_send_packet will restore SR from the stack
moveq #0, d0 ; d0 contains the header byte
jmp bdp_send_raw_packet
.sub_trap7
dl $127
.bda_check_end
endif
btst #5, GA_COMMFLAGS_SUB ; test if sub buffer contains data
beq.b .noout
; Request program ram bank 0
SUB_ACCESS_PRAM 0
moveq #0, d0
move.w $020000 + BDP_OUT_BUFSIZE, d0 ; Read data size
beq.b .emptybuf
; Send data to the debugger
move.l d0, -(sp) ; Push data size
pea.l $020000 + BDP_OUT_BUFFER ; Push data buffer address
jsr _main_bdp_write ; Call function
addq #8, sp
; Acknowledge to the sub cpu by resetting data size
clr.w $020000 + BDP_OUT_BUFSIZE
; Release sub cpu
.emptybuf SUB_RELEASE_PRAM
.noout
rts
endif
; vim: ts=8 sw=8 sts=8 et
|
; A256716: a(n) = n*(n+1)*(22*n-19)/6.
; 0,1,25,94,230,455,791,1260,1884,2685,3685,4906,6370,8099,10115,12440,15096,18105,21489,25270,29470,34111,39215,44804,50900,57525,64701,72450,80794,89755,99355,109616,120560,132209,144585,157710,171606,186295,201799,218140,235340,253421,272405,292314,313170,334995,357811,381640,406504,432425,459425,487526,516750,547119,578655,611380,645316,680485,716909,754610,793610,833931,875595,918624,963040,1008865,1056121,1104830,1155014,1206695,1259895,1314636,1370940,1428829,1488325,1549450,1612226,1676675,1742819,1810680,1880280,1951641,2024785,2099734,2176510,2255135,2335631,2418020,2502324,2588565,2676765,2766946,2859130,2953339,3049595,3147920,3248336,3350865,3455529,3562350,3671350,3782551,3895975,4011644,4129580,4249805,4372341,4497210,4624434,4754035,4886035,5020456,5157320,5296649,5438465,5582790,5729646,5879055,6031039,6185620,6342820,6502661,6665165,6830354,6998250,7168875,7342251,7518400,7697344,7879105,8063705,8251166,8441510,8634759,8830935,9030060,9232156,9437245,9645349,9856490,10070690,10287971,10508355,10731864,10958520,11188345,11421361,11657590,11897054,12139775,12385775,12635076,12887700,13143669,13403005,13665730,13931866,14201435,14474459,14750960,15030960,15314481,15601545,15892174,16186390,16484215,16785671,17090780,17399564,17712045,18028245,18348186,18671890,18999379,19330675,19665800,20004776,20347625,20694369,21045030,21399630,21758191,22120735,22487284,22857860,23232485,23611181,23993970,24380874,24771915,25167115,25566496,25970080,26377889,26789945,27206270,27626886,28051815,28481079,28914700,29352700,29795101,30241925,30693194,31148930,31609155,32073891,32543160,33016984,33495385,33978385,34466006,34958270,35455199,35956815,36463140,36974196,37490005,38010589,38535970,39066170,39601211,40141115,40685904,41235600,41790225,42349801,42914350,43483894,44058455,44638055,45222716,45812460,46407309,47007285,47612410,48222706,48838195,49458899,50084840,50716040,51352521,51994305,52641414,53293870,53951695,54614911,55283540,55957604,56637125
lpb $0,1
add $2,4
add $3,$0
add $1,$3
add $2,5
add $3,$0
sub $0,1
add $3,$2
add $3,$2
lpe
|
; A103750: Expansion of (1+2*x^3)/(1-x+x^3-2*x^4).
; Submitted by Christian Krause
; 1,1,1,2,3,4,4,5,7,11,14,17,20,28,39,53,65,82,107,148,196,253,319,419,558,745,964,1244,1615,2141,2825,3698,4787,6244,8196,10805,14135,18427,24014,31489,41332,54172,70711,92357,120849,158482,207547,271412,354628,464045
lpb $0
sub $0,1
sub $4,4
add $4,$1
add $1,$3
add $1,$2
mov $5,$3
sub $3,$2
add $5,$2
mov $2,$3
mov $3,$5
sub $3,$1
add $4,3
sub $4,$1
add $2,$4
add $4,$2
lpe
mov $0,$3
add $0,1
|
/* Copyright 2018 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 <mutex> // NOLINT
#include "tensorflow/compiler/jit/flags.h"
#include "tensorflow/compiler/xla/parse_flags_from_env.h"
#include "tensorflow/core/util/command_line_flags.h"
namespace tensorflow {
namespace {
BuildXlaOpsPassFlags* build_ops_flags;
MarkForCompilationPassFlags* mark_for_compilation_flags;
XlaDeviceFlags* device_flags;
XlaOpsCommonFlags* ops_flags;
std::vector<Flag>* flag_list;
std::once_flag flags_init;
void AppendMarkForCompilationPassFlagsInternal(std::vector<Flag>* flag_list) {
std::vector<Flag> new_flags = {
Flag("tf_xla_auto_jit", &mark_for_compilation_flags->tf_xla_auto_jit,
"Control compilation of operators into XLA computations on CPU and "
"GPU devices. 0 = use ConfigProto setting; -1 = off; 1 = on for "
"things very likely to be improved; 2 = on for everything. "
"Experimental."),
Flag("tf_xla_min_cluster_size",
&mark_for_compilation_flags->tf_xla_min_cluster_size,
"Minimum number of operators in an XLA compilation. Ignored for "
"operators placed on an XLA device or operators explicitly marked "
"for compilation."),
Flag("tf_xla_max_cluster_size",
&mark_for_compilation_flags->tf_xla_max_cluster_size,
"Maximum number of operators in an XLA compilation."),
Flag("tf_xla_clustering_debug",
&mark_for_compilation_flags->tf_xla_clustering_debug,
"Dump graphs during XLA compilation."),
Flag("tf_xla_cpu_global_jit",
&mark_for_compilation_flags->tf_xla_cpu_global_jit,
"Enables global JIT compilation for CPU via SessionOptions."),
Flag("tf_xla_clustering_fuel",
&mark_for_compilation_flags->tf_xla_clustering_fuel,
"Places an artificial limit on the number of ops marked as "
"eligible for clustering."),
Flag("tf_xla_disable_deadness_safety_checks_for_debugging",
&mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging,
"Disable deadness related safety checks when clustering (this is "
"unsound).")};
flag_list->insert(flag_list->end(), new_flags.begin(), new_flags.end());
}
void AllocateAndParseFlags() {
build_ops_flags = new BuildXlaOpsPassFlags;
build_ops_flags->tf_xla_enable_lazy_compilation = true;
build_ops_flags->tf_xla_print_cluster_outputs = false;
mark_for_compilation_flags = new MarkForCompilationPassFlags;
mark_for_compilation_flags->tf_xla_auto_jit = 0;
mark_for_compilation_flags->tf_xla_min_cluster_size = 4;
mark_for_compilation_flags->tf_xla_max_cluster_size =
std::numeric_limits<int32>::max();
mark_for_compilation_flags->tf_xla_clustering_debug = false;
mark_for_compilation_flags->tf_xla_cpu_global_jit = false;
mark_for_compilation_flags->tf_xla_clustering_fuel =
std::numeric_limits<int64>::max();
mark_for_compilation_flags
->tf_xla_disable_deadness_safety_checks_for_debugging = false;
device_flags = new XlaDeviceFlags;
device_flags->tf_xla_compile_on_demand = false;
ops_flags = new XlaOpsCommonFlags;
ops_flags->tf_xla_always_defer_compilation = false;
flag_list = new std::vector<Flag>({
Flag("tf_xla_enable_lazy_compilation",
&build_ops_flags->tf_xla_enable_lazy_compilation, ""),
Flag("tf_xla_print_cluster_outputs",
&build_ops_flags->tf_xla_print_cluster_outputs,
"If true then insert Print nodes to print out values produced by "
"XLA clusters."),
Flag("tf_xla_compile_on_demand", &device_flags->tf_xla_compile_on_demand,
"Switch a device into 'on-demand' mode, where instead of "
"autoclustering ops are compiled one by one just-in-time."),
Flag("tf_xla_always_defer_compilation",
&ops_flags->tf_xla_always_defer_compilation, ""),
});
AppendMarkForCompilationPassFlagsInternal(flag_list);
xla::ParseFlagsFromEnvAndDieIfUnknown("TF_XLA_FLAGS", *flag_list);
}
} // namespace
const BuildXlaOpsPassFlags& GetBuildXlaOpsPassFlags() {
std::call_once(flags_init, &AllocateAndParseFlags);
return *build_ops_flags;
}
MarkForCompilationPassFlags* GetMarkForCompilationPassFlags() {
std::call_once(flags_init, &AllocateAndParseFlags);
return mark_for_compilation_flags;
}
XlaDeviceFlags* GetXlaDeviceFlags() {
std::call_once(flags_init, &AllocateAndParseFlags);
return device_flags;
}
const XlaOpsCommonFlags& GetXlaOpsCommonFlags() {
std::call_once(flags_init, &AllocateAndParseFlags);
return *ops_flags;
}
void AppendMarkForCompilationPassFlags(std::vector<Flag>* flag_list) {
std::call_once(flags_init, &AllocateAndParseFlags);
AppendMarkForCompilationPassFlagsInternal(flag_list);
}
} // namespace tensorflow
|
INCLUDE "config_private.inc"
SECTION code_clib
SECTION code_stdlib
PUBLIC __strtoul__
EXTERN l_valid_base, l_eat_ws, l_eat_sign, l_eat_digits, error_lzc
EXTERN l_neg_dehl, l_char2num, l_mulu_40_32x8, l_eat_base_prefix
__strtoul__:
; strtol, strtoul helper
;
; enter : bc = base
; de = char **endp
; hl = char *
;
; exit : carry reset indicates no error
;
; a = 0 (number not negated) or 1 (number negated)
; dehl = result
; bc = char * (& next unconsumed char in string)
;
; carry set indicates error, a holds error code
;
; a = 0/-1 for invalid string, -2 for invalid base
; dehl = 0
; bc = original char *
;
; a = 3 indicates negate on unsigned overflow
; bc = char * (& next unconsumed char following number)
;
; a = 2 indicates unsigned overflow
; bc = char * (& next unconsumed char following number)
;
; a = 1 indicates negative underflow
; bc = char * (& next unconsumed char following number)
;
; uses : af, bc, de, hl, ix
IF __CPU_Z180__ || __CPU_R2K__ || __CPU_R3K__
dec sp
ld ix,0
add ix,sp
call z180_entry
inc sp
ret
z180_entry:
ENDIF
ld a,d
or e
jr z, no_endp
; have char **endp
push de ; save char **endp
call no_endp
; strtoul() done, now must write endp
; bc = char * (first uninterpretted char)
; dehl = result
; a = error code (if carry set)
; carry set = overflow or error
; stack = char **endp
ex (sp),hl
ld (hl),c
inc hl
ld (hl),b
pop hl
ret
no_endp:
call l_valid_base
ld d,a ; d = base
ld c,l
ld b,h ; bc = original char *
jr z, valid_base ; accept base == 0
jr nc, invalid_base
valid_base:
; bc = original char *
; hl = char *
; d = base
call l_eat_ws ; skip whitespace
call l_eat_sign ; carry set if negative
jr nc, positive
; negative sign found
call positive
; return here to negate result
; bc = char * (first uninterpretted char)
; dehl = result
; a = error code (if carry set)
; carry set = overflow or error
inc a ; indicate negate applied
ret c ; return if error
; successful conversion, check for signed overflow
ld a,d
add a,a ; carry set if signed overflow
call l_neg_dehl ; negate, carry unaffected
ld a,1
ret
positive:
; bc = original char*
; hl = char *
; d = base
ld a,d ; a = base
call l_eat_base_prefix
ld d,a ; d = base
; there must be at least one valid digit
ld a,(hl)
call l_char2num
jr c, invalid_input
cp d
jr nc, invalid_input
; there is special code for base 2, 8, 10, 16
ld e,a
ld a,d
IF __CLIB_OPT_TXT2NUM & $40
cp 10
jr z, decimal
ENDIF
IF __CLIB_OPT_TXT2NUM & $80
cp 16
jr z, hex
ENDIF
IF __CLIB_OPT_TXT2NUM & $20
cp 8
jr z, octal
ENDIF
IF __CLIB_OPT_TXT2NUM & $10
cp 2
jr z, binary
ENDIF
; use generic algorithm
; hl = char *
; d = base
; e = first numerical digit
IF __CPU_Z180__ || __CPU_R2K__ || __CPU_R3K__
ld (ix+0),d
ELSE
ld ixl,d
ENDIF
ld c,l
ld b,h
inc bc ; bc = & next char to consume
ld d,0
ld l,d
ld h,d
ex de,hl ; dehl = initial digit
loop:
; dehl = result
; bc = char *
; ixl = base
; get next digit
ld a,(bc)
call l_char2num ; a = digit
jr c, number_complete
IF __CPU_Z180__ || __CPU_R2K__ || __CPU_R3K__
cp (ix+0)
jr nc, number_complete
ELSE
cp ixl ; digit in 0..base-1 ?
jr nc, number_complete
ENDIF
inc bc ; consume the char
; multiply pending result by base
push af ; save new digit
push bc ; save char *
IF __CPU_Z180__ || __CPU_R2K__ || __CPU_R3K__
ld a,(ix+0)
call l_mulu_40_32x8
ELSE
ld a,ixl ; a = base
call l_mulu_40_32x8 ; ADEHL = DEHL * A
ENDIF
pop bc ; bc = char *
or a ; result confined to 32 bits ?
jr nz, unsigned_overflow
pop af ; a = digit to add
; add digit to result
add a,l ; dehl += a
ld l,a
jr nc, loop
inc h
jr nz, loop
inc e
jr nz, loop
inc d
jr nz, loop
push af
unsigned_overflow:
; bc = char * (next unconsumed char)
; ixl = base
; stack = junk
pop af
u_oflow:
; consume the entire number before reporting error
ld l,c
ld h,b ; hl = char *
IF __CPU_Z180__ || __CPU_R2K__ || __CPU_R3K__
ld c,(ix+0)
ELSE
ld c,ixl ; c = base
ENDIF
call l_eat_digits
ld c,l
ld b,h
ld a,2
scf
; bc = char * (next unconsumed char)
; a = 2 (error overflow)
; carry set for error
ret
invalid_base:
call invalid_input
ld a,-2
ret
invalid_input:
; bc = original char*
xor a
; bc = original char *
; dehl = 0
; a = 0 (error invalid input string)
; carry set for error
jp error_lzc
number_complete:
xor a ; carry reset and a=0
ret
IF __CLIB_OPT_TXT2NUM & $40
decimal:
; hl = char *
EXTERN l_atoul
ex de,hl
call l_atoul
jr c, u_oflow
xor a
ret
ENDIF
IF __CLIB_OPT_TXT2NUM & $80
hex:
; hl = char *
EXTERN l_htoul
ex de,hl
call l_htoul
jr c, u_oflow
xor a
ret
ENDIF
IF __CLIB_OPT_TXT2NUM & $20
octal:
; hl = char *
EXTERN l_otoul
ex de,hl
call l_otoul
jr c, u_oflow
xor a
ret
ENDIF
IF __CLIB_OPT_TXT2NUM & $10
binary:
; hl = char *
EXTERN l_btoul
ex de,hl
call l_btoul
jr c, u_oflow
xor a
ret
ENDIF
|
%macro onKey 2
cmp al, %1
jne %%notPressed
call %2
%%notPressed:
%endmacro
keyboardHandler:
startInterrupt
in al, 60h ; Read keyboard state
onKey 0x1F, speedUp ; Speed up the main timer when S is pressed
finishInterrupt
|
; A242851: 64*n^6 - 80*n^4 + 24*n^2 - 1.
; -1,7,2911,40391,242047,950599,2883167,7338631,16451071,33489287,63202399,112211527,189447551,306634951,478821727,724955399,1068505087,1538129671,2168392031,3000519367,4083209599,5473483847,7237584991,9451922311,12204062207,15593764999,19734067807,24752413511,30791825791,38012130247,46591221599,56726376967,68635615231,82559102471,98760603487,117528979399,139179731327,164056590151,192533152351,225014561927,261939238399,303780650887,351049138271,404293775431,464104285567,531112998599,605996855647
mul $0,2
pow $0,2
mov $1,$0
sub $0,2
mov $2,$1
sub $2,1
mul $0,$2
sub $0,$1
mul $0,2
mul $0,$2
mul $0,2
sub $0,24
div $0,32
mul $0,8
add $0,7
|
//==================================================================================================
/**
Copyright 2017 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
**/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_SIMD_IS_LESS_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_SIMD_IS_LESS_HPP_INCLUDED
#include <boost/simd/function/scalar/is_less.hpp>
#include <boost/simd/arch/common/generic/function/autodispatcher.hpp>
#if defined(BOOST_HW_SIMD_X86_OR_AMD_AVAILABLE)
# if BOOST_HW_SIMD_X86_OR_AMD >= BOOST_HW_SIMD_X86_SSE_VERSION
# include <boost/simd/arch/x86/sse1/simd/function/is_less.hpp>
# endif
# if BOOST_HW_SIMD_X86_OR_AMD >= BOOST_HW_SIMD_X86_SSE2_VERSION
# include <boost/simd/arch/x86/sse2/simd/function/is_less.hpp>
# endif
# if BOOST_HW_SIMD_X86_OR_AMD >= BOOST_HW_SIMD_X86_SSE4_2_VERSION
# include <boost/simd/arch/x86/sse4_2/simd/function/is_less.hpp>
# endif
#endif
#endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r9
push %rax
push %rbp
push %rbx
push %rdx
lea addresses_WT_ht+0x102c3, %rdx
nop
add $22165, %r14
mov (%rdx), %ax
nop
nop
nop
nop
nop
add $30042, %rbp
lea addresses_UC_ht+0x13c95, %rax
nop
nop
nop
nop
nop
and %r9, %r9
movups (%rax), %xmm5
vpextrq $0, %xmm5, %rbx
and %rbp, %rbp
pop %rdx
pop %rbx
pop %rbp
pop %rax
pop %r9
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_UC+0x153c3, %rsi
lea addresses_WC+0x3143, %rdi
nop
dec %rbp
mov $85, %rcx
rep movsq
nop
and $8924, %rax
// Faulty Load
lea addresses_WC+0x11f43, %r14
nop
nop
nop
nop
cmp $12780, %rcx
mov (%r14), %esi
lea oracles, %r8
and $0xff, %rsi
shlq $12, %rsi
mov (%r8,%rsi,1), %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WC', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC', 'congruent': 7, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC', 'congruent': 7, 'same': False}}
[Faulty Load]
{'src': {'type': 'addresses_WC', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 5}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'38': 21829}
38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38
*/
|
;=============================================================================+
; MD5.asm - by Greg Hoyer 7-20-2003 | |
;-----------------------------------------------+ |
; |
; MASM source file for the MD5x86ASM library. |
; |
;=============================================================================+
; *****************************************************************************
;**
.386P ;**
.387 ;**
.MODEL FLAT, STDCALL ;**
OPTION CASEMAP :NONE ;**
OPTION PROLOGUE:NONE ;**
OPTION EPILOGUE:NONE ;**
;**
; *****************************************************************************
INCLUDE MD5.inc
; *****************************************************************************
;**
.data ;**
;**
MD5InternalData \ ;**
DB 0,1,1,5,5,3,0,7, \ ;**
7,5,5,5,5,4,5,6, \ ;**
4,7,5,7,6,4,5,6 ;**
;**
.data? ;**
;**
MD5SineTable DD 65 dup (?) ;**
;**
;The 65th dword is needed because of the way MD5_Startup ;**
;writes overlapping -Q-words directly to the buffer. ;**
;**
; *****************************************************************************
.code
; *****************************************************************************
;**
MD5_Startup PROC PUBLIC ;**
;**
; *****************************************************************************
;**
xor eax, eax ;**
finit ;**
push 4F800000h ;**
push 0 ;**
fstcw word ptr [esp+2] ;**
g fstcw word ptr [esp] ;**
or word ptr [esp], 0F3Fh ;**
fldcw word ptr [esp] ;**
push 1 ;**
@@: fild dword ptr [esp] ;**
fsin ;**
fabs ;**
fmul dword ptr [esp+8] ;**
fistp qword ptr [eax*4+MD5SineTable] ;**
inc dword ptr [esp] ;**
inc eax ;**
test al, 40h ;**
jz @b ;**
fldcw word ptr [esp+6] ;**
add esp, 12 ;**
ret ;**
;**
MD5_Startup ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD5_Init PROC PUBLIC lpMD5CTXT:DWORD ;**
;**
; *****************************************************************************
;**
push edi ;**
mov edi, dword ptr [esp+8] ;**
mov al, 01h ;**
@@: stosb ;**
add al, 22h ;**
jnc @b ;**
mov al, 0FEh ;**
@@: stosb ;**
sub al, 22h ;**
jnc @b ;**
xor eax, eax ;**
stosd ;**
stosd ;**
pop edi ;**
ret 4 ;**
;**
MD5_Init ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD5_Read PROC PUBLIC lpMD5CTXT:DWORD, lpBuf:DWORD, bufLen:DWORD ;**
;**
; *****************************************************************************
;**
pushad ;**
mov esi, dword ptr [esp+40] ;**
mov ebp, dword ptr [esp+36] ;**
lea edi, [ebp+24] ;**
mov edx, dword ptr [esp+44] ;**
mov ebx, edi ;**
mov eax, edx ;**
shl eax, 3 ;**
mov ecx, edx ;**
shr ecx, 29 ;**
push dword ptr [ebp+16] ;**
add dword ptr [ebp+16], eax ;**
adc dword ptr [ebp+20], ecx ;**
pop eax ;**
shr eax, 3 ;**
and eax, 3Fh ;**
@mn: xor ecx, ecx ;**
mov cl, 40h ;**
sub ecx, eax ;**
cmp ecx, edx ;**
jbe @f ;**
mov ecx, edx ;**
@@: sub edx, ecx ;**
add edi, eax ;**
add eax, ecx ;**
rep movsb ;**
mov edi, ebx ;**
cmp eax, 40h ;**
jb @f ;**
push edi ;**
push ebp ;**
call MD5_BTrnsf ;**
@@: xor eax, eax ;**
or edx, edx ;**
jnz @mn ;**
popad ;**
ret 12 ;**
;**
MD5_Read ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD5_Digest PROC PUBLIC lpMD5CTXT:DWORD, lpMD5HASH:DWORD ;**
;**
; *****************************************************************************
;**
pushad ;**
mov esi, dword ptr [esp+36] ;**
mov edi, dword ptr [esp+40] ;**
lea ebp, [esi+16] ;**
mov ebx, edi ;**
sub esp, 64 ;**
movsd ;**
movsd ;**
movsd ;**
movsd ;**
lodsd ;**
shr eax, 3 ;**
add esi, 4 ;**
and eax, 3Fh ;**
mov edi, esp ;**
mov ecx, eax ;**
rep movsb ;**
inc eax ;**
sub ecx, eax ;**
mov al, 80h ;**
stosb ;**
xor eax, eax ;**
cmp ecx, -56 ;**
jae @f ;**
xor eax, eax ;**
add ecx, 64 ;**
rep stosb ;**
mov edi, esp ;**
push edi ;**
push ebx ;**
call MD5_BTrnsf ;**
@@: xor eax, eax ;**
add ecx, 56 ;**
rep stosb ;**
mov esi, ebp ;**
movsd ;**
movsd ;**
push esp ;**
push ebx ;**
call MD5_BTrnsf ;**
add esp, 64 ;**
popad ;**
ret 8 ;**
;**
MD5_Digest ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD5_BTrnsf PROC PRIVATE phash:DWORD, lpBlock:DWORD ;**
;**
; *****************************************************************************
;**
pushad ;**
mov eax, dword ptr [esp+36] ;**
xor ecx, ecx ;**
mov cl, 4 ;**
@@: push dword ptr [eax] ;**
add eax, 4 ;**
loop @b ;**
@mn: mov ebp, ecx ;**
shr ebp, 12 ;**
add dl, dh ;**
and dl, 0Fh ;**
test ch, 03h ;**
jnz @f ;**
xor cl, cl ;**
test ch, 0Fh ;**
jnz @f ;**
mov esi, offset MD5InternalData ;**
mov edx, dword ptr [esi+ebp*2] ;**
mov ebx, dword ptr [esi+ebp*4+8] ;**
@@: add cl, bl ;**
ror ebx, 8 ;**
push edx ;**
push ecx ;**
push ebx ;**
mov ebx, dword ptr [esp+20] ;**
mov ecx, dword ptr [esp+16] ;**
mov edx, dword ptr [esp+12] ;**
test ebp, 02h ;**
jnz @hi ;**
test ebp, 01h ;**
jnz @f ;**
mov eax, ebx ;**
and ebx, ecx ;**
not eax ;**
and eax, edx ;**
or eax, ebx ;**
jmp @fghi ;**
@@: mov eax, edx ;**
and edx, ebx ;**
not eax ;**
and eax, ecx ;**
or eax, edx ;**
jmp @fghi ;**
@hi: test ebp, 01h ;**
jnz @f ;**
mov eax, ebx ;**
xor eax, ecx ;**
xor eax, edx ;**
jmp @fghi ;**
@@: mov eax, edx ;**
not eax ;**
or eax, ebx ;**
xor eax, ecx ;**
@fghi: pop ebx ;**
pop ecx ;**
pop edx ;**
add eax, dword ptr [esp+12] ;**
mov esi, dword ptr [esp+56] ;**
movzx edi, dl ;**
add eax, dword ptr [esi+edi*4] ;**
movzx esi, ch ;**
add eax, dword ptr [MD5SineTable+esi*4] ;**
rol eax, cl ;**
add eax, dword ptr [esp+8] ;**
mov dword ptr [esp+12], eax ;**
mov esi, esp ;**
mov edi, esp ;**
lodsd ;**
movsd ;**
movsd ;**
movsd ;**
stosd ;**
inc ch ;**
test ch, 40h ;**
jz @mn ;**
mov eax, dword ptr [esp+52] ;**
xor ecx, ecx ;**
mov cl, 4 ;**
sub eax, ecx ;**
@@: pop edx ;**
add dword ptr [eax+ecx*4], edx ;**
loop @b ;**
popad ;**
ret 8 ;**
;**
MD5_BTrnsf ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD5_Compare PROC PUBLIC lpHash1:DWORD, lpHash2:DWORD ;**
;**
; *****************************************************************************
;**
push esi ;**
push edi ;**
push ecx ;**
mov esi, dword ptr [esp+16] ;**
mov edi, dword ptr [esp+20] ;**
xor ecx, ecx ;**
mov cl, 16 ;**
xor eax, eax ;**
repe cmpsb ;**
pushfd ;**
setnz al ;**
jnc @f ;**
sbb eax, eax ;**
@@: popfd ;**
pop ecx ;**
pop edi ;**
pop esi ;**
ret 8 ;**
;**
MD5_Compare ENDP ;**
;**
; *****************************************************************************
; *****************************************************************************
;**
MD52StringW PROC PUBLIC lpMD5HASH:DWORD, lpwBuffer:DWORD, bUpper:DWORD ;**
stc ;**
jmp MD52StringWA ;**
;**
MD52StringW ENDP ;**
;**
MD52StringA PROC PUBLIC lpMD5HASH:DWORD, lpaBuffer:DWORD, bUpper:DWORD ;**
clc ;**
;**
; *****************************************************************************
;**
MD52StringWA:: ;**
;**
pushad ;**
mov esi, dword ptr [esp+36] ;**
mov edi, dword ptr [esp+40] ;**
sbb ebx, ebx ;**
xor ecx, ecx ;**
xor edx, edx ;**
mov cl, 32 ;**
cmp dword ptr [esp+44], edx ;**
jnz @f ;**
mov edx, ecx ;**
@@: add edx, 7 ;**
@mn: push ecx ;**
inc ecx ;**
and ecx, 1 ;**
lodsb ;**
sub esi, ecx ;**
shl ecx, 2 ;**
shr eax, cl ;**
and eax, 0Fh ;**
cmp al, 10 ;**
jb @f ;**
add al, dl ;**
@@: add al, 30h ;**
stosb ;**
xor eax, eax ;**
or ebx, ebx ;**
jz @f ;**
stosb ;**
@@: pop ecx ;**
loop @mn ;**
stosb ;**
or ebx, ebx ;**
jz @f ;**
stosb ;**
@@: popad ;**
mov eax, dword ptr [esp+8] ;**
ret 12 ;**
;**
MD52StringA ENDP ;**
;**
; *****************************************************************************
OPTION PROLOGUE:PROLOGUEDEF
OPTION EPILOGUE:EPILOGUEDEF
END |
copyright zengfr site:http://github.com/zengfr/romhack
01689E move.b D0, ($1,A6)
0168A2 move.b D0, ($2,A6)
copyright zengfr site:http://github.com/zengfr/romhack
|
db DEX_DUGTRIO ; pokedex id
db 35, 80, 50, 120, 70
; hp atk def spd spc
db GROUND, GROUND ; type
db 50 ; catch rate
db 153 ; base exp
INCBIN "gfx/pokemon/front/dugtrio.pic", 0, 1 ; sprite dimensions
dw DugtrioPicFront, DugtrioPicBack
db SCRATCH, GROWL, DIG, NO_MOVE ; level 1 learnset
db GROWTH_MEDIUM_FAST ; growth rate
; tm/hm learnset
tmhm TOXIC, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, HYPER_BEAM, \
RAGE, EARTHQUAKE, FISSURE, DIG, MIMIC, \
DOUBLE_TEAM, BIDE, REST, ROCK_SLIDE, SUBSTITUTE
; end
db 0 ; padding
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
%>
<%docstring>cacheflush(addr, nbytes, cache) -> str
Invokes the syscall cacheflush.
See 'man 2 cacheflush' for more information.
Arguments:
addr(char*): addr
nbytes(int): nbytes
cache(int): cache
Returns:
int
</%docstring>
<%page args="addr=0, nbytes=0, cache=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['addr']
can_pushstr_array = []
argument_names = ['addr', 'nbytes', 'cache']
argument_values = [addr, nbytes, cache]
# 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=%r' % (name, arg))
# 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, str):
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_cacheflush']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* cacheflush(${', '.join(syscall_repr)}) */
%for name, arg in string_arguments.items():
${pwnlib.shellcraft.pushstr(arg, append_null=('\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)} |
; A051958: a(n) = 2 a(n-1) + 24 a(n-2), a(0)=0, a(1)=1.
; 0,1,2,28,104,880,4256,29632,161408,1033984,5941760,36699136,216000512,1312780288,7809572864,47125872640,281681494016,1694383931392,10149123719168,60963461791744,365505892843520,2194134868688896
mov $20,$0
mov $22,$0
lpb $22,1
clr $0,20
mov $0,$20
sub $22,1
sub $0,$22
mov $17,$0
mov $19,$0
lpb $19,1
mov $0,$17
sub $19,1
sub $0,$19
mov $13,$0
mov $15,2
lpb $15,1
mov $0,$13
sub $15,1
add $0,$15
sub $0,1
mov $9,$0
mov $11,2
lpb $11,1
mov $0,$9
sub $11,1
add $0,$11
sub $0,1
mov $5,$0
mov $7,2
lpb $7,1
mov $0,$5
sub $7,1
add $0,$7
cal $0,83578 ; a(n) = (6^n + (-4)^n)/2.
sub $0,1
mov $1,$0
mov $8,$7
lpb $8,1
mov $6,$1
sub $8,1
lpe
lpe
lpb $5,1
mov $5,0
sub $6,$1
lpe
mov $1,$6
mov $12,$11
lpb $12,1
mov $10,$1
sub $12,1
lpe
lpe
lpb $9,1
mov $9,0
sub $10,$1
lpe
mov $1,$10
mov $16,$15
lpb $16,1
mov $14,$1
sub $16,1
lpe
lpe
lpb $13,1
mov $13,0
sub $14,$1
lpe
mov $1,$14
div $1,25
add $18,$1
lpe
add $21,$18
lpe
mov $1,$21
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %rdi
push %rdx
lea addresses_D_ht+0x1cba8, %r11
xor $38179, %rdx
mov (%r11), %rdi
nop
nop
dec %r12
pop %rdx
pop %rdi
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r9
push %rax
push %rbp
push %rdx
push %rsi
// Store
mov $0x728, %r12
nop
nop
nop
nop
nop
cmp $39358, %r14
mov $0x5152535455565758, %rax
movq %rax, (%r12)
nop
nop
sub $30236, %r14
// Store
mov $0x37dee80000000208, %rsi
nop
inc %rbp
mov $0x5152535455565758, %r14
movq %r14, (%rsi)
nop
nop
nop
nop
nop
cmp $5596, %rsi
// Faulty Load
mov $0x969a200000003a8, %rax
nop
nop
nop
nop
and %r9, %r9
vmovups (%rax), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $0, %xmm7, %rdx
lea oracles, %r9
and $0xff, %rdx
shlq $12, %rdx
mov (%r9,%rdx,1), %rdx
pop %rsi
pop %rdx
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'congruent': 6, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 5, 'size': 8, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 7, 'size': 8, 'same': False, 'NT': False}}
{'53': 1, '4d': 9, '8f': 3, 'cb': 3, '4c': 6, '03': 1, '2f': 1, '51': 1, 'ae': 3, '9f': 4, '9a': 2, '2c': 2}
03 9f 4d 9f 9f 4d 9f 8f 8f 8f 4c cb cb cb 9a 4d 9a 4d 2c 2c 4d 4d ae 4d 4d ae ae 2f 4c 51 4c 4c 4d 4c 4c 53
*/
|
//=================================================================================================
/*!
// \file src/mathtest/dmatsmatmult/U3x3bUCb.cpp
// \brief Source file for the U3x3bUCb dense matrix/sparse matrix multiplication math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD 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 names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsmatmult/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'U3x3bUCb'..." << std::endl;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::UpperMatrix< blaze::StaticMatrix<TypeB,3UL,3UL> > U3x3b;
typedef blaze::UpperMatrix< blaze::CompressedMatrix<TypeB> > UCb;
// Creator type definitions
typedef blazetest::Creator<U3x3b> CU3x3b;
typedef blazetest::Creator<UCb> CUCb;
// Running the tests
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_DMATSMATMULT_OPERATION_TEST( CU3x3b(), CUCb( 3UL, i ) );
}
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse matrix multiplication:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// 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.
//
// The following only applies to changes made to this file as part of YugaByte development.
//
// Portions Copyright (c) YugaByte, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations
// under the License.
//
#include "yb/integration-tests/cluster_itest_util.h"
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
#include <boost/optional.hpp>
#include <glog/stl_logging.h>
#include <gtest/gtest.h>
#include "yb/client/schema.h"
#include "yb/client/yb_table_name.h"
#include "yb/common/wire_protocol-test-util.h"
#include "yb/common/wire_protocol.h"
#include "yb/common/wire_protocol.pb.h"
#include "yb/consensus/consensus.proxy.h"
#include "yb/consensus/consensus_meta.h"
#include "yb/consensus/opid_util.h"
#include "yb/consensus/quorum_util.h"
#include "yb/gutil/strings/substitute.h"
#include "yb/master/master.pb.h"
#include "yb/master/master.proxy.h"
#include "yb/rpc/rpc_fwd.h"
#include "yb/server/server_base.proxy.h"
#include "yb/tserver/tablet_server_test_util.h"
#include "yb/tserver/tserver_admin.proxy.h"
#include "yb/tserver/tserver_service.pb.h"
#include "yb/tserver/tserver_service.proxy.h"
#include "yb/util/enums.h"
#include "yb/util/format.h"
#include "yb/util/logging.h"
#include "yb/util/monotime.h"
#include "yb/util/net/net_fwd.h"
#include "yb/util/net/net_util.h"
#include "yb/util/result.h"
#include "yb/util/status.h"
#include "yb/util/status_format.h"
#include "yb/util/status_log.h"
#include "yb/util/strongly_typed_bool.h"
#include "yb/util/test_util.h"
namespace yb {
namespace itest {
using client::YBClient;
using client::YBSchema;
using client::YBSchemaBuilder;
using client::YBTable;
using client::YBTableName;
using consensus::CONSENSUS_CONFIG_ACTIVE;
using consensus::CONSENSUS_CONFIG_COMMITTED;
using consensus::ChangeConfigRequestPB;
using consensus::ChangeConfigResponsePB;
using consensus::ConsensusConfigType;
using consensus::ConsensusStatePB;
using consensus::CountVoters;
using consensus::GetConsensusStateRequestPB;
using consensus::GetConsensusStateResponsePB;
using consensus::GetLastOpIdRequestPB;
using consensus::GetLastOpIdResponsePB;
using consensus::LeaderStepDownRequestPB;
using consensus::LeaderStepDownResponsePB;
using consensus::RaftPeerPB;
using consensus::RunLeaderElectionResponsePB;
using consensus::RunLeaderElectionRequestPB;
using consensus::kInvalidOpIdIndex;
using consensus::LeaderLeaseCheckMode;
using consensus::LeaderLeaseStatus;
using master::ListTabletServersResponsePB;
using master::MasterServiceProxy;
using master::TabletLocationsPB;
using rpc::Messenger;
using rpc::RpcController;
using std::min;
using std::shared_ptr;
using std::string;
using std::unordered_map;
using std::vector;
using strings::Substitute;
using tserver::CreateTsClientProxies;
using tserver::ListTabletsResponsePB;
using tserver::DeleteTabletRequestPB;
using tserver::DeleteTabletResponsePB;
using tserver::TabletServerAdminServiceProxy;
using tserver::TabletServerErrorPB;
using tserver::TabletServerServiceProxy;
using tserver::WriteRequestPB;
using tserver::WriteResponsePB;
const string& TServerDetails::uuid() const {
return instance_id.permanent_uuid();
}
std::string TServerDetails::ToString() const {
return Format("TabletServer: $0, Rpc address: $1", instance_id.permanent_uuid(),
DesiredHostPort(registration.common(), CloudInfoPB()));
}
client::YBSchema SimpleIntKeyYBSchema() {
YBSchema s;
YBSchemaBuilder b;
b.AddColumn("key")->Type(INT32)->NotNull()->PrimaryKey();
CHECK_OK(b.Build(&s));
return s;
}
Result<std::vector<OpId>> GetLastOpIdForEachReplica(
const TabletId& tablet_id,
const std::vector<TServerDetails*>& replicas,
consensus::OpIdType opid_type,
const MonoDelta& timeout,
consensus::OperationType op_type) {
struct Getter {
const TabletId& tablet_id;
consensus::OpIdType opid_type;
consensus::OperationType op_type;
Result<OpId> operator()(TServerDetails* ts, rpc::RpcController* controller) const {
GetLastOpIdRequestPB opid_req;
GetLastOpIdResponsePB opid_resp;
opid_req.set_tablet_id(tablet_id);
opid_req.set_dest_uuid(ts->uuid());
opid_req.set_opid_type(opid_type);
if (op_type != consensus::OperationType::UNKNOWN_OP) {
opid_req.set_op_type(op_type);
}
RETURN_NOT_OK(ts->consensus_proxy->GetLastOpId(opid_req, &opid_resp, controller));
return OpId::FromPB(opid_resp.opid());
}
};
return GetForEachReplica(
replicas, timeout,
Getter{.tablet_id = tablet_id, .opid_type = opid_type, .op_type = op_type});
}
vector<TServerDetails*> TServerDetailsVector(const TabletServerMap& tablet_servers) {
vector<TServerDetails*> result;
result.reserve(tablet_servers.size());
for (auto& pair : tablet_servers) {
result.push_back(pair.second.get());
}
return result;
}
vector<TServerDetails*> TServerDetailsVector(const TabletServerMapUnowned& tablet_servers) {
vector<TServerDetails*> result;
result.reserve(tablet_servers.size());
for (auto& pair : tablet_servers) {
result.push_back(pair.second);
}
return result;
}
TabletServerMapUnowned CreateTabletServerMapUnowned(const TabletServerMap& tablet_servers,
const std::set<std::string>& exclude) {
TabletServerMapUnowned result;
for (auto& pair : tablet_servers) {
if (exclude.find(pair.first) != exclude.end()) {
continue;
}
result.emplace(pair.first, pair.second.get());
}
return result;
}
Status WaitForServersToAgree(const MonoDelta& timeout,
const TabletServerMap& tablet_servers,
const string& tablet_id,
int64_t minimum_index,
int64_t* actual_index,
MustBeCommitted must_be_committed) {
return WaitForServersToAgree(timeout,
TServerDetailsVector(tablet_servers),
tablet_id,
minimum_index,
actual_index,
must_be_committed);
}
Status WaitForServersToAgree(const MonoDelta& timeout,
const TabletServerMapUnowned& tablet_servers,
const TabletId& tablet_id,
int64_t minimum_index,
int64_t* actual_index,
MustBeCommitted must_be_committed) {
return WaitForServersToAgree(
timeout, TServerDetailsVector(tablet_servers), tablet_id, minimum_index, actual_index,
must_be_committed);
}
Status WaitForServersToAgree(const MonoDelta& timeout,
const vector<TServerDetails*>& servers,
const string& tablet_id,
int64_t minimum_index,
int64_t* actual_index,
MustBeCommitted must_be_committed) {
auto deadline = CoarseMonoClock::Now() + timeout;
if (actual_index != nullptr) {
*actual_index = 0;
}
vector<OpIdType> opid_types{consensus::OpIdType::RECEIVED_OPID};
if (must_be_committed) {
// In this mode we require that last received and committed op ids from all servers converge
// on the same value.
opid_types.push_back(consensus::OpIdType::COMMITTED_OPID);
}
Status last_non_ok_status;
vector<OpId> received_ids;
vector<OpId> committed_ids;
for (int attempt = 1; CoarseMonoClock::Now() < deadline; attempt++) {
vector<OpId> ids;
Status s;
for (auto opid_type : opid_types) {
auto ids_of_this_type = GetLastOpIdForEachReplica(tablet_id, servers, opid_type, timeout);
if (!ids_of_this_type.ok()) {
s = ids_of_this_type.status();
break;
}
if (opid_type == consensus::OpIdType::RECEIVED_OPID) {
received_ids = *ids_of_this_type;
} else {
committed_ids = *ids_of_this_type;
}
std::copy(ids_of_this_type->begin(), ids_of_this_type->end(), std::back_inserter(ids));
}
if (s.ok()) {
int64_t cur_index = kInvalidOpIdIndex;
bool any_behind = false;
bool any_disagree = false;
for (const OpId& id : ids) {
if (cur_index == kInvalidOpIdIndex) {
cur_index = id.index;
}
if (id.index != cur_index) {
any_disagree = true;
break;
}
if (id.index < minimum_index) {
any_behind = true;
break;
}
}
if (!any_behind && !any_disagree) {
LOG(INFO) << "All servers converged on OpIds: " << ids;
if (actual_index != nullptr) {
*actual_index = cur_index;
}
return Status::OK();
}
} else {
LOG(WARNING) << "Got error getting last opid for each replica: " << s.ToString();
last_non_ok_status = s;
}
LOG(INFO) << "Not converged past " << minimum_index << " yet: " << ids;
SleepFor(MonoDelta::FromMilliseconds(min(attempt * 100, 1000)));
}
return STATUS_FORMAT(
TimedOut,
"All replicas of tablet $0 could not converge on an index of at least $1 after $2. "
"must_be_committed=$3. Latest received ids: $3, committed ids: $4",
tablet_id, minimum_index, timeout, must_be_committed, received_ids, committed_ids);
}
// Wait until all specified replicas have logged the given index.
Status WaitUntilAllReplicasHaveOp(const int64_t log_index,
const string& tablet_id,
const vector<TServerDetails*>& replicas,
const MonoDelta& timeout,
int64_t* actual_minimum_index) {
MonoTime start = MonoTime::Now();
MonoDelta passed = MonoDelta::FromMilliseconds(0);
while (true) {
auto op_ids = GetLastOpIdForEachReplica(tablet_id, replicas, consensus::RECEIVED_OPID, timeout);
if (op_ids.ok()) {
if (actual_minimum_index != nullptr) {
*actual_minimum_index = std::numeric_limits<int64_t>::max();
}
bool any_behind = false;
for (const OpId& op_id : *op_ids) {
if (actual_minimum_index != nullptr) {
*actual_minimum_index = std::min(*actual_minimum_index, op_id.index);
}
if (op_id.index < log_index) {
any_behind = true;
break;
}
}
if (!any_behind) return Status::OK();
} else {
LOG(WARNING) << "Got error getting last opid for each replica: " << op_ids.ToString();
}
passed = MonoTime::Now().GetDeltaSince(start);
if (passed.MoreThan(timeout)) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(50));
}
string replicas_str;
for (const TServerDetails* replica : replicas) {
if (!replicas_str.empty()) replicas_str += ", ";
replicas_str += "{ " + replica->ToString() + " }";
}
return STATUS(TimedOut, Substitute("Index $0 not available on all replicas after $1. "
"Replicas: [ $2 ]",
log_index, passed.ToString()));
}
Status WaitUntilNumberOfAliveTServersEqual(int n_tservers,
MasterServiceProxy* master_proxy,
const MonoDelta& timeout) {
master::ListTabletServersRequestPB req;
master::ListTabletServersResponsePB resp;
rpc::RpcController controller;
controller.set_timeout(timeout);
// The field primary_only means only tservers that are alive (tservers that have sent at least on
// heartbeat in the last FLAG_tserver_unresponsive_timeout_ms milliseconds.)
req.set_primary_only(true);
MonoTime start = MonoTime::Now();
MonoDelta passed = MonoDelta::FromMilliseconds(0);
while (true) {
Status s = master_proxy->ListTabletServers(req, &resp, &controller);
if (s.ok() &&
controller.status().ok() &&
!resp.has_error()) {
if (resp.servers_size() == n_tservers) {
passed = MonoTime::Now().GetDeltaSince(start);
return Status::OK();
}
} else {
string error;
if (!s.ok()) {
error = s.ToString();
} else if (!controller.status().ok()) {
error = controller.status().ToString();
} else {
error = resp.error().ShortDebugString();
}
LOG(WARNING) << "Got error getting list of tablet servers: " << error;
}
passed = MonoTime::Now().GetDeltaSince(start);
if (passed.MoreThan(timeout)) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(50));
controller.Reset();
}
return STATUS(TimedOut, Substitute("Number of alive tservers not equal to $0 after $1 ms. ",
n_tservers, timeout.ToMilliseconds()));
}
Status CreateTabletServerMap(MasterServiceProxy* master_proxy,
rpc::ProxyCache* proxy_cache,
TabletServerMap* ts_map) {
master::ListTabletServersRequestPB req;
master::ListTabletServersResponsePB resp;
rpc::RpcController controller;
RETURN_NOT_OK(master_proxy->ListTabletServers(req, &resp, &controller));
RETURN_NOT_OK(controller.status());
if (resp.has_error()) {
return STATUS(RemoteError, "Response had an error", resp.error().ShortDebugString());
}
ts_map->clear();
for (const ListTabletServersResponsePB::Entry& entry : resp.servers()) {
HostPort host_port = HostPortFromPB(DesiredHostPort(
entry.registration().common(), CloudInfoPB()));
std::unique_ptr<TServerDetails> peer(new TServerDetails());
peer->instance_id.CopyFrom(entry.instance_id());
peer->registration.CopyFrom(entry.registration());
CreateTsClientProxies(host_port,
proxy_cache,
&peer->tserver_proxy,
&peer->tserver_admin_proxy,
&peer->consensus_proxy,
&peer->generic_proxy);
const auto& key = peer->instance_id.permanent_uuid();
CHECK(ts_map->emplace(key, std::move(peer)).second) << "duplicate key: " << key;
}
return Status::OK();
}
Status GetConsensusState(const TServerDetails* replica,
const string& tablet_id,
consensus::ConsensusConfigType type,
const MonoDelta& timeout,
ConsensusStatePB* consensus_state,
LeaderLeaseStatus* leader_lease_status) {
DCHECK_ONLY_NOTNULL(replica);
GetConsensusStateRequestPB req;
GetConsensusStateResponsePB resp;
RpcController controller;
controller.set_timeout(timeout);
req.set_dest_uuid(replica->uuid());
req.set_tablet_id(tablet_id);
req.set_type(type);
RETURN_NOT_OK(replica->consensus_proxy->GetConsensusState(req, &resp, &controller));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
*consensus_state = resp.cstate();
if (leader_lease_status) {
*leader_lease_status = resp.has_leader_lease_status() ?
resp.leader_lease_status() :
LeaderLeaseStatus::NO_MAJORITY_REPLICATED_LEASE; // Could be anything but HAS_LEASE.
}
return Status::OK();
}
Status WaitUntilCommittedConfigNumVotersIs(int config_size,
const TServerDetails* replica,
const std::string& tablet_id,
const MonoDelta& timeout) {
return WaitUntilCommittedConfigMemberTypeIs(config_size, replica, tablet_id, timeout,
RaftPeerPB::VOTER);
}
Status WaitUntilCommittedConfigMemberTypeIs(int config_size,
const TServerDetails* replica,
const std::string& tablet_id,
const MonoDelta& timeout,
RaftPeerPB::MemberType member_type) {
DCHECK_ONLY_NOTNULL(replica);
MonoTime start = MonoTime::Now();
MonoTime deadline = start + timeout;
int backoff_exp = 0;
const int kMaxBackoffExp = 7;
Status s;
ConsensusStatePB cstate;
while (true) {
MonoDelta remaining_timeout = deadline.GetDeltaSince(MonoTime::Now());
s = GetConsensusState(replica, tablet_id, CONSENSUS_CONFIG_COMMITTED,
remaining_timeout, &cstate);
if (s.ok()) {
if (CountMemberType(cstate.config(), member_type) == config_size) {
return Status::OK();
}
}
if (MonoTime::Now().GetDeltaSince(start).MoreThan(timeout)) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(1 << backoff_exp));
backoff_exp = min(backoff_exp + 1, kMaxBackoffExp);
}
return STATUS(TimedOut, Substitute("Number of replicas of type $0 does not equal $1 after "
"waiting for $2. Last consensus state: $3. Last status: $4",
RaftPeerPB::MemberType_Name(member_type), config_size,
timeout.ToString(), cstate.ShortDebugString(), s.ToString()));
}
template<class Context>
Status WaitUntilCommittedOpIdIndex(TServerDetails* replica,
const string& tablet_id,
const MonoDelta& timeout,
CommittedEntryType type,
Context context) {
MonoTime start = MonoTime::Now();
MonoTime deadline = start;
deadline.AddDelta(timeout);
bool config = type == CommittedEntryType::CONFIG;
Status s;
OpId op_id;
ConsensusStatePB cstate;
while (true) {
MonoDelta remaining_timeout = deadline.GetDeltaSince(MonoTime::Now());
int64_t op_index = -1;
if (config) {
s = GetConsensusState(replica, tablet_id, CONSENSUS_CONFIG_COMMITTED,
remaining_timeout, &cstate);
if (s.ok()) {
op_index = cstate.config().opid_index();
}
} else {
auto last_op_id_result = GetLastOpIdForReplica(
tablet_id, replica, consensus::COMMITTED_OPID, remaining_timeout);
if (last_op_id_result.ok()) {
op_id = *last_op_id_result;
op_index = op_id.index;
} else {
s = last_op_id_result.status();
}
}
if (s.ok() && context.Check(op_index)) {
if (config) {
LOG(INFO) << "Committed config state is: " << cstate.ShortDebugString() << " for replica: "
<< replica->instance_id.permanent_uuid();
} else {
LOG(INFO) << "Committed op_id index is: " << op_id << " for replica: "
<< replica->instance_id.permanent_uuid();
}
return Status::OK();
}
auto passed = MonoTime::Now().GetDeltaSince(start);
if (passed.MoreThan(timeout)) {
auto name = config ? "config" : "consensus";
auto last_value = config ? cstate.ShortDebugString() : AsString(op_id);
return STATUS(TimedOut,
Substitute("Committed $0 opid_index does not equal $1 "
"after waiting for $2. Last value: $3, Last status: $4",
name,
context.Desired(),
passed.ToString(),
last_value,
s.ToString()));
}
if (!config) {
LOG(INFO) << "Committed index is at: " << op_id.index << " and not yet at "
<< context.Desired();
}
SleepFor(MonoDelta::FromMilliseconds(100));
}
}
class WaitUntilCommittedOpIdIndexContext {
public:
explicit WaitUntilCommittedOpIdIndexContext(std::string desired)
: desired_(std::move(desired)) {
}
const string& Desired() const {
return desired_;
}
private:
string desired_;
};
class WaitUntilCommittedOpIdIndexIsContext : public WaitUntilCommittedOpIdIndexContext {
public:
explicit WaitUntilCommittedOpIdIndexIsContext(int64_t value)
: WaitUntilCommittedOpIdIndexContext(Substitute("equal $0", value)),
value_(value) {
}
bool Check(int64_t current) {
return value_ == current;
}
private:
int64_t value_;
};
Status WaitUntilCommittedOpIdIndexIs(int64_t opid_index,
TServerDetails* replica,
const string& tablet_id,
const MonoDelta& timeout,
CommittedEntryType type) {
return WaitUntilCommittedOpIdIndex(
replica,
tablet_id,
timeout,
type,
WaitUntilCommittedOpIdIndexIsContext(opid_index));
}
class WaitUntilCommittedOpIdIndexIsGreaterThanContext : public WaitUntilCommittedOpIdIndexContext {
public:
explicit WaitUntilCommittedOpIdIndexIsGreaterThanContext(int64_t* value)
: WaitUntilCommittedOpIdIndexContext(Substitute("greater than $0", *value)),
original_value_(*value), value_(value) {
}
bool Check(int64_t current) {
if (current > *value_) {
CHECK_EQ(*value_, original_value_);
*value_ = current;
return true;
}
return false;
}
private:
int64_t original_value_;
int64_t* const value_;
};
Status WaitUntilCommittedOpIdIndexIsGreaterThan(int64_t* index,
TServerDetails* replica,
const TabletId& tablet_id,
const MonoDelta& timeout,
CommittedEntryType type) {
return WaitUntilCommittedOpIdIndex(
replica,
tablet_id,
timeout,
type,
WaitUntilCommittedOpIdIndexIsGreaterThanContext(index));
}
Status WaitUntilCommittedOpIdIndexIsAtLeast(int64_t* index,
TServerDetails* replica,
const TabletId& tablet_id,
const MonoDelta& timeout,
CommittedEntryType type) {
int64_t tmp_index = *index - 1;
Status s = WaitUntilCommittedOpIdIndexIsGreaterThan(
&tmp_index,
replica,
tablet_id,
timeout,
type);
*index = tmp_index;
return s;
}
Status GetReplicaStatusAndCheckIfLeader(const TServerDetails* replica,
const string& tablet_id,
const MonoDelta& timeout,
LeaderLeaseCheckMode lease_check_mode) {
ConsensusStatePB cstate;
LeaderLeaseStatus leader_lease_status;
Status s = GetConsensusState(replica, tablet_id, CONSENSUS_CONFIG_ACTIVE,
timeout, &cstate, &leader_lease_status);
if (PREDICT_FALSE(!s.ok())) {
VLOG(1) << "Error getting consensus state from replica: "
<< replica->instance_id.permanent_uuid();
return STATUS(NotFound, "Error connecting to replica", s.ToString());
}
const string& replica_uuid = replica->instance_id.permanent_uuid();
if (cstate.has_leader_uuid() && cstate.leader_uuid() == replica_uuid &&
(lease_check_mode == LeaderLeaseCheckMode::DONT_NEED_LEASE ||
leader_lease_status == consensus::LeaderLeaseStatus::HAS_LEASE)) {
return Status::OK();
}
VLOG(1) << "Replica not leader of config: " << replica->instance_id.permanent_uuid();
return STATUS_FORMAT(IllegalState,
"Replica found but not leader; lease check mode: $0", lease_check_mode);
}
Status WaitUntilLeader(const TServerDetails* replica,
const string& tablet_id,
const MonoDelta& timeout,
const LeaderLeaseCheckMode lease_check_mode) {
MonoTime start = MonoTime::Now();
MonoTime deadline = start;
deadline.AddDelta(timeout);
int backoff_exp = 0;
const int kMaxBackoffExp = 7;
Status s;
while (true) {
MonoDelta remaining_timeout = deadline.GetDeltaSince(MonoTime::Now());
s = GetReplicaStatusAndCheckIfLeader(replica, tablet_id, remaining_timeout,
lease_check_mode);
if (s.ok()) {
return Status::OK();
}
if (MonoTime::Now().GetDeltaSince(start).MoreThan(timeout)) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(1 << backoff_exp));
backoff_exp = min(backoff_exp + 1, kMaxBackoffExp);
}
return STATUS(TimedOut, Substitute("Replica $0 is not leader after waiting for $1: $2",
replica->ToString(), timeout.ToString(), s.ToString()));
}
Status FindTabletLeader(const TabletServerMap& tablet_servers,
const string& tablet_id,
const MonoDelta& timeout,
TServerDetails** leader) {
return FindTabletLeader(TServerDetailsVector(tablet_servers), tablet_id, timeout, leader);
}
Status FindTabletLeader(const TabletServerMapUnowned& tablet_servers,
const string& tablet_id,
const MonoDelta& timeout,
TServerDetails** leader) {
return FindTabletLeader(TServerDetailsVector(tablet_servers), tablet_id, timeout, leader);
}
Status FindTabletLeader(const vector<TServerDetails*>& tservers,
const string& tablet_id,
const MonoDelta& timeout,
TServerDetails** leader) {
MonoTime start = MonoTime::Now();
MonoTime deadline = start;
deadline.AddDelta(timeout);
Status s;
int i = 0;
while (true) {
MonoDelta remaining_timeout = deadline.GetDeltaSince(MonoTime::Now());
s = GetReplicaStatusAndCheckIfLeader(tservers[i], tablet_id, remaining_timeout);
if (s.ok()) {
*leader = tservers[i];
return Status::OK();
}
if (deadline.ComesBefore(MonoTime::Now())) break;
i = (i + 1) % tservers.size();
if (i == 0) {
SleepFor(MonoDelta::FromMilliseconds(10));
}
}
return STATUS(TimedOut, Substitute("Unable to find leader of tablet $0 after $1. "
"Status message: $2", tablet_id,
MonoTime::Now().GetDeltaSince(start).ToString(),
s.ToString()));
}
Status StartElection(const TServerDetails* replica,
const string& tablet_id,
const MonoDelta& timeout,
consensus::TEST_SuppressVoteRequest suppress_vote_request) {
RunLeaderElectionRequestPB req;
req.set_dest_uuid(replica->uuid());
req.set_tablet_id(tablet_id);
req.set_suppress_vote_request(suppress_vote_request);
RunLeaderElectionResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(replica->consensus_proxy->RunLeaderElection(req, &resp, &rpc));
if (resp.has_error()) {
return StatusFromPB(resp.error().status())
.CloneAndPrepend(Substitute("Code $0", TabletServerErrorPB::Code_Name(resp.error().code())));
}
return Status::OK();
}
Status RequestVote(const TServerDetails* replica,
const std::string& tablet_id,
const std::string& candidate_uuid,
int64_t candidate_term,
const OpIdPB& last_logged_opid,
boost::optional<bool> ignore_live_leader,
boost::optional<bool> is_pre_election,
const MonoDelta& timeout) {
RSTATUS_DCHECK(
last_logged_opid.IsInitialized(), Uninitialized, "Last logged op id is uninitialized");
consensus::VoteRequestPB req;
req.set_dest_uuid(replica->uuid());
req.set_tablet_id(tablet_id);
req.set_candidate_uuid(candidate_uuid);
req.set_candidate_term(candidate_term);
*req.mutable_candidate_status()->mutable_last_received() = last_logged_opid;
if (ignore_live_leader) req.set_ignore_live_leader(*ignore_live_leader);
if (is_pre_election) req.set_preelection(*is_pre_election);
consensus::VoteResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(replica->consensus_proxy->RequestConsensusVote(req, &resp, &rpc));
if (resp.has_vote_granted() && resp.vote_granted())
return Status::OK();
if (resp.has_error())
return StatusFromPB(resp.error().status());
if (resp.has_consensus_error())
return StatusFromPB(resp.consensus_error().status());
return STATUS(IllegalState, "Unknown error (vote not granted)");
}
Status LeaderStepDown(
const TServerDetails* replica,
const string& tablet_id,
const TServerDetails* new_leader,
const MonoDelta& timeout,
const bool disable_graceful_transition,
TabletServerErrorPB* error) {
LeaderStepDownRequestPB req;
req.set_dest_uuid(replica->uuid());
req.set_tablet_id(tablet_id);
if (disable_graceful_transition) {
req.set_disable_graceful_transition(disable_graceful_transition);
}
if (new_leader) {
req.set_new_leader_uuid(new_leader->uuid());
}
LeaderStepDownResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(replica->consensus_proxy->LeaderStepDown(req, &resp, &rpc));
if (resp.has_error()) {
if (error != nullptr) {
*error = resp.error();
}
return StatusFromPB(resp.error().status())
.CloneAndPrepend(Substitute("Code $0", TabletServerErrorPB::Code_Name(resp.error().code())));
}
return WaitFor([&]() -> Result<bool> {
rpc.Reset();
GetConsensusStateRequestPB state_req;
state_req.set_dest_uuid(replica->uuid());
state_req.set_tablet_id(tablet_id);
GetConsensusStateResponsePB state_resp;
RETURN_NOT_OK(replica->consensus_proxy->GetConsensusState(state_req, &state_resp, &rpc));
return state_resp.cstate().leader_uuid() != replica->uuid();
}, timeout, "Leader change");
}
Status WriteSimpleTestRow(const TServerDetails* replica,
const std::string& tablet_id,
int32_t key,
int32_t int_val,
const string& string_val,
const MonoDelta& timeout) {
WriteRequestPB req;
WriteResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
req.set_tablet_id(tablet_id);
AddTestRowInsert(key, int_val, string_val, &req);
RETURN_NOT_OK(replica->tserver_proxy->Write(req, &resp, &rpc));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
return Status::OK();
}
namespace {
Status SendAddRemoveServerRequest(const TServerDetails* leader,
const ChangeConfigRequestPB& req,
ChangeConfigResponsePB* resp,
RpcController* rpc,
const MonoDelta& timeout,
TabletServerErrorPB::Code* error_code,
bool retry) {
Status status = Status::OK();
MonoTime start = MonoTime::Now();
do {
RETURN_NOT_OK(leader->consensus_proxy->ChangeConfig(req, resp, rpc));
if (!resp->has_error()) {
break;
}
if (error_code) *error_code = resp->error().code();
status = StatusFromPB(resp->error().status());
if (!retry) {
break;
}
if (resp->error().code() != TabletServerErrorPB::LEADER_NOT_READY_CHANGE_CONFIG) {
break;
}
rpc->Reset();
} while (MonoTime::Now().GetDeltaSince(start).LessThan(timeout));
return status;
}
} // namespace
Status AddServer(const TServerDetails* leader,
const std::string& tablet_id,
const TServerDetails* replica_to_add,
consensus::RaftPeerPB::MemberType member_type,
const boost::optional<int64_t>& cas_config_opid_index,
const MonoDelta& timeout,
TabletServerErrorPB::Code* error_code,
bool retry) {
ChangeConfigRequestPB req;
ChangeConfigResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
req.set_dest_uuid(leader->uuid());
req.set_tablet_id(tablet_id);
req.set_type(consensus::ADD_SERVER);
RaftPeerPB* peer = req.mutable_server();
peer->set_permanent_uuid(replica_to_add->uuid());
peer->set_member_type(member_type);
CopyRegistration(replica_to_add->registration.common(), peer);
if (cas_config_opid_index) {
req.set_cas_config_opid_index(*cas_config_opid_index);
}
return SendAddRemoveServerRequest(leader, req, &resp, &rpc, timeout, error_code, retry);
}
Status RemoveServer(const TServerDetails* leader,
const std::string& tablet_id,
const TServerDetails* replica_to_remove,
const boost::optional<int64_t>& cas_config_opid_index,
const MonoDelta& timeout,
TabletServerErrorPB::Code* error_code,
bool retry) {
ChangeConfigRequestPB req;
ChangeConfigResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
req.set_dest_uuid(leader->uuid());
req.set_tablet_id(tablet_id);
req.set_type(consensus::REMOVE_SERVER);
if (cas_config_opid_index) {
req.set_cas_config_opid_index(*cas_config_opid_index);
}
RaftPeerPB* peer = req.mutable_server();
peer->set_permanent_uuid(replica_to_remove->uuid());
return SendAddRemoveServerRequest(leader, req, &resp, &rpc, timeout, error_code, retry);
}
Status ListTablets(const TServerDetails* ts,
const MonoDelta& timeout,
vector<ListTabletsResponsePB::StatusAndSchemaPB>* tablets) {
tserver::ListTabletsRequestPB req;
tserver::ListTabletsResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(ts->tserver_proxy->ListTablets(req, &resp, &rpc));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
tablets->assign(resp.status_and_schema().begin(), resp.status_and_schema().end());
return Status::OK();
}
Status ListRunningTabletIds(const TServerDetails* ts,
const MonoDelta& timeout,
vector<string>* tablet_ids) {
vector<ListTabletsResponsePB::StatusAndSchemaPB> tablets;
RETURN_NOT_OK(ListTablets(ts, timeout, &tablets));
tablet_ids->clear();
for (const ListTabletsResponsePB::StatusAndSchemaPB& t : tablets) {
if (t.tablet_status().state() == tablet::RUNNING) {
tablet_ids->push_back(t.tablet_status().tablet_id());
}
}
return Status::OK();
}
Status GetTabletLocations(const shared_ptr<MasterServiceProxy>& master_proxy,
const string& tablet_id,
const MonoDelta& timeout,
master::TabletLocationsPB* tablet_locations) {
master::GetTabletLocationsResponsePB resp;
master::GetTabletLocationsRequestPB req;
*req.add_tablet_ids() = tablet_id;
rpc::RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(master_proxy->GetTabletLocations(req, &resp, &rpc));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
if (resp.errors_size() > 0) {
CHECK_EQ(1, resp.errors_size()) << resp.ShortDebugString();
return StatusFromPB(resp.errors(0).status());
}
CHECK_EQ(1, resp.tablet_locations_size()) << resp.ShortDebugString();
*tablet_locations = resp.tablet_locations(0);
return Status::OK();
}
Status GetTableLocations(const shared_ptr<MasterServiceProxy>& master_proxy,
const YBTableName& table_name,
const MonoDelta& timeout,
const RequireTabletsRunning require_tablets_running,
master::GetTableLocationsResponsePB* table_locations) {
master::GetTableLocationsRequestPB req;
table_name.SetIntoTableIdentifierPB(req.mutable_table());
req.set_require_tablets_running(require_tablets_running);
req.set_max_returned_locations(std::numeric_limits<int32_t>::max());
rpc::RpcController rpc;
rpc.set_timeout(timeout);
RETURN_NOT_OK(master_proxy->GetTableLocations(req, table_locations, &rpc));
if (table_locations->has_error()) {
return StatusFromPB(table_locations->error().status());
}
return Status::OK();
}
Status WaitForNumVotersInConfigOnMaster(const shared_ptr<MasterServiceProxy>& master_proxy,
const std::string& tablet_id,
int num_voters,
const MonoDelta& timeout) {
Status s;
MonoTime deadline = MonoTime::Now();
deadline.AddDelta(timeout);
int num_voters_found = 0;
while (true) {
TabletLocationsPB tablet_locations;
MonoDelta time_remaining = deadline.GetDeltaSince(MonoTime::Now());
s = GetTabletLocations(master_proxy, tablet_id, time_remaining, &tablet_locations);
if (s.ok()) {
num_voters_found = 0;
for (const TabletLocationsPB::ReplicaPB& r : tablet_locations.replicas()) {
if (r.role() == RaftPeerPB::LEADER || r.role() == RaftPeerPB::FOLLOWER) num_voters_found++;
}
if (num_voters_found == num_voters) break;
}
if (deadline.ComesBefore(MonoTime::Now())) break;
SleepFor(MonoDelta::FromMilliseconds(10));
}
RETURN_NOT_OK(s);
if (num_voters_found != num_voters) {
return STATUS(IllegalState,
Substitute("Did not find exactly $0 voters, found $1 voters",
num_voters, num_voters_found));
}
return Status::OK();
}
Status WaitForNumTabletsOnTS(TServerDetails* ts,
int count,
const MonoDelta& timeout,
vector<ListTabletsResponsePB::StatusAndSchemaPB>* tablets) {
Status s;
MonoTime deadline = MonoTime::Now();
deadline.AddDelta(timeout);
while (true) {
s = ListTablets(ts, MonoDelta::FromSeconds(10), tablets);
if (s.ok() && tablets->size() == count) break;
if (deadline.ComesBefore(MonoTime::Now())) break;
SleepFor(MonoDelta::FromMilliseconds(10));
}
RETURN_NOT_OK(s);
if (tablets->size() != count) {
return STATUS(IllegalState,
Substitute("Did not find exactly $0 tablets, found $1 tablets",
count, tablets->size()));
}
return Status::OK();
}
Status WaitUntilTabletInState(TServerDetails* ts,
const std::string& tablet_id,
tablet::RaftGroupStatePB state,
const MonoDelta& timeout,
const MonoDelta& list_tablets_timeout) {
MonoTime start = MonoTime::Now();
MonoTime deadline = start;
deadline.AddDelta(timeout);
vector<ListTabletsResponsePB::StatusAndSchemaPB> tablets;
Status s;
tablet::RaftGroupStatePB last_state = tablet::UNKNOWN;
while (true) {
s = ListTablets(ts, list_tablets_timeout, &tablets);
if (s.ok()) {
bool seen = false;
for (const ListTabletsResponsePB::StatusAndSchemaPB& t : tablets) {
if (t.tablet_status().tablet_id() == tablet_id) {
seen = true;
last_state = t.tablet_status().state();
if (last_state == state) {
return Status::OK();
}
}
}
if (!seen) {
s = STATUS(NotFound, "Tablet " + tablet_id + " not found");
}
}
if (deadline.ComesBefore(MonoTime::Now())) {
break;
}
SleepFor(MonoDelta::FromMilliseconds(10));
}
return STATUS(TimedOut, Substitute("T $0 P $1: Tablet not in $2 state after $3: "
"Tablet state: $4, Status message: $5",
tablet_id, ts->uuid(),
tablet::RaftGroupStatePB_Name(state),
MonoTime::Now().GetDeltaSince(start).ToString(),
tablet::RaftGroupStatePB_Name(last_state), s.ToString()));
}
// Wait until the specified tablet is in RUNNING state.
Status WaitUntilTabletRunning(TServerDetails* ts,
const std::string& tablet_id,
const MonoDelta& timeout) {
return WaitUntilTabletInState(ts, tablet_id, tablet::RUNNING, timeout);
}
Status DeleteTablet(const TServerDetails* ts,
const std::string& tablet_id,
const tablet::TabletDataState delete_type,
const boost::optional<int64_t>& cas_config_opid_index_less_or_equal,
const MonoDelta& timeout,
tserver::TabletServerErrorPB::Code* error_code) {
DeleteTabletRequestPB req;
DeleteTabletResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
req.set_dest_uuid(ts->uuid());
req.set_tablet_id(tablet_id);
req.set_delete_type(delete_type);
if (cas_config_opid_index_less_or_equal) {
req.set_cas_config_opid_index_less_or_equal(*cas_config_opid_index_less_or_equal);
}
RETURN_NOT_OK(ts->tserver_admin_proxy->DeleteTablet(req, &resp, &rpc));
if (resp.has_error()) {
if (error_code) {
*error_code = resp.error().code();
}
return StatusFromPB(resp.error().status());
}
return Status::OK();
}
Status StartRemoteBootstrap(const TServerDetails* ts,
const string& tablet_id,
const string& bootstrap_source_uuid,
const HostPort& bootstrap_source_addr,
int64_t caller_term,
const MonoDelta& timeout) {
consensus::StartRemoteBootstrapRequestPB req;
consensus::StartRemoteBootstrapResponsePB resp;
RpcController rpc;
rpc.set_timeout(timeout);
req.set_dest_uuid(ts->uuid());
req.set_tablet_id(tablet_id);
req.set_bootstrap_peer_uuid(bootstrap_source_uuid);
HostPortToPB(bootstrap_source_addr, req.mutable_source_private_addr()->Add());
req.set_caller_term(caller_term);
RETURN_NOT_OK(ts->consensus_proxy->StartRemoteBootstrap(req, &resp, &rpc));
if (resp.has_error()) {
return StatusFromPB(resp.error().status());
}
return Status::OK();
}
Status GetLastOpIdForMasterReplica(const shared_ptr<ConsensusServiceProxy>& consensus_proxy,
const string& tablet_id,
const string& dest_uuid,
const consensus::OpIdType opid_type,
const MonoDelta& timeout,
OpIdPB* opid) {
GetLastOpIdRequestPB opid_req;
GetLastOpIdResponsePB opid_resp;
RpcController controller;
controller.Reset();
controller.set_timeout(timeout);
opid_req.set_dest_uuid(dest_uuid);
opid_req.set_tablet_id(tablet_id);
opid_req.set_opid_type(opid_type);
Status s = consensus_proxy->GetLastOpId(opid_req, &opid_resp, &controller);
if (!s.ok()) {
return STATUS(InvalidArgument, Substitute(
"Failed to fetch opid type $0 from master uuid $1 with error : $2",
opid_type, dest_uuid, s.ToString()));
}
if (opid_resp.has_error()) {
return StatusFromPB(opid_resp.error().status());
}
*opid = opid_resp.opid();
return Status::OK();
}
Result<OpId> GetLastOpIdForReplica(
const TabletId& tablet_id,
TServerDetails* replica,
consensus::OpIdType opid_type,
const MonoDelta& timeout) {
return VERIFY_RESULT(GetLastOpIdForEachReplica(tablet_id, {replica}, opid_type, timeout))[0];
}
} // namespace itest
} // namespace yb
|
#include "EventAggregator4BDDTest.h"
using namespace bdd;
// On demand singleton function
#define SINGLETON_FUNC_BODY(T)\
static T s_Singleton;\
return s_Singleton;
TSetupEvent& EventAggregator4BDDTest::SetupEvent()
{
SINGLETON_FUNC_BODY(TSetupEvent);
}
TTearDownEvent& EventAggregator4BDDTest::TearDownEvent()
{
SINGLETON_FUNC_BODY(TTearDownEvent);
}
TExecuteStepEvent& EventAggregator4BDDTest::ExecuteStepEvent()
{
SINGLETON_FUNC_BODY(TExecuteStepEvent);
}
|
; signed int __fs2sint_callee(float f)
SECTION code_fp_math48
PUBLIC cm48_sdcciyp_ds2sint_callee
EXTERN cm48_sdcciyp_dcallee1, am48_dfix16
cm48_sdcciyp_ds2sint_callee:
; double to signed int
;
; enter : stack = sdcc_float x, ret
;
; exit : hl = (int)(x)
;
; uses : af, bc, de, hl, bc', de', hl'
call cm48_sdcciyp_dcallee1 ; AC'= math48(x)
jp am48_dfix16
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r14
push %r15
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x3a9, %rsi
lea addresses_normal_ht+0x111e9, %rdi
nop
nop
nop
sub $43839, %r14
mov $34, %rcx
rep movsb
nop
add %r15, %r15
lea addresses_normal_ht+0x64ed, %r10
nop
nop
and %rdi, %rdi
mov (%r10), %r14w
nop
nop
nop
cmp $13352, %r10
lea addresses_WT_ht+0xb38d, %r15
nop
dec %rbx
movb $0x61, (%r15)
nop
nop
and $51501, %r14
lea addresses_UC_ht+0xbba9, %rdi
nop
cmp %rsi, %rsi
mov (%rdi), %r10d
nop
nop
nop
nop
nop
cmp %r10, %r10
lea addresses_WT_ht+0x2ea9, %rdi
nop
nop
nop
add $12051, %r10
mov (%rdi), %bx
nop
nop
nop
cmp $3626, %rcx
lea addresses_D_ht+0x53a9, %r14
nop
and %r15, %r15
movl $0x61626364, (%r14)
nop
add $9218, %rdi
lea addresses_UC_ht+0xcd89, %rsi
lea addresses_A_ht+0xe3a9, %rdi
nop
nop
nop
and %rdx, %rdx
mov $4, %rcx
rep movsq
nop
cmp $43368, %rsi
lea addresses_WC_ht+0xa3a9, %rsi
lea addresses_WC_ht+0x1dba9, %rdi
nop
nop
nop
nop
and $9825, %rdx
mov $106, %rcx
rep movsw
nop
nop
nop
nop
nop
dec %r14
lea addresses_WC_ht+0x29a9, %rsi
lea addresses_D_ht+0x123a9, %rdi
nop
nop
sub %rdx, %rdx
mov $96, %rcx
rep movsq
nop
add %rsi, %rsi
lea addresses_A_ht+0x21c1, %rcx
nop
nop
nop
sub %r15, %r15
mov $0x6162636465666768, %r14
movq %r14, %xmm6
and $0xffffffffffffffc0, %rcx
vmovaps %ymm6, (%rcx)
nop
sub $50087, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r15
pop %r14
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r8
push %rax
push %rdi
// Store
lea addresses_normal+0x143a9, %r8
nop
nop
nop
cmp %rdi, %rdi
movl $0x51525354, (%r8)
nop
nop
nop
dec %r15
// Faulty Load
lea addresses_RW+0xcba9, %rax
nop
nop
nop
nop
sub %r8, %r8
movb (%rax), %r10b
lea oracles, %r15
and $0xff, %r10
shlq $12, %r10
mov (%r15,%r10,1), %r10
pop %rdi
pop %rax
pop %r8
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 10}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 6}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 11}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 10}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 9}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': True, 'congruent': 1}}
{'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
*/
|
; A184387: a(n) = sum of numbers from 1 to sigma(n), where sigma(n) = A000203(n).
; 1,6,10,28,21,78,36,120,91,171,78,406,105,300,300,496,171,780,210,903,528,666,300,1830,496,903,820,1596,465,2628,528,2016,1176,1485,1176,4186,741,1830,1596,4095,903,4656,990,3570,3081,2628,1176,7750,1653,4371,2628,4851,1485,7260,2628,7260,3240,4095,1830,14196,1953,4656,5460,8128,3570,10440,2346,8001,4656,10440,2628,19110,2775,6555,7750,9870,4656,14196,3240,17391,7381,8001,3570,25200,5886,8778,7260,16290,4095,27495,6328,14196,8256,10440,7260,31878,4851,14706,12246,23653,5253,23436,5460,22155,18528,13203,5886,39340,6105,23436,11628,30876,6555,28920,10440,22155,16653,16290,10440,64980,8911,17391,14196,25200,12246,48828,8256,32640,15576,31878,8778,56616,12880,20910,28920,36585,9591,41616,9870,56616,18528,23436,14196,81406,16290,24753,26106,35511,11325,69378,11628,45150,27495,41616,18528,77028,12561,28920,23436,71631,18528,66066,13530,43365,41616,31878,14196,115440,16836,52650,33930,47586,15225,64980,30876,69378,28920,36585,16290,149331,16653,56616,30876,64980,26106,73920,23436,56616,51360,64980,18528,129286,18915,43365,56616,79800,19701,109746,20100,108345,37128,46971,28920,127260,31878,48828,48828,94395,28920,166176,22578,71631,41616,52650,34980,180300,32896,54615,43956,127260,31878,104196,25200,127260,81406,58653,26106,157080,26565,93528,73920,101475,27495,149331,41616,88410,51360,93528,28920,277140,29403,79800,66430,94395,58653,127260,39340,115440,56616,109746
cal $0,88580 ; a(n) = 1 + sigma(n).
bin $0,2
mov $1,$0
|
; A130481: a(n) = Sum_{k=0..n} (k mod 3) (i.e., partial sums of A010872).
; 0,1,3,3,4,6,6,7,9,9,10,12,12,13,15,15,16,18,18,19,21,21,22,24,24,25,27,27,28,30,30,31,33,33,34,36,36,37,39,39,40,42,42,43,45,45,46,48,48,49,51,51,52,54,54,55,57,57,58,60,60,61,63,63,64,66,66,67,69,69,70,72,72,73,75,75,76,78,78,79,81,81,82,84,84,85,87,87,88,90,90,91,93,93,94,96,96,97,99,99
mov $1,$0
mod $1,3
div $1,2
add $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)cmpix"
.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
sta ab
sta xb
lda #<da
sta 172
lda #>da
sta 173
next lda db
sta da
sta dr
lda ab
sta ar
sec
sbc db
php
pla
and #%10000011
sta flags+1
lda pb
ora #%00110000
and #%01111100
flags ora #0
sta pr
lda xb
sta xr
lda yb
sta yr
lda sb
sta sr
ldx sb
txs
lda pb
pha
lda ab
ldx xb
ldy yb
plp
cmd cmp (172,x)
php
cld
sta aa
stx xa
sty ya
pla
sta pa
tsx
stx sa
jsr check
inc cmd+1
dec xb
clc
lda db
adc #17
sta db
bcc jmpnext
lda #0
sta db
clc
lda ab
adc #17
sta ab
bcc jmpnext
lda #0
sta ab
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 "cmpiy"
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
|
; A214733: a(n) = -a(n-1) - 3*a(n-2) with n>1, a(0)=0, a(1)=1.
; Submitted by Jamie Morken(s2)
; 0,1,-1,-2,5,1,-16,13,35,-74,-31,253,-160,-599,1079,718,-3955,1801,10064,-15467,-14725,61126,-16951,-166427,217280,282001,-933841,87838,2713685,-2977199,-5163856,14095453,1396115,-43682474,39494129,91553293,-210035680,-64624199,694731239,-500858642,-1583335075,3085911001,1664094224,-10921827227,5929544555,26835937126,-44624570791,-35883240587,169756952960,-62107231199,-447163627681,633485321278,708005561765,-2608461525599,484444840304,7340939736493,-8794274257405,-13228544952074,39611367724289
mov $1,1
lpb $0
sub $0,1
sub $1,$2
add $2,$1
sub $1,$2
add $2,$1
mul $1,3
lpe
mov $0,$2
|
* Spreadsheet 24/02-92
* - window item redraw
section prog
include win1_keys_wman
include win1_keys_wstatus
include win1_keys_wwork
include win1_keys_qdos_pt
include win1_keys_qdos_io
include win1_mac_oli
include win1_spread_keys
xdef rdw_cchg ; redraw one gird cell cell
xdef rdw_lchg ; redraw one loose item
xdef rdw_mkav ; make loose item available
xdef rdw_selc ; selective redraw for loose items
xdef rdw_grid ; redraw complete grid
xdef rdw_grdr ; redraw grid, col/row dimensions
*+++
* redraw complete grid
*
*---
rdw_grid subr a0-a3/d1-d3
tst.w da_dupdt(a6)
bne.s grid_exit
move.l da_wwork(a6),a4
move.l da_wmvec(a6),a2
move.l ww_chid(a4),a0
move.l ww_pappl(a4),a3 ; application window list
move.l (a3),a3 ; first appl. window
xjsr idx_ownx
xjsr idx_owny
moveq #wm.drall,d3
jsr wm.mdraw(a2)
tst.l d0
grid_exit
subend
*+++
* redraw complete grid
* and reset column/row dimensions
*---
rdw_grdr subr a1-a3/d1-d3
tst.w da_dupdt(a6)
bne.s grdr_exit
move.l da_wwork(a6),a4
move.l da_wmvec(a6),a2
move.l ww_chid(a4),a0
move.l ww_pappl(a4),a3 ; application window list
move.l (a3),a3 ; first appl. window
moveq #0,d1 ; first appl. window
moveq #0,d2 ; only set area
jsr wm.swapp(a2)
moveq #iow.spap,d0
move.w wwa_watt+wwa_papr(a3),d1 ; set paper colour
jsr wm.trap3(a2)
;;; move.l d3,-(sp)
;;; moveq #forever,d3
;;; trap #do.io
;;; move.l (sp)+,d3
moveq #iow.clra,d0
jsr wm.trap3(a2)
;;; move.l d3,-(sp)
;;; moveq #forever,d3
;;; trap #do.io
;;; move.l (sp)+,d3
moveq #wm.drall,d3
xjsr med_grid
grdr_exit
tst.l d0
subend
*+++
* selective redraw of loose items
*
* redraw all loose items with change bit set (WM.LDRAW)
*
* Entry Exit
* A0 channel ID preserved
* A4 working defintion preserved
*
* error code: any IOSS errors
* condition code: set
*---
rdw_selc
movem.l d3/a2,-(sp)
move.l da_wmvec(a6),a2
moveq #wm.drsel,d3 ; selective..
jsr wm.ldraw(a2) ; ..redraw of loose items
beq.s rdw_selc_ok
xjmp kill
rdw_selc_ok
movem.l (sp)+,d3/a2
tst.l d0
rts
*+++
* change selective redraw of loose item
*
* set the change bit in for this loose item in status area, redraws
* it, and clears change bit again
*
* Entry Exit
* A0 channel ID preserved
* A4 working defintion preserved
* D1.w loose item number preserved
*
* error code: any IOSS errors
* condition code: set
*---
r_lchg reg a1
rdw_lchg
movem.l r_lchg,-(sp)
move.l ww_wstat(a4),a1
bset #wsi..chg,ws_litem(a1,d1.w); set item change bit
bsr.s rdw_selc ; do a selective redraw
bclr #wsi..chg,ws_litem(a1,d1.w); clear change bit
movem.l (sp)+,r_lchg
tst.l d0
rts
*+++
* make loose item available
*
* Entry Exit
* A0 channel ID preserved
* A4 working defintion preserved
* D1.w loose item number preserved
*
* error code: any IOSS errors
* condition code: set
*---
r_mkav reg a1
rdw_mkav
movem.l r_mkav,-(sp)
move.l ww_wstat(a4),a1
move.b #wsi.mkav,ws_litem(a1,d1.w); set item change bit
bsr.s rdw_selc ; do a selective redraw
bclr #wsi..chg,ws_litem(a1,d1.w); clear change bit
movem.l (sp)+,r_mkav
tst.l d0
rts
*+++
* redraw one cell in gird
*
* Entry Exit
* d1.l c|r of cell preserved
* a4 wwork preserved
*
* error codes: any IOSS errors
* condition codes set
*---
r_rdw reg a0-a3/d3/d1
rdw_cchg
tst.w da_dupdt(a6) ; update of display allowed
bne.s cchg_no
movem.l r_rdw,-(sp)
move.l da_wmvec(a6),a2
move.l ww_chid(a4),a0
move.l ww_pappl(a4),a3 ; application window list
move.l (a3),a3 ; first application window
move.l wwa_mstt(a3),a1 ; status area
xjsr cel_numb ; get number of cell
bset #wsi..chg,0(a1,d1.l) ; change status for cell
moveq #wm.drsel,d3 ; draw selective
jsr wm.mdraw(a2)
bclr #wsi..chg,0(a1,d1.l) ; reset change bit
movem.l (sp)+,r_rdw
tst.l d0
rts
cchg_no
moveq #0,d0
rts
end
|
.MODEL SMALL
.STACK 100H
.DATA
INPUT_MSG DB 0ah,0dh,'Enter a hex number: $'
OUTPUT_MSG DB 0AH,0DH,'Hex number is: $'
BIT_MSG DB 0AH,0DH,'Number of 1 bits : $'
COUNT DW 30h
.CODE
MAIN PROC
;making the DS to point to data segment
MOV AX,@DATA
MOV DS,AX
CALL INPUT
CALL OUTPUT
CALL BIT
EXIT:
MOV AH,4CH
INT 21H
MAIN ENDP
INPUT PROC
LEA DX , INPUT_MSG
MOV AH,9
INT 21H
PUSH CX
MOV Cl,4
MOV CH,4
MOV AH,1
TOP1:
INT 21H
CMP AL, 0DH
JE output
CMP AL,41H
JNL LETTER
AND AL,0FH
JMP SHIFT
LETTER:
CMP AL,61H
JNL LOWER
SUB AL,37H
JMP SHIFT
LOWER:
SUB AL,57H
SHIFT:
SHL Bx,CL
OR BL,AL
DEc CH
JNZ TOP1
POP CX
RET
INPUT ENDP
OUTPUT PROC
LEA DX, OUTPUT_MSG
MOV AH,9
INT 21H
PUSH CX
MOV Cl,16
MOV AH,2
TOP2:
ROL BX,1
JNC ZERO
MOV DL,'1'
INC COUNT
JMP NEXT
ZERO:
MOV DL,'0'
NEXT:
INT 21H
LOOP TOP2
POP CX
RET
OUTPUT ENDP
BIT PROC
LEA DX,BIT_MSG
MOV AH,9
INT 21H
MOV Dx,COUNT
MOV AH,2
INT 21H
RET
BIT ENDP
END MAIN
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#ifndef OPENCV_CUDA_DYNAMIC_SMEM_HPP
#define OPENCV_CUDA_DYNAMIC_SMEM_HPP
/** @file
* @deprecated Use @ref cudev instead.
*/
//! @cond IGNORED
namespace cv {
namespace cuda {
namespace device {
template<class T>
struct DynamicSharedMem {
__device__ __forceinline__
operator T *() {
extern __shared__ int __smem[];
return (T *) __smem;
}
__device__ __forceinline__
operator const T *() const {
extern __shared__ int __smem[];
return (T *) __smem;
}
};
// specialize for double to avoid unaligned memory access compile errors
template<>
struct DynamicSharedMem<double> {
__device__ __forceinline__
operator double *() {
extern __shared__ double __smem_d[];
return (double *) __smem_d;
}
__device__ __forceinline__
operator const double *() const {
extern __shared__ double __smem_d[];
return (double *) __smem_d;
}
};
}
}
}
//! @endcond
#endif // OPENCV_CUDA_DYNAMIC_SMEM_HPP
|
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
; GlobalMemoryStatusEx Example - Author: William F Cravener 01 . 17 . 09
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.486 ; create 32 bit code
.model flat,stdcall ; 32 bit memory model
option casemap :none ; case sensitive
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
include \masm32\include\windows.inc
include \masm32\include\gdi32.inc
include \masm32\include\user32.inc
include \masm32\include\kernel32.inc
include \masm32\include\masm32.inc
includelib \masm32\lib\gdi32.lib
includelib \masm32\lib\user32.lib
includelib \masm32\lib\kernel32.lib
includelib \masm32\lib\masm32.lib
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DWORDDWORD STRUCT
lowDWORD DWORD ?
highDWORD DWORD ?
DWORDDWORD ENDS
MEMORYSTATUSEX STRUCT
dwLength DWORD ?
dwMemoryLoad DWORD ?
ullTotalPhys DWORDDWORD <>
ullAvailPhys DWORDDWORD <>
ullTotalPageFile DWORDDWORD <>
ullAvailPageFile DWORDDWORD <>
ullTotalVirtual DWORDDWORD <>
ullAvailVirtual DWORDDWORD <>
ullAvailExtendedVirtual DWORDDWORD <>
MEMORYSTATUSEX ENDS
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WinMain PROTO :DWORD,:DWORD,:DWORD,:DWORD
WndProc PROTO :DWORD,:DWORD,:DWORD,:DWORD
TopXY PROTO :DWORD,:DWORD
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.data
hInstance dd 0
hWnd dd 0
szClassName db "MemFree",0
szDisplayName db "MemFree",0
MemString1 db "Total physical memory: ",0
PhysicalMem1 db 10 dup(0)
MemString2 db " Free physical memory: ",0
PhysicalMem2 db 10 dup(0)
MemString3 db " Total page file size: ",0
PagingMem3 db 10 dup(0)
MemString4 db " Free page file size: ",0
PagingMem4 db 10 dup(0)
MemString5 db " Total virtual memory: ",0
VirtualMem5 db 10 dup(0)
MemString6 db " Free virtual memory: ",0
VirtualMem6 db 10 dup(0)
MemString7 db "Free extended virtual: ",0
VirtualMem7 db 10 dup(0)
paintstruct PAINTSTRUCT <>
memStatusEx MEMORYSTATUSEX <>
lgfnt LOGFONT <14,0,0,0,0,0,0,0,0,0,0,0,0,"Lucida Console">
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.code
start:
invoke FindWindow,ADDR szClassName,0
cmp eax,0
je @F
mov eax,0
ret
@@:
invoke GetModuleHandle,0
mov hInstance,eax
invoke WinMain,hInstance,0,0,0
invoke ExitProcess,eax
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WinMain proc hInst:DWORD,hPrevInst:DWORD,CmdLine:DWORD,CmdShow:DWORD
LOCAL wc:WNDCLASSEX
LOCAL msg:MSG
LOCAL Wwd:DWORD
LOCAL Wht:DWORD
LOCAL Wtx:DWORD
LOCAL Wty:DWORD
mov wc.cbSize,sizeof WNDCLASSEX
mov wc.style,CS_HREDRAW or CS_VREDRAW or CS_BYTEALIGNWINDOW
mov wc.lpfnWndProc,OFFSET WndProc
mov wc.cbClsExtra,0
mov wc.cbWndExtra,0
mov eax,hInst
mov wc.hInstance,eax
mov wc.hbrBackground,COLOR_WINDOW+1
mov wc.lpszMenuName,0
mov wc.lpszClassName,OFFSET szClassName
invoke LoadIcon,hInstance,500
mov wc.hIcon,eax
invoke LoadCursor,0,IDC_ARROW
mov wc.hCursor,eax
invoke LoadIcon,hInstance,500
mov wc.hIconSm,eax
invoke RegisterClassEx,ADDR wc
mov Wwd,320
mov Wht,220
invoke GetSystemMetrics,SM_CXSCREEN ; get screen width in pixels
invoke TopXY,Wwd,eax
mov Wtx,eax
invoke GetSystemMetrics,SM_CYSCREEN ; get screen height in pixels
invoke TopXY,Wht,eax
mov Wty,eax
invoke CreateWindowEx,WS_EX_OVERLAPPEDWINDOW,
ADDR szClassName,
ADDR szDisplayName,
WS_OVERLAPPEDWINDOW,
Wtx,Wty,Wwd,Wht,
NULL,NULL,
hInstance,NULL
mov hWnd,eax
invoke ShowWindow,hWnd,SW_SHOWNORMAL
invoke UpdateWindow,hWnd
StartLoop:
invoke GetMessage,ADDR msg,0,0,0
cmp eax,0
je ExitLoop
invoke TranslateMessage,ADDR msg
invoke DispatchMessage,ADDR msg
jmp StartLoop
ExitLoop:
mov eax,msg.wParam
ret
WinMain endp
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WndProc proc hWin:DWORD,uMsg:DWORD,wParam:DWORD,lParam:DWORD
LOCAL hDC:DWORD
LOCAL hFont:DWORD
.if uMsg == WM_CREATE
call ShowRAMFreeProc
.elseif uMsg == WM_PAINT
invoke BeginPaint,hWin,ADDR paintstruct
mov hDC,eax
invoke CreateFontIndirect,ADDR lgfnt
mov hFont,eax
invoke SelectObject,hDC,hFont
invoke TextOut,hDC,20,20,ADDR MemString1,24
invoke lstrlen,ADDR PhysicalMem1
invoke TextOut,hDC,200,20,ADDR PhysicalMem1,eax
invoke TextOut,hDC,20,40,ADDR MemString2,24
invoke lstrlen,ADDR PhysicalMem2
invoke TextOut,hDC,200,40,ADDR PhysicalMem2,eax
invoke TextOut,hDC,20,60,ADDR MemString3,24
invoke lstrlen,ADDR PagingMem3
invoke TextOut,hDC,200,60,ADDR PagingMem3,eax
invoke TextOut,hDC,20,80,ADDR MemString4,24
invoke lstrlen,ADDR PagingMem4
invoke TextOut,hDC,200,80,ADDR PagingMem4,eax
invoke TextOut,hDC,20,100,ADDR MemString5,24
invoke lstrlen,ADDR VirtualMem5
invoke TextOut,hDC,200,100,ADDR VirtualMem5,eax
invoke TextOut,hDC,20,120,ADDR MemString6,24
invoke lstrlen,ADDR VirtualMem6
invoke TextOut,hDC,200,120,ADDR VirtualMem6,eax
invoke TextOut,hDC,20,140,ADDR MemString7,24
invoke lstrlen,ADDR VirtualMem7
invoke TextOut,hDC,200,140,ADDR VirtualMem7,eax
invoke DeleteObject,hFont
invoke EndPaint,hWin,ADDR paintstruct
.elseif uMsg == WM_DESTROY
invoke PostQuitMessage,0
.else
invoke DefWindowProc,hWin,uMsg,wParam,lParam
ret
.endif
xor eax,eax
ret
WndProc endp
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ShowRAMFreeProc proc
push eax
push ecx
push edx
push edi
push esi
mov memStatusEx.dwLength,sizeof MEMORYSTATUSEX
invoke GlobalMemoryStatusEx,ADDR memStatusEx
mov eax,memStatusEx.ullTotalPhys.lowDWORD
mov edx,memStatusEx.ullTotalPhys.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET PhysicalMem1
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullAvailPhys.lowDWORD
mov edx,memStatusEx.ullAvailPhys.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET PhysicalMem2
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullTotalPageFile.lowDWORD
mov edx,memStatusEx.ullTotalPageFile.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET PagingMem3
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullAvailPageFile.lowDWORD
mov edx,memStatusEx.ullAvailPageFile.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET PagingMem4
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullTotalVirtual.lowDWORD
mov edx,memStatusEx.ullTotalVirtual.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET VirtualMem5
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullAvailVirtual.lowDWORD
mov edx,memStatusEx.ullAvailVirtual.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET VirtualMem6
invoke dwtoa,esi,edi
mov eax,memStatusEx.ullAvailExtendedVirtual.lowDWORD
mov edx,memStatusEx.ullAvailExtendedVirtual.highDWORD
mov ecx,1024
div ecx
mov esi,eax
mov edi,OFFSET VirtualMem7
invoke dwtoa,esi,edi
pop esi
pop edi
pop edx
pop ecx
pop eax
ret
ShowRAMFreeProc endp
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TopXY proc wDim:DWORD, sDim:DWORD
shr sDim,1
shr wDim,1
mov eax,wDim
sub sDim,eax
mov eax,sDim
ret
TopXY endp
; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
end start
|
; A023022: Number of partitions of n into two relatively prime parts. After initial term, this is the "half-totient" function phi(n)/2 (A000010(n)/2).
; 1,1,1,2,1,3,2,3,2,5,2,6,3,4,4,8,3,9,4,6,5,11,4,10,6,9,6,14,4,15,8,10,8,12,6,18,9,12,8,20,6,21,10,12,11,23,8,21,10,16,12,26,9,20,12,18,14,29,8,30,15,18,16,24,10,33,16,22,12,35,12,36,18,20,18,30,12,39,16,27,20,41,12,32,21,28,20,44,12,36,22,30,23,36,16,48,21,30,20,50,16,51,24,24,26,53,18,54,20,36,24,56,18,44,28,36,29,48,16,55,30,40,30,50,18,63,32,42,24,65,20,54,33,36,32,68,22,69,24,46,35,60,24,56,36,42,36,74,20,75,36,48,30,60,24,78,39,52,32,66,27,81,40,40,41,83,24,78,32,54,42,86,28,60,40,58,44,89,24,90,36,60,44,72,30,80,46,54,36,95,32,96,48,48,42,98,30,99,40,66,50,84,32,80,51,66,48,90,24,105,52,70,53,84,36,90,54,72,40,96,36,111,48,60,56,113,36,114,44,60,56,116,36,92,58,78,48,119,32,120,55,81,60,84,40,108,60,82,50,125
add $0,1
cal $0,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
mov $1,$0
sub $1,1
div $1,2
add $1,1
|
; A159850: Numerator of Hermite(n, 17/22).
; Submitted by Christian Krause
; 1,17,47,-7429,-160415,4464217,269993839,-1892147821,-489536076223,-4658915114335,987008017069999,28053710866880683,-2150502256703365727,-118026514721378720791,4759029349325350323695,480777330814562061542723,-9102061914203466628786559,-2016304877455443234982794959,3168699798290526716120389423,8836891942766849685759101461595,135657481354496602817183174280161,-40464379819965110231181937111357063,-1377305777182958609447017822584848273,192018159949383950510213330196922582771
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
mov $3,$1
mov $1,$2
mul $2,17
mul $3,-1
mul $3,$0
mul $3,242
lpe
mov $0,$1
|
;================================================================================
; New Item Handlers
;--------------------------------------------------------------------------------
; REMEMBER TO UPDATE THE TABLES IN UTILITIES.ASM!
;--------------------------------------------------------------------------------
; #$4C - Bomb Capacity (50)
; #$4D - Arrow Capacity (70)
; #$4E - 1/2 Magic
; #$4F - 1/4 Magic
; #$50 - Safe Master Sword
; #$51 - Bomb Capacity (+5)
; #$52 - Bomb Capacity (+10)
; #$53 - Arrow Capacity (+5)
; #$54 - Arrow Capacity (+10)
; #$55 - Programmable Item 1
; #$56 - Programmable Item 2
; #$57 - Programmable Item 3
; #$58 - Upgrade-Only Silver Arrows
; #$59 - Rupoor
; #$5A - Null Item
; #$5B - Red Clock
; #$5C - Blue Clock
; #$5D - Green Clock
; #$5E - Progressive Sword
; #$5F - Progressive Shield
; #$60 - Progressive Armor
; #$61 - Progressive Lifting Glove
; #$62 - RNG Pool Item (Single)
; #$63 - RNG Pool Item (Multi)
; #$64 - Progressive Bow
; #$65 - Progressive Bow
; #$6A - Goal Item (Single/Triforce)
; #$6B - Goal Item (Multi/Power Star)
; #$6C - Goal Item (Multi/Triforce Piece)
; #$6D - Server Request F0 (Hearts / Powder / Mushroom / Bonkable)
; #$6E - Server Request F1 (NPC)
; #$6F - Server Request F2 (Tablets / Pedestal)
; #$70 - Maps
; #$80 - Compasses
; #$90 - Big Keys
; #$A0 - Small Keys
; #$FE - Server Request (Asychronous Chest)
; #$FF - Null Chest
;--------------------------------------------------------------------------------
; Service Indexes
; 0x00 - 0x04 - chests
; 0xF0 - freestanding heart / powder / mushroom / bonkable
; 0xF1 - freestanding heart 2 / boss heart / npc
; 0xF3 - tablet/pedestal
;--------------------------------------------------------------------------------
;GetAnimatedSpriteGfxFile:
; LDY.b #$32
; CMP.b #$39 : BCS + ; If tile index >= 0x39, use sprite file 0x32 (Blank file)
;
; LDY.b #$5D
;
; CMP.b #$23 : BEQ + ; If tile index is 0x23 (Pendant)...
; CMP.b #$37 : BCS + ; ...or tile index >= 0x37, use sprite file 0x5D (Pendant, Boots, 20 Rupees)
;
; LDY.b #$5C
;
; CMP.b #$0C : BEQ + ; If tile index is 0x0C (Flute)...
; CMP.b #$24 : BCS + ; ...or tile index >= 24, use sprite file 0x5C (Rupees, Crystal, Heart Piece ... ...)
;
; ; Otherwise, use sprite file 0x5B (Medallions, Mirror, Flippers, Lantern, Compass...)
; LDY.b #$5B
;+
;JML GetAnimatedSpriteGfxFile_return
;--------------------------------------------------------------------------------
GetAnimatedSpriteGfxFile:
CMP.b #$0C : BNE +
LDY.b #$5C : JML GetAnimatedSpriteGfxFile_return
+
CMP.b #$23 : BNE +
LDY.b #$5D : JML GetAnimatedSpriteGfxFile_return
+
CMP.b #$48 : BNE +
LDY.b #$60 : JML GetAnimatedSpriteGfxFile_return
+
CMP.b #$24 : !BGE +
LDY.b #$5B : JML GetAnimatedSpriteGfxFile_return
+
CMP.b #$37 : !BGE +
LDY.b #$5C : JML GetAnimatedSpriteGfxFile_return
+
CMP.b #$39 : !BGE +
LDY.b #$5D : JML GetAnimatedSpriteGfxFile_return
+
LDY.b #$32
JML GetAnimatedSpriteGfxFile_return
;--------------------------------------------------------------------------------
GetAnimatedSpriteBufferPointer_table:
; Original data:
dw $09C0, $0030, $0060, $0090, $00C0, $0300, $0318, $0330
dw $0348, $0360, $0378, $0390, $0930, $03F0, $0420, $0450
dw $0468, $0600, $0630, $0660, $0690, $06C0, $06F0, $0720 ; disassembly (incorrectly?) says this is $0270
dw $0750, $0768, $0900, $0930, $0960, $0990, $09F0, $0000
dw $00F0, $0A20, $0A50, $0660, $0600, $0618, $0630, $0648
dw $0678, $06D8, $06A8, $0708, $0738, $0768, $0960, $0900
dw $03C0, $0990, $09A8, $09C0, $09D8, $0A08, $0A38, $0600
dw $0630
; New data:
dw $0600, $0630, $0660, $0690 ; 50 Bombs / 70 Arrows / Half Magic / Quarter Magic
dw $06C0, $06F0, $0720 ; +5/+10 Bomb Arrows
;#$4x
dw $0750 ; +10 Arrows
dw $0900 ; Upgrade-Only Silver Arrows
dw $09D8 ; Unused
dw $0930, $0960, $0990, $09C0 ; Lvl 1/2/3/4 Sword (Freestanding)
dw $09F0 ; Null-Item
dw $09C0 ; Clock
dw $0A20 ; Triforce
dw $0A50 ; Power Star
GetAnimatedSpriteBufferPointer:
;PHB : PHK : PLB
LDA.b $00 : ADC.l GetAnimatedSpriteBufferPointer_table, X
;PLB
RTL
;--------------------------------------------------------------------------------
macro ProgrammableItemLogic(index)
LDA.l ProgrammableItemLogicPointer_<index> : BNE ?jump
LDA.l ProgrammableItemLogicPointer_<index>+1 : BNE ?jump
LDA.l ProgrammableItemLogicPointer_<index>+2 : BNE ?jump
BRA ?end
?jump:
JSL.l ProgrammableItemLogicJump_<index>
?end:
endmacro
macro ValueShift()
TAX : LDA.b #$01
?start:
CPX #$00 : BEQ ?end
ASL
DEX
BRA ?start : ?end:
endmacro
;--------------------------------------------------------------------------------
;carry clear if pass
;carry set if caught
;incsrc eventdata.asm
ProcessEventItems:
;STA $FFFFFF
LDA $00 : PHA
LDA $01 : PHA
LDA $02 : PHA
PHY : PHP
PHB : LDA.b #$AF : PHA : PLB
LDA $02D8
CMP.b #$E0 : BNE +
REP #$30 ; set 16-bit accumulator & index registers
LDA RNGItem : ASL : TAX
LDA.l EventDataOffsets, X : !ADD #EventDataTable : STA $00
SEP #$20 ; set 8-bit accumulator
LDA.b #$AF : STA $02
JSL.l LoadDialogAddressIndirect
LDA RNGItem : INC : STA RNGItem
SEP #$10 ; set 8-bit index registers
REP #$20 ; set 16-bit accumulator
LDA GoalItemRequirement : BEQ ++
LDA GoalCounter : INC : STA GoalCounter
CMP GoalItemRequirement : !BLT ++
LDA TurnInGoalItems : AND.w #$00FF : BNE ++
JSL.l ActivateGoal
++
SEP #$20 ; set 8-bit accumulator
LDX.b #$01 : BRA .done
+
LDX.b #$00
.done
PLB
PLP : PLY
PLA : STA $02
PLA : STA $01
PLA : STA $00
RTS
;--------------------------------------------------------------------------------
AddReceivedItemExpandedGetItem:
PHX
LDA $02D8 ; check inventory
JSL.l FreeDungeonItemNotice
CMP.b #$0B : BNE + ; Bow
LDA BowTracking : AND.b #$40 : BEQ ++
LDA.l SilverArrowsUseRestriction : BNE ++
LDA.b #03 : STA BowEquipment ; set bow to silver
++
JMP .done
+ CMP.b #$3B : BNE + ; Silver Bow
LDA.l SilverArrowsUseRestriction : BNE .noequip
LDA.l SilverArrowsAutoEquip : AND.b #$01 : BEQ .noequip
LDA ArrowsFiller : BNE ++ ; check arrows
LDA.b #$03 : BRA +++ ; bow without arrow
++
LDA.b #$04 ; bow with arrow
+++
STA BowEquipment
.noequip
LDA BowTracking : ORA #$40 : STA BowTracking ; mark silver bow on y-toggle
JMP .done
+ CMP.b #$4C : BNE + ; 50 bombs
;LDA.b #$07 : STA BombCapacityUpgrades ; upgrade bombs
LDA.b #50 : !SUB.l StartingMaxBombs : STA BombCapacityUpgrades ; upgrade bombs
LDA.b #50 : STA BombsFiller ; fill bombs
JMP .done
+ CMP.b #$4D : BNE + ; 70 arrows
;LDA #$07 : STA ArrowCapacityUpgrades ; upgrade arrows
LDA.b #70 : !SUB.l StartingMaxArrows : STA ArrowCapacityUpgrades ; upgrade arrows
LDA.b #70 : STA ArrowsFiller ; fill arrows
JMP .done
+ CMP.b #$4E : BNE + ; 1/2 magic
LDA MagicConsumption : CMP #$02 : !BGE ++
INC : STA MagicConsumption ; upgrade magic
++
LDA.b #$80 : STA MagicFiller ; fill magic
JMP .done
+ CMP.b #$4F : BNE + ; 1/4 magic
LDA.b #$02 : STA MagicConsumption ; upgrade magic
LDA.b #$80 : STA MagicFiller ; fill magic
JMP .done
+ CMP.b #$50 : BNE + ; Master Sword (Safe)
LDA SwordEquipment : CMP.b #$02 : !BGE + ; skip if we have a better sword
LDA.b #$02 : STA SwordEquipment ; set master sword
JMP .done
+ CMP.b #$51 : BNE + ; +5 Bombs
LDA BombCapacityUpgrades : !ADD.b #$05 : STA BombCapacityUpgrades ; upgrade bombs +5
LDA.l Upgrade5BombsRefill : STA BombsFiller ; fill bombs
JMP .done
+ CMP.b #$52 : BNE + ; +10 Bombs
LDA BombCapacityUpgrades : !ADD.b #$0A : STA BombCapacityUpgrades ; upgrade bombs +10
LDA.l Upgrade10BombsRefill : STA BombsFiller ; fill bombs
JMP .done
+ CMP.b #$53 : BNE + ; +5 Arrows
LDA ArrowCapacityUpgrades : !ADD.b #$05 : STA ArrowCapacityUpgrades ; upgrade arrows +5
LDA.l Upgrade5ArrowsRefill : STA ArrowsFiller ; fill arrows
JMP .done
+ CMP.b #$54 : BNE + ; +10 Arrows
LDA ArrowCapacityUpgrades : !ADD.b #$0A : STA ArrowCapacityUpgrades ; upgrade arrows +10
LDA.l Upgrade10ArrowsRefill : STA ArrowsFiller ; fill arrows
JMP .done
+ CMP.b #$55 : BNE + ; Programmable Object 1
%ProgrammableItemLogic(1)
JMP .done
+ CMP.b #$56 : BNE + ; Programmable Object 2
%ProgrammableItemLogic(2)
JMP .done
+ CMP.b #$57 : BNE + ; Programmable Object 3
%ProgrammableItemLogic(3)
JMP .done
+ CMP.b #$58 : BNE + ; Upgrade-Only Sivler Arrows
LDA.l SilverArrowsUseRestriction : BNE +++
LDA.l SilverArrowsAutoEquip : AND.b #$01 : BEQ +++
LDA BowEquipment : BEQ ++ : CMP.b #$03 : !BGE ++
!ADD.b #$02 : STA BowEquipment ; switch to silver bow
++
+++
LDA.l ArrowMode : BEQ ++
LDA.b #$01 : STA ArrowsFiller
++
+ CMP.b #$59 : BNE + ; 1 Rupoor
REP #$20 : LDA CurrentRupees : !SUB RupoorDeduction : STA CurrentRupees : SEP #$20 ; Take 1 rupee
JMP .done
+ CMP.b #$5A : BNE + ; Null Item
JMP .done
+ CMP.b #$5B : BNE + ; Red Clock
REP #$20 ; set 16-bit accumulator
LDA ChallengeTimer : !ADD.l RedClockAmount : STA ChallengeTimer
LDA ChallengeTimer+2 : ADC.l RedClockAmount+2 : STA ChallengeTimer+2
SEP #$20 ; set 8-bit accumulator
JMP .done
+ CMP.b #$5C : BNE + ; Blue Clock
REP #$20 ; set 16-bit accumulator
LDA ChallengeTimer : !ADD.l BlueClockAmount : STA ChallengeTimer
LDA ChallengeTimer+2 : ADC.l BlueClockAmount+2 : STA ChallengeTimer+2
SEP #$20 ; set 8-bit accumulator
JMP .done
+ CMP.b #$5D : BNE + ; Green Clock
REP #$20 ; set 16-bit accumulator
LDA ChallengeTimer : !ADD.l GreenClockAmount : STA ChallengeTimer
LDA ChallengeTimer+2 : ADC.l GreenClockAmount+2 : STA ChallengeTimer+2
SEP #$20 ; set 8-bit accumulator
JMP .done
+ CMP.b #$5E : BNE + ; Progressive Sword
JMP .done
+ CMP.b #$5F : BNE + ; Progressive Shield
JMP .done
+ CMP.b #$60 : BNE + ; Progressive Armor
JMP .done
+ CMP.b #$61 : BNE + ; Progressive Lifting Glove
JMP .done
+ CMP.b #$62 : BNE + ; RNG Pool Item (Single)
JMP .done
+ CMP.b #$63 : BNE + ; RNG Pool Item (Multi)
JMP .done
+ CMP.b #$64 : BNE + ; Progressive Bow
JMP .done
+ CMP.b #$65 : BNE + ; Progressive Bow
JMP .done
+ CMP.b #$6A : BNE + ; Goal Collectable (Single/Triforce)
JSL.l ActivateGoal
JMP .done
+ CMP.b #$6B : BNE + ; Goal Collectable (Multi/Power Star)
BRA .multi_collect
+ CMP.b #$6C : BNE + ; Goal Collectable (Multi/Power Star) Alternate Graphic
.multi_collect
REP #$20 ; set 16-bit accumulator
LDA.l GoalItemRequirement : BEQ ++
LDA.l GoalCounter : INC : STA.l GoalCounter
CMP.w GoalItemRequirement : !BLT ++
LDA.l TurnInGoalItems : AND.w #$00FF : BNE ++
JSL.l ActivateGoal
++
SEP #$20 ; set 8-bit accumulator
JMP .done
+ CMP.b #$6D : BNE + ; Server Request F0
JSL.l ItemGetServiceRequest_F0
JMP .done
+ CMP.b #$6E : BNE + ; Server Request F1
JSL.l ItemGetServiceRequest_F1
JMP .done
+ CMP.b #$6F : BNE + ; Server Request F2
JSL.l ItemGetServiceRequest_F2
JMP .done
;+ CMP.b #$FE : BNE + ; Server Request (Null Chest)
; JSL.l ItemGetServiceRequest
; JMP .done
+ CMP.b #$70 : !BLT + : CMP.b #$80 : !BGE + ; Free Map
AND #$0F : CMP #$08 : !BGE ++
%ValueShift()
ORA MapField : STA MapField ; Map 1
JMP .done
++
!SUB #$08
%ValueShift()
BIT.b #$C0 : BEQ +++ : LDA.b #$C0 : +++ ; Make Hyrule Castle / Sewers Count for Both
ORA MapField+1 : STA MapField+1 ; Map 2
JMP .done
+ CMP.b #$80 : !BLT + : CMP.b #$90 : !BGE + ; Free Compass
AND #$0F : CMP #$08 : !BGE ++
%ValueShift()
ORA CompassField : STA CompassField ; Compass 1
JMP .done
++
!SUB #$08
%ValueShift()
BIT.b #$C0 : BEQ +++ : LDA.b #$C0 : +++ ; Make Hyrule Castle / Sewers Count for Both
ORA CompassField+1 : STA CompassField+1 ; Compass 2
JMP .done
+ CMP.b #$90 : !BLT + : CMP.b #$A0 : !BGE + ; Free Big Key
AND #$0F : CMP #$08 : !BGE ++
%ValueShift()
ORA BigKeyField : STA BigKeyField ; Big Key 1
JMP .done
++
!SUB #$08
%ValueShift()
BIT.b #$C0 : BEQ +++ : LDA.b #$C0 : +++ ; Make Hyrule Castle / Sewers Count for Both
ORA BigKeyField+1 : STA BigKeyField+1 ; Big Key 2
JMP .done
+ CMP.b #$A0 : !BLT + : CMP.b #$B0 : !BGE + ; Free Small Key
AND #$0F : TAX
LDA DungeonKeys, X : INC : STA DungeonKeys, X ; Increment Key Count
CPX.b #$00 : BNE ++
STA HyruleCastleKeys ; copy HC to sewers
++ : CPX.b #$01 : BNE ++
STA SewerKeys ; copy sewers to HC
++
LDA.l GenericKeys : BEQ +
.generic
LDA CurrentSmallKeys : INC : STA CurrentSmallKeys
JMP .done
.normal
TXA : ASL : CMP $040C : BNE ++
LDA CurrentSmallKeys : INC : STA CurrentSmallKeys
++
JMP .done
+
.done
PLX
LDA $02E9 : CMP.b #$01 ; thing we wrote over
RTL
; #$70 - Maps
; #$80 - Compasses
; #$90 - Big Keys
; #$A0 - Small Keys
;--------------------------------------------------------------------------------
!SCRATCH_AREA = "$7F5020"
!SINGLE_INDEX_TEMP = "$7F5020"
!SINGLE_INDEX_OFFSET_TEMP = "$7F5021"
!SINGLE_INDEX_BITMASK_TEMP = "$7F5022"
!LOCK_IN = "$7F5090"
!ITEM_BUSY = "$7F5091"
;2B:Bottle Already Filled w/ Red Potion
;2C:Bottle Already Filled w/ Green Potion
;2D:Bottle Already Filled w/ Blue Potion
;3C:Bottle Already Filled w/ Bee
;3D:Bottle Already Filled w/ Fairy
;48:Bottle Already Filled w/ Gold Bee
AddReceivedItemExpanded:
{
PHA : PHX
JSL.l PreItemGet
LDA $02D8 ; Item Value
JSR AttemptItemSubstitution
STA $02D8
JSR IncrementItemCounters
CMP.b #$16 : BNE ++ ; Bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$2B : BNE ++ ; Red Potion w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$2C : BNE ++ ; Green Potion w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$2D : BNE ++ ; Blue Potion w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$3C : BNE ++ ; Bee w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$3D : BNE ++ ; Fairy w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$48 : BNE ++ ; Gold Bee w/bottle
JSR.w CountBottles : CMP.l BottleLimit : !BLT +++
LDA.l BottleLimitReplacement : STA $02D8
+++ : JMP .done
++ : CMP.b #$4E : BNE ++ ; Progressive Magic
LDA MagicConsumption : BEQ +++
LDA.b #$4F : STA $02D8
+++ : JMP .done
++ : CMP.b #$5E : BNE ++ ; Progressive Sword
LDA SwordEquipment : CMP.l ProgressiveSwordLimit : !BLT +
LDA.l ProgressiveSwordReplacement : STA $02D8 : JMP .done
+ : CMP.b #$00 : BNE + ; No Sword
LDA.b #$49 : STA $02D8 : JMP .done
+ : CMP.b #$01 : BNE + ; Fighter Sword
LDA.b #$50 : STA $02D8 : JMP .done
+ : CMP.b #$02 : BNE + ; Master Sword
LDA.b #$02 : STA $02D8 : JMP .done
+ ; Everything Else
LDA.b #$03 : STA $02D8 : JMP .done
++ : CMP.b #$5F : BNE ++ ; Progressive Shield
LDA ShieldEquipment : CMP.l ProgressiveShieldLimit : !BLT +
LDA.l ProgressiveShieldReplacement : STA $02D8 : JMP .done
+ : CMP.b #$00 : BNE + ; No Shield
LDA.b #$04 : STA $02D8 : JMP .done
+ : CMP.b #$01 : BNE + ; Fighter Shield
LDA.b #$05 : STA $02D8 : JMP .done
+ ; Everything Else
LDA.b #$06 : STA $02D8 : JMP .done
++ : CMP.b #$60 : BNE ++ ; Progressive Armor
LDA ArmorEquipment : CMP.l ProgressiveArmorLimit : !BLT +
LDA.l ProgressiveArmorReplacement : STA $02D8 : JMP .done
+ : CMP.b #$00 : BNE + ; No Armor
LDA.b #$22 : STA $02D8 : JMP .done
+ ; Everything Else
LDA.b #$23 : STA $02D8 : JMP .done
++ : CMP.b #$61 : BNE ++ ; Progressive Lifting Glove
LDA GloveEquipment : BNE + ; No Lift
LDA.b #$1B : STA $02D8 : BRA .done
+ ; Everything Else
LDA.b #$1C : STA $02D8 : BRA .done
++ : CMP.b #$64 : BNE ++ : -- ; Progressive Bow
LDA BowEquipment : INC : LSR : CMP.l ProgressiveBowLimit : !BLT +
LDA.l ProgressiveBowReplacement : STA $02D8 : JMP .done
+ : CMP.b #$00 : BNE + ; No Bow
LDA.b #$3A : STA $02D8 : BRA .done
+ ; Any Bow
LDA.b #$3B : STA $02D8 : BRA .done
++ : CMP.b #$65 : BNE ++ ; Progressive Bow 2
LDA.l BowTracking : ORA #$20 : STA.l BowTracking
BRA --
; ++ : CMP.b #$FE : BNE ++ ; Server Request (Null Chest)
; JSL ChestItemServiceRequest
; BRA .done
++ : CMP.b #$62 : BNE ++ ; RNG Item (Single)
JSL.l GetRNGItemSingle : STA $02D8
XBA : JSR.w MarkRNGItemSingle
LDA #$FF : STA !LOCK_IN ; clear lock-in
BRA .done
++ : CMP.b #$63 : BNE ++ ; RNG Item (Multi)
JSL.l GetRNGItemMulti : STA $02D8
LDA #$FF : STA !LOCK_IN ; clear lock-in
BRA .done
++
.done
PLX : PLA
PHB : PHK ; we're skipping the corresponding instructions to grab the data bank
JML.l AddReceivedItem+2
}
;--------------------------------------------------------------------------------
;DATA AddReceivedItemExpanded
{
; This is a temporary measure for Fish to have consistent addresses
org $A08800
.y_offsets
db -5, -5, -5, -5, -5, -4, -4, -5
db -5, -4, -4, -4, -2, -4, -4, -4
db -4, -4, -4, -4, -4, -4, -4, -4
db -4, -4, -4, -4, -4, -4, -4, -4
db -4, -4, -4, -5, -4, -4, -4, -4
db -4, -4, -2, -4, -4, -4, -4, -4
db -4, -4, -4, -4, -2, -2, -2, -4
db -4, -4, -4, -4, -4, -4, -4, -4
db -4, -4, -2, -2, -4, -2, -4, -4
db -4, -5, -4, -4
;new
db -4, -4, -4, -4
db -5 ; Master Sword (Safe)
db -4, -4, -4, -4 ; +5/+10 Bomb Arrows
db -4, -4, -4 ; 3x Programmable Item
db -4 ; Upgrade-Only Sivler Arrows
db -4 ; 1 Rupoor
db -4 ; Null Item
db -4, -4, -4 ; Red, Blue & Green Clocks
db -4, -4, -4, -4 ; Progressive Sword, Shield, Armor & Gloves
db -4, -4 ; RNG Single & Multi
db -4, -4 ; Progressive Bow x2
db -4, -4, -4, -4 ; Unused
db -4, -4, -4 ; Goal Item Single, Multi & Alt Multi
db -4, -4, -4 ; Unused
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Free Map
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Free Compass
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Free Big Key
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Free Small Key
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Unused
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Unused
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Unused
db -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4 ; Unused
.x_offsets
db 4, 4, 4, 4, 4, 0, 0, 4
db 4, 4, 4, 4, 5, 0, 0, 0
db 0, 0, 0, 4, 0, 4, 0, 0
db 4, 0, 0, 0, 0, 0, 0, 0
db 0, 0, 0, 0, 4, 0, 0, 0
db 0, 0, 5, 0, 0, 0, 0, 0
db 0, 0, 0, 0, 4, 4, 4, 0
db 0, 0, 0, 0, 0, 0, 0, 0
db 0, 0, 4, 4, 0, 4, 0, 0
db 0, 4, 0, 0
;new
db 0, 0, 0, 0
db 4 ; Master Sword (Safe)
db 0, 0, 0, 0 ; +5/+10 Bomb Arrows
db 0, 0, 0 ; 3x Programmable Item
db 0 ; Upgrade-Only Sivler Arrows
db 4 ; 1 Rupoor
db 0 ; Null Item
db 0, 0, 0 ; Red, Blue & Green Clocks
db 0, 0, 0, 0 ; Progressive Sword, Shield, Armor & Gloves
db 0, 0 ; RNG Single & Multi
db 0, 0 ; Progressive Bow x2
db 0, 0, 0, 0 ; Unused
db 0, 0, 0 ; Goal Item Single, Multi & Alt Multi
db 0, 0, 0 ; Unused
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Free Map
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Free Compass
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Free Big Key
;db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; *EVENT*
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Free Small Key
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Unused
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Unused
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Unused
db 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ; Unused
.item_graphics_indices
db $06, $18, $18, $18, $2D, $20, $2E, $09
db $09, $0A, $08, $05, $10, $0B, $2C, $1B
db $1A, $1C, $14, $19, $0C, $07, $1D, $2F
db $07, $15, $12, $0D, $0D, $0E, $11, $17
db $28, $27, $04, $04, $0F, $16, $03, $13
db $01, $1E, $10, $00, $00, $00, $00, $00
db $00, $30, $22, $21, $24, $24, $24, $23
db $23, $23, $29, $2A, $2C, $2B, $03, $03
db $34, $35, $31, $33, $02, $32, $36, $37
db $2C, $06, $0C, $38
;new
db $39, $3A, $3B, $3C
;5x
db $18 ; Master Sword (Safe)
db $3D, $3E, $3F, $40 ; +5/+10 Bomb Arrows
db $00, $00, $00 ; 3x Programmable Item
db $41 ; Upgrade-Only Sivler Arrows
db $24 ; 1 Rupoor
db $47 ; Null Item
db $48, $48, $48 ; Red, Blue & Green Clocks
db $FF, $FF, $04, $0D ; Progressive Sword, Shield, Armor & Gloves
db $FF, $FF ; RNG Single & Multi
db $FF, $FF ; Progressive Bow x2
db $FF, $FF, $FF, $FF ; Unused
db $49, $4A, $49 ; Goal Item Single, Multi & Alt Multi
db $FF, $FF, $FF ; Unused
db $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21, $21 ; Free Map
db $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16, $16 ; Free Compass
db $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22, $22 ; Free Big Key
db $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F, $0F ; Free Small Key
;db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; *EVENT*
;db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; *EVENT*
;db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; *EVENT*
;db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; *EVENT*
db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; Unused
db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; Unused
db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; Unused
db $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49, $49 ; Unused
.wide_item_flag
db $00, $00, $00, $00, $00, $02, $02, $00
db $00, $00, $00, $00, $00, $02, $02, $02
db $02, $02, $02, $00, $02, $00, $02, $02
db $00, $02, $02, $02, $02, $02, $02, $02
db $02, $02, $02, $02, $00, $02, $02, $02
db $02, $02, $00, $02, $02, $02, $02, $02
db $02, $02, $02, $02, $00, $00, $00, $02
db $02, $02, $02, $02, $02, $02, $02, $02
db $02, $02, $00, $00, $02, $00, $02, $02
db $02, $00, $02, $02
;new
db $02, $02, $02, $02
db $00 ; Master Sword (Safe)
db $02, $02, $02, $02 ; +5/+10 Bomb Arrows
db $02, $02, $02 ; 3x Programmable Item
db $02 ; Upgrade-Only Sivler Arrows
db $00 ; 1 Rupoor
db $02 ; Null Item
db $02, $02, $02 ; Red, Blue & Green Clocks
db $02, $02, $02, $02 ; Progressive Sword, Shield, Armor & Gloves
db $02, $02 ; RNG Single & Multi
db $02, $02 ; Progressive Bow x2
db $02, $02, $02, $02 ; Unused
db $02, $02, $02 ; Goal Item Single, Multi & Alt Multi
db $02, $02, $02 ; Unused
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Free Map
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Free Compass
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Free Big Key
db $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00, $00 ; Free Small Key
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Unused
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Unused
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Unused
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Unused
db $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02, $02 ; Unused
.properties
db 5, -1, 5, 5, 5, 5, 5, 1
db 2, 1, 1, 1, 2, 2, 2, 4
db 4, 4, 1, 1, 2, 1, 1, 1
db 2, 1, 2, 1, 4, 4, 2, 1
db 6, 1, 2, 1, 2, 2, 1, 2
db 2, 4, 1, 1, 4, 2, 1, 4
db 2, 2, 4, 4, 4, 2, 1, 4
db 1, 2, 2, 1, 2, 2, 1, 1
db 4, 4, 1, 2, 2, 4, 4, 4
db 2, 5, 2, 1
;new
db 4, 4, 4, 4
db 5 ; Master Sword (Safe)
db 4, 4, 4, 4 ; +5/+10 Bomb Arrows
db 4, 4, 4 ; 3x Programmable Item
db 1 ; Upgrade-Only Sivler Arrows
db 3 ; 1 Rupoor
db 1 ; Null Item
db 1, 2, 4 ; Red, Blue & Green Clocks
db $FF, $FF, $FF, $FF ; Progressive Sword, Shield, Armor & Gloves
db $FF, $FF ; RNG Single & Multi
db 0, 0 ; Progressive Bow
db 0, 0, 0, 0 ; Unused
db 4, 4, 4 ; Goal Item Single, Multi & Alt Multi
db 0, 0, 0 ; Unused
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Free Map
db 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 ; Free Compass
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Free Big Key
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Free Small Key
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Unused
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Unused
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Unused
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Unused
db 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 ; Unused
; \item Target SRAM addresses for items you receive
.item_target_addr
dw $F359, $F359, $F359, $F359, $F35A, $F35A, $F35A, $F345
dw $F346, $F34B, $F342, $F340, $F341, $F344, $F35C, $F347
dw $F348, $F349, $F34A, $F34C, $F34C, $F350, $F35C, $F36B
dw $F351, $F352, $F353, $F354, $F354, $F34E, $F356, $F357
dw $F37A, $F34D, $F35B, $F35B, $F36F, $F364, $F36C, $F375
dw $F375, $F344, $F341, $F35C, $F35C, $F35C, $F36D, $F36E
dw $F36E, $F375, $F366, $F368, $F360, $F360, $F360, $F374
dw $F374, $F374, $F340, $F340, $F35C, $F35C, $F36C, $F36C
dw $F360, $F360, $F372, $F376, $F376, $F373, $F360, $F360
dw $F35C, $F359, $F34C, $F355
;new
dw $F375, $F376, $F373, $F373
dw $F359 ; Master Sword (Safe)
dw $F375, $F375, $F376, $F376 ; +5/+10 Bomb Arrows
dw $F41A, $F41C, $F41E ; 3x Programmable Item
dw $F340 ; Upgrade-Only Silver Arrows
dw $F360 ; 1 Rupoor
dw $F36A ; Null Item
dw $F454, $F454, $F454 ; Red, Blue & Green Clocks
dw $F359, $F35A, $F35B, $F354 ; Progressive Sword, Shield, Armor & Gloves
dw $F36A, $F36A ; RNG Single & Multi
dw $F340, $F340 ; Progressive Bow x2
dw $F36A, $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A ; Goal Item Single, Multi & Alt Multi
dw $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Free Map
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Free Compass
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Free Big Key
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Free Small Key
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Unused
dw $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A, $F36A ; Unused
}
; DATA Values to write to the above SRAM locations.
{
.item_values
db $01, $02, $03, $04, $01, $02, $03, $01
db $01, $01, $01, $01, $01, $02, $FF, $01
db $01, $01, $01, $01, $02, $01, $FF, $FF
db $01, $01, $02, $01, $02, $01, $01, $01
db $FF, $01, $FF, $02, $FF, $FF, $FF, $FF
db $FF, $FF, $02, $FF, $FF, $FF, $FF, $FF
db $FF, $FF, $FF, $FF, $FF, $FB, $EC, $FF
db $FF, $FF, $01, $03, $FF, $FF, $FF, $FF
db $9C, $CE, $FF, $01, $0A, $FF, $FF, $FF
db $FF, $01, $03, $01
;new
db $32, $46, $80, $80
db $02 ; Master Sword (Safe)
db $FF, $FF, $FF, $FF ; +5/+10 Bomb Arrows
db $FF, $FF, $FF ; 3x Programmable Item
db $FF ; Upgrade-Only Sivler Arrows
db $FF ; 1 Rupoor
db $FF ; Null Item
db $FF, $FF, $FF ; Red, Blue & Green Clocks
db $FF, $FF, $FF, $FF ; Progressive Sword, Shield, Armor & Gloves
db $FF, $FF ; RNG Single & Multi
db $FF, $FF ; Progressive Bow
db $FF, $FF, $FF, $FF ; Unused
db $FF, $FF, $FF ; Goal Item Single, Multi & Alt Multi
db $FF, $FF, $FF ; Unused
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Free Map
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Free Compass
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Free Big Key
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Free Small Key
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Unused
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Unused
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Unused
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Unused
db $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF ; Unused
;0x00 - Sewer Passage
;0x02 - Hyrule Castle
;0x04 - Eastern Palace
;0x06 - Desert Palace
;0x08 - Hyrule Castle 2
;0x0A - Swamp Palace
;0x0C - Dark Palace
;0x0E - Misery Mire
;0x10 - Skull Woods
;0x12 - Ice Palace
;0x14 - Tower of Hera
;0x16 - Gargoyle's Domain
;0x18 - Turtle Rock
;0x1A - Ganon's Tower
.item_masks ; these are dungeon correlations to $7EF364 - $7EF369 so it knows where to store compasses, etc
; sewers and castle get 2 bits active so that they can share their items elegantly
dw $C000, $C000, $2000, $1000, $0800, $0400, $0200, $0100
dw $0080, $0040, $0020, $0010, $0008, $0004, $4B8B, $20AB ; last two can be re-used
; caves
dw $9CCE, $0390, $2F82, $AD03, $02E9, $01C9, $06D0, $72A5
dw $A548, $4873, $01A0, $D8AD, $C902, $D020, $A002, $9802
dw $E48D, $DA02, $D8AC, $D002, $A215, $BD08, $84E2, $0085
dw $E3BD, $8584, $A901, $857E, $B902, $857A, $0087, $0A98
dw $BDAA, $84E2, $0085, $E3BD, $8584, $A901, $857E, $B902
dw $857A, $0230, $0087, $1FC0, $02D0, $5664, $04A9, $4BC0
dw $06F0, $1EC0, $0AD0, $02A9, $790F, $7EF3, $798F, $7EF3
dw $1BC0, $04F0, $1CC0, $07D0, $1B22, $1BEE, $0182, $A201
dw $C004, $F037, $A20C, $C001, $F038, $A206, $C002, $D039
dw $8A14, $0007, $0087, $00EE, $2902, $C907, $D007, $A906
dw $8F04, $F3C7, $C07E, $D022, $A70A, $D000, $A904, $8701
dw $8000, $C0C9, $F025, $C008, $F032, $C004, $D033, $AE11
dw $040C, $20C2, $C6BD, $0785, $8700, $E200, $8220, $00B0
dw $3EC0, $0AD0, $082C, $1003, $A905, $8D02, $0309, $20C0
dw $44D0
}
;--------------------------------------------------------------------------------
BottleListExpanded:
db $16, $2B, $2C, $2D, $3D, $3C, $48
PotionListExpanded:
db $2E, $2F, $30, $FF, $0E
;--------------------------------------------------------------------------------
Link_ReceiveItemAlternatesExpanded:
{
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1 ; db -1, -1, -1, -1, $44, -1, -1, -1
db -1, -1, $35, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1 ; db -1, -1, $46, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1, -1, -1, -1, -1
db -1, -1, -1, -1
db -1, -1, -1, -1
db -1 ; Master Sword (Safe)
db -1, -1, -1, -1 ; +5/+10 Bomb Arrows
db -1, -1, -1 ; 3x Programmable Item
db -1 ; Upgrade-Only Silver Arrows
db -1 ; 1 Rupoor
db -1 ; Null Item
db -1, -1, -1 ; Red, Blue & Green Clocks
db -1, -1, -1, -1 ; Progressive Sword, Shield, Armor & Gloves
db -1, -1 ; RNG Single & Multi
db -1, -1 ; Progressive Bow
db -1, -1, -1, -1 ; Unused
db -1, -1 ; Goal Item Single, Multi & Alt Multi
db -1, -1, -1, -1 ; Unused
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Free Map
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Free Compass
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Free Big Key
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Free Small Key
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Unused
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Unused
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Unused
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Unused
db -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 ; Unused
}
;--------------------------------------------------------------------------------
.loadAlternate
PHB : PHK : PLB
;TYA : JSR IncrementItemCounters
;LDA Link_ReceiveItemAlternatesExpanded, Y : STA $03
TYA : JSR AttemptItemSubstitution : STA $03
CPY $03 : BNE + : LDA.b #$FF : STA $03 : +
PLB
RTL
;--------------------------------------------------------------------------------
;DrawHUDSilverArrows:
; LDA BowEquipment : AND.w #$00FF : BNE +
; LDA BowTracking : AND.w #$0040 : BEQ +
; LDA.w #$2810 : STA $11C8
; LDA.w #$2811 : STA $11CA
; LDA.w #$2820 : STA $1208
; LDA.w #$2821 : STA $120A
; +
; LDA.w #$11CE : STA $00 ; thing we wrote over
;RTL
;--------------------------------------------------------------------------------
;Return BowEquipment but also draw silver arrows if you have the upgrade even if you don't have the bow
CheckHUDSilverArrows:
LDA.l ArrowMode : BEQ .normal
.rupee_arrows
JSL.l DrawHUDArrows
LDA BowEquipment
RTL
.normal
LDA BowEquipment : BNE +
LDA BowTracking : AND.b #$40 : BEQ ++
JSL.l DrawHUDArrows
++
LDA BowEquipment
+
RTL
;--------------------------------------------------------------------------------
DrawHUDArrows:
LDA.l ArrowMode : BEQ .normal
.rupee_arrows
LDA CurrentArrows : BEQ .none ; assuming silvers will increment this. if we go with something else, reorder these checks
LDA BowEquipment : BNE +
LDA BowTracking : AND.b #$40 : BNE .silver
BRA .wooden
+ CMP.b #03 : !BGE .silver
.wooden
LDA.b #$A7 : STA $7EC720 ; draw wooden arrow marker
LDA.b #$20 : STA $7EC721
LDA.b #$A9 : STA $7EC722
LDA.b #$20 : STA $7EC723
RTL
.normal ; in normal arrow mode this function is only ever called for silvers
.silver
LDA.b #$86 : STA $7EC720 ; draw silver arrow marker
LDA.b #$24 : STA $7EC721
LDA.b #$87 : STA $7EC722
LDA.b #$24 : STA $7EC723
RTL
.none
LDA.b #$7F : STA $7EC720 ; draw no arrow marker
LDA.b #$24 : STA $7EC721
LDA.b #$7F : STA $7EC722
LDA.b #$24 : STA $7EC723
RTL
;--------------------------------------------------------------------------------
!SCRATCH_AREA = "$7F5020"
!SINGLE_INDEX_TEMP = "$7F5020"
!SINGLE_INDEX_OFFSET_TEMP = "$7F5021"
!SINGLE_INDEX_BITMASK_TEMP = "$7F5022"
!LOCK_IN = "$7F5090"
GetRNGItemSingle:
PHY
LDA !LOCK_IN : CMP.b #$FF : BEQ + : TAX : XBA : LDA.l RNGSingleItemTable, X : RTL : +
LDX.b #$00
.single_reroll
JSL.l GetRandomInt : AND.b #$7F ; select random value
INX : CPX #$7F : !BLT + : LDA.b #$00 : BRA +++ : + ; default to 0 if too many attempts
CMP.l RNGSingleTableSize : !BGE .single_reroll
+++
STA !SINGLE_INDEX_TEMP ; put our index value here
LDX #$00
TAY
.recheck
TYA
JSR.w CheckSingleItem : BEQ .single_unused ; already used
LDA !SINGLE_INDEX_TEMP : INC ; increment index
CMP.l RNGSingleTableSize : !BLT +++ : LDA.b #$00 : +++ ; rollover index if needed
STA !SINGLE_INDEX_TEMP ; store index
INX : TAY : TXA : CMP.l RNGSingleTableSize : !BLT .recheck
LDA.b #$5A ; everything is gone, default to null item - MAKE THIS AN OPTION FOR THIS AND THE OTHER ONE
BRA .single_done
.single_unused
LDA !SINGLE_INDEX_TEMP
.single_done
TAX : LDA.l RNGSingleItemTable, X
XBA : LDA.l !SINGLE_INDEX_TEMP : STA !LOCK_IN : XBA
PLY
RTL
;--------------------------------------------------------------------------------
CheckSingleItem:
LSR #3 : TAX
LDA.l RNGItem, X : STA !SINGLE_INDEX_BITMASK_TEMP ; load value to temporary
PHX
LDA !SINGLE_INDEX_TEMP : AND #$07 : TAX ; load 0-7 part into X
LDA !SINGLE_INDEX_BITMASK_TEMP
---
CPX.b #$00 : BEQ +++
LSR
DEX
BRA ---
+++
PLX
AND.b #$01
RTS
;--------------------------------------------------------------------------------
MarkRNGItemSingle:
;STA !SINGLE_INDEX_TEMP
LSR #3 : STA !SINGLE_INDEX_OFFSET_TEMP : TAX
LDA.l RNGItem, X
STA.l !SINGLE_INDEX_BITMASK_TEMP
LDA.l !SINGLE_INDEX_TEMP : AND #$07 : TAX ; load 0-7 part into X
LDA.b #01
---
CPX.b #$00 : BEQ +++
ASL
DEX
BRA ---
+++
PHA
LDA.l !SINGLE_INDEX_OFFSET_TEMP : TAX
PLA
ORA.l !SINGLE_INDEX_BITMASK_TEMP
STA.l RNGItem, X
RTS
;--------------------------------------------------------------------------------
GetRNGItemMulti:
LDA !LOCK_IN : CMP #$FF : BEQ + : TAX : XBA : LDA.l RNGMultiItemTable, X : RTL : +
LDX.b #$00
- ; reroll
JSL.l GetRandomInt : AND.b #$7F ; select random value
INX : CPX #$7F : !BLT + : LDA.b 00 : BRA .done : + ; default to 0 if too many attempts
CMP.l RNGMultiTableSize : !BGE -
.done
STA !LOCK_IN
TAX : XBA : LDA.l RNGMultiItemTable, X
RTL
;--------------------------------------------------------------------------------
IncrementItemCounters:
PHX : PHA
LDX.b #$00
-
LDA.l ItemSubstitutionRules, X
CMP.b #$FF : BEQ .exit
CMP 1,s : BNE .noMatch
.match
PHX
TXA : LSR #2 : TAX
LDA ItemLimitCounts, X : INC : STA ItemLimitCounts, X
PLX
BEQ .exit
.noMatch
INX #4
BRA -
.exit
PLA : PLX
RTS
;--------------------------------------------------------------------------------
AttemptItemSubstitution:
PHX : PHA
LDX.b #$00
-
LDA.l ItemSubstitutionRules, X
CMP.b #$FF : BEQ .exit
CMP 1,s : BNE .noMatch
.match
PHX
TXA : LSR #2 : TAX
LDA ItemLimitCounts, X
PLX
CMP.l ItemSubstitutionRules+1, X : !BLT +
LDA.l ItemSubstitutionRules+2, X : STA 1,s
+
BEQ .exit
.noMatch
INX #4
BRA -
.exit
PLA : PLX
RTS
;--------------------------------------------------------------------------------
CountBottles:
PHX
LDX.b #$00
LDA BottleContentsOne : BEQ ++ : INX
++ : LDA BottleContentsTwo : BEQ ++ : INX
++ : LDA BottleContentsThree : BEQ ++ : INX
++ : LDA BottleContentsFour : BEQ ++ : INX
++
TXA
PLX
RTS
;--------------------------------------------------------------------------------
ActivateGoal:
STZ $11
STZ $B0
JML.l StatsFinalPrep
;--------------------------------------------------------------------------------
ChestPrep:
LDA.b #$01 : STA $02E9
JSL.l IncrementChestCounter
LDA.l ServerRequestMode : BEQ +
JSL.l ChestItemServiceRequest
RTL
+
LDY $0C ; get item value
SEC
RTL
;--------------------------------------------------------------------------------
; Set a flag in SRAM if we pick up a compass in its own dungeon with HUD compass
; counts on
MaybeFlagCompassTotalPickup:
LDA.l CompassMode : AND.b #$0F : BEQ .done
LDA $040C : CMP #$FF : BEQ .done
LSR : STA $04 : LDA #$0F : !SUB $04 ; Compute flag "index"
CPY #$25 : BEQ .setFlag ; Set flag if it's a compass for this dungeon
STA $04
TYA : AND #$0F : CMP $04 : BNE .done ; Check if compass is for this dungeon
.setFlag
CMP #$08 : !BGE ++
%ValueShift()
ORA CompassCountDisplay : STA CompassCountDisplay
BRA .done
++
!SUB #$08
%ValueShift()
BIT.b #$C0 : BEQ + : LDA.b #$C0 : + ; Make Hyrule Castle / Sewers Count for Both
ORA CompassCountDisplay+1 : STA CompassCountDisplay+1
.done
RTL
;--------------------------------------------------------------------------------
; Set the compass count display flag if we're entering a dungeon and alerady have
; that compass
MaybeFlagCompassTotalEntrance:
LDX $040C : CPX #$FF : BEQ .done ; Skip if we're not entering dungeon
LDA.l CompassMode : AND.w #$000F : BEQ .done ; Skip if we're not showing compass counts
CMP.w #$0002 : BEQ .countShown
LDA CompassField : AND.l DungeonItemMasks, X : BEQ .done ; skip if we don't have compass
.countShown
SEP #$20
TXA : LSR : STA.b $04 : LDA.b #$0F : !SUB $04 ; Compute flag "index"
CMP #$08 : !BGE ++
%ValueShift()
ORA CompassCountDisplay : STA CompassCountDisplay
REP #$20
BRA .done
++
!SUB #$08
%ValueShift()
BIT.b #$C0 : BEQ + : LDA.b #$C0 : + ; Make Hyrule Castle / Sewers Count for Both
ORA CompassCountDisplay+1 : STA CompassCountDisplay+1
REP #$20
.done
RTL
;--------------------------------------------------------------------------------
|
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015-2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 "../btloadtestsuite.h"
#include "behaviac/common/profiler/profiler.h"
LOAD_TEST(btunittest, enter_exit_action_ut_0)
{
AgentNodeTest* myTestAgent = initTestEnvNode("node_test/enter_exit_action_ut_0", format);
myTestAgent->resetProperties();
behaviac::EBTStatus status = myTestAgent->btexec();
//CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(0, myTestAgent->action_0_exit_count);
CHECK_EQUAL(0, myTestAgent->action_1_exit_count);
CHECK_EQUAL(0, myTestAgent->action_2_exit_count);
CHECK_EQUAL(behaviac::BT_RUNNING, status);
int loopCount = 1000;
while (loopCount > 0)
{
status = myTestAgent->btexec();
//CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(0, myTestAgent->action_0_exit_count);
CHECK_EQUAL(0, myTestAgent->action_1_exit_count);
CHECK_EQUAL(0, myTestAgent->action_2_exit_count);
CHECK_EQUAL(behaviac::BT_RUNNING, status);
--loopCount;
}
//
myTestAgent->testVar_0 = 0;
status = myTestAgent->btexec();
//CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(1, myTestAgent->action_0_exit_count);
CHECK_EQUAL(1, myTestAgent->action_1_exit_count);
CHECK_EQUAL(1, myTestAgent->action_2_exit_count);
CHECK_EQUAL(behaviac::BT_SUCCESS, status);
loopCount = 100;
while (loopCount > 0)
{
status = myTestAgent->btexec();
--loopCount;
}
//CHECK_EQUAL(101, myTestAgent->action_0_enter_count);
CHECK_EQUAL(101, myTestAgent->action_1_enter_count);
CHECK_EQUAL(101, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(101, myTestAgent->action_0_exit_count);
CHECK_EQUAL(101, myTestAgent->action_1_exit_count);
CHECK_EQUAL(101, myTestAgent->action_2_exit_count);
CHECK_EQUAL(behaviac::BT_SUCCESS, status);
finlTestEnvNode(myTestAgent);
}
LOAD_TEST(btunittest, enter_exit_action_ut_1)
{
AgentNodeTest* myTestAgent = initTestEnvNode("node_test/enter_exit_action_ut_1", format);
myTestAgent->resetProperties();
behaviac::EBTStatus status = myTestAgent->btexec();
//CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(0, myTestAgent->action_0_exit_count);
CHECK_EQUAL(0, myTestAgent->action_1_exit_count);
CHECK_EQUAL(0, myTestAgent->action_2_exit_count);
CHECK_EQUAL(3, myTestAgent->testVar_1);
CHECK_STR_EQUAL("hello", myTestAgent->testVar_str_0.c_str());
CHECK_EQUAL(behaviac::BT_RUNNING, status);
myTestAgent->testVar_0 = 0;
status = myTestAgent->btexec();
//CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
//CHECK_EQUAL(1, myTestAgent->action_0_exit_count);
CHECK_EQUAL(1, myTestAgent->action_1_exit_count);
CHECK_EQUAL(1, myTestAgent->action_2_exit_count);
CHECK_EQUAL(5, myTestAgent->testVar_1);
CHECK_STR_EQUAL("world", myTestAgent->testVar_str_0.c_str());
CHECK_EQUAL(behaviac::BT_SUCCESS, status);
finlTestEnvNode(myTestAgent);
}
LOAD_TEST(btunittest, enter_exit_action_ut_2)
{
AgentNodeTest* myTestAgent = initTestEnvNode("node_test/enter_exit_action_ut_2", format);
myTestAgent->resetProperties();
behaviac::EBTStatus status = myTestAgent->btexec();
CHECK_EQUAL(1, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
CHECK_EQUAL(1, myTestAgent->action_0_exit_count);
CHECK_EQUAL(0, myTestAgent->action_1_exit_count);
CHECK_EQUAL(0, myTestAgent->action_2_exit_count);
CHECK_EQUAL(3, myTestAgent->testVar_1);
CHECK_STR_EQUAL("hello", myTestAgent->testVar_str_0.c_str());
CHECK_EQUAL(behaviac::BT_RUNNING, status);
myTestAgent->testVar_0 = 0;
status = myTestAgent->btexec();
CHECK_EQUAL(2, myTestAgent->action_0_enter_count);
CHECK_EQUAL(1, myTestAgent->action_1_enter_count);
CHECK_EQUAL(1, myTestAgent->action_2_enter_count);
CHECK_EQUAL(2, myTestAgent->action_0_exit_count);
CHECK_EQUAL(1, myTestAgent->action_1_exit_count);
CHECK_EQUAL(1, myTestAgent->action_2_exit_count);
CHECK_EQUAL(5, myTestAgent->testVar_1);
CHECK_STR_EQUAL("world", myTestAgent->testVar_str_0.c_str());
CHECK_EQUAL(behaviac::BT_SUCCESS, status);
finlTestEnvNode(myTestAgent);
}
|
; A026571: a(n)=T(n,n-2), T given by A026568. Also a(n) = number of integer strings s(0),...,s(n) counted by T, such that s(n)=2.
; Submitted by Jon Maiga
; 1,2,7,16,44,106,273,672,1696,4214,10573,26392,66151,165578,415277,1041480,2615004,6568450,16512355,41531360,104526093,263206638,663143211,1671581968,4215574482,10635988422,26846320149,67790042264
lpb $0
mov $2,$0
sub $0,1
seq $2,26587 ; a(n) = T(n, n-2), T given by A026584. Also a(n) = number of integer strings s(0),...,s(n) counted by T, such that s(n)=2.
add $1,$2
lpe
add $1,1
mov $0,$1
|
;--------------------------------------------------------------
; ZX81 HRG library for the Memotech expansion
; by Stefano Bodrato, Feb. 2010
;--------------------------------------------------------------
;
; $Id: mt_pixladdr.asm,v 1.3 2015/01/19 01:32:52 pauloscustodio Exp $
;
PUBLIC pixeladdress
;;XREF 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
|
;*****************************************************************************
;* checkasm-a.asm: assembly check tool
;*****************************************************************************
;* Copyright (C) 2008-2012 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Henrik Gramner <hengar-6@student.ltu.se>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* This program is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;* GNU General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at licensing@x264.com.
;*****************************************************************************
%include "x86inc.asm"
SECTION_RODATA
error_message: db "failed to preserve register", 0
%if ARCH_X86_64
; just random numbers to reduce the chance of incidental match
ALIGN 16
x6: ddq 0x79445c159ce790641a1b2550a612b48c
x7: ddq 0x86b2536fcd8cf6362eed899d5a28ddcd
x8: ddq 0x3f2bf84fc0fcca4eb0856806085e7943
x9: ddq 0xd229e1f5b281303facbd382dcf5b8de2
x10: ddq 0xab63e2e11fa38ed971aeaff20b095fd9
x11: ddq 0x77d410d5c42c882d89b0c0765892729a
x12: ddq 0x24b3c1d2a024048bc45ea11a955d8dd5
x13: ddq 0xdd7b8919edd427862e8ec680de14b47c
x14: ddq 0x11e53e2b2ac655ef135ce6888fa02cbf
x15: ddq 0x6de8f4c914c334d5011ff554472a7a10
n7: dq 0x21f86d66c8ca00ce
n8: dq 0x75b6ba21077c48ad
n9: dq 0xed56bb2dcb3c7736
n10: dq 0x8bda43d3fd1a7e06
n11: dq 0xb64a9c9e5d318408
n12: dq 0xdf9a54b303f1d3a3
n13: dq 0x4a75479abd64e097
n14: dq 0x249214109d5d1c88
%endif
SECTION .text
cextern_naked puts
; max number of args used by any x264 asm function.
; (max_args % 4) must equal 3 for stack alignment
%define max_args 15
%if ARCH_X86_64
;-----------------------------------------------------------------------------
; void x264_checkasm_stack_clobber( uint64_t clobber, ... )
;-----------------------------------------------------------------------------
cglobal checkasm_stack_clobber, 1,2
; Clobber the stack with junk below the stack pointer
%define size (max_args+6)*8
SUB rsp, size
mov r1, size-8
.loop:
mov [rsp+r1], r0
sub r1, 8
jge .loop
ADD rsp, size
RET
%if WIN64
%assign free_regs 7
%else
%assign free_regs 9
%endif
;-----------------------------------------------------------------------------
; intptr_t x264_checkasm_call( intptr_t (*func)(), int *ok, ... )
;-----------------------------------------------------------------------------
INIT_XMM
cglobal checkasm_call, 2,15,16
SUB rsp, max_args*8+16
mov r6, r0
mov [rsp+max_args*8], r1
; All arguments have been pushed on the stack instead of registers in order to
; test for incorrect assumptions that 32-bit ints are zero-extended to 64-bit.
mov r0, r6mp
mov r1, r7mp
mov r2, r8mp
mov r3, r9mp
%if UNIX64
mov r4, r10mp
mov r5, r11mp
%assign i 6
%rep max_args-6
mov r9, [rsp+stack_offset+(i+1)*8]
mov [rsp+(i-6)*8], r9
%assign i i+1
%endrep
%else
%assign i 4
%rep max_args-4
mov r9, [rsp+stack_offset+(i+7)*8]
mov [rsp+i*8], r9
%assign i i+1
%endrep
%endif
%if WIN64
%assign i 6
%rep 16-6
mova m %+ i, [x %+ i]
%assign i i+1
%endrep
%endif
%assign i 14
%rep 15-free_regs
mov r %+ i, [n %+ i]
%assign i i-1
%endrep
call r6
%assign i 14
%rep 15-free_regs
xor r %+ i, [n %+ i]
or r14, r %+ i
%assign i i-1
%endrep
%if WIN64
%assign i 6
%rep 16-6
pxor m %+ i, [x %+ i]
por m6, m %+ i
%assign i i+1
%endrep
packsswb m6, m6
movq r5, m6
or r14, r5
%endif
jz .ok
mov r9, rax
lea r0, [error_message]
call puts
mov r1, [rsp+max_args*8]
mov dword [r1], 0
mov rax, r9
.ok:
ADD rsp, max_args*8+16
RET
%else
; just random numbers to reduce the chance of incidental match
%define n3 dword 0x6549315c
%define n4 dword 0xe02f3e23
%define n5 dword 0xb78d0d1d
%define n6 dword 0x33627ba7
;-----------------------------------------------------------------------------
; intptr_t x264_checkasm_call( intptr_t (*func)(), int *ok, ... )
;-----------------------------------------------------------------------------
cglobal checkasm_call, 1,7
mov r3, n3
mov r4, n4
mov r5, n5
mov r6, n6
%rep max_args
push dword [esp+24+max_args*4]
%endrep
call r0
add esp, max_args*4
xor r3, n3
xor r4, n4
xor r5, n5
xor r6, n6
or r3, r4
or r5, r6
or r3, r5
jz .ok
mov r3, eax
lea r1, [error_message]
push r1
call puts
add esp, 4
mov r1, r1m
mov dword [r1], 0
mov eax, r3
.ok:
RET
%endif ; ARCH_X86_64
;-----------------------------------------------------------------------------
; int x264_stack_pagealign( int (*func)(), int align )
;-----------------------------------------------------------------------------
cglobal stack_pagealign, 2,2
push rbp
mov rbp, rsp
and rsp, ~0xfff
sub rsp, r1
call r0
leave
RET
|
.text
.align 2
.thumb
.thumb_func
.global newmovesetstyle
main:
mov r1, r9
lsl r1, r1, #0x2
ldr r0, table
add r0, r0, r1
ldr r0, [r0, #0x0]
ldr r6, there
add r6, #0x6
ldrb r7, [r6, #0x0]
loop: lsl r1, r7, #0x1
add r1, r1, r7
add r3, r0, r1
ldrb r1, [r3, #0x2]
mov r4, r10
cmp r4, r1
beq learn
cmp r1, #0xFF
beq exit
add r7, #0x1
b loop
learn: ldr r2, there
add r7, #0x1
strb r7, [r6, #0x0]
ldrb r1, [r3, #0x1]
lsl r1, r1, #0x8
ldrb r0, [r3, #0x0]
orr r0, r1
strh r0, [r2, #0x0]
ldr r1, return
bx r1
exit: ldr r0, return2
bx r0
.align
return: .word 0x0803EB65
return2: .word 0x0803EB73
table: .word 0x08900000
there: .word 0x02024022
|
<%
from pwnlib.shellcraft.i386.linux import syscall
%>
<%page args="buf, size"/>
<%docstring>
Invokes the syscall getcwd. See 'man 2 getcwd' for more information.
Arguments:
buf(char): buf
size(size_t): size
</%docstring>
${syscall('SYS_getcwd', buf, size)}
|
; A020792: Decimal expansion of 1/sqrt(35).
; Submitted by Jamie Morken(s4)
; 1,6,9,0,3,0,8,5,0,9,4,5,7,0,3,3,1,5,5,0,1,9,2,3,6,6,5,4,7,3,1,8,9,0,5,8,5,2,6,1,5,7,1,7,8,0,2,2,6,9,5,4,3,7,7,9,6,5,6,3,4,1,9,1,1,8,3,6,6,3,5,5,9,7,4,4,4,7,2,2,9,6,2,1,8,7,8,6,4,3,6,3,3,8,0,3,1,1,9,3
mov $1,1
mov $2,1
mov $3,$0
add $3,5
mov $4,$0
add $0,5
add $4,3
mul $4,2
mov $7,10
pow $7,$4
mov $9,10
lpb $3
mov $4,$2
pow $4,2
mul $4,35
mov $5,$1
pow $5,2
add $4,$5
mov $6,$1
mov $1,$4
mul $6,$2
mul $6,2
mov $2,$6
mov $8,$4
div $8,$7
max $8,2
div $1,$8
div $2,$8
sub $3,1
lpe
mov $3,$9
pow $3,$0
div $2,$3
mov $0,$2
mod $0,10
|
; A069127: Centered 14-gonal numbers.
; 1,15,43,85,141,211,295,393,505,631,771,925,1093,1275,1471,1681,1905,2143,2395,2661,2941,3235,3543,3865,4201,4551,4915,5293,5685,6091,6511,6945,7393,7855,8331,8821,9325,9843,10375,10921,11481,12055,12643,13245,13861,14491,15135,15793,16465,17151,17851,18565,19293,20035,20791,21561,22345,23143,23955,24781,25621,26475,27343,28225,29121,30031,30955,31893,32845,33811,34791,35785,36793,37815,38851,39901,40965,42043,43135,44241,45361,46495,47643,48805,49981,51171,52375,53593,54825,56071,57331,58605,59893,61195,62511,63841,65185,66543,67915,69301,70701,72115,73543,74985,76441,77911,79395,80893,82405,83931,85471,87025,88593,90175,91771,93381,95005,96643,98295,99961,101641,103335,105043,106765,108501,110251,112015,113793,115585,117391,119211,121045,122893,124755,126631,128521,130425,132343,134275,136221,138181,140155,142143,144145,146161,148191,150235,152293,154365,156451,158551,160665,162793,164935,167091,169261,171445,173643,175855,178081,180321,182575,184843,187125,189421,191731,194055,196393,198745,201111,203491,205885,208293,210715,213151,215601,218065,220543,223035,225541,228061,230595,233143,235705,238281,240871,243475,246093,248725,251371,254031,256705,259393,262095,264811,267541,270285,273043,275815,278601,281401,284215,287043,289885,292741,295611,298495,301393,304305,307231,310171,313125,316093,319075,322071,325081,328105,331143,334195,337261,340341,343435,346543,349665,352801,355951,359115,362293,365485,368691,371911,375145,378393,381655,384931,388221,391525,394843,398175,401521,404881,408255,411643,415045,418461,421891,425335,428793,432265,435751
sub $1,$0
bin $1,2
mul $1,14
add $1,1
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <endian.h>
#include <poll.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
#include "readline.hpp"
#define MAX_EVENT 1000
void echo_cli(FILE* fp, int sockfd) {
char recvbuf[1024] = {0};
char sendbuf[1024] = {0};
int epollfd = epoll_create1(0);
struct epoll_event ev0;
ev0.events = POLLIN;
ev0.data.fd = sockfd;
epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev0);
struct epoll_event ev1;
ev1.events = POLLIN;
ev1.data.fd = fileno(fp);
epoll_ctl(epollfd, EPOLL_CTL_ADD, fileno(fp), &ev1);
vector<struct epoll_event> revents;
revents.resize(MAX_EVENT);
for (;;) {
int rn = epoll_wait(epollfd, &*revents.begin(), MAX_EVENT, -1);
if (rn == 0) continue;
if (rn < 0) ERR_EXIT("epoll wait");
for (int i = 0; i < rn; i++) {
if (revents[i].data.fd == fileno(fp)) {
if (fgets(sendbuf, sizeof sendbuf, stdin) == NULL) {
break;
}
writen(sockfd, sendbuf, strlen(sendbuf));
bzero(sendbuf, sizeof sendbuf);
}
if (revents[i].data.fd == sockfd) {
if (revents[i].events & POLLIN) {
std::cout << "POLLIN" << std::endl;
}
if (revents[i].events & POLLHUP) {
std::cout << "POLLHUP" << std::endl;
}
int n;
if ( (n = readline(sockfd, recvbuf, sizeof recvbuf)) == 0) {
printf("server close\n");
close(sockfd);
exit(0);
}
fputs(recvbuf, stdout);
bzero(recvbuf, sizeof recvbuf);
}
}
}
close(sockfd);
}
int main()
{
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
ERR_EXIT("SOCKET");
}
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htobe16(8900);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sock, (struct sockaddr*)&servaddr, sizeof servaddr) < 0) {
ERR_EXIT("connect");
}
struct sockaddr_in localaddr;
socklen_t addrlen = sizeof localaddr;
if (getsockname(sock, (struct sockaddr*)&localaddr, &addrlen) < 0) {
ERR_EXIT("getsockname");
}
std::cout << "ip=" << inet_ntoa(localaddr.sin_addr) << "port=" <<
be16toh(localaddr.sin_port) << std::endl;
echo_cli(stdin, sock);
exit(-1);
}
|
/*
* SPDX-License-Identifier: Apache-2.0
*/
//===--------------- LRN.cpp - Shape Inference for LRN Op -----------------===//
//
// This file implements shape inference for the ONNX LRN Operator.
//
//===----------------------------------------------------------------------===//
#include "src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp"
using namespace mlir;
namespace onnx_mlir {
LogicalResult ONNXLRNOpShapeHelper::computeShape(
ONNXLRNOpAdaptor operandAdaptor) {
// Shape inference indicated by passing a null rewriter pointer.
// Basic information.
auto rank = operandAdaptor.X().getType().cast<ShapedType>().getRank();
// Perform transposition according to perm attribute.
DimsExpr outputDims;
MemRefBoundsIndexCapture XBounds(operandAdaptor.X());
for (decltype(rank) i = 0; i < rank; ++i) {
outputDims.emplace_back(XBounds.getDim(i));
}
// Set type for the first output.
dimsForOutput() = outputDims;
return success();
}
} // namespace onnx_mlir
|
;; Licensed to the .NET Foundation under one or more agreements.
;; The .NET Foundation licenses this file to you under the MIT license.
;; -----------------------------------------------------------------------------------------------------------
;; #include "asmmacros.inc"
;; -----------------------------------------------------------------------------------------------------------
LEAF_ENTRY macro Name, Section
Section segment para 'CODE'
align 16
public Name
Name proc
endm
LEAF_END macro Name, Section
Name endp
Section ends
endm
; - TAILCALL_RAX: ("jmp rax") should be used for tailcalls, this emits an instruction
; sequence which is recognized by the unwinder as a valid epilogue terminator
TAILJMP_RAX TEXTEQU <DB 048h, 0FFh, 0E0h>
POINTER_SIZE equ 08h
;;
;; void CallingConventionConverter_ReturnVoidReturnThunk()
;;
LEAF_ENTRY CallingConventionConverter_ReturnVoidReturnThunk, _TEXT
ret
LEAF_END CallingConventionConverter_ReturnVoidReturnThunk, _TEXT
;;
;; int CallingConventionConverter_ReturnIntegerReturnThunk(int)
;;
LEAF_ENTRY CallingConventionConverter_ReturnIntegerReturnThunk, _TEXT
mov rax, rcx
ret
LEAF_END CallingConventionConverter_ReturnIntegerReturnThunk, _TEXT
;;
;; Note: The "__jmpstub__" prefix is used to indicate to debugger
;; that it must step-through this stub when it encounters it while
;; stepping.
;;
;; __jmpstub__CallingConventionConverter_CommonCallingStub
;;
;;
;; struct CallingConventionConverter_CommonCallingStub_PointerData
;; {
;; void *ManagedCallConverterThunk;
;; void *UniversalThunk;
;; }
;;
;; struct CommonCallingStubInputData
;; {
;; ULONG_PTR CallingConventionId;
;; CallingConventionConverter_CommonCallingStub_PointerData *commonData;
;; }
;;
;; r10 - Points at CommonCallingStubInputData
;;
;;
LEAF_ENTRY __jmpstub__CallingConventionConverter_CommonCallingStub, _TEXT
mov r11, [r10] ; put CallingConventionId into r11 as "parameter" to universal transition thunk
mov r10, [r10 + POINTER_SIZE] ; get pointer to CallingConventionConverter_CommonCallingStub_PointerData into r10
mov rax, [r10 + POINTER_SIZE] ; get address of UniversalTransitionThunk
mov r10, [r10] ; get address of ManagedCallConverterThunk
TAILJMP_RAX
LEAF_END __jmpstub__CallingConventionConverter_CommonCallingStub, _TEXT
;;
;; void CallingConventionConverter_GetStubs(IntPtr *returnVoidStub, IntPtr *returnIntegerStub, IntPtr *commonStub)
;;
LEAF_ENTRY CallingConventionConverter_GetStubs, _TEXT
lea rax, [CallingConventionConverter_ReturnVoidReturnThunk]
mov [rcx], rax
lea rax, [CallingConventionConverter_ReturnIntegerReturnThunk]
mov [rdx], rax
lea rax, [__jmpstub__CallingConventionConverter_CommonCallingStub]
mov [r8], rax
ret
LEAF_END CallingConventionConverter_GetStubs, _TEXT
end
|
; ************************************************************************************************
; ************************************************************************************************
;
; Name: convert.asm
; Purpose: Convert to/from float and int
; Created: 22nd February 2021
; Author: Paul Robson (paul@robsons.org.uk)
;
; ************************************************************************************************
; ************************************************************************************************
.section code
FPItoF: ;; <intToFloat>
debug
jmp FPItoF
FPFtoI: ;; <floatToInt>
debug
jmp FPFtoI
FPFToS: ;; <floatToString>
debug
jmp FPFtoS
FPSToF: ;; <stringToFloat>
clc
rts
.send code
; ************************************************************************************************
;
; Changes and Updates
;
; ************************************************************************************************
;
; Date Notes
; ==== =====
; 07-Mar-21 Pre code read v0.01
;
; ************************************************************************************************
|
//===-- asmstmt.cpp -------------------------------------------------------===//
//
// LDC – the LLVM D compiler
//
// This file originates from work by David Friedman for GDC released under
// the GPL 2 and Artistic licenses. See the LICENSE file for details.
//
//===----------------------------------------------------------------------===//
#include "dmd/declaration.h"
#include "dmd/dsymbol.h"
#include "dmd/errors.h"
#include "dmd/scope.h"
#include "dmd/statement.h"
#include "gen/dvalue.h"
#include "gen/functions.h"
#include "gen/irstate.h"
#include "gen/llvm.h"
#include "gen/llvmhelpers.h"
#include "gen/logger.h"
#include "gen/tollvm.h"
#include "ir/irfunction.h"
#include "llvm/IR/InlineAsm.h"
#include <cassert>
#include <cstring>
#include <deque>
#include <string>
#include <sstream>
typedef enum {
Arg_Integer,
Arg_Pointer,
Arg_Memory,
Arg_FrameRelative,
Arg_LocalSize,
Arg_Dollar
} AsmArgType;
typedef enum { Mode_Input, Mode_Output, Mode_Update } AsmArgMode;
struct AsmArg {
Expression *expr;
AsmArgType type;
AsmArgMode mode;
AsmArg(AsmArgType type, Expression *expr, AsmArgMode mode) {
this->type = type;
this->expr = expr;
this->mode = mode;
}
};
struct AsmCode {
std::string insnTemplate;
std::vector<AsmArg> args;
std::vector<bool> regs;
unsigned dollarLabel;
int clobbersMemory;
explicit AsmCode(int n_regs) {
regs.resize(n_regs, false);
dollarLabel = 0;
clobbersMemory = 0;
}
};
struct AsmParserCommon {
virtual ~AsmParserCommon() = default;
virtual void run(Scope *sc, InlineAsmStatement *asmst) = 0;
virtual std::string getRegName(int i) = 0;
};
AsmParserCommon *asmparser = nullptr;
#include "asm-x86.h" // x86 assembly parser
#define ASM_X86_64
#include "asm-x86.h" // x86_64 assembly parser
#undef ASM_X86_64
/**
* Replaces <<func>> with the name of the currently codegen'd function.
*
* This kludge is required to handle labels correctly, as the instruction
* strings for jumps, … are generated during semantic3, but attribute inference
* might change the function type (and hence the mangled name) right at the end
* of semantic3.
*/
static void replace_func_name(IRState *p, std::string &insnt) {
static const std::string needle("<<func>>");
const char *mangle = mangleExact(p->func()->decl);
size_t pos;
while (std::string::npos != (pos = insnt.find(needle))) {
// This will only happen for few instructions, and only once for those.
insnt.replace(pos, needle.size(), mangle);
}
}
Statement *gccAsmSemantic(GccAsmStatement *s, Scope *sc);
Statement *asmSemantic(AsmStatement *s, Scope *sc) {
if (!s->tokens) {
return nullptr;
}
sc->func->hasReturnExp |= 8;
// GCC-style asm starts with a string literal or a `(`
if (s->tokens->value == TOKstring || s->tokens->value == TOKlparen) {
auto gas = createGccAsmStatement(s->loc, s->tokens);
return gccAsmSemantic(gas, sc);
}
// this is DMD-style asm
sc->func->hasReturnExp |= 32;
auto ias = createInlineAsmStatement(s->loc, s->tokens);
s = ias;
bool err = false;
llvm::Triple const &t = *global.params.targetTriple;
if (!(t.getArch() == llvm::Triple::x86 ||
t.getArch() == llvm::Triple::x86_64)) {
s->error(
"DMD-style `asm { op; }` statements are not supported for the \"%s\" "
"architecture.",
t.getArchName().str().c_str());
errorSupplemental(s->loc, "Use GDC-style `asm { \"op\" : …; }` syntax or "
"`ldc.llvmasm.__asm` instead.");
err = true;
}
if (!global.params.useInlineAsm) {
s->error(
"the `asm` statement is not allowed when the -noasm switch is used");
err = true;
}
if (err) {
if (!global.gag) {
fatal();
}
return s;
}
// puts(toChars());
if (!asmparser) {
if (t.getArch() == llvm::Triple::x86) {
asmparser = new AsmParserx8632::AsmParser;
} else if (t.getArch() == llvm::Triple::x86_64) {
asmparser = new AsmParserx8664::AsmParser;
}
}
asmparser->run(sc, ias);
return s;
}
void AsmStatement_toIR(InlineAsmStatement *stmt, IRState *irs) {
IF_LOG Logger::println("InlineAsmStatement::toIR(): %s", stmt->loc.toChars());
LOG_SCOPE;
// sanity check
assert((irs->func()->decl->hasReturnExp & 40) == 40);
// get asm block
IRAsmBlock *asmblock = irs->asmBlock;
assert(asmblock);
// debug info
gIR->DBuilder.EmitStopPoint(stmt->loc);
if (!stmt->asmcode) {
return;
}
static std::string i_cns = "i";
static std::string p_cns = "i";
static std::string m_cns = "*m";
static std::string mw_cns = "=*m";
static std::string mrw_cns = "+*m";
static std::string memory_name = "memory";
AsmCode *code = static_cast<AsmCode *>(stmt->asmcode);
std::vector<LLValue *> input_values;
std::vector<std::string> input_constraints;
std::vector<LLValue *> output_values;
std::vector<std::string> output_constraints;
std::vector<std::string> clobbers;
// FIXME
//#define HOST_WIDE_INT long
// HOST_WIDE_INT var_frame_offset; // "frame_offset" is a macro
bool clobbers_mem = code->clobbersMemory;
int input_idx = 0;
int n_outputs = 0;
int arg_map[10];
assert(code->args.size() <= 10);
auto arg = code->args.begin();
for (unsigned i = 0; i < code->args.size(); i++, ++arg) {
bool is_input = true;
LLValue *arg_val = nullptr;
std::string cns;
switch (arg->type) {
case Arg_Integer:
arg_val = DtoRVal(arg->expr);
do_integer:
cns = i_cns;
break;
case Arg_Pointer:
assert(arg->expr->op == TOKvar);
arg_val = DtoRVal(arg->expr);
cns = p_cns;
break;
case Arg_Memory:
arg_val = DtoRVal(arg->expr);
switch (arg->mode) {
case Mode_Input:
cns = m_cns;
break;
case Mode_Output:
cns = mw_cns;
is_input = false;
break;
case Mode_Update:
cns = mrw_cns;
is_input = false;
break;
}
break;
case Arg_FrameRelative:
// FIXME
llvm_unreachable("Arg_FrameRelative not supported.");
/* if (auto ve = arg->expr->isVarExp())
arg_val = ve->var->toSymbol()->Stree;
else
assert(0);
if ( getFrameRelativeValue(arg_val, & var_frame_offset) ) {
// arg_val = irs->integerConstant(var_frame_offset);
cns = i_cns;
} else {
this->error("%s", "argument not frame relative");
return;
}
if (arg->mode != Mode_Input)
clobbers_mem = true;
break;*/
case Arg_LocalSize:
// FIXME
llvm_unreachable("Arg_LocalSize not supported.");
/* var_frame_offset = cfun->x_frame_offset;
if (var_frame_offset < 0)
var_frame_offset = - var_frame_offset;
arg_val = irs->integerConstant( var_frame_offset );*/
goto do_integer;
default:
llvm_unreachable("Unknown inline asm reference type.");
}
if (is_input) {
arg_map[i] = --input_idx;
input_values.push_back(arg_val);
input_constraints.push_back(cns);
} else {
arg_map[i] = n_outputs++;
output_values.push_back(arg_val);
output_constraints.push_back(cns);
}
}
// Telling GCC that callee-saved registers are clobbered makes it preserve
// those registers. This changes the stack from what a naked function
// expects.
// FIXME
// if (! irs->func->naked) {
assert(asmparser);
for (size_t i = 0; i < code->regs.size(); i++) {
if (code->regs[i]) {
clobbers.push_back(asmparser->getRegName(i));
}
}
if (clobbers_mem) {
clobbers.push_back(memory_name);
}
// }
// Remap argument numbers
for (unsigned i = 0; i < code->args.size(); i++) {
if (arg_map[i] < 0) {
arg_map[i] = -arg_map[i] - 1 + n_outputs;
}
}
bool pct = false;
auto p = code->insnTemplate.begin();
auto q = code->insnTemplate.end();
// printf("start: %.*s\n", code->insnTemplateLen, code->insnTemplate);
while (p < q) {
if (pct) {
if (*p >= '0' && *p <= '9') {
// %% doesn't check against nargs
*p = '0' + arg_map[*p - '0'];
pct = false;
} else if (*p == '$') {
pct = false;
}
// assert(*p == '%');// could be 'a', etc. so forget it..
} else if (*p == '$') {
pct = true;
}
++p;
}
IF_LOG {
Logger::cout() << "final asm: " << code->insnTemplate << '\n';
std::ostringstream ss;
ss << "GCC-style output constraints: {";
for (const auto &oc : output_constraints) {
ss << " " << oc;
}
ss << " }";
Logger::println("%s", ss.str().c_str());
ss.str("");
ss << "GCC-style input constraints: {";
for (const auto &ic : input_constraints) {
ss << " " << ic;
}
ss << " }";
Logger::println("%s", ss.str().c_str());
ss.str("");
ss << "GCC-style clobbers: {";
for (const auto &c : clobbers) {
ss << " " << c;
}
ss << " }";
Logger::println("%s", ss.str().c_str());
}
// rewrite GCC-style constraints to LLVM-style constraints
std::string llvmOutConstraints;
std::string llvmInConstraints;
int n = 0;
for (auto &oc : output_constraints) {
// rewrite update constraint to in and out constraints
if (oc[0] == '+') {
assert(oc == mrw_cns && "What else are we updating except memory?");
/* LLVM doesn't support updating operands, so split into an input
* and an output operand.
*/
// Change update operand to pure output operand.
oc = mw_cns;
// Add input operand with same value, with original as "matching
// output".
std::ostringstream ss;
ss << '*' << (n + asmblock->outputcount);
// Must be at the back; unused operands before used ones screw up
// numbering.
input_constraints.push_back(ss.str());
input_values.push_back(output_values[n]);
}
llvmOutConstraints += oc;
llvmOutConstraints += ",";
n++;
}
asmblock->outputcount += n;
for (const auto &ic : input_constraints) {
llvmInConstraints += ic;
llvmInConstraints += ",";
}
std::string clobstr;
for (const auto &c : clobbers) {
clobstr = "~{" + c + "},";
asmblock->clobs.insert(clobstr);
}
IF_LOG {
{
Logger::println("Output values:");
LOG_SCOPE
size_t i = 0;
for (auto ov : output_values) {
Logger::cout() << "Out " << i++ << " = " << *ov << '\n';
}
}
{
Logger::println("Input values:");
LOG_SCOPE
size_t i = 0;
for (auto iv : input_values) {
Logger::cout() << "In " << i++ << " = " << *iv << '\n';
}
}
}
// excessive commas are removed later...
replace_func_name(irs, code->insnTemplate);
// push asm statement
auto asmStmt = new IRAsmStmt;
asmStmt->code = code->insnTemplate;
asmStmt->out_c = llvmOutConstraints;
asmStmt->in_c = llvmInConstraints;
asmStmt->out.insert(asmStmt->out.begin(), output_values.begin(),
output_values.end());
asmStmt->in.insert(asmStmt->in.begin(), input_values.begin(),
input_values.end());
asmStmt->isBranchToLabel = stmt->isBranchToLabel;
asmblock->s.push_back(asmStmt);
}
//////////////////////////////////////////////////////////////////////////////
// rewrite argument indices to the block scope indices
static void remap_outargs(std::string &insnt, size_t nargs, size_t idx) {
static const std::string digits[10] = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
assert(nargs <= 10);
static const std::string prefix("<<out");
static const std::string suffix(">>");
std::string argnum;
std::string needle;
char buf[10];
for (unsigned i = 0; i < nargs; i++) {
needle = prefix + digits[i] + suffix;
size_t pos = insnt.find(needle);
if (std::string::npos != pos) {
sprintf(buf, "%llu", static_cast<unsigned long long>(idx++));
}
while (std::string::npos != (pos = insnt.find(needle))) {
insnt.replace(pos, needle.size(), buf);
}
}
}
// rewrite argument indices to the block scope indices
static void remap_inargs(std::string &insnt, size_t nargs, size_t idx) {
static const std::string digits[10] = {"0", "1", "2", "3", "4",
"5", "6", "7", "8", "9"};
assert(nargs <= 10);
static const std::string prefix("<<in");
static const std::string suffix(">>");
std::string argnum;
std::string needle;
char buf[10];
for (unsigned i = 0; i < nargs; i++) {
needle = prefix + digits[i] + suffix;
size_t pos = insnt.find(needle);
if (std::string::npos != pos) {
sprintf(buf, "%llu", static_cast<unsigned long long>(idx++));
}
while (std::string::npos != (pos = insnt.find(needle))) {
insnt.replace(pos, needle.size(), buf);
}
}
}
void CompoundAsmStatement_toIR(CompoundAsmStatement *stmt, IRState *p) {
IF_LOG Logger::println("CompoundAsmStatement::toIR(): %s",
stmt->loc.toChars());
LOG_SCOPE;
const bool isCompoundGccAsmStatement =
(stmt->statements && stmt->statements->length &&
stmt->statements->front()->isGccAsmStatement());
if (isCompoundGccAsmStatement) {
for (Statement *s : *stmt->statements) {
if (auto gas = s->isGccAsmStatement()) {
Statement_toIR(gas, p);
} else {
s->error("DMD-style assembly statement unsupported within GCC-style "
"`asm` block");
fatal();
}
}
return;
}
// disable inlining by default
if (!p->func()->decl->allowInlining) {
p->func()->setNeverInline();
}
// create asm block structure
assert(!p->asmBlock);
auto asmblock = new IRAsmBlock(stmt);
assert(asmblock);
p->asmBlock = asmblock;
// do asm statements
for (Statement *s : *stmt->statements) {
if (s) {
if (s->isGccAsmStatement()) {
s->error("GCC-style assembly statement unsupported within DMD-style "
"`asm` block");
fatal();
}
Statement_toIR(s, p);
}
}
// build forwarder for in-asm branches to external labels
// this additional asm code sets the __llvm_jump_target variable
// to a unique value that will identify the jump target in
// a post-asm switch
// maps each goto destination to its special value
std::map<LabelDsymbol *, int> gotoToVal;
// location of the special value determining the goto label
// will be set if post-asm dispatcher block is needed
LLValue *jump_target = nullptr;
{
FuncDeclaration *fd = gIR->func()->decl;
OutBuffer mangleBuf;
mangleToBuffer(fd, &mangleBuf);
const char *fdmangle = mangleBuf.peekChars();
// we use a simple static counter to make sure the new end labels are
// unique
static size_t uniqueLabelsId = 0;
std::ostringstream asmGotoEndLabel;
printLabelName(asmGotoEndLabel, fdmangle, "_llvm_asm_end");
asmGotoEndLabel << uniqueLabelsId++;
// initialize the setter statement we're going to build
auto outSetterStmt = new IRAsmStmt;
std::string asmGotoEnd = "\n\tjmp " + asmGotoEndLabel.str() + "\n";
std::ostringstream code;
code << asmGotoEnd;
int n_goto = 1;
for (IRAsmStmt *a : asmblock->s) {
// skip non-branch statements
LabelDsymbol *const targetLabel = a->isBranchToLabel;
if (!targetLabel) {
continue;
}
Identifier *const ident = targetLabel->ident;
// if internal, no special handling is necessary, skip
if (llvm::any_of(asmblock->internalLabels,
[ident](Identifier *i) { return i->equals(ident); })) {
continue;
}
// if we already set things up for this branch target, skip
if (gotoToVal.find(targetLabel) != gotoToVal.end()) {
continue;
}
// record that the jump needs to be handled in the post-asm dispatcher
gotoToVal[targetLabel] = n_goto;
// provide an in-asm target for the branch and set value
IF_LOG Logger::println(
"statement '%s' references outer label '%s': creating forwarder",
a->code.c_str(), ident->toChars());
printLabelName(code, fdmangle, ident->toChars());
code << ":\n\t";
code << "movl $<<in" << n_goto << ">>, $<<out0>>\n";
// FIXME: Store the value -> label mapping somewhere, so it can be
// referenced later
outSetterStmt->in.push_back(DtoConstUint(n_goto));
outSetterStmt->in_c += "i,";
code << asmGotoEnd;
++n_goto;
}
if (code.str() != asmGotoEnd) {
// finalize code
outSetterStmt->code = code.str();
outSetterStmt->code += asmGotoEndLabel.str() + ":\n";
// create storage for and initialize the temporary
jump_target = DtoAllocaDump(DtoConstUint(0), 0, "__llvm_jump_target");
// setup variable for output from asm
outSetterStmt->out_c = "=*m,";
outSetterStmt->out.push_back(jump_target);
asmblock->s.push_back(outSetterStmt);
} else {
delete outSetterStmt;
}
}
// build a fall-off-end-properly asm statement
FuncDeclaration *thisfunc = p->func()->decl;
bool useabiret = false;
p->asmBlock->asmBlock->abiret = nullptr;
if (thisfunc->fbody->endsWithAsm() == stmt &&
thisfunc->type->nextOf()->ty != Tvoid) {
// there can't be goto forwarders in this case
assert(gotoToVal.empty());
emitABIReturnAsmStmt(asmblock, stmt->loc, thisfunc);
useabiret = true;
}
// build asm block
std::vector<LLValue *> outargs;
std::vector<LLValue *> inargs;
std::vector<LLType *> outtypes;
std::vector<LLType *> intypes;
std::string out_c;
std::string in_c;
std::string clobbers;
std::string code;
size_t asmIdx = asmblock->retn;
Logger::println("do outputs");
size_t n = asmblock->s.size();
for (size_t i = 0; i < n; ++i) {
IRAsmStmt *a = asmblock->s[i];
assert(a);
size_t onn = a->out.size();
for (size_t j = 0; j < onn; ++j) {
outargs.push_back(a->out[j]);
outtypes.push_back(a->out[j]->getType());
}
if (!a->out_c.empty()) {
out_c += a->out_c;
}
remap_outargs(a->code, onn + a->in.size(), asmIdx);
asmIdx += onn;
}
Logger::println("do inputs");
for (size_t i = 0; i < n; ++i) {
IRAsmStmt *a = asmblock->s[i];
assert(a);
size_t inn = a->in.size();
for (size_t j = 0; j < inn; ++j) {
inargs.push_back(a->in[j]);
intypes.push_back(a->in[j]->getType());
}
if (!a->in_c.empty()) {
in_c += a->in_c;
}
remap_inargs(a->code, inn + a->out.size(), asmIdx);
asmIdx += inn;
if (!code.empty()) {
code += "\n\t";
}
code += a->code;
}
asmblock->s.clear();
// append inputs
out_c += in_c;
// append clobbers
for (const auto &c : asmblock->clobs) {
out_c += c;
}
// remove excessive comma
if (!out_c.empty()) {
out_c.resize(out_c.size() - 1);
}
IF_LOG {
Logger::println("code = \"%s\"", code.c_str());
Logger::println("constraints = \"%s\"", out_c.c_str());
}
// build return types
LLType *retty;
if (asmblock->retn) {
retty = asmblock->retty;
} else {
retty = llvm::Type::getVoidTy(gIR->context());
}
// build argument types
std::vector<LLType *> types;
types.insert(types.end(), outtypes.begin(), outtypes.end());
types.insert(types.end(), intypes.begin(), intypes.end());
llvm::FunctionType *fty = llvm::FunctionType::get(retty, types, false);
IF_LOG Logger::cout() << "function type = " << *fty << '\n';
std::vector<LLValue *> args;
args.insert(args.end(), outargs.begin(), outargs.end());
args.insert(args.end(), inargs.begin(), inargs.end());
IF_LOG {
Logger::cout() << "Arguments:" << '\n';
Logger::indent();
size_t i = 0;
for (auto arg : args) {
Stream cout = Logger::cout();
cout << '$' << i << " ==> " << *arg;
if (!llvm::isa<llvm::Instruction>(arg) &&
!llvm::isa<LLGlobalValue>(arg)) {
cout << '\n';
}
++i;
}
Logger::undent();
}
llvm::InlineAsm *ia = llvm::InlineAsm::get(fty, code, out_c, true);
llvm::CallInst *call = p->ir->CreateCall(
ia, args, retty == LLType::getVoidTy(gIR->context()) ? "" : "asm");
p->addInlineAsmSrcLoc(stmt->loc, call);
IF_LOG Logger::cout() << "Complete asm statement: " << *call << '\n';
// capture abi return value
if (useabiret) {
IRAsmBlock *block = p->asmBlock;
if (block->retfixup) {
block->asmBlock->abiret = (*block->retfixup)(p->ir, call);
} else if (p->asmBlock->retemu) {
block->asmBlock->abiret = DtoLoad(block->asmBlock->abiret);
} else {
block->asmBlock->abiret = call;
}
}
p->asmBlock = nullptr;
// if asm contained external branches, emit goto forwarder code
if (!gotoToVal.empty()) {
assert(jump_target);
// make new blocks
llvm::BasicBlock *bb = p->insertBB("afterasmgotoforwarder");
llvm::LoadInst *val =
p->ir->CreateLoad(jump_target, "__llvm_jump_target_value");
llvm::SwitchInst *sw = p->ir->CreateSwitch(val, bb, gotoToVal.size());
// add all cases
for (const auto &pair : gotoToVal) {
llvm::BasicBlock *casebb = p->insertBBBefore(bb, "case");
sw->addCase(LLConstantInt::get(llvm::IntegerType::get(gIR->context(), 32),
pair.second),
casebb);
p->ir->SetInsertPoint(casebb);
DtoGoto(stmt->loc, pair.first);
}
p->ir->SetInsertPoint(bb);
}
}
//////////////////////////////////////////////////////////////////////////////
void AsmStatement_toNakedIR(InlineAsmStatement *stmt, IRState *irs) {
IF_LOG Logger::println("InlineAsmStatement::toNakedIR(): %s",
stmt->loc.toChars());
LOG_SCOPE;
// is there code?
if (!stmt->asmcode) {
return;
}
AsmCode *code = static_cast<AsmCode *>(stmt->asmcode);
// build asm stmt
replace_func_name(irs, code->insnTemplate);
irs->nakedAsm << "\t" << code->insnTemplate << std::endl;
}
|
;=============================================================================|
; _______ _________ _______ _______ |
; ( ____ \\__ __/|\ /|( ____ \( ____ ) |
; | ( \/ ) ( | ) ( || ( \/| ( )| |
; | (__ | | | (___) || (__ | (____)| By Hákon Hjaltalín. |
; | __) | | | ___ || __) | __) Licensed under MIT. |
; | ( | | | ( ) || ( | (\ ( |
; | (____/\ | | | ) ( || (____/\| ) \ \__ |
; (_______/ )_( |/ \|(_______/|/ \__/ |
;=============================================================================|
bits 64
;=============================================================================;
; ETHER OPERATING SYSTEM ;
; OS KERNEL ;
;=============================================================================;
%include "./version.asm"
struc memory_region
.base resq 1
.length resq 1
.type resd 1
.reserved resd 1
endstruc
extern boot_info
extern multiboot_parse
extern mem_lower
extern mem_upper
extern bios_boot_device
extern bios_memory_map
extern sse_init
extern itoa
extern stringinit
extern vga_text_print_string
extern vga_text_clear_screen
extern vga_text_put_char
extern pmm_init
extern pmm_reserve_region
section .text
global main
main:
; Set segment
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
mov esp, 0x90000
; Initialize SSE and string functions
call sse_init
call stringinit
call vga_text_clear_screen
lea qword rdi, [welcome_text]
call vga_text_print_string
; Parse the multiboot info struct
call multiboot_parse
; Calculate memory size for PMM
mov qword rax, [mem_upper]
mov rbx, 64
mul rbx
add rax, 1024
add qword rax, [mem_lower]
xor rdx, rdx
mov rbx, 1024
div rbx
; RAX contains size of memory in MiB
mov rdi, rax
call pmm_init
lea qword rdi, [mem_text_1]
call vga_text_print_string
mov rdi, rax
lea qword rsi, [integer]
mov rdx, 15
mov rcx, 10
call itoa
lea qword rdi, [integer]
call vga_text_print_string
lea qword rdi, [mem_text_2]
call vga_text_print_string
lea qword rdi, [boot_dev_text]
call vga_text_print_string
; The BIOS boot device was parsed by multiboot_parse
mov qword rdi, [bios_boot_device]
lea qword rsi, [integer]
mov rdx, 15
mov rcx, 16
call itoa
lea qword rdi, [integer]
call vga_text_print_string
mov rdi, 0x0A
call vga_text_put_char
; Iterate through memory map and reserve regions
lea qword rdi, [bios_memory_map]
xor rcx, rcx
.next_entry:
mov dword eax, [rdi+memory_region.type]
cmp eax, 4
jbe .cont
mov dword [rdi+memory_region.type], 2
.cont:
cmp rcx, 0
je .cont2
cmp qword [rdi+memory_region.base], 0
je .finish
.cont2:
xor r10, r10
mov qword r8, [rdi+memory_region.base]
mov qword r9, [rdi+memory_region.length]
mov dword r10d, [rdi+memory_region.type]
push rdi
push rcx
lea qword rdi, [region_text_1]
call vga_text_print_string
mov rdi, r8
lea qword rsi, [integer]
mov rdx, 18
mov rcx, 16
call itoa
lea qword rdi, [integer]
call vga_text_print_string
lea qword rdi, [region_text_2]
call vga_text_print_string
mov rdi, r9
lea qword rsi, [integer]
mov rdx, 18
mov rcx, 16
call itoa
lea qword rdi, [integer]
call vga_text_print_string
lea qword rdi, [region_text_3]
call vga_text_print_string
dec r10
cmp r10, 0
je .available
cmp r10, 1
je .reserved
cmp r10, 2
je .acpi_reclaim
lea qword rdi, [acpi_nvs_text]
call vga_text_print_string
jmp .skip_entry
.available:
lea qword rdi, [available_text]
call vga_text_print_string
jmp .skip_entry
.reserved:
lea qword rdi, [reserved_text]
call vga_text_print_string
jmp .skip_entry
.acpi_reclaim:
lea qword rdi, [acpi_reclaim_text]
call vga_text_print_string
.skip_entry:
mov rdi, 0x0A
call vga_text_put_char
pop rcx
pop rdi
add rdi, 24
inc rcx
jmp .next_entry
.finish:
; Make sure to reserve the kernel
mov rdi, 0x100000 ; Kernel is located at 0x100000
mov rsi, 0x100000 ; Assume kernel is 1MiB
;call pmm_reserve_region
cli
hlt
section .data
integer times 18 db 0
welcome_text db "Ether Operating System ", ETHER_VERSION_STRING, " ", ETHER_VERSION_CODENAME, 13, 10, 0
mem_text_1 db "Memory manager initialized with ", 0
mem_text_2 db "MiB of memory.", 13, 10, 0
boot_dev_text db "BIOS boot device: 0x", 0
region_text_1 db "Region start: 0x", 0
region_text_2 db " Region length: 0x", 0
region_text_3 db " Region type: ", 0
acpi_nvs_text db "ACPI NVS Memory", 0
acpi_reclaim_text db "ACPI Reclaim", 0
reserved_text db "Reserved", 0
available_text db "Available", 0
|
/* Copyright 2021 Neil Zaim
*
* This file is part of WarpX.
*
* License: BSD-3-Clause-LBNL
*/
#include "ParticleCreationFunc.H"
#include "BinaryCollisionUtils.H"
#include "Particles/MultiParticleContainer.H"
#include <AMReX_GpuContainers.H>
#include <AMReX_ParmParse.H>
#include <AMReX_Vector.H>
#include <string>
ParticleCreationFunc::ParticleCreationFunc (const std::string collision_name,
MultiParticleContainer const * const mypc)
{
amrex::ParmParse pp_collision_name(collision_name);
m_collision_type = BinaryCollisionUtils::get_collision_type(collision_name, mypc);
#ifdef AMREX_USE_GPU
amrex::Vector<int> host_num_products;
#else
amrex::Gpu::DeviceVector<int>& host_num_products = m_num_products;
#endif
if (m_collision_type == CollisionType::ProtonBoronFusion)
{
// Proton-Boron fusion only produces alpha particles
m_num_product_species = 1;
// Proton-Boron fusion produces 3 alpha particles per fusion reaction
host_num_products.push_back(3);
}
#ifdef AMREX_USE_GPU
m_num_products.resize(m_num_product_species);
amrex::Gpu::copyAsync(amrex::Gpu::hostToDevice, host_num_products.begin(),
host_num_products.end(),
m_num_products.begin());
amrex::Gpu::streamSynchronize();
#endif
}
|
; A198848: 11*6^n-1.
; 10,65,395,2375,14255,85535,513215,3079295,18475775,110854655,665127935,3990767615,23944605695,143667634175,862005805055,5172034830335,31032208982015,186193253892095,1117159523352575,6702957140115455,40217742840692735,241306457044156415,1447838742264938495,8687032453589630975,52122194721537785855,312733168329226715135,1876399009975360290815,11258394059852161744895,67550364359112970469375,405302186154677822816255,2431813116928066936897535,14590878701568401621385215,87545272209410409728311295
mov $1,6
pow $1,$0
mul $1,11
sub $1,1
mov $0,$1
|
; A066438: a(n) = 7^n mod n.
; 0,1,1,1,2,1,0,1,1,9,7,1,7,7,13,1,7,1,7,1,7,5,7,1,7,23,1,21,7,19,7,1,13,15,28,1,7,11,31,1,7,7,7,25,37,3,7,1,0,49,37,9,7,1,43,49,1,49,7,1,7,49,28,1,37,37,7,21,67,49,7,1,7,49,43,45,28,25,7,1,1,49,7,49,62,49,82,9,7,19,84,9,64,49,68,1,7,49,19,1
add $0,1
mov $1,1
mov $2,$0
lpb $0
sub $0,1
mul $1,7
mod $1,$2
lpe
mov $0,$1
|
; Used in wram.asm
flag_array: MACRO
ds ((\1) + 7) / 8
ENDM
box_struct: MACRO
\1Species:: db
\1Item:: db
\1Moves:: ds NUM_MOVES
\1ID:: dw
\1Exp:: ds 3
\1StatExp::
\1HPExp:: dw
\1AtkExp:: dw
\1DefExp:: dw
\1SpdExp:: dw
\1SpcExp:: dw
\1DVs:: dw
\1PP:: ds NUM_MOVES
\1Happiness:: db
\1PokerusStatus:: db
\1CaughtData::
\1CaughtTime::
\1CaughtLevel:: db
\1CaughtGender::
\1CaughtLocation:: db
\1Level:: db
\1BoxEnd::
ENDM
party_struct: MACRO
box_struct \1
\1Status:: db
\1Unused:: db
\1HP:: dw
\1MaxHP:: dw
\1Stats:: ; big endian
\1Attack:: dw
\1Defense:: dw
\1Speed:: dw
\1SpclAtk:: dw
\1SpclDef:: dw
\1StructEnd::
ENDM
red_box_struct: MACRO
\1Species:: db
\1HP:: dw
\1BoxLevel:: db
\1Status:: db
\1Type::
\1Type1:: db
\1Type2:: db
\1CatchRate:: db
\1Moves:: ds NUM_MOVES
\1ID:: dw
\1Exp:: ds 3
\1HPExp:: dw
\1AttackExp:: dw
\1DefenseExp:: dw
\1SpeedExp:: dw
\1SpecialExp:: dw
\1DVs:: dw
\1PP:: ds NUM_MOVES
ENDM
red_party_struct: MACRO
red_box_struct \1
\1Level:: db
\1Stats::
\1MaxHP:: dw
\1Attack:: dw
\1Defense:: dw
\1Speed:: dw
\1Special:: dw
ENDM
battle_struct: MACRO
\1Species:: db
\1Item:: db
\1Moves:: ds NUM_MOVES
\1DVs:: dw
\1PP:: ds NUM_MOVES
\1Happiness:: db
\1Level:: db
\1Status:: ds 2
\1HP:: dw
\1MaxHP:: dw
\1Stats:: ; big endian
\1Attack:: dw
\1Defense:: dw
\1Speed:: dw
\1SpclAtk:: dw
\1SpclDef:: dw
\1Type::
\1Type1:: db
\1Type2:: db
\1StructEnd::
ENDM
box: MACRO
\1Count:: db
\1Species:: ds MONS_PER_BOX + 1
\1Mons::
\1Mon1:: box_struct \1Mon1
\1Mon2:: ds BOXMON_STRUCT_LENGTH * (MONS_PER_BOX - 1)
\1MonOTs:: ds NAME_LENGTH * MONS_PER_BOX
\1MonNicknames:: ds MON_NAME_LENGTH * MONS_PER_BOX
\1MonNicknamesEnd::
\1End::
ds 2 ; padding
ENDM
map_connection_struct: MACRO
\1ConnectedMapGroup:: db
\1ConnectedMapNumber:: db
\1ConnectionStripPointer:: dw
\1ConnectionStripLocation:: dw
\1ConnectionStripLength:: db
\1ConnectedMapWidth:: db
\1ConnectionStripYOffset:: db
\1ConnectionStripXOffset:: db
\1ConnectionWindow:: dw
ENDM
channel_struct: MACRO
\1MusicID:: dw
\1MusicBank:: db
\1Flags1:: db ; 0:on/off 1:subroutine 2:looping 3:sfx 4:noise 5:rest
\1Flags2:: db ; 0:vibrato on/off 1:pitch slide 2:duty cycle pattern 4:pitch offset
\1Flags3:: db ; 0:vibrato up/down 1:pitch slide direction
\1MusicAddress:: dw
\1LastMusicAddress:: dw
dw
\1NoteFlags:: db ; 5:rest
\1Condition:: db ; conditional jumps
\1DutyCycle:: db ; bits 6-7 (0:12.5% 1:25% 2:50% 3:75%)
\1VolumeEnvelope:: db ; hi:volume lo:fade
\1Frequency:: dw ; 11 bits
\1Pitch:: db ; 0:rest 1-c:note
\1Octave:: db ; 7-0 (0 is highest)
\1Transposition:: db ; raises existing octaves (to repeat phrases)
\1NoteDuration:: db ; frames remaining for the current note
\1Field16:: ds 1
ds 1
\1LoopCount:: db
\1Tempo:: dw
\1Tracks:: db ; hi:left lo:right
\1DutyCyclePattern:: db
\1VibratoDelayCount:: db ; initialized by \1VibratoDelay
\1VibratoDelay:: db ; number of frames a note plays until vibrato starts
\1VibratoExtent:: db
\1VibratoRate:: db ; hi:frames for each alt lo:frames to the next alt
\1PitchSlideTarget:: dw ; frequency endpoint for pitch slide
\1PitchSlideAmount:: db
\1PitchSlideAmountFraction:: db
\1Field25:: db
ds 1
\1PitchOffset:: dw
\1Field29:: ds 1
\1Field2a:: ds 2
\1Field2c:: ds 1
\1NoteLength:: db ; frames per 16th note
\1Field2e:: ds 1
\1Field2f:: ds 1
\1Field30:: ds 1
ds 1
ENDM
battle_tower_struct: MACRO
\1Name:: ds NAME_LENGTH - 1
\1TrainerClass:: db
\1Mon1:: party_struct \1Mon1
\1Mon1Name:: ds MON_NAME_LENGTH
\1Mon1NameEnd::
\1Mon2:: party_struct \1Mon2
\1Mon2Name:: ds MON_NAME_LENGTH
\1Mon2NameEnd::
\1Mon3:: party_struct \1Mon3
\1Mon3Name:: ds MON_NAME_LENGTH
\1Mon3NameEnd::
\1TrainerData:: ds BATTLETOWER_TRAINERDATALENGTH
\1TrainerEnd::
ENDM
mailmsg: MACRO
\1Message:: ds MAIL_MSG_LENGTH
\1MessageEnd:: db
\1Author:: ds PLAYER_NAME_LENGTH
\1Nationality:: dw
\1AuthorID:: dw
\1Species:: db
\1Type:: db
\1End::
ENDM
roam_struct: MACRO
\1Species:: db
\1Level:: db
\1MapGroup:: db
\1MapNumber:: db
\1HP:: db
\1DVs:: dw
ENDM
bugcontestwinner: MACRO
\1WinnerID:: db
\1Mon:: db
\1Score:: dw
ENDM
hof_mon: MACRO
\1Species:: db
\1ID:: dw
\1DVs:: dw
\1Level:: db
\1Nickname:: ds MON_NAME_LENGTH - 1
\1End::
ENDM
hall_of_fame: MACRO
\1WinCount:: db
\1Mon1:: hof_mon \1Mon1
\1Mon2:: hof_mon \1Mon2
\1Mon3:: hof_mon \1Mon3
\1Mon4:: hof_mon \1Mon4
\1Mon5:: hof_mon \1Mon5
\1Mon6:: hof_mon \1Mon6
\1End:: db
ENDM
link_battle_record: MACRO
\1ID:: dw
\1Name:: ds NAME_LENGTH - 1
\1Wins:: dw
\1Losses:: dw
\1Draws:: dw
\1End::
ENDM
trademon: MACRO
\1Species:: db
\1SpeciesName:: ds MON_NAME_LENGTH
\1Nickname:: ds MON_NAME_LENGTH
\1SenderName:: ds NAME_LENGTH
\1OTName:: ds NAME_LENGTH
\1DVs:: dw
\1ID:: dw
\1CaughtData:: db
\1End::
ENDM
move_struct: MACRO
\1Animation:: db
\1Effect:: db
\1Power:: db
\1Type:: db
\1Accuracy:: db
\1PP:: db
\1EffectChance:: db
ENDM
slot_reel: MACRO
\1ReelAction:: db
\1TilemapAddr:: dw
\1Position:: db
\1SpinDistance:: db
\1SpinRate:: db
\1OAMAddr:: dw
\1XCoord:: db
\1ManipCounter:: db
\1ManipDelay:: db
\1Field0b:: ds 1
\1Field0c:: ds 1
\1Field0d:: ds 1
\1Field0e:: ds 1
\1StopDelay:: db
ENDM
object_struct: MACRO
\1Sprite:: db
\1MapObjectIndex:: db
\1SpriteTile:: db
\1MovementType:: db
\1Flags:: dw
\1Palette:: db
\1Walking:: db
\1Direction:: db
\1StepType:: db
\1StepDuration:: db
\1Action:: db
\1ObjectStepFrame:: db
\1Facing:: db
\1StandingTile:: db ; collision
\1LastTile:: db ; collision
\1StandingMapX:: db
\1StandingMapY:: db
\1LastMapX:: db
\1LastMapY:: db
\1ObjectInitX:: db
\1ObjectInitY:: db
\1Radius:: db
\1SpriteX:: db
\1SpriteY:: db
\1SpriteXOffset:: db
\1SpriteYOffset:: db
\1MovementByteIndex:: db
\1Field1c:: ds 1
\1Field1d:: ds 1
\1Field1e:: ds 1
\1Field1f:: ds 1
\1Range:: db
ds 7
\1StructEnd::
ENDM
map_object: MACRO
\1ObjectStructID:: db
\1ObjectSprite:: db
\1ObjectYCoord:: db
\1ObjectXCoord:: db
\1ObjectMovement:: db
\1ObjectRadius:: db
\1ObjectHour:: db
\1ObjectTimeOfDay:: db
\1ObjectColor:: db
\1ObjectRange:: db
\1ObjectScript:: dw
\1ObjectEventFlag:: dw
ds 2
ENDM
sprite_oam_struct: MACRO
\1YCoord:: db
\1XCoord:: db
\1TileID:: db
\1Attributes:: db
; bit 7: priority
; bit 6: y flip
; bit 5: x flip
; bit 4: pal # (non-cgb)
; bit 3: vram bank (cgb only)
; bit 2-0: pal # (cgb only)
ENDM
sprite_anim_struct: MACRO
\1Index:: db
\1FramesetID:: db
\1AnimSeqID:: db
\1TileID:: db
\1XCoord:: db
\1YCoord:: db
\1XOffset:: db
\1YOffset:: db
\1Duration:: db
\1DurationOffset:: db
\1FrameIndex:: db
\1JumptableIndex:: db
\1Var1:: ds 1
\1Var2:: ds 1
\1Var3:: ds 1
\1Var4:: ds 1
ENDM
battle_anim_struct: MACRO
\1Index:: db
\1OAMFlags:: db
\1FixY:: db
\1FramesetID:: db
\1Function:: db
\1Palette:: db
\1TileID:: db
\1XCoord:: db
\1YCoord:: db
\1XOffset:: db
\1YOffset:: db
\1Param:: db
\1Duration:: db
\1Frame:: db
\1JumptableIndex:: db
\1Var1:: db
\1Var2:: db
ds 7
ENDM
battle_bg_effect: MACRO
\1Function:: db
\1JumptableIndex:: db
\1BattleTurn:: db
\1Param:: db
ENDM
|
; A034188: Number of binary codes of length 3 with n words.
; 1,1,3,3,6,3,3,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
add $0,1
lpb $0
add $2,$0
sub $0,1
trn $0,1
trn $2,5
add $3,1
trn $3,$2
add $1,$3
lpe
mov $0,$1
|
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.14.26428.1
TITLE C:\Users\dkovari\Documents\GitHub\ExtrasToolbox\+extras\external_libs\zlib\src\zlib-1.2.11\compress.c
.686P
.XMM
include listing.inc
.model flat
INCLUDELIB MSVCRTD
INCLUDELIB OLDNAMES
PUBLIC _compress@16
PUBLIC _compress2@20
PUBLIC _compressBound@4
EXTRN _deflate@8:PROC
EXTRN _deflateEnd@4:PROC
EXTRN _deflateInit_@16:PROC
_DATA SEGMENT
$SG92676 DB '1.2.11', 00H
_DATA ENDS
; Function compile flags: /Odtp
; File c:\users\dkovari\documents\github\extrastoolbox\+extras\external_libs\zlib\src\zlib-1.2.11\compress.c
_TEXT SEGMENT
_sourceLen$ = 8 ; size = 4
_compressBound@4 PROC
; 83 : {
push ebp
mov ebp, esp
; 84 : return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
mov eax, DWORD PTR _sourceLen$[ebp]
shr eax, 12 ; 0000000cH
add eax, DWORD PTR _sourceLen$[ebp]
mov ecx, DWORD PTR _sourceLen$[ebp]
shr ecx, 14 ; 0000000eH
add eax, ecx
mov edx, DWORD PTR _sourceLen$[ebp]
shr edx, 25 ; 00000019H
lea eax, DWORD PTR [eax+edx+13]
; 85 : (sourceLen >> 25) + 13;
; 86 : }
pop ebp
ret 4
_compressBound@4 ENDP
_TEXT ENDS
; Function compile flags: /Odtp
; File c:\users\dkovari\documents\github\extrastoolbox\+extras\external_libs\zlib\src\zlib-1.2.11\compress.c
_TEXT SEGMENT
_stream$ = -84 ; size = 56
tv86 = -28 ; size = 4
tv80 = -24 ; size = 4
tv76 = -20 ; size = 4
tv72 = -16 ; size = 4
_max$ = -12 ; size = 4
_left$ = -8 ; size = 4
_err$ = -4 ; size = 4
_dest$ = 8 ; size = 4
_destLen$ = 12 ; size = 4
_source$ = 16 ; size = 4
_sourceLen$ = 20 ; size = 4
_level$ = 24 ; size = 4
_compress2@20 PROC
; 28 : {
push ebp
mov ebp, esp
sub esp, 84 ; 00000054H
; 29 : z_stream stream;
; 30 : int err;
; 31 : const uInt max = (uInt)-1;
mov DWORD PTR _max$[ebp], -1
; 32 : uLong left;
; 33 :
; 34 : left = *destLen;
mov eax, DWORD PTR _destLen$[ebp]
mov ecx, DWORD PTR [eax]
mov DWORD PTR _left$[ebp], ecx
; 35 : *destLen = 0;
mov edx, DWORD PTR _destLen$[ebp]
mov DWORD PTR [edx], 0
; 36 :
; 37 : stream.zalloc = (alloc_func)0;
mov DWORD PTR _stream$[ebp+32], 0
; 38 : stream.zfree = (free_func)0;
mov DWORD PTR _stream$[ebp+36], 0
; 39 : stream.opaque = (voidpf)0;
mov DWORD PTR _stream$[ebp+40], 0
; 40 :
; 41 : err = deflateInit(&stream, level);
push 56 ; 00000038H
push OFFSET $SG92676
mov eax, DWORD PTR _level$[ebp]
push eax
lea ecx, DWORD PTR _stream$[ebp]
push ecx
call _deflateInit_@16
mov DWORD PTR _err$[ebp], eax
; 42 : if (err != Z_OK) return err;
cmp DWORD PTR _err$[ebp], 0
je SHORT $LN5@compress2
mov eax, DWORD PTR _err$[ebp]
jmp $LN1@compress2
$LN5@compress2:
; 43 :
; 44 : stream.next_out = dest;
mov edx, DWORD PTR _dest$[ebp]
mov DWORD PTR _stream$[ebp+12], edx
; 45 : stream.avail_out = 0;
mov DWORD PTR _stream$[ebp+16], 0
; 46 : stream.next_in = (z_const Bytef *)source;
mov eax, DWORD PTR _source$[ebp]
mov DWORD PTR _stream$[ebp], eax
; 47 : stream.avail_in = 0;
mov DWORD PTR _stream$[ebp+4], 0
$LN4@compress2:
; 48 :
; 49 : do {
; 50 : if (stream.avail_out == 0) {
cmp DWORD PTR _stream$[ebp+16], 0
jne SHORT $LN6@compress2
; 51 : stream.avail_out = left > (uLong)max ? max : (uInt)left;
mov ecx, DWORD PTR _left$[ebp]
cmp ecx, DWORD PTR _max$[ebp]
jbe SHORT $LN9@compress2
mov edx, DWORD PTR _max$[ebp]
mov DWORD PTR tv72[ebp], edx
jmp SHORT $LN10@compress2
$LN9@compress2:
mov eax, DWORD PTR _left$[ebp]
mov DWORD PTR tv72[ebp], eax
$LN10@compress2:
mov ecx, DWORD PTR tv72[ebp]
mov DWORD PTR _stream$[ebp+16], ecx
; 52 : left -= stream.avail_out;
mov edx, DWORD PTR _left$[ebp]
sub edx, DWORD PTR _stream$[ebp+16]
mov DWORD PTR _left$[ebp], edx
$LN6@compress2:
; 53 : }
; 54 : if (stream.avail_in == 0) {
cmp DWORD PTR _stream$[ebp+4], 0
jne SHORT $LN7@compress2
; 55 : stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
mov eax, DWORD PTR _sourceLen$[ebp]
cmp eax, DWORD PTR _max$[ebp]
jbe SHORT $LN11@compress2
mov ecx, DWORD PTR _max$[ebp]
mov DWORD PTR tv76[ebp], ecx
jmp SHORT $LN12@compress2
$LN11@compress2:
mov edx, DWORD PTR _sourceLen$[ebp]
mov DWORD PTR tv76[ebp], edx
$LN12@compress2:
mov eax, DWORD PTR tv76[ebp]
mov DWORD PTR _stream$[ebp+4], eax
; 56 : sourceLen -= stream.avail_in;
mov ecx, DWORD PTR _sourceLen$[ebp]
sub ecx, DWORD PTR _stream$[ebp+4]
mov DWORD PTR _sourceLen$[ebp], ecx
$LN7@compress2:
; 57 : }
; 58 : err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
cmp DWORD PTR _sourceLen$[ebp], 0
je SHORT $LN13@compress2
mov DWORD PTR tv80[ebp], 0
jmp SHORT $LN14@compress2
$LN13@compress2:
mov DWORD PTR tv80[ebp], 4
$LN14@compress2:
mov edx, DWORD PTR tv80[ebp]
push edx
lea eax, DWORD PTR _stream$[ebp]
push eax
call _deflate@8
mov DWORD PTR _err$[ebp], eax
; 59 : } while (err == Z_OK);
cmp DWORD PTR _err$[ebp], 0
je $LN4@compress2
; 60 :
; 61 : *destLen = stream.total_out;
mov ecx, DWORD PTR _destLen$[ebp]
mov edx, DWORD PTR _stream$[ebp+20]
mov DWORD PTR [ecx], edx
; 62 : deflateEnd(&stream);
lea eax, DWORD PTR _stream$[ebp]
push eax
call _deflateEnd@4
; 63 : return err == Z_STREAM_END ? Z_OK : err;
cmp DWORD PTR _err$[ebp], 1
jne SHORT $LN15@compress2
mov DWORD PTR tv86[ebp], 0
jmp SHORT $LN16@compress2
$LN15@compress2:
mov ecx, DWORD PTR _err$[ebp]
mov DWORD PTR tv86[ebp], ecx
$LN16@compress2:
mov eax, DWORD PTR tv86[ebp]
$LN1@compress2:
; 64 : }
mov esp, ebp
pop ebp
ret 20 ; 00000014H
_compress2@20 ENDP
_TEXT ENDS
; Function compile flags: /Odtp
; File c:\users\dkovari\documents\github\extrastoolbox\+extras\external_libs\zlib\src\zlib-1.2.11\compress.c
_TEXT SEGMENT
_dest$ = 8 ; size = 4
_destLen$ = 12 ; size = 4
_source$ = 16 ; size = 4
_sourceLen$ = 20 ; size = 4
_compress@16 PROC
; 73 : {
push ebp
mov ebp, esp
; 74 : return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
push -1
mov eax, DWORD PTR _sourceLen$[ebp]
push eax
mov ecx, DWORD PTR _source$[ebp]
push ecx
mov edx, DWORD PTR _destLen$[ebp]
push edx
mov eax, DWORD PTR _dest$[ebp]
push eax
call _compress2@20
; 75 : }
pop ebp
ret 16 ; 00000010H
_compress@16 ENDP
_TEXT ENDS
END
|
; A311385: Coordination sequence Gal.6.221.1 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
; Submitted by Jon Maiga
; 1,4,8,12,16,22,28,34,38,42,46,50,54,58,62,66,72,78,84,88,92,96,100,104,108,112,116,122,128,134,138,142,146,150,154,158,162,166,172,178,184,188,192,196,200,204,208,212,216,222
mov $1,$0
mov $2,$0
mul $0,12
sub $0,1
seq $1,313718 ; Coordination sequence Gal.6.133.4 where G.u.t.v denotes the coordination sequence for a vertex of type v in tiling number t in the Galebach list of u-uniform tilings.
mod $0,$1
add $0,1
mul $2,2
add $0,$2
|
title "Trap Processing"
;++
;
; Copyright (c) Microsoft Corporation. All rights reserved.
;
; You may only use this code if you agree to the terms of the Windows Research Kernel Source Code License agreement (see License.txt).
; If you do not agree to the terms, do not use the code.
;
;
; Module Name:
;
; trap.asm
;
; Abstract:
;
; This module implements the code necessary to field and process i386
; trap conditions.
;
;--
.586p
.xlist
KERNELONLY equ 1
include ks386.inc
include callconv.inc ; calling convention macros
include i386\kimacro.inc
include mac386.inc
include i386\mi.inc
include ..\..\vdm\i386\vdm.inc
include vdmtib.inc
include fastsys.inc
include irqli386.inc
.list
FAST_BOP equ 1
page ,132
extrn _KeI386FxsrPresent:BYTE
extrn ExpInterlockedPopEntrySListFault:DWORD
extrn ExpInterlockedPopEntrySListResume:DWORD
extrn _KeGdiFlushUserBatch:DWORD
extrn _KeTickCount:DWORD
extrn _ExpTickCountMultiplier:DWORD
extrn _KiDoubleFaultTSS:dword
extrn _KeErrorMask:dword
extrn _KiNMITSS:dword
extrn _KeServiceDescriptorTable:dword
if DBG
extrn _MmInjectUserInpageErrors:dword
EXTRNP _MmTrimProcessMemory,1
endif
extrn _KiHardwareTrigger:dword
extrn _KiBugCheckData:dword
extrn _KdpOweBreakpoint:byte
extrn Ki386BiosCallReturnAddress:near
extrn _PoHiberInProgress:byte
extrn _KiI386PentiumLockErrataPresent:BYTE
extrn _KdDebuggerNotPresent:byte
extrn _KdDebuggerEnabled:byte
EXTRNP _KeEnterKernelDebugger,0
EXTRNP _KiDeliverApc,3
EXTRNP _PsConvertToGuiThread,0
EXTRNP _ZwUnmapViewOfSection,2
EXTRNP _KiHandleNmi,0
EXTRNP _KiSaveProcessorState,2
EXTRNP _HalHandleNMI,1,IMPORT
EXTRNP _HalBeginSystemInterrupt,3,IMPORT
EXTRNP _HalEndSystemInterrupt,2,IMPORT
EXTRNP _KiDispatchException,5
EXTRNP _PsWatchWorkingSet,3
extrn _PsWatchEnabled:byte
EXTRNP _MmAccessFault,4
extrn _MmUserProbeAddress:DWORD
EXTRNP _KeBugCheck2,6
EXTRNP _KeTestAlertThread,1
EXTRNP _KiContinue,3
EXTRNP _KiRaiseException,5
EXTRNP _VdmDispatchOpcodeV86_try,1
EXTRNP _VdmDispatchOpcode_try,1
EXTRNP _VdmDispatchPageFault,3
EXTRNP _Ki386VdmReflectException,1
EXTRNP _Ki386VdmSegmentNotPresent,0
extrn _DbgPrint:proc
EXTRNP _KdSetOwedBreakpoints
extrn _KiFreezeFlag:dword
EXTRNP _Ki386CheckDivideByZeroTrap,1
EXTRNP _Ki386CheckDelayedNpxTrap,2
EXTRNP _VdmDispatchIRQ13, 1
EXTRNP _VdmDispatchBop,1
EXTRNP _VdmFetchBop1,1
EXTRNP _VdmFetchBop4,1
EXTRNP _VdmTibPass1,3
extrn _KeI386VirtualIntExtensions:dword
EXTRNP _NTFastDOSIO,2
EXTRNP _NtSetLdtEntries,6
EXTRNP _NtCallbackReturn,3
extrn OpcodeIndex:byte
extrn _KeFeatureBits:DWORD
extrn _KeServiceDescriptorTableShadow:dword
extrn _KiIgnoreUnexpectedTrap07:byte
extrn _KeUserPopEntrySListFault:dword
extrn _KeUserPopEntrySListResume:dword
ifndef NT_UP
EXTRNP KiAcquireQueuedSpinLockCheckForFreeze,2,,FASTCALL
EXTRNP KeReleaseQueuedSpinLockFromDpcLevel,1,,FASTCALL
endif
;
; Equates for exceptions which cause system fatal error
;
EXCEPTION_DIVIDED_BY_ZERO EQU 0
EXCEPTION_DEBUG EQU 1
EXCEPTION_NMI EQU 2
EXCEPTION_INT3 EQU 3
EXCEPTION_BOUND_CHECK EQU 5
EXCEPTION_INVALID_OPCODE EQU 6
EXCEPTION_NPX_NOT_AVAILABLE EQU 7
EXCEPTION_DOUBLE_FAULT EQU 8
EXCEPTION_NPX_OVERRUN EQU 9
EXCEPTION_INVALID_TSS EQU 0AH
EXCEPTION_SEGMENT_NOT_PRESENT EQU 0BH
EXCEPTION_STACK_FAULT EQU 0CH
EXCEPTION_GP_FAULT EQU 0DH
EXCEPTION_RESERVED_TRAP EQU 0FH
EXCEPTION_NPX_ERROR EQU 010H
EXCEPTION_ALIGNMENT_CHECK EQU 011H
;
; Exception flags
;
EXCEPT_UNKNOWN_ACCESS EQU 0H
EXCEPT_LIMIT_ACCESS EQU 10H
;
; Equates for some opcodes and instruction prefixes
;
IOPL_MASK EQU 3000H
IOPL_SHIFT_COUNT EQU 12
;
; Debug register 6 (dr6) BS (single step) bit mask
;
DR6_BS_MASK EQU 4000H
;
; EFLAGS overflow bit
;
EFLAGS_OF_BIT EQU 4000H
;
; The mask of selector's table indicator (ldt or gdt)
;
TABLE_INDICATOR_MASK EQU 4
;
; Opcode for Pop SegReg and iret instructions
;
POP_DS EQU 1FH
POP_ES EQU 07h
POP_FS EQU 0A10FH
POP_GS EQU 0A90FH
IRET_OP EQU 0CFH
CLI_OP EQU 0FAH
STI_OP EQU 0FBH
PUSHF_OP EQU 9CH
POPF_OP EQU 9DH
INTNN_OP EQU 0CDH
FRSTOR_ECX EQU 021DD9Bh
FWAIT_OP EQU 09bh
;
; Force assume into place
;
_TEXT$00 SEGMENT PARA PUBLIC 'CODE'
ASSUME DS:NOTHING, ES:NOTHING, SS:NOTHING, FS:NOTHING, GS:NOTHING
_TEXT$00 ENDS
_DATA SEGMENT DWORD PUBLIC 'DATA'
;
; Definitions for gate descriptors
;
GATE_TYPE_386INT EQU 0E00H
GATE_TYPE_386TRAP EQU 0F00H
GATE_TYPE_TASK EQU 0500H
D_GATE EQU 0
D_PRESENT EQU 8000H
D_DPL_3 EQU 6000H
D_DPL_0 EQU 0
;
; Definitions for present x86 trap and interrupt gate attributes
;
D_TRAP032 EQU D_PRESENT+D_DPL_0+D_GATE+GATE_TYPE_386TRAP
D_TRAP332 EQU D_PRESENT+D_DPL_3+D_GATE+GATE_TYPE_386TRAP
D_INT032 EQU D_PRESENT+D_DPL_0+D_GATE+GATE_TYPE_386INT
D_INT332 EQU D_PRESENT+D_DPL_3+D_GATE+GATE_TYPE_386INT
D_TASK EQU D_PRESENT+D_DPL_0+D_GATE+GATE_TYPE_TASK
;
; This is the protected mode interrupt descriptor table.
;
if DBG
;
; NOTE - embedded enlish messages won't fly for NLS! (OK for debug code only)
;
BadInterruptMessage db 0ah,7,7,'!!! Unexpected Interrupt %02lx !!!',0ah,00
Ki16BitStackTrapMessage db 0ah,'Exception inside of 16bit stack',0ah,00
public KiBiosReenteredAssert
KiBiosReenteredAssert db 0ah,'Bios has been re-entered. Not safe. ',0ah,00
endif
;
; NMI only one processor at a time. This is handled in the kernel
; using a queued spinlock to avoid thrashing the lock in case a
; crash dump is underway.
;
KiLockNMI dd 0
;
; Define a value that we'll use to track the processor that owns the NMI lock.
; This information is needed in order to handle nested NMIs properly. A
; distinguished value is used in cases where the NMI lock is unowned.
;
ifndef NT_UP
KI_NMI_UNOWNED equ 0FFFFFFFFh
KiNMIOwner dd KI_NMI_UNOWNED
endif
;
; Define a counter that will be used to limit NMI recursion.
;
KiNMIRecursionCount dd 0
;++
;
; DEFINE_SINGLE_EMPTY_VECTOR - helper for DEFINE_EMPTY_VECTORS
;
;--
DEFINE_SINGLE_EMPTY_VECTOR macro number
IDTEntry _KiUnexpectedInterrupt&number, D_INT032
_TEXT$00 SEGMENT
public _KiUnexpectedInterrupt&number
_KiUnexpectedInterrupt&number proc
push dword ptr (&number + PRIMARY_VECTOR_BASE)
;; jmp _KiUnexpectedInterruptTail ; replaced with following jmp which will then jump
jmp _KiAfterUnexpectedRange ; to the _KiUnexpectedInterruptTail location
; in a manner suitable for BBT, which needs to treat
; this whole set of KiUnexpectedInterrupt&number
; vectors as DATA, meaning a relative jmp will not
; be adjusted properly in the BBT Instrumented or
; Optimized code.
;
_KiUnexpectedInterrupt&number endp
_TEXT$00 ENDS
endm
FPOFRAME macro a, b
.FPO ( a, b, 0, 0, 0, FPO_TRAPFRAME )
endm
FXSAVE_ESI macro
db 0FH, 0AEH, 06
endm
FXSAVE_ECX macro
db 0FH, 0AEH, 01
endm
FXRSTOR_ECX macro
db 0FH, 0AEH, 09
endm
;++
;
; DEFINE_EMPTY_VECTORS emits an IDTEntry macro (and thus and IDT entry)
; into the data segment. It then emits an unexpected interrupt target
; with push of a constant into the code segment. Labels in the code
; segment are defined to bracket the unexpected interrupt targets so
; that KeConnectInterrupt can correctly test for them.
;
; Empty vectors will be defined from 30 to ff, which is the hardware
; vector set.
;
;--
NUMBER_OF_IDT_VECTOR EQU 0ffH
DEFINE_EMPTY_VECTORS macro
;
; Set up
;
empty_vector = 00H
_TEXT$00 SEGMENT
public _KiStartUnexpectedRange@0
_KiStartUnexpectedRange@0 equ $
_TEXT$00 ENDS
rept (NUMBER_OF_IDT_VECTOR - (($ - _IDT)/8)) + 1
DEFINE_SINGLE_EMPTY_VECTOR %empty_vector
empty_vector = empty_vector + 1
endm ;; rept
_TEXT$00 SEGMENT
public _KiEndUnexpectedRange@0
_KiEndUnexpectedRange@0 equ $
;; added by to handle BBT unexpected interrupt problem
;;
_KiAfterUnexpectedRange equ $ ;; BBT
jmp [KiUnexpectedInterruptTail] ;; BBT
KiUnexpectedInterruptTail dd offset _KiUnexpectedInterruptTail ;; BBT
public _KiBBTUnexpectedRange
_KiBBTUnexpectedRange equ $ ;; BBT
_TEXT$00 ENDS
endm ;; DEFINE_EMPTY_VECTORS macro
IDTEntry macro name,access
dd offset FLAT:name
dw access
dw KGDT_R0_CODE
endm
INIT SEGMENT DWORD PUBLIC 'CODE'
;
; The IDT table is put into the INIT code segment so the memory
; can be reclaimed afer bootup
;
ALIGN 4
public _IDT, _IDTLEN, _IDTEnd
_IDT label byte
IDTEntry _KiTrap00, D_INT032 ; 0: Divide Error
IDTEntry _KiTrap01, D_INT032 ; 1: DEBUG TRAP
IDTEntry _KiTrap02, D_INT032 ; 2: NMI/NPX Error
IDTEntry _KiTrap03, D_INT332 ; 3: Breakpoint
IDTEntry _KiTrap04, D_INT332 ; 4: INTO
IDTEntry _KiTrap05, D_INT032 ; 5: BOUND/Print Screen
IDTEntry _KiTrap06, D_INT032 ; 6: Invalid Opcode
IDTEntry _KiTrap07, D_INT032 ; 7: NPX Not Available
IDTEntry _KiTrap08, D_INT032 ; 8: Double Exception
IDTEntry _KiTrap09, D_INT032 ; 9: NPX Segment Overrun
IDTEntry _KiTrap0A, D_INT032 ; A: Invalid TSS
IDTEntry _KiTrap0B, D_INT032 ; B: Segment Not Present
IDTEntry _KiTrap0C, D_INT032 ; C: Stack Fault
IDTEntry _KiTrap0D, D_INT032 ; D: General Protection
IDTEntry _KiTrap0E, D_INT032 ; E: Page Fault
IDTEntry _KiTrap0F, D_INT032 ; F: Intel Reserved
IDTEntry _KiTrap10, D_INT032 ;10: 486 coprocessor error
IDTEntry _KiTrap11, D_INT032 ;11: 486 alignment
IDTEntry _KiTrap0F, D_INT032 ;12: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;13: XMMI unmasked numeric exception
IDTEntry _KiTrap0F, D_INT032 ;14: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;15: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;16: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;17: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;18: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;19: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1A: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1B: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1C: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1D: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1E: Intel Reserved
IDTEntry _KiTrap0F, D_INT032 ;1F: Reserved for APIC
;
; Note IDTEntry 0x21 is reserved for WOW apps.
;
rept 2AH - (($ - _IDT)/8)
IDTEntry 0, 0 ;invalid IDT entry
endm
IDTEntry _KiGetTickCount, D_INT332 ;2A: KiGetTickCount service
IDTEntry _KiCallbackReturn, D_INT332 ;2B: KiCallbackReturn
IDTEntry _KiRaiseAssertion, D_INT332 ;2C: KiRaiseAssertion service
IDTEntry _KiDebugService, D_INT332 ;2D: debugger calls
IDTEntry _KiSystemService, D_INT332 ;2E: system service calls
IDTEntry _KiTrap0F, D_INT032 ;2F: Reserved for APIC
;
; Generate per-vector unexpected interrupt entries for 30 - ff
;
DEFINE_EMPTY_VECTORS
_IDTLEN equ $ - _IDT
_IDTEnd equ $
INIT ends
public _KiUnexpectedEntrySize
_KiUnexpectedEntrySize dd _KiUnexpectedInterrupt1 - _KiUnexpectedInterrupt0
;
; defines all the possible instruction prefix
;
PrefixTable label byte
db 0f2h ; rep prefix
db 0f3h ; rep ins/outs prefix
db 67h ; addr prefix
db 0f0h ; lock prefix
db 66h ; operand prefix
db 2eh ; segment override prefix:cs
db 3eh ; ds
db 26h ; es
db 64h ; fs
db 65h ; gs
db 36h ; ss
PREFIX_REPEAT_COUNT EQU 11 ; Prefix table length
;
; defines all the possible IO privileged IO instructions
;
IOInstructionTable label byte
; db 0fah ; cli
; db 0fdh ; sti
db 0e4h, 0e5h, 0ech, 0edh ; IN
db 6ch, 6dh ; INS
db 0e6h, 0e7h, 0eeh, 0efh ; OUT
db 6eh, 6fh ; OUTS
IO_INSTRUCTION_TABLE_LENGTH EQU 12
;
; definition for floating status word error mask
;
FSW_INVALID_OPERATION EQU 1
FSW_DENORMAL EQU 2
FSW_ZERO_DIVIDE EQU 4
FSW_OVERFLOW EQU 8
FSW_UNDERFLOW EQU 16
FSW_PRECISION EQU 32
FSW_STACK_FAULT EQU 64
FSW_CONDITION_CODE_0 EQU 100H
FSW_CONDITION_CODE_1 EQU 200H
FSW_CONDITION_CODE_2 EQU 400H
FSW_CONDITION_CODE_3 EQU 4000H
_DATA ENDS
_TEXT$00 SEGMENT
ASSUME DS:NOTHING, ES:NOTHING, SS:FLAT, FS:NOTHING, GS:NOTHING
page , 132
subttl "Macro to Handle v86 trap d"
;++
;
; Macro Description:
;
; This macro is a fast way to handle v86 bop instructions.
; Note, all the memory write operations in this macro are done in such a
; way that if a page fault occurs the memory will still be in a consistent
; state.
;
; That is, we must process the trapped instruction in the following order:
;
; 1. Read and Write user memory
; 2. Update VDM state flags
; 3. Update trap frame
;
; Arguments:
;
; interrupts disabled
;
; Return Value:
;
;--
FAST_V86_TRAP_6 MACRO
local DoFastIo, a, b
BOP_FOR_FASTWRITE EQU 4350C4C4H
BOP_FOR_FASTREAD EQU 4250C4C4H
TRAP6_IP EQU 32 ; 8 * 4
TRAP6_CS EQU 36 ; 8 * 4 + 4
TRAP6_FLAGS EQU 40 ; 8 * 4 + 8
TRAP6_SP EQU 44 ; 8 * 4 + 12
TRAP6_SS EQU 48 ; 8 * 4 + 16
TRAP6_ES EQU 52
TRAP6_DS EQU 56
TRAP6_FS EQU 60
TRAP6_GS EQU 64
TRAP6_EAX EQU 28
TRAP6_EDX EQU 20
pushad ;eax, ecx, edx, ebx, old esp, ebp, esi, edi
mov eax, KGDT_R3_DATA OR RPL_MASK
mov ds, ax
mov es, ax
mov eax, KGDT_R0_PCR
mov fs, ax
mov ax, word ptr [esp+TRAP6_CS] ; [eax] = v86 user cs
shl eax, 4
and dword ptr [esp+TRAP6_IP], 0FFFFH
add eax, [esp+TRAP6_IP]; [eax] = addr of BOP
;
; Set the magic PCR bit indicating we are executing VDM management code
; so faults on potentially invalid or plain bad user addresses do
; not bugcheck the system. Note both interrupts are disabled and
; (for performance reasons) we do not have any exception handlers
; set up.
;
mov dword ptr PCR[PcVdmAlert], offset FLAT:V86Trap6Recovery
;
; Fetch the actual opcode from user space.
;
mov edx, [eax] ; [edx] = xxxxc4c4 bop + maj bop # + mi #
cmp edx, BOP_FOR_FASTREAD
je DoFastIo
cmp edx, BOP_FOR_FASTWRITE
je DoFastIo
cmp dx, 0c4c4h ; Is it a bop?
jne V86Trap6PassThrough ; It's an error condition
mov eax,PCR[PcTeb]
shr edx, 16
mov eax,[eax].TeVdm
cmp eax, _MmUserProbeAddress ; check if user address
jae V86Trap6PassThrough ; if ae, then not user address
and edx, 0ffh
mov dword ptr [eax].VtEIEvent, VdmBop
mov dword ptr [eax].VtEIBopNumber, edx
mov dword ptr [eax].VtEIInstSize, 3
lea eax, [eax].VtVdmContext
;
; Save V86 state to Vdm structure
;
mov edx, [esp+TRAP6_EDX] ; get edx
cmp eax, _MmUserProbeAddress ; check if user address
jae V86Trap6PassThrough ; if ae, then not user address
mov [eax].CsEcx, ecx
mov [eax].CsEbx, ebx ; Save non-volatile registers
mov [eax].CsEsi, esi
mov [eax].CsEdi, edi
mov ecx, [esp+TRAP6_EAX] ; Get eax
mov [eax].CsEbp, ebp
mov [eax].CsEdx, edx
mov [eax].CsEax, ecx
mov ebx, [esp]+TRAP6_IP ; (ebx) = user ip
mov ecx, [esp]+TRAP6_CS ; (ecx) = user cs
mov esi, [esp]+TRAP6_SP ; (esi) = user esp
mov edi, [esp]+TRAP6_SS ; (edi) = user ss
mov edx, [esp]+TRAP6_FLAGS; (edx) = user eflags
mov [eax].CsEip, ebx
and esi, 0ffffh
mov [eax].CsSegCs, ecx
mov [eax].CsEsp, esi
mov [eax].CsSegSs, edi
test _KeI386VirtualIntExtensions, V86_VIRTUAL_INT_EXTENSIONS
jz short @f
test edx, EFLAGS_VIF
jnz short a
and edx, NOT EFLAGS_INTERRUPT_MASK
jmp short a
@@: test ds:FIXED_NTVDMSTATE_LINEAR, VDM_VIRTUAL_INTERRUPTS ; check interrupt
jnz short a
and edx, NOT EFLAGS_INTERRUPT_MASK
a:
mov [eax].CsEFlags, edx
mov ebx, [esp]+TRAP6_DS ; (ebx) = user ds
mov ecx, [esp]+TRAP6_ES ; (ecx) = user es
mov edx, [esp]+TRAP6_FS ; (edx) = user fs
mov esi, [esp]+TRAP6_GS ; (esi) = user gs
mov [eax].CsSegDs, ebx
mov [eax].CsSegEs, ecx
mov [eax].CsSegFs, edx
mov [eax].CsSegGs, esi
;
; Load Monitor context
;
add eax, VtMonitorContext - VtVdmContext ; (eax)->monitor context
mov ebx, [eax].CsEbx ; We don't need to load volatile registers.
mov esi, [eax].CsEsi ; because monitor uses SystemCall to return
mov edi, [eax].CsEdi ; back to v86. C compiler knows that
mov ebp, [eax].CsEbp ; SystemCall does not preserve volatile
; registers.
; es, ds are set up already.
;
; Note these push instructions won't fail. Do NOT combine the
; 'move ebx, [eax].CsEbx' with 'push ebx' to 'push [eax].CsEbx'
;
push ebx ; note, these push instructions won't fail
push esi
push edi
push ebp
mov dword ptr PCR[PcVdmAlert], offset FLAT:V86Trap6Recovery2
mov ebx, [eax].CsSegSs
mov esi, [eax].CsEsp
mov edi, [eax].CsEFlags
mov edx, [eax].CsSegCs
mov ecx, [eax].CsEip
;
; after this point, we don't need to worry about instruction fault
; Clear magic flag as no more potentially bogus references will be made.
;
mov dword ptr PCR[PcVdmAlert], 0
and edi, EFLAGS_USER_SANITIZE
or edi, EFLAGS_INTERRUPT_MASK
mov [esp + TRAP6_SS + 16], ebx ; Build Iret frame (can not single step!)
mov [esp + TRAP6_SP + 16], esi
mov [esp + TRAP6_FLAGS + 16], edi
test edi, EFLAGS_V86_MASK
jne short @f
or edx, RPL_MASK
cmp edx, 8
jge short @f
mov edx, KGDT_R3_CODE OR RPL_MASK
@@: mov [esp + TRAP6_CS + 16], edx
mov [esp + TRAP6_IP + 16], ecx
pop ebp
pop edi
pop esi
pop ebx
add esp, 32
;
; Adjust Tss esp0 value and set return value to SUCCESS
;
mov ecx, PCR[PcPrcbData+PbCurrentThread]
mov ecx, [ecx].thInitialStack
mov edx, PCR[PcTss]
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esp+8+2],EFLAGS_V86_MASK/010000h ; is this a V86 frame?
jnz short @f
sub ecx, TsV86Gs - TsHardwareSegSs
@@:
sub ecx, NPX_FRAME_LENGTH
xor eax, eax ; ret status = SUCCESS
mov [edx].TssEsp0, ecx
mov edx, KGDT_R3_TEB OR RPL_MASK
mov fs, dx
iretd
DoFastIo:
;
; Clear magic flag as no bogus references are going to be made.
;
mov dword ptr PCR[PcVdmAlert], 0
xor eax, eax
mov edx, [esp]+TRAP6_EDX ; Restore edx
add esp, 7 * 4 ; leave eax in the TsErrCode
xchg [esp], eax ; Restore eax, store a zero errcode
sub esp, TsErrcode ; build a trap frame
mov [esp].TsEbx, ebx
mov [esp].TsEax, eax
mov [esp].TsEbp, ebp
mov [esp].TsEsi, esi
mov [esp].TsEdi, edi
mov [esp].TsEcx, ecx
mov [esp].TsEdx, edx
if DBG
mov [esp].TsPreviousPreviousMode, -1
mov [esp]+TsDbgArgMark, 0BADB0D00h
endif
mov edi, PCR[PcExceptionList]
mov [esp]+TsExceptionList, edi
ifdef NT_UP
mov ebx, KGDT_R0_PCR
mov fs, bx
endif
mov ebx, PCR[PcPrcbData+PbCurrentThread] ; fetch current thread
and dword ptr [esp].TsDr7, 0
test byte ptr [ebx].ThDebugActive, 0ffh ; See if debug registers are active
mov ebp, esp
cld
je short @f
mov ebx,dr0
mov esi,dr1
mov edi,dr2
mov [ebp]+TsDr0,ebx
mov [ebp]+TsDr1,esi
mov [ebp]+TsDr2,edi
mov ebx,dr3
mov esi,dr6
mov edi,dr7
mov [ebp]+TsDr3,ebx
xor ebx, ebx
mov [ebp]+TsDr6,esi
mov [ebp]+TsDr7,edi
mov dr7, ebx ; Clear out control before reloading
;
; Load KernelDr* into processor
;
mov edi,dword ptr PCR[PcPrcb]
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr0
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr1
mov dr0,ebx
mov dr1,esi
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr2
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr3
mov dr2,ebx
mov dr3,esi
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr6
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr7
mov dr6,ebx
mov dr7,esi
@@:
xor edx, edx
mov dx, word ptr [ebp].TsSegCs
shl edx, 4
xor ebx, ebx
add edx, [ebp].TsEip
;
; Set the magic PCR bit indicating we are executing VDM management code
; so faults on potentially invalid or plain bad user addresses do
; not bugcheck the system. Note both interrupts are disabled and
; (for performance reasons) we do not have any exception handlers
; set up.
;
mov dword ptr PCR[PcVdmAlert], offset FLAT:V86Trap6Recovery1
;
; Fetch the actual opcode from user space.
;
mov bl, [edx+3] ; [bl] = minor BOP code
;
; Clear magic flag as no bogus references are going to be made.
;
mov dword ptr PCR[PcVdmAlert], 0
;
; Raise Irql to APC level before enabling interrupts.
;
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti
push ebx
push ebp ; (ebp)->TrapFrame
call _NTFastDOSIO@8
jmp Kt061i
V86Trap6PassThrough:
;
; Clear magic flag as no bogus references are going to be made.
;
mov dword ptr PCR[PcVdmAlert], 0
V86Trap6Recovery:
popad
jmp Kt6SlowBop ; Fall through
V86Trap6Recovery1:
jmp Kt6SlowBop1 ; Fall through
V86Trap6Recovery2:
add esp, 16
popad
jmp Kt6SlowBop ; Fall through
endm
page , 132
subttl "Macro to dispatch user APC"
;++
;
; Macro Description:
;
; This macro is called before returning to user mode. It dispatches
; any pending user mode APCs.
;
; Arguments:
;
; TFrame - TrapFrame
; interrupts disabled
;
; Return Value:
;
;--
DISPATCH_USER_APC macro TFrame, ReturnCurrentEax
local a, b, c
c:
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [TFrame]+TsEflags+2, EFLAGS_V86_MASK/010000h ; is previous mode v86?
jnz short b ; if nz, yes, go check for APC
test byte ptr [TFrame]+TsSegCs,MODE_MASK ; is previous mode user mode?
jz a ; No, previousmode=Kernel, jump out
b: mov ebx, PCR[PcPrcbData+PbCurrentThread]; get addr of current thread
mov byte ptr [ebx]+ThAlerted, 0 ; clear kernel mode alerted
cmp byte ptr [ebx]+ThApcState.AsUserApcPending, 0
je a ; if eq, no user APC pending
mov ebx, TFrame
ifnb <ReturnCurrentEax>
mov [ebx].TsEax, eax ; Store return code in trap frame
mov dword ptr [ebx]+TsSegFs, KGDT_R3_TEB OR RPL_MASK
mov dword ptr [ebx]+TsSegDs, KGDT_R3_DATA OR RPL_MASK
mov dword ptr [ebx]+TsSegEs, KGDT_R3_DATA OR RPL_MASK
mov dword ptr [ebx]+TsSegGs, 0
endif
;
; Save previous IRQL and set new priority level
;
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti ; Allow higher priority ints
;
; call the APC delivery routine.
;
; ebx - Trap frame
; 0 - Null exception frame
; 1 - Previous mode
;
; call APC deliver routine
;
stdCall _KiDeliverApc, <1, 0, ebx>
pop ecx ; (ecx) = OldIrql
LowerIrql ecx
ifnb <ReturnCurrentEax>
mov eax, [ebx].TsEax ; Restore eax, just in case
endif
cli
jmp b
ALIGN 4
a:
endm
if DBG
page ,132
subttl "Processing Exception occurred in a 16 bit stack"
;++
;
; Routine Description:
;
; This routine is called after an exception being detected during
; a 16 bit stack. The system will switch 16 stack to 32 bit
; stack and bugcheck.
;
; Arguments:
;
; None.
;
; Return value:
;
; system stopped.
;
;--
align dword
public _Ki16BitStackException
_Ki16BitStackException proc
.FPO (2, 0, 0, 0, 0, FPO_TRAPFRAME)
push ss
push esp
mov eax, PCR[PcPrcbData+PbCurrentThread] ; get current thread address
add esp, [eax]+ThStackLimit ; compute 32-bit stack address
mov eax, KGDT_R0_DATA
mov ss, ax
lea ebp, [esp+8]
cld
SET_DEBUG_DATA
if DBG
push offset FLAT:Ki16BitStackTrapMessage
call _dbgPrint
add esp, 4
endif
stdCall _KeBugCheck2, <0F000FFFFh,0,0,0,0,ebp> ; Never return
ret
_Ki16BitStackException endp
endif
page ,132
subttl "System Service Call"
;++
;
; Routine Description:
;
; This routine gains control when trap occurs via vector 2EH.
; INT 2EH is reserved for system service calls.
;
; The system service is executed by locating its routine address in
; system service dispatch table and calling the specified function.
; On return necessary state is restored.
;
; Arguments:
;
; eax - System service number.
; edx - Pointer to arguments
;
; Return Value:
;
; eax - System service status code.
;
;--
;
; The specified system service number is not within range. Attempt to
; convert the thread to a GUI thread if the specified system service is
; not a base service and the thread has not already been converted to a
; GUI thread.
;
Kss_ErrorHandler:
cmp ecx, SERVICE_TABLE_TEST ; test if GUI service
jne short Kss_LimitError ; if ne, not GUI service
push edx ; save argument registers
push ebx ;
stdcall _PsConvertToGuiThread ; attempt to convert to GUI thread
or eax, eax ; check if service was successful
pop eax ; restore argument registers
pop edx ;
mov ebp, esp ; reset trap frame address
mov [esi]+ThTrapFrame, ebp ; save address of trap frame
jz _KiSystemServiceRepeat ; if eq, successful conversion
;
; The conversion to a GUI thread failed. The correct return value is encoded
; in a byte table indexed by the service number that is at the end of the
; service address table. The encoding is as follows:
;
; 0 - return 0.
; -1 - return -1.
; 1 - return status code.
;
lea edx, _KeServiceDescriptorTableShadow + SERVICE_TABLE_TEST ;
mov ecx, [edx]+SdLimit ; get service number limit
mov edx, [edx]+SdBase ; get service table base
lea edx, [edx][ecx*4] ; get ending service table address
and eax, SERVICE_NUMBER_MASK ; isolate service number
add edx, eax ; compute return value address
movsx eax, byte ptr [edx] ; get status byte
or eax, eax ; check for 0 or -1
jle Kss70 ; if le, return value set
Kss_LimitError: ;
mov eax, STATUS_INVALID_SYSTEM_SERVICE ; set return status
jmp kss70 ;
ENTER_DR_ASSIST kss_a, kss_t,NoAbiosAssist,NoV86Assist
ENTER_DR_ASSIST FastCallDrSave, FastCallDrReturn,NoAbiosAssist,NoV86Assist
;
; General System service entrypoint
;
PUBLIC _KiSystemService
_KiSystemService proc
ENTER_SYSCALL kss_a, kss_t ; set up trap frame and save state
jmp _KiSystemServiceRepeat
_KiSystemService endp
;
; Fast System Call entry point
;
; At entry:
; EAX = service number
; EDX = Pointer to caller's arguments
; ECX = unused
; ESP = DPC stack for this processor
;
; Create a stack frame like a call to inner privilege then continue
; in KiSystemService.
;
;
; Normal entry is at KiFastCallEntry, not KiFastCallEntry2. Entry
; is via KiFastCallEntry2 if a trace trap occured and EIP
; was KiFastCallEntry. This happens if a single step exception occurs
; on the instruction following SYSENTER instruction because this
; instruction does not sanitize this flag.
;
; This is NOT a performance path.
PUBLIC _KiFastCallEntry2
_KiFastCallEntry2:
;
; Sanitize the segment registers
;
mov ecx, KGDT_R0_PCR
mov fs, ecx
mov ecx, KGDT_R3_DATA OR RPL_MASK
mov ds, ecx
mov es, ecx
;
; When we trap into the kernel via fast system call we start on the DPC stack. We need
; shift to the threads stack before enabling interrupts.
;
mov ecx, PCR[PcTss] ;
mov esp, [ecx]+TssEsp0
push KGDT_R3_DATA OR RPL_MASK ; Push user SS
push edx ; Push ESP
pushfd
.errnz (EFLAGS_TF AND 0FFFF00FFh)
or byte ptr [esp+1], EFLAGS_TF/0100h ; Set TF flag ready for return or
; get/set thread context
jmp short Kfsc10
;
; If the sysenter instruction was executed in 16 bit mode, generate
; an error rather than trying to process the system call. There is
; no way to return to the correct code in user mode.
;
Kfsc90:
mov ecx, PCR[PcTss] ;
mov esp, [ecx]+TssEsp0
push 0 ; save VX86 Es, Ds, Fs, Gs
push 0
push 0
push 0
push KGDT_R3_DATA OR RPL_MASK ; SS
push 0 ; can't know user esp
push EFLAGS_INTERRUPT_MASK+EFLAGS_V86_MASK+2h; eflags with VX86 set
push KGDT_R3_CODE OR RPL_MASK ; CS
push 0 ; don't know original EIP
jmp _KiTrap06 ; turn exception into illegal op.
Kfsc91: jmp Kfsc90
align 16
PUBLIC _KiFastCallEntry
_KiFastCallEntry proc
;
; Sanitize the segment registers
;
mov ecx, KGDT_R3_DATA OR RPL_MASK
push KGDT_R0_PCR
pop fs
mov ds, ecx
mov es, ecx
;
; When we trap into the kernel via fast system call we start on the DPC stack. We need
; shift to the threads stack before enabling interrupts.
;
mov ecx, PCR[PcTss] ;
mov esp, [ecx]+TssEsp0
push KGDT_R3_DATA OR RPL_MASK ; Push user SS
push edx ; Push ESP
pushfd
Kfsc10:
push 2 ; Sanitize eflags, clear direction, NT etc
add edx, 8 ; (edx) -> arguments
popfd ;
.errnz(EFLAGS_INTERRUPT_MASK AND 0FFFF00FFh)
or byte ptr [esp+1], EFLAGS_INTERRUPT_MASK/0100h ; Enable interrupts in eflags
push KGDT_R3_CODE OR RPL_MASK ; Push user CS
push dword ptr ds:[USER_SHARED_DATA+UsSystemCallReturn] ; push return address
push 0 ; put pad dword for error on stack
push ebp ; save the non-volatile registers
push ebx ;
push esi ;
push edi ;
mov ebx, PCR[PcSelfPcr] ; Get PRCB address
push KGDT_R3_TEB OR RPL_MASK ; Push user mode FS
mov esi, [ebx].PcPrcbData+PbCurrentThread ; get current thread address
;
; Save the old exception list in trap frame and initialize a new empty
; exception list.
;
push [ebx].PcExceptionList ; save old exception list
mov [ebx].PcExceptionList, EXCEPTION_CHAIN_END ; set new empty list
mov ebp, [esi].ThInitialStack
;
; Save the old previous mode in trap frame, allocate remainder of trap frame,
; and set the new previous mode.
;
push MODE_MASK ; Save previous mode as user
sub esp,TsPreviousPreviousMode ; allocate remainder of trap frame
sub ebp, NPX_FRAME_LENGTH + KTRAP_FRAME_LENGTH
mov byte ptr [esi].ThPreviousMode,MODE_MASK ; set new previous mode of user
;
; Now the full trap frame is build.
; Calculate initial stack pointer from thread initial stack to contain NPX and trap.
; If this isn't the same as esp then we are a VX86 thread and we are rejected
;
cmp ebp, esp
jne short Kfsc91
;
; Set the new trap frame address.
;
and dword ptr [ebp].TsDr7, 0
test byte ptr [esi].ThDebugActive, 0ffh ; See if we need to save debug registers
mov [esi].ThTrapFrame, ebp ; set new trap frame address
jnz Dr_FastCallDrSave ; if nz, debugging is active on thread
Dr_FastCallDrReturn: ;
SET_DEBUG_DATA ; Note this destroys edi
sti ; enable interrupts
?FpoValue = 0
;
; (eax) = Service number
; (edx) = Callers stack pointer
; (esi) = Current thread address
;
; All other registers have been saved and are free.
;
; Check if the service number within valid range
;
_KiSystemServiceRepeat:
mov edi, eax ; copy system service number
shr edi, SERVICE_TABLE_SHIFT ; isolate service table number
and edi, SERVICE_TABLE_MASK ;
mov ecx, edi ; save service table number
add edi, [esi]+ThServiceTable ; compute service descriptor address
mov ebx, eax ; save system service number
and eax, SERVICE_NUMBER_MASK ; isolate service table offset
;
; If the specified system service number is not within range, then attempt
; to convert the thread to a GUI thread and retry the service dispatch.
;
cmp eax, [edi]+SdLimit ; check if valid service
jae Kss_ErrorHandler ; if ae, try to convert to GUI thread
;
; If the service is a GUI service and the GDI user batch queue is not empty,
; then call the appropriate service to flush the user batch.
;
cmp ecx, SERVICE_TABLE_TEST ; test if GUI service
jne short Kss40 ; if ne, not GUI service
mov ecx, PCR[PcTeb] ; get current thread TEB address
xor ebx, ebx ; get number of batched GDI calls
KiSystemServiceAccessTeb:
or ebx, [ecx]+TbGdiBatchCount ; may cause an inpage exception
jz short Kss40 ; if z, no batched calls
push edx ; save address of user arguments
push eax ; save service number
call [_KeGdiFlushUserBatch] ; flush GDI user batch
pop eax ; restore service number
pop edx ; restore address of user arguments
;
; The arguments are passed on the stack. Therefore they always need to get
; copied since additional space has been allocated on the stack for the
; machine state frame. Note that we don't check for the zero argument case -
; copy is always done regardless of the number of arguments because the
; zero argument case is very rare.
;
Kss40: inc dword ptr PCR[PcPrcbData+PbSystemCalls] ; system calls
if DBG
mov ecx, [edi]+SdCount ; get count table address
jecxz short @f ; if zero, table not specified
inc dword ptr [ecx+eax*4] ; increment service count
@@: ;
endif
FPOFRAME ?FpoValue, 0
mov esi, edx ; (esi)->User arguments
mov ebx, [edi]+SdNumber ; get argument table address
xor ecx, ecx
mov cl, byte ptr [ebx+eax] ; (ecx) = argument size
mov edi, [edi]+SdBase ; get service table address
mov ebx, [edi+eax*4] ; (ebx)-> service routine
sub esp, ecx ; allocate space for arguments
shr ecx, 2 ; (ecx) = number of argument DWORDs
mov edi, esp ; (edi)->location to receive 1st arg
cmp esi, _MmUserProbeAddress ; check if user address
jae kss80 ; if ae, then not user address
KiSystemServiceCopyArguments:
rep movsd ; copy the arguments to top of stack.
; Since we usually copy more than 3
; arguments. rep movsd is faster than
; mov instructions.
;
; Check if low resource usage should be simulated.
;
if DBG
test _MmInjectUserInpageErrors, 2
jz short @f
stdCall _MmTrimProcessMemory, <0>
jmp short kssdoit
@@:
mov eax,PCR[PcPrcbData+PbCurrentThread]
mov eax,[eax]+ThApcState+AsProcess
test dword ptr [eax]+PrFlags,0100000h ; is this a inpage-err process?
je short @f
stdCall _MmTrimProcessMemory, <0>
@@:
endif
;
; Make actual call to system service
;
kssdoit:
call ebx ; call system service
kss60:
;
; Check for return to user mode at elevated IRQL.
;
if DBG
test byte ptr [ebp]+TsSegCs,MODE_MASK ; test if previous mode user
jz short kss50b ; if z, previous mode not user
mov esi,eax ; save return status
CurrentIrql ; get current IRQL
or al,al ; check if IRQL is passive level
jnz kss100 ; if nz, IRQL not passive level
mov eax,esi ; restore return status
;
; Check if kernel APCs are disabled or a process is attached.
;
mov ecx,PCR[PcPrcbData+PbCurrentThread] ; get current thread address
mov dl,[ecx]+ThApcStateIndex ; get APC state index
or dl,dl ; check if process attached
jne kss120 ; if ne, process is attached
mov edx,[ecx]+ThCombinedApcDisable ; get kernel APC disable
or edx,edx ; check if kernel APCs disabled
jne kss120 ; if ne, kernel APCs disabled.
kss50b: ;
endif
kss61:
;
; Upon return, (eax)= status code. This code may also be entered from a failed
; KiCallbackReturn call.
;
mov esp, ebp ; deallocate stack space for arguments
;
; Restore old trap frame address from the current trap frame.
;
kss70: mov ecx, PCR[PcPrcbData+PbCurrentThread] ; get current thread address
mov edx, [ebp].TsEdx ; restore previous trap frame address
mov [ecx].ThTrapFrame, edx ;
;
; System service's private version of KiExceptionExit
; (Also used by KiDebugService)
;
; Check for pending APC interrupts, if found, dispatch to them
; (saving eax in frame first).
;
public _KiServiceExit
_KiServiceExit:
cli ; disable interrupts
DISPATCH_USER_APC ebp, ReturnCurrentEax
;
; Exit from SystemService
;
EXIT_ALL NoRestoreSegs, NoRestoreVolatile
;
; The address of the argument list is not a user address. If the previous mode
; is user, then return an access violation as the status of the system service.
; Otherwise, copy the argument list and execute the system service.
;
kss80: test byte ptr [ebp].TsSegCs, MODE_MASK ; test previous mode
jz KiSystemServiceCopyArguments ; if z, previous mode kernel
mov eax, STATUS_ACCESS_VIOLATION ; set service status
jmp kss60 ;
;++
;
; _KiServiceExit2 - same as _KiServiceExit BUT the full trap_frame
; context is restored
;
;--
public _KiServiceExit2
_KiServiceExit2:
cli ; disable interrupts
DISPATCH_USER_APC ebp
;
; Exit from SystemService
;
EXIT_ALL ; RestoreAll
if DBG
kss100: push PCR[PcIrql] ; put bogus value on stack for dbg
?FpoValue = ?FpoValue + 1
FPOFRAME ?FpoValue, 0
mov byte ptr PCR[PcIrql],0 ; avoid recursive trap
cli ;
;
; IRQL_GT_ZERO_AT_SYSTEM_SERVICE - attempted return to usermode at elevated
; IRQL.
;
; KeBugCheck2(IRQL_GT_ZERO_AT_SYSTEM_SERVICE,
; System Call Handler (address of system routine),
; Irql,
; 0,
; 0,
; TrapFrame);
;
stdCall _KeBugCheck2,<IRQL_GT_ZERO_AT_SYSTEM_SERVICE,ebx,eax,0,0,ebp>
;
; APC_INDEX_MISMATCH - attempted return to user mode with kernel APCs disabled
; or a process attached.
;
; KeBugCheck2(APC_INDEX_MISMATCH,
; System Call Handler (address of system routine),
; Thread->ApcStateIndex,
; Thread->CombinedApcDisable,
; 0,
; TrapFrame);
;
kss120: movzx eax,byte ptr [ecx]+ThApcStateIndex ; get APC state index
mov edx,[ecx]+ThCombinedApcDisable ; get kernel APC disable
stdCall _KeBugCheck2,<APC_INDEX_MISMATCH,ebx,eax,edx,0,ebp>
endif
ret
_KiFastCallEntry endp
;
; BBT cannot instrument code between this label and BBT_Exclude_Trap_Code_End
;
public _BBT_Exclude_Trap_Code_Begin
_BBT_Exclude_Trap_Code_Begin equ $
int 3
;
; Fast path NtGetTickCount
;
align 16
ENTER_DR_ASSIST kitx_a, kitx_t,NoAbiosAssist
PUBLIC _KiGetTickCount
_KiGetTickCount proc
cmp [esp+4], KGDT_R3_CODE OR RPL_MASK
jnz short @f
Kgtc00:
mov eax,dword ptr cs:[_KeTickCount]
mul dword ptr cs:[_ExpTickCountMultiplier]
shrd eax,edx,24 ; compute resultant tick count
iretd
@@:
;
; if v86 mode, we dont handle it
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esp+8+2], EFLAGS_V86_MASK/010000h
jnz ktgc20
;
; if kernel mode, must be get tick count
;
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [esp+4], MODE_MASK
jz short Kgtc00
;
; else check if the caller is USER16
; if eax = ebp = 0xf0f0f0f0 it is get-tick-count
; if eax = ebp = 0xf0f0f0f1 it is set-ldt-entry
;
cmp eax, ebp ; if eax != ebp, not USER16
jne ktgc20
and eax, 0fffffff0h
cmp eax, 0f0f0f0f0h
jne ktgc20
cmp ebp, 0f0f0f0f0h ; Is it user16 gettickcount?
je short Kgtc00 ; if z, yes
cmp ebp, 0f0f0f0f1h ; If this is setldt entry
jne ktgc20 ; if nz, we don't know what
; it is.
;
; The idea here is that user16 can call 32 bit api to
; update LDT entry without going through the penalty
; of DPMI.
;
push 0 ; push dummy error code
ENTER_TRAP kitx_a, kitx_t
sti
xor eax, eax
mov ebx, [ebp+TsEbx]
mov ecx, [ebp+TsEcx]
mov edx, [ebp+TsEdx]
stdCall _NtSetLdtEntries <ebx, ecx, edx, eax, eax, eax>
mov [ebp+TsEax], eax
and dword ptr [ebp+TsEflags], 0FFFFFFFEH ; clear carry flag
cmp eax, 0 ; success?
je short ktgc10
or dword ptr [ebp+TsEflags], 1 ; set carry flag
ktgc10:
jmp _KiExceptionExit
ktgc20:
;
; We need to *trap* this int 2a. For exception, the eip should
; point to the int 2a instruction not the instruction after it.
;
sub word ptr [esp], 2
push 0
jmp _KiTrap0D
_KiGetTickCount endp
page ,132
subttl "Return from User Mode Callback"
;++
;
; NTSTATUS
; NtCallbackReturn (
; IN PVOID OutputBuffer OPTIONAL,
; IN ULONG OutputLength,
; IN NTSTATUS Status
; )
;
; Routine Description:
;
; This function returns from a user mode callout to the kernel mode
; caller of the user mode callback function.
;
; N.B. This service uses a nonstandard calling sequence. The trap
; is converted to a standard system call so that the exit sequence
; can take advantage of any processor support for fast user mode
; return.
;
; Arguments:
;
; OutputBuffer (ecx) - Supplies an optional pointer to an output buffer.
;
; OutputLength (edx) - Supplies the length of the output buffer.
;
; Status (eax) - Supplies the status value returned to the caller of
; the callback function.
;
; Return Value:
;
; If the callback return cannot be executed, then an error status is
; returned. Otherwise, the specified callback status is returned to
; the caller of the callback function.
;
; N.B. This function returns to the function that called out to user
; mode if a callout is currently active.
;
;--
ENTER_DR_ASSIST kcb_a, kcb_t, NoAbiosAssist, NoV86Assist
align 16
PUBLIC _KiCallbackReturn
_KiCallbackReturn proc
ENTER_SYSCALL kcb_a, kcb_t, , , SaveEcx
mov ecx, [ebp].TsEcx ; Recover ecx from the trap frame
stdCall _NtCallbackReturn, <ecx,edx,eax>
; If it returns, then exit with a failure code as any system call would.
jmp kss61
_KiCallbackReturn endp
page ,132
subttl "Raise Assertion"
;++
;
; Routine Description:
;
; This routine is entered as the result of the execution of an int 2c
; instruction. Its function is to raise an assertion.
;
; Arguments:
;
; None.
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kira_a, kira_t, NoAbiosAssist
align dword
public _KiRaiseAssertion
_KiRaiseAssertion proc
push 0 ; push dummy error code
ENTER_TRAP kira_a, kira_t ;
sub dword ptr [ebp]+TsEip, 2 ; convert trap to a fault
mov ebx, [ebp]+TsEip ; set exception address
mov eax, STATUS_ASSERTION_FAILURE ; set exception code
jmp CommonDispatchException0Args ; finish in common code
_KiRaiseAssertion endp
page ,132
subttl "Common Trap Exit"
;++
;
; KiUnexpectedInterruptTail
;
; Routine Description:
; This function is jumped to by an IDT entry who has no interrupt
; handler.
;
; Arguments:
;
; (esp) - Dword, vector
; (esp+4) - Processor generated IRet frame
;
;--
ENTER_DR_ASSIST kui_a, kui_t
public _KiUnexpectedInterruptTail
_KiUnexpectedInterruptTail proc
ENTER_INTERRUPT kui_a, kui_t, PassDwordParm
inc dword ptr PCR[PcPrcbData+PbInterruptCount]
mov ebx, [esp] ; get vector & leave it on the stack
sub esp, 4 ; make space for OldIrql
; esp - ptr to OldIrql
; ebx - Vector
; HIGH_LEVEL - Irql
stdCall _HalBeginSystemInterrupt, <HIGH_LEVEL,ebx,esp>
or eax, eax
jnz short kui10
;
; spurious interrupt
;
add esp, 8
jmp kee99
kui10:
if DBG
push dword ptr [esp+4] ; Vector #
push offset FLAT:BadInterruptMessage
call _DbgPrint ; display unexpected interrupt message
add esp, 8
endif
;
; end this interrupt
;
INTERRUPT_EXIT
_KiUnexpectedInterruptTail endp
;++
;
; N.B. KiExceptionExit and Kei386EoiHelper are identical and have
; been combined.
;
; KiExceptionExit
;
; Routine Description:
;
; This code is transferred to at the end of the processing for
; an exception. Its function is to restore machine state, and
; continue thread execution. If control is returning to user mode
; and there is a user APC pending, then control is transferred to
; the user APC delivery routine.
;
; N.B. It is assumed that this code executes at IRQL zero or APC_LEVEL.
; Therefore page faults and access violations can be taken.
;
; NOTE: This code is jumped to, not called.
;
; Arguments:
;
; (ebp) -> base of trap frame.
;
; Return Value:
;
; None.
;
;--
;++
;
; Kei386EoiHelper
;
; Routine Description:
;
; This code is transferred to at the end of an interrupt. (via the
; exit_interrupt macro). It checks for user APC dispatching and
; performs the exit_all for the interrupt.
;
; NOTE: This code is jumped to, not called.
;
; Arguments:
;
; (esp) -> base of trap frame.
; interrupts are disabled
;
; Return Value:
;
; None.
;
;--
align 4
public _KiExceptionExit
cPublicProc Kei386EoiHelper, 0
_KiExceptionExit:
.FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME)
cli ; disable interrupts
DISPATCH_USER_APC ebp
;
; Exit from Exception
;
kee99:
EXIT_ALL ,,NoPreviousMode
stdENDP Kei386EoiHelper
;
; V86ExitHelp
;
; Restore volatiles for V86 mode, and move seg regs
;
; Arguments:
;
; esp = ebp = &TrapFrame
;
; Return Value:
;
; None, returns to previous mode using IRETD.
;
align dword
V86ExitHelp:
add esp,TsEdx
pop edx
pop ecx
pop eax
lea esp, [ebp]+TsEdi ; Skip PreMode, ExceptList and fs
pop edi ; restore non-volatiles
pop esi
pop ebx
pop ebp
;
; Esp MUST point to the Error Code on the stack. Because we use it to
; store the entering esp.
;
cmp word ptr [esp+8], 80h ; check for abios code segment?
ja AbiosExitHelp
v86eh90:
add esp, 4 ; remove error code from trap frame
iretd ; return
Abios_ExitHelp_Target2:
;
; End of ABIOS stack check
;
;
; AbiosExit:
;
; This routine remaps current 32bit stack to 16bit stack at return
; from interrupt time and returns from interrupt.
;
; Arguments:
;
; (esp) -> TrapFrame
;
; Return Value:
;
; None, returns to previous mode using IRETD.
; Note: May use above exit to remove error code from stack.
;
align dword
AbiosExitHelp:
cmp word ptr [esp+2], 0 ; (esp+2) = Low word of error code
jz short v86eh90
cmp word ptr [esp], 0 ; (esp) = High word of error code
jnz short v86eh90
shr dword ptr [esp], 16
mov word ptr [esp + 2], KGDT_STACK16
lss sp, dword ptr [esp]
movzx esp, sp
iretd ; return
page , 132
subttl "trap processing"
;++
;
; Routine Description:
;
; _KiTrapxx - protected mode trap entry points
;
; These entry points are for internally generated exceptions,
; such as a general protection fault. They do not handle
; external hardware interrupts, or user software interrupts.
;
; Arguments:
;
; On entry the stack looks like:
;
; [ss]
; [esp]
; eflags
; cs
; eip
; ss:sp-> [error]
;
; The cpu saves the previous SS:ESP, eflags, and CS:EIP on
; the new stack if there was a privilege transition. If no
; privilege level transition occurred, then there is no
; saved SS:ESP.
;
; Some exceptions save an error code, others do not.
;
; Return Value:
;
; None.
;
;--
page , 132
subttl "Macro to dispatch exception"
;++
;
; Macro Description:
;
; This macro allocates exception record on stack, sets up exception
; record using specified parameters and finally sets up arguments
; and calls _KiDispatchException.
;
; Arguments:
;
; ExcepCode - Exception code to put into exception record
; ExceptFlags - Exception flags to put into exception record
; ExceptRecord - Associated exception record
; ExceptAddress - Addr of instruction which the hardware exception occurs
; NumParms - Number of additional parameters
; ParameterList - the additional parameter list
;
; Return Value:
;
; None.
;
;--
DISPATCH_EXCEPTION macro ExceptCode, ExceptFlags, ExceptRecord, ExceptAddress,\
NumParms, ParameterList
local de10, de20
.FPO ( ExceptionRecordSize/4+NumParms, 0, 0, 0, 0, FPO_TRAPFRAME )
; Set up exception record for raising exception
?i = 0
sub esp, ExceptionRecordSize + NumParms * 4
; allocate exception record
mov dword ptr [esp]+ErExceptionCode, ExceptCode
; set up exception code
mov dword ptr [esp]+ErExceptionFlags, ExceptFlags
; set exception flags
mov dword ptr [esp]+ErExceptionRecord, ExceptRecord
; set associated exception record
mov dword ptr [esp]+ErExceptionAddress, ExceptAddress
mov dword ptr [esp]+ErNumberParameters, NumParms
; set number of parameters
IRP z, <ParameterList>
mov dword ptr [esp]+(ErExceptionInformation+?i*4), z
?i = ?i + 1
ENDM
; set up arguments and call _KiDispatchException
mov ecx, esp ; (ecx)->exception record
mov eax,[ebp]+TsSegCs
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jz de10
mov eax,0FFFFh
de10: and eax,MODE_MASK
; 1 - first chance TRUE
; eax - PreviousMode
; ebp - trap frame addr
; 0 - Null exception frame
; ecx - exception record addr
; dispatchexception as appropriate
stdCall _KiDispatchException, <ecx, 0, ebp, eax, 1>
mov esp, ebp ; (esp) -> trap frame
ENDM
page , 132
subttl "dispatch exception"
;++
;
; CommonDispatchException
;
; Routine Description:
;
; This routine allocates exception record on stack, sets up exception
; record using specified parameters and finally sets up arguments
; and calls _KiDispatchException.
;
; NOTE:
;
; The purpose of this routine is to save code space. Use this routine
; only if:
; 1. ExceptionRecord is NULL
; 2. ExceptionFlags is 0
; 3. Number of parameters is less or equal than 3.
;
; Otherwise, you should use DISPATCH_EXCEPTION macro to set up your special
; exception record.
;
; Arguments:
;
; (eax) = ExcepCode - Exception code to put into exception record
; (ebx) = ExceptAddress - Addr of instruction which the hardware exception occurs
; (ecx) = NumParms - Number of additional parameters
; (edx) = Parameter1
; (esi) = Parameter2
; (edi) = Parameter3
;
; Return Value:
;
; None.
;
;--
CommonDispatchException0Args:
xor ecx, ecx ; zero arguments
call CommonDispatchException
CommonDispatchException1Arg0d:
xor edx, edx ; zero edx
CommonDispatchException1Arg:
mov ecx, 1 ; one argument
call CommonDispatchException ; there is no return
CommonDispatchException2Args0d:
xor edx, edx ; zero edx
CommonDispatchException2Args:
mov ecx, 2 ; two arguments
call CommonDispatchException ; there is no return
public CommonDispatchException
align dword
CommonDispatchException proc
cPublicFpo 0, ExceptionRecordLength/4
;
; Set up exception record for raising exception
;
sub esp, ExceptionRecordLength
; allocate exception record
mov dword ptr [esp]+ErExceptionCode, eax
; set up exception code
xor eax, eax
mov dword ptr [esp]+ErExceptionFlags, eax
; set exception flags
mov dword ptr [esp]+ErExceptionRecord, eax
; set associated exception record
mov dword ptr [esp]+ErExceptionAddress, ebx
mov dword ptr [esp]+ErNumberParameters, ecx
; set number of parameters
cmp ecx, 0
je short de00
lea ebx, [esp + ErExceptionInformation]
mov [ebx], edx
mov [ebx+4], esi
mov [ebx+8], edi
de00:
;
; set up arguments and call _KiDispatchException
;
mov ecx, esp ; (ecx)->exception record
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jz short de10
mov eax,0FFFFh
jmp short de20
de10: mov eax,[ebp]+TsSegCs
de20: and eax,MODE_MASK
; 1 - first chance TRUE
; eax - PreviousMode
; ebp - trap frame addr
; 0 - Null exception frame
; ecx - exception record addr
stdCall _KiDispatchException,<ecx, 0, ebp, eax, 1>
mov esp, ebp ; (esp) -> trap frame
jmp _KiExceptionExit
CommonDispatchException endp
page , 132
subttl "Macro to verify base trap frame"
;++
;
; Macro Description:
;
; This macro verifies the base trap frame is intact.
;
; It is possible while returning to UserMode that we take an exception.
; Any exception which may block, such as not-present, needs to verify
; that the base trap frame is not partially dismantled.
;
; Arguments:
; The macro MUST be used directly after ENTER_TRAP macro
; as it assumes all sorts of stuff about ESP!
;
; Return Value:
;
; If the base frame was incomplete it is totally restored and the
; return EIP of the current frame is (virtually) backed up to the
; beginning of the exit_all - the effect is that the base frame
; will be completely exited again. (ie, the exit_all of the base
; frame is atomic, if it's interrupted we restore it and do it over).
;
; None.
;
;--
MODIFY_BASE_TRAP_FRAME macro
local vbfdone
mov edi, PCR[PcPrcbData+PbCurrentThread] ; Get current thread
lea eax, [esp]+KTRAP_FRAME_LENGTH + NPX_FRAME_LENGTH ; adjust for base frame
sub eax, [edi].ThInitialStack ; Bias out this stack
je short vbfdone ; if eq, then this is the base frame
cmp eax, -TsEflags ; second frame is only this big
jc short vbfdone ; is stack deeper then 2 frames?
; yes, then done
;
; Stack usage is not exactly one frame, and it's not large enough
; to be two complete frames; therefore, we may have a partial base
; frame. (unless it's a kernel thread)
;
; See if this is a kernel thread as kernel threads don't have a base
; frame (and therefore don't need correcting).
;
mov eax, PCR[PcTeb]
or eax, eax ; Any Teb?
jle short vbfdone ; Br if zero or kernel thread address
call KiRestoreBaseFrame
align 4
vbfdone:
ENDM
;++ KiRestoreBaseFrame
;
; Routine Description:
;
; Only to be used from MODIFY_BASE_TRAP_FRAME macro.
; Makes lots of assumptions about esp & trap frames
;
; Arguments:
;
; Stack:
; +-------------------------+
; | |
; | |
; | Npx save area |
; | |
; | |
; +-------------------------+
; | (possible mvdm regs) |
; +-------------------------+ <- PCR[PcInitialStack]
; | |
; | Partial base trap frame |
; | |
; | ------------+
; +------------/ | <- Esp @ time of current frame. Location
; | | where base trap frame is incomplete
; | Completed 'current' |
; | trap frame |
; | |
; | |
; | |
; | |
; +-------------------------+ <- EBP
; | return address (dword) |
; +-------------------------+ <- current ESP
; | |
; | |
;
; Return:
;
; Stack:
; +-------------------------+
; | |
; | |
; | Npx save area |
; | |
; | |
; +-------------------------+
; | (possible mvdm regs) |
; +-------------------------+ <- PCR[PcInitialStack]
; | |
; | Base trap frame |
; | |
; | |
; | |
; | |
; | |
; +-------------------------+ <- return esp & ebp
; | |
; | Current trap frame |
; | | EIP set to beginning of
; | | exit_all code
; | |
; | |
; | |
; +-------------------------+ <- EBP, ESP
; | |
; | |
;
;--
KiRestoreBaseFrame proc
pop ebx ; Get return address
IF DBG
mov eax, [esp].TsEip ; EIP of trap
;
; This code is to handle a very specific problem of a not-present
; fault during an exit_all. If it's not this problem then stop.
;
cmp word ptr [eax], POP_GS
je short @f
cmp byte ptr [eax], POP_ES
je short @f
cmp byte ptr [eax], POP_DS
je short @f
cmp word ptr [eax], POP_FS
je short @f
cmp byte ptr [eax], IRET_OP
je short @f
int 3
@@:
ENDIF
;
; Move current trap frame out of the way to make space for
; a full base trap frame
;
mov eax, PCR[PcPrcbData+PbCurrentThread] ; Get current thread
mov edi, [eax].ThInitialStack
sub edi, NPX_FRAME_LENGTH + KTRAP_FRAME_LENGTH + TsEFlags + 4 ; (edi) = bottom of target
mov esi, esp ; (esi) = bottom of source
mov esp, edi ; make space before copying the data
mov ebp, edi ; update location of our trap frame
push ebx ; put return address back on stack
mov ecx, (TsEFlags+4)/4 ; # of dword to move
rep movsd ; Move current trap frame
;
; Part of the base frame was destroyed when the current frame was
; originally pushed. Now that the current frame has been moved out of
; the way restore the base frame. We know that any missing data from
; the base frame was reloaded into it's corresponding registers which
; were then pushed into the current frame. So we can restore the missing
; data from the current frame.
;
mov ecx, esi ; Location of esp at time of fault
mov edi, [eax].ThInitialStack
sub edi, NPX_FRAME_LENGTH + KTRAP_FRAME_LENGTH ; (edi) = base trap frame
mov ebx, edi
sub ecx, edi ; (ecx) = # of bytes which were
; removed from base frame before
; trap occured
IF DBG
test ecx, 3
jz short @f ; assume dword alignments only
int 3
@@:
ENDIF
mov esi, ebp ; (esi) = current frame
shr ecx, 2 ; copy in dwords
rep movsd
;
; The base frame is restored. Instead of backing EIP up to the
; start of the interrupted EXIT_ALL, we simply move the EIP to a
; well known EXIT_ALL. However, this causes a couple of problems
; since this exit_all restores every register whereas the original
; one may not. So:
;
; - When exiting from a system call, eax is normally returned by
; simply not restoring it. We 'know' that the current trap frame's
; EAXs is always the correct one to return. (We know this because
; exit_all always restores eax (if it's going to) before any other
; instruction which may cause a fault).
;
; - Not all enter's push the PreviousPreviousMode. Since this is
; the base trap frame we know that this must be UserMode.
;
mov eax, [ebp].TsEax ; make sure correct
mov [ebx].TsEax, eax ; eax is in base frame
mov byte ptr [ebx].TsPreviousPreviousMode, 1 ; UserMode
mov [ebp].TsEbp, ebx
mov [ebp].TsEip, offset _KiServiceExit2 ; ExitAll which
; restores everything
;
; Since we backed up Eip we need to reset some of the kernel selector
; values in case they were already restored by the attempted base frame pop
;
mov dword ptr [ebp].TsSegDs, KGDT_R3_DATA OR RPL_MASK
mov dword ptr [ebp].TsSegEs, KGDT_R3_DATA OR RPL_MASK
mov dword ptr [ebp].TsSegFs, KGDT_R0_PCR
;
; The backed up EIP is before interrupts were disabled. Re-enable
; interrupts for the current trap frame
;
or [ebp].TsEFlags, EFLAGS_INTERRUPT_MASK
ret
KiRestoreBaseFrame endp
page ,132
subttl "Divide error processing"
;++
;
; Routine Description:
;
; Handle divide error fault.
;
; The divide error fault occurs if a DIV or IDIV instructions is
; executed with a divisor of 0, or if the quotient is too big to
; fit in the result operand.
;
; An INTEGER DIVIDED BY ZERO exception will be raised for the fault.
; If the fault occurs in kernel mode, the system will be terminated.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction.
; No error code is provided with the divide error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit0_a, kit0_t,NoAbiosAssist
align dword
public _KiTrap00
_KiTrap00 proc
push 0 ; push dummy error code
ENTER_TRAP kit0_a, kit0_t
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt0040 ; trap occured in V86 mode
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz short Kt0000
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne Kt0020
;
; Set up exception record for raising Integer_Divided_by_zero exception
; and call _KiDispatchException
;
Kt0000:
if DBG
test [ebp]+TsEFlags, EFLAGS_INTERRUPT_MASK ; faulted with
jnz short @f ; interrupts disabled?
xor eax, eax
mov esi, [ebp]+TsEip ; [esi] = faulting instruction
stdCall _KeBugCheck2,<IRQL_NOT_LESS_OR_EQUAL,eax,-1,eax,esi,ebp>
@@:
endif
sti
;
; Flat mode
;
; The intel processor raises a divide by zero exception on DIV instructions
; which overflow. To be compatible with other processors we want to
; return overflows as such and not as divide by zero's. The operand
; on the div instruction is tested to see if it's zero or not.
;
stdCall _Ki386CheckDivideByZeroTrap,<ebp>
mov ebx, [ebp]+TsEip ; (ebx)-> faulting instruction
jmp CommonDispatchException0Args ; Won't return
Kt0010:
;
; 16:16 mode
;
sti
mov ebx, [ebp]+TsEip ; (ebx)-> faulting instruction
mov eax, STATUS_INTEGER_DIVIDE_BY_ZERO
jmp CommonDispatchException0Args ; never return
Kt0020:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt0010
Kt0040:
stdCall _Ki386VdmReflectException_A, <0>
or al,al
jz short Kt0010 ; couldn't reflect, gen exception
jmp _KiExceptionExit
_KiTrap00 endp
page ,132
subttl "Debug Exception"
;++
;
; Routine Description:
;
; Handle debug exception.
;
; The processor triggers this exception for any of the following
; conditions:
;
; 1. Instruction breakpoint fault.
; 2. Data address breakpoint trap.
; 3. General detect fault.
; 4. Single-step trap.
; 5. Task-switch breakpoint trap.
;
;
; Arguments:
;
; At entry, the values of saved CS and EIP depend on whether the
; exception is a fault or a trap.
; No error code is provided with the divide error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
align dword
;
; We branch here to handle a trap01 fromt he fast system call entry
; we need to propagate the trap bit to the return eflags etc and
; continue.
;
Kt0100: mov [ebp].TsEip, _KiFastCallEntry2
and dword ptr [ebp].TsEflags, NOT EFLAGS_TF
jmp _KiExceptionExit ; join common code
ENTER_DR_ASSIST kit1_a, kit1_t, NoAbiosAssist
align dword
public _KiTrap01
_KiTrap01 proc
; Set up machine state frame for displaying
push 0 ; push dummy error code
ENTER_TRAP kit1_a, kit1_t
;
; Inspect old EIP in case this is a single stepped
; sysenter instruction.
;
mov ecx, [ebp]+TsEip
cmp ecx, _KiFastCallEntry
je Kt0100
;
; See if were doing the fast bop optimization of touching user memory
; with ints disabled. If we are then ignore data breakpoints.
;
;
if FAST_BOP
cmp dword ptr PCR[PcVdmAlert], 0
jne Kt01VdmAlert
endif
;
; If caller is user mode, we want interrupts back on.
; . all relevant state has already been saved
; . user mode code always runs with ints on
;
; If caller is kernel mode, we want them off!
; . some state still in registers, must prevent races
; . kernel mode code can run with ints off
;
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz kit01_30 ; fault occured in V86 mode => Usermode
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs,MODE_MASK
jz kit01_10
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne kit01_30
kit01_05:
sti
kit01_10:
;
; Set up exception record for raising single step exception
; and call _KiDispatchException
;
kit01_20:
and dword ptr [ebp]+TsEflags, not EFLAGS_TF
mov ebx, [ebp]+TsEip ; (ebx)-> faulting instruction
mov eax, STATUS_SINGLE_STEP
jmp CommonDispatchException0Args ; Never return
kit01_30:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je kit01_05
stdCall _Ki386VdmReflectException_A, <01h>
test ax,0FFFFh
jz Kit01_20
jmp _KiExceptionExit
if FAST_BOP
Kt01VdmAlert:
;
; If a DEBUG trap occured while we are in VDM alert mode (processing
; v86 trap without building trap frame), we will restore all the
; registers and return to its recovery routine.
;
mov eax, PCR[PcVdmAlert]
mov dword ptr PCR[PcVdmAlert], 0
mov [ebp].TsEip, eax
mov esp,ebp ; (esp) -> trap frame
jmp _KiExceptionExit ; join common code
endif ; FAST_BOP
_KiTrap01 endp
page ,132
subttl "Nonmaskable Interrupt"
;++
;
; Routine Description:
;
; Handle Nonmaskable interrupt.
;
; An NMI is typically used to signal serious system conditions
; such as bus time-out, memory parity error, and so on.
;
; Upon detection of the NMI, the system will be terminated, ie a
; bugcheck will be raised, no matter what previous mode is.
;
; Arguments:
;
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
; ENTER_DR_ASSIST kit2_a, kit2_t, NoAbiosAssist
align dword
public _KiTrap02
_KiTrap02 proc
.FPO (1, 0, 0, 0, 0, 2)
cli
;
; Set CR3, the I/O map base address, and LDT segment selector
; in the old TSS since they are not set on context
; switches. These values will be needed to return to the
; interrupted task.
mov eax, PCR[PcTss] ; get old TSS address
mov ecx, PCR[PcPrcbData+PbCurrentThread] ; get thread address
mov edi, [ecx].ThApcState.AsProcess ; get process address
mov ecx, [edi]+PrDirectoryTableBase ; get directory base
mov [eax]+TssCR3, ecx ; set previous cr3
mov cx, [edi]+PrIopmOffset ; get IOPM offset
mov [eax]+TssIoMapBase, cx ; set IOPM offset
mov ecx, [edi]+PrLdtDescriptor ; get LDT descriptor
test ecx, ecx ; does task use LDT?
jz @f
mov cx, KGDT_LDT
@@: mov [eax]+TssLDT, cx ; set LDT into old TSS
;
; Update the TSS pointer in the PCR to point to the NMI TSS
; (which is what we're running on, or else we wouldn't be here)
;
push dword ptr PCR[PcTss]
mov eax, PCR[PcGdt]
mov ch, [eax+KGDT_NMI_TSS+KgdtBaseHi]
mov cl, [eax+KGDT_NMI_TSS+KgdtBaseMid]
shl ecx, 16
mov cx, [eax+KGDT_NMI_TSS+KgdtBaseLow]
mov PCR[PcTss], ecx
;
; Clear Nested Task bit in EFLAGS
;
pushfd
and [esp], not 04000h
popfd
;
; Clear the busy bit in the TSS selector
;
mov ecx, PCR[PcGdt]
lea eax, [ecx] + KGDT_NMI_TSS
mov byte ptr [eax+5], 089h ; 32bit, dpl=0, present, TSS32, not busy
;
; Allow only one processor at a time to enter the NMI path. While
; waiting, spin on a LOCAL data structure (to avoid cache thrashing
; during a crashdump which can cause the dump to hang), and poll for
; Freeze IPI requests so that the correct state for this processor
; appears in the crashdump.
;
;
; (1) make a trap frame,
; (2) acquire lock
; (3) while not lock owner
; (4) if (IPI_FREEZE)
; (5) KeFreezeExecutionTarget(&TrapFrame, NULL)
; (6) let the HAL have it
; (7) release lock to next in line
;
; Build trap frame from the data in the previous TSS.
;
mov eax, [esp] ; get saved TSS address
push 0 ; build trap frame, starting with
push 0 ; faked V86Gs thru V86Es
push 0
push 0
push [eax].TssSs ; copy fields from TSS to
push [eax].TssEsp ; trap frame.
push [eax].TssEflags
push [eax].TssCs
push [eax].TssEip
push 0
push [eax].TssEbp
push [eax].TssEbx
push [eax].TssEsi
push [eax].TssEdi
push [eax].TssFs
push PCR[PcExceptionList]
push -1 ; previous mode
push [eax].TssEax
push [eax].TssEcx
push [eax].TssEdx
push [eax].TssDs
push [eax].TssEs
push [eax].TssGs
push 0 ; fake out the debug registers
push 0
push 0
push 0
push 0
push 0
push 0 ; temp ESP
push 0 ; temp CS
push 0
push 0
push [eax].TssEip
push [eax].TssEbp
mov ebp, esp ; ebp -> TrapFrame
stdCall _KiSaveProcessorState, <ebp, 0> ; save processor state
.FPO ( 0, 0, 0, 0, 0, FPO_TRAPFRAME )
stdCall _KiHandleNmi ; Rundown the list of NMI handlers
or al, al ; did someone handle it?
jne short Kt02100 ; jif handled
;
; In the UP case, jump to the recursive NMI processing code if this is a
; nested NMI.
;
; In the MP case, attempt to acquire the NMI lock, checking for freeze
; execution in case another processor is trying to dump memory. We need
; a special check here to jump to the recursive NMI processing code if
; we're already the owner of the NMI lock.
;
ifdef NT_UP
cmp ds:KiNMIRecursionCount, 0
jne short Kt0260
else
;
; Check if we recursed out of the HAL and back into the NMI handler.
;
xor ebx, ebx
mov bl, PCR[PcNumber] ; extend processor number to 32 bits
cmp ds:KiNMIOwner, ebx ; check against the NMI lock owner
je short Kt0260 ; go handle nested NMI if needed
;
; We aren't dealing with a recursive NMI out of the HAL, so try to acquire the
; NMI lock.
;
lea eax, KiLockNMI ; build in stack queued spin lock.
push eax
push 0
mov ecx, esp
mov edx, ebp
fstCall KiAcquireQueuedSpinLockCheckForFreeze
endif
jmp short Kt0280
;
; The processor will hold off nested NMIs until an iret instruction is
; executed or until we enter and leave SMM mode. There is exposure in this
; second case because the processor doesn't save the "NMI disabled" indication
; along with the rest of the processor state in the SMRAM save state map. As
; a result, it unconditionally enables NMIs when leaving SMM mode.
;
; This means that we're exposed to nested NMIs in the following cases.
;
; 1) When the HAL issues an iret to enter the int 10 BIOS code needed to print
; an error message to the screen.
;
; 2) When the NMI handler is preempted by a BIOS SMI.
;
; 3) When we take some kind of exception from the context of the NMI handler
; (e.g. due to a debugger breakpoint) and automatically run an iret when
; exiting the exception handler.
;
; Case (3) isn't of concern since the NMI handler shouldn't be raising
; exceptions except when being debugged.
;
; For (2), NMIs can become "unmasked" while in SMM mode if the SMM code
; actually issues an iret instruction, meaning they may actually occur
; before the SMI handler exits. We assume that these NMIs will be handled by
; the SMM code. After the SMI handler exits, NMIs will be "unmasked" and
; we'll continue in the NMI handler, running on the NMI TSS. If a nested NMI
; comes in at this point, it will be dispatched using the following sequence.
;
; a) The NMI sends us through a task gate, causing a task switch from the
; NMI TSS back onto itself.
;
; b) The processor saves the current execution context in the old TSS.
; This is the NMI TSS in our case.
;
; c) The processor sets up the exception handler context by loading the
; contents of the new TSS. Since this is also the NMI TSS, we'll just
; reload our interrupted context and keep executing as if nothing had
; happened.
;
; The only side effect of this "invisible" NMI is that the backlink field of
; the NMI TSS will be stomped, meaning the link to the TSS containing our
; interrupted context is broken.
;
; In case (1), the NMI isn't invisible since the HAL will "borrow" the
; KGDT_TSS before issuing the iret. It does this when it finds that the NMI
; TSS doesn't contain space for an IOPM. Due to "borrowing" the TSS, the
; nested NMI will put us back at the top of this NMI handler. We've again
; lost touch with the original interrupted context since the NMI TSS backlink
; now points to a TSS containing the state of the interrupted HAL code.
;
; To increase the chances of displaying a blue screen in the presence of
; hardware that erroneously generates multiple NMIs, we reenter the HAL NMI
; handler in response to the first few NMIs fitting into case (1). Once the
; number of nested NMIs exceeds an arbitrarily chosen threshold value, we
; decide that we're seeing an "NMI storm" of sorts and go into a tight loop.
; We can't bugcheck the system directly since this will invoke the same HAL
; int 10 code that allowed us to keep looping through this routine in the
; first place.
;
; The only other case where this handler needs to explicitly account for
; nested NMIs is to avoid exiting the handler when our original interrupted
; context has been lost as will happen in cases (2) and (3).
;
KI_NMI_RECURSION_LIMIT equ 8
Kt0260:
cmp ds:KiNMIRecursionCount, KI_NMI_RECURSION_LIMIT
jb short Kt0280
;
; When we first hit the recursion limit, take a shot at entering the debugger.
; Go into a tight loop if this somehow causes additional recursion.
;
jne short Kt0270
cmp _KdDebuggerNotPresent, 0
jne short Kt0270
cmp _KdDebuggerEnabled, 0
je short Kt0270
stdCall _KeEnterKernelDebugger
Kt0270:
jmp short Kt0270
;
; This processor now owns the NMI lock. See if the HAL will handle the NMI.
; If the HAL does not handle it, it will NOT return, so if we get back here,
; it's handled.
;
; Before handing off to the HAL, set the NMI owner field and increment the NMI
; recursion count so we'll be able to properly handle cases where we recurse
; out of the HAL back into the NMI handler.
;
Kt0280:
ifndef NT_UP
mov ds:KiNMIOwner, ebx
endif
inc ds:KiNMIRecursionCount
stdCall _HalHandleNMI,<0>
;
; We're back, therefore the Hal has dealt with the NMI. Clear the NMI owner
; flag, decrement the NMI recursion count, and release the NMI lock.
;
; As described above, we can't safely resume execution if we're running in the
; context of a nested NMI. Bugcheck the machine if the NMI recursion counter
; indicates that this is the case.
;
dec ds:KiNMIRecursionCount
jnz Kt02200
ifndef NT_UP
mov ds:KiNMIOwner, KI_NMI_UNOWNED
mov ecx, esp ; release queued spinlock.
fstCall KeReleaseQueuedSpinLockFromDpcLevel
add esp, 8 ; free queued spinlock context
endif
Kt02100:
;
; As described in the comments above, we can experience "invisible" nested
; NMIs whose only effect will be pointing the backlink field of the NMI TSS
; to itself. Our interrupted context is gone in these cases so we can't leave
; this exception handler if we find a self referencing backlink. The backlink
; field is found in the first 2 bytes of the TSS structure.
;
; N.B. This still leaves a window where an invisible NMI can cause us to iret
; back onto the NMI TSS. The busy bit of the NMI TSS will be cleared on
; the first iret, which will lead to a general protection fault when we
; try to iret back into the NMI TSS (iret expects the targeted task to be
; marked "busy").
;
mov eax, PCR[PcTss]
cmp word ptr [eax], KGDT_NMI_TSS ; check for a self reference
je Kt02200
add esp, KTRAP_FRAME_LENGTH ; free trap frame
pop dword ptr PCR[PcTss] ; restore PcTss
mov ecx, PCR[PcGdt]
lea eax, [ecx] + KGDT_TSS
mov byte ptr [eax+5], 08bh ; 32bit, dpl=0, present, TSS32, *busy*
pushfd ; Set Nested Task bit in EFLAGS
or [esp], 04000h ; so iretd will do a task switch
popfd
iretd ; Return from NMI
jmp _KiTrap02 ; in case we NMI again
;
; We'll branch here if we need to bugcheck the machine directly.
;
Kt02200:
mov eax, EXCEPTION_NMI
jmp _KiSystemFatalException
_KiTrap02 endp
page ,132
subttl "DebugService Breakpoint"
;++
;
; Routine Description:
;
; Handle INT 2d DebugService
;
; The trap is caused by an INT 2d. This is used instead of a
; BREAKPOINT exception so that parameters can be passed for the
; requested debug service. A BREAKPOINT instruction is assumed
; to be right after the INT 2d - this allows this code to share code
; with the breakpoint handler.
;
; Arguments:
; eax - ServiceClass - which call is to be performed
; ecx - Arg1 - generic first argument
; edx - Arg2 - generic second argument
; ebx - Arg3 - generic third argument
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kids_a, kids_t, NoAbiosAssist
align dword
public _KiDebugService
_KiDebugService proc
push 0 ; push dummy error code
ENTER_TRAP kids_a, kids_t
; sti ; *NEVER sti here*
inc dword ptr [ebp]+TsEip
mov eax, [ebp]+TsEax ; ServiceClass
mov ecx, [ebp]+TsEcx ; Arg1 (already loaded)
mov edx, [ebp]+TsEdx ; Arg2 (already loaded)
jmp KiTrap03DebugService
_KiDebugService endp
page ,132
subttl "Single Byte INT3 Breakpoin"
;++
;
; Routine Description:
;
; Handle INT 3 breakpoint.
;
; The trap is caused by a single byte INT 3 instruction. A
; BREAKPOINT exception with additional parameter indicating
; READ access is raised for this trap if previous mode is user.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the instruction immediately
; following the INT 3 instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit3_a, kit3_t, NoAbiosAssist
align dword
public _KiTrap03
_KiTrap03 proc
push 0 ; push dummy error code
ENTER_TRAP kit3_a, kit3_t
cmp ds:_PoHiberInProgress, 0
jnz short kit03_01
lock inc ds:_KiHardwareTrigger ; trip hardware analyzer
kit03_01:
mov eax, BREAKPOINT_BREAK
KiTrap03DebugService:
;
; If caller is user mode, we want interrupts back on.
; . all relevant state has already been saved
; . user mode code always runs with ints on
;
; If caller is kernel mode, we want them off!
; . some state still in registers, must prevent races
; . kernel mode code can run with ints off
;
;
; Arguments:
; eax - ServiceClass - which call is to be performed
; ecx - Arg1 - generic first argument
; edx - Arg2 - generic second argument
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz kit03_30 ; fault occured in V86 mode => Usermode
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs,MODE_MASK
jz kit03_10
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne kit03_30
kit03_05:
sti
kit03_10:
;
; Set up exception record and arguments for raising breakpoint exception
;
mov esi, ecx ; ExceptionInfo 2
mov edi, edx ; ExceptionInfo 3
mov edx, eax ; ExceptionInfo 1
mov ebx, [ebp]+TsEip
dec ebx ; (ebx)-> int3 instruction
mov ecx, 3
mov eax, STATUS_BREAKPOINT
call CommonDispatchException ; Never return
kit03_30:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je kit03_05
stdCall _Ki386VdmReflectException_A, <03h>
test ax,0FFFFh
jz Kit03_10
jmp _KiExceptionExit
_KiTrap03 endp
page ,132
subttl "Integer Overflow"
;++
;
; Routine Description:
;
; Handle INTO overflow.
;
; The trap occurs when the processor encounters an INTO instruction
; and the OF flag is set.
;
; An INTEGER_OVERFLOW exception will be raised for this fault.
;
; N.B. i386 will not generate fault if only OF flag is set.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the instruction immediately
; following the INTO instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit4_a, kit4_t, NoAbiosAssist
align dword
public _KiTrap04
_KiTrap04 proc
push 0 ; push dummy error code
ENTER_TRAP kit4_a, kit4_t
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz short Kt0430 ; in a vdm, reflect to vdm
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs,MODE_MASK
jz short Kt0410 ; in kernel mode, gen exception
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne short Kt0420 ; maybe in a vdm
; Set up exception record and arguments for raising exception
Kt0410: sti
mov ebx, [ebp]+TsEip ; (ebx)-> instr. after INTO
dec ebx ; (ebx)-> INTO
mov eax, STATUS_INTEGER_OVERFLOW
jmp CommonDispatchException0Args ; Never return
Kt0430:
stdCall _Ki386VdmReflectException_A, <04h>
test al,0fh
jz Kt0410 ; couldn't reflect, gen exception
jmp _KiExceptionExit
Kt0420:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt0410
jmp Kt0430
_KiTrap04 endp
page ,132
subttl "Bound Check fault"
;++
;
; Routine Description:
;
; Handle bound check fault.
;
; The bound check fault occurs if a BOUND instruction finds that
; the tested value is outside the specified range.
;
; For bound check fault, an ARRAY BOUND EXCEEDED exception will be
; raised.
; For kernel mode exception, it causes system to be terminated.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting BOUND
; instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit5_a, kit5_t, NoAbiosAssist
align dword
public _KiTrap05
_KiTrap05 proc
push 0 ; push dummy error code
ENTER_TRAP kit5_a, kit5_t
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz short Kt0530 ; fault in V86 mode
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jnz short Kt0500 ; if nz, previous mode = user
mov eax, EXCEPTION_BOUND_CHECK ; (eax) = exception type
jmp _KiSystemFatalException ; go terminate the system
kt0500: cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne short Kt0520 ; maybe in a vdm
;
; set exception record and arguments and call _KiDispatchException
;
Kt0510: sti
mov ebx, [ebp]+TsEip ; (ebx)->BOUND instruction
mov eax, STATUS_ARRAY_BOUNDS_EXCEEDED
jmp CommonDispatchException0Args ; Won't return
Kt0520:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt0510
Kt0530:
stdCall _Ki386VdmReflectException_A, <05h>
test al,0fh
jz Kt0510 ; couldn't reflect, gen exception
jmp _KiExceptionExit
_KiTrap05 endp
page ,132
subttl "Invalid OP code"
;++
;
; Routine Description:
;
; Handle invalid op code fault.
;
; The invalid opcode fault occurs if CS:EIP point to a bit pattern which
; is not recognized as an instruction by the x86. This may happen if:
;
; 1. the opcode is not a valid 80386 instruction
; 2. a register operand is specified for an instruction which requires
; a memory operand
; 3. the LOCK prefix is used on an instruction that cannot be locked
;
; If fault occurs in USER mode:
; an Illegal_Instruction exception will be raised
; if fault occurs in KERNEL mode:
; system will be terminated.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the first byte of the invalid
; instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:FLAT, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit6_a, kit6_t, NoAbiosAssist,, kit6_v
align dword
public _KiTrap06
_KiTrap06 proc
;
; KiTrap06 is performance critical for VDMs and rarely executed in
; native mode. So this routine is tuned for the VDM case.
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esp]+8h+2,EFLAGS_V86_MASK/010000h
jz Kt060i
if FAST_BOP
FAST_V86_TRAP_6
endif
Kt6SlowBop:
push 0 ; push dummy error code
ENTER_TRAPV86 kit6_a, kit6_v
Kt6SlowBop1:
Kt06VMpf:
;
; If the current process is NOT a VDM just hand it an
; illegal instruction exception.
;
mov ecx,PCR[PcPrcbData+PbCurrentThread]
mov ecx,[ecx]+ThApcState+AsProcess
cmp dword ptr [ecx]+PrVdmObjects,0 ; if not a vdm process,
je Kt0635 ; then deliver exception
;
; Raise Irql to APC level before enabling interrupts to prevent
; a setcontext from editing the trapframe.
;
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
if DBG
cmp eax, PASSIVE_LEVEL
je @f
int 3
@@:
endif
sti
;
; Call VdmDispatchBop to try and handle the opcode immediately.
; If it returns FALSE (meaning too complicated for us to quickly parse)
; then reflect the opcode off to the ntvdm monitor to handle it.
;
stdCall _VdmDispatchBop, <ebp>
;
; If the operation was processed directly above then return back now.
;
test al,0fh
jnz short Kt061i
;
; The operation could not be processed directly above so reflect it
; back to the ntvdm monitor now.
;
stdCall _Ki386VdmReflectException,<6>
test al,0fh
jnz Kt061i
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp Kt0635
Kt061i:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
cli
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jz Kt062i
;
; EXIT_TRAPv86 does not exit if a user mode apc has switched
; the context from V86 mode to flat mode (VDM monitor context)
;
EXIT_TRAPV86
Kt062i:
jmp _KiExceptionExit
Kt060i:
;
; Non-v86 (user or kernel) executing code arrives here for
; invalid opcode traps.
;
push 0 ; Push dummy error code
ENTER_TRAP kit6_a, kit6_t
Kt06pf:
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz short Kt0635 ; if z, kernel mode - go dispatch exception
;
; UserMode. Did the fault happen in a vdm running in protected mode?
;
cmp word ptr [ebp]+TsSegCs, KGDT_R3_CODE OR RPL_MASK
jz short kt0605 ; normal 32-bit mode so give exception
;
; The code segment is not a normal flat 32-bit entity, so see if
; this process is a vdm. If so, then try to handle it. If not,
; give this process an exception.
;
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
jne Kt0650
kt0605:
;
; Invalid Opcode exception could be either INVALID_LOCK_SEQUENCE or
; ILLEGAL_INSTRUCTION.
;
mov esi, [ebp]+TsEip
sti
; This should be a completely valid user address, but for consistency
; it will be probed here.
cmp esi, _MmUserProbeAddress ; Probe captured EIP
jb short kt0606
mov esi, _MmUserProbeAddress ; Use bad user EIP to force exception
kt0606:
mov ecx, MAX_INSTRUCTION_PREFIX_LENGTH
;
; Set up an exception handler in case we fault
; while reading the user mode instruction.
;
push ebp ; pass trapframe to handler
push offset FLAT:Kt6_ExceptionHandler
; set up exception registration record
push PCR[PcExceptionList]
mov PCR[PcExceptionList], esp
; esi -> address of faulting instruction
@@:
mov al, byte ptr [esi] ; (al) = instruction byte
cmp al, MI_LOCK_PREFIX ; Is it a lock prefix?
je short Kt0640 ; Yes, raise Invalid_lock exception
add esi, 1
loop short @b ; keep on looping
pop PCR[PcExceptionList]
add esp, 8 ; clear stack
Kt0630:
;
; Set up exception record for raising Illegal instruction exception
;
Kt0635:
sti
mov ebx, [ebp]+TsEip ; (ebx)-> invalid instruction
mov eax, STATUS_ILLEGAL_INSTRUCTION
jmp CommonDispatchException0Args ; Won't return
;
; Set up exception record for raising Invalid lock sequence exception
;
Kt0640:
pop PCR[PcExceptionList]
add esp, 8 ; clear stack
mov ebx, [ebp]+TsEip ; (ebx)-> invalid instruction
mov eax, STATUS_INVALID_LOCK_SEQUENCE
jmp CommonDispatchException0Args ; Won't return
Kt0650:
; Raise Irql to APC level before enabling interrupts
RaiseIrql APC_LEVEL
push eax ; SaveOldIrql
sti
stdCall _VdmDispatchBop, <ebp>
test al,0fh
jnz short Kt0660
stdCall _Ki386VdmReflectException,<6>
test al,0fh
jnz Kt0660
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp short Kt0635
Kt0660:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp _KiExceptionExit
_KiTrap06 endp
;
; Error and exception blocks for KiTrap06
;
Kt6_ExceptionHandler proc
;
; WARNING: Here we directly unlink the exception handler from the
; exception registration chain. NO unwind is performed.
;
mov esp, [esp+8] ; (esp)-> ExceptionList
pop PCR[PcExceptionList]
add esp, 4 ; pop out except handler
pop ebp ; (ebp)-> trap frame
test dword ptr [ebp].TsSegCs, MODE_MASK ; if premode=kernel
jnz Kt0630 ; nz, prevmode=user, go return
;
; Raise bugcheck if prevmode=kernel
;
stdCall _KeBugCheck2, <KMODE_EXCEPTION_NOT_HANDLED,0,0,0,0,ebp>
Kt6_ExceptionHandler endp
page ,132
subttl "Coprocessor Not Avalaible"
;++
;
; Routine Description:
;
; Handle Coprocessor not available exception.
;
; If we are REALLY emulating the FPU, the trap 07 vector is edited
; to point directly at the emulator's entry point. So this code is
; only hit when FPU hardware DOES exist.
;
; The current thread's coprocessor state is loaded into the
; coprocessor. If the coprocessor has a different thread's state
; in it (UP only) it is first saved away. The thread is then continued.
; Note: the thread's state may contain the TS bit - In this case the
; code loops back to the top of the Trap07 handler. (which is where
; we would end up if we let the thread return to user code anyway).
;
; If the thread's NPX context is in the coprocessor and we hit a Trap07
; there is an NPX error which needs to be processed. If the trap was
; from usermode the error is dispatched. If the trap was from kernelmode
; the error is remembered, but we clear CR0 so the kernel code can
; continue. We can do this because the kernel mode code will restore
; CR0 (and set TS) to signal a delayed error for this thread.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the first byte of the faulting
; instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit7_a, kit7_t, NoAbiosAssist
align dword
public _KiTrap07
_KiTrap07 proc
push 0 ; push dummy error code
ENTER_TRAP kit7_a, kit7_t
Kt0700:
mov eax, PCR[PcPrcbData+PbCurrentThread]
mov ecx, [eax].ThInitialStack ; (ecx) -> top of kernel stack
sub ecx, NPX_FRAME_LENGTH
.errnz (CR0_EM AND 0FFFFFF00h)
test byte ptr [ecx].FpCr0NpxState,CR0_EM
jnz Kt07140
Kt0701: cmp byte ptr [eax].ThNpxState, NPX_STATE_LOADED
mov ebx, cr0
je Kt0710
;
; Trap occured and this thread's NPX state is not loaded. Load it now
; and resume the application. If someone else's state is in the coprocessor
; (uniprocessor implementation only) then save it first.
;
and ebx, NOT (CR0_MP+CR0_TS+CR0_EM)
mov cr0, ebx ; allow frstor (& fnsave) to work
ifdef NT_UP
Kt0702:
mov edx, PCR[PcPrcbData+PbNpxThread] ; Owner of NPX state
or edx, edx ; NULL?
jz Kt0704 ; Yes - skip save
;
; Due to an hardware errata we need to know that the coprocessor
; doesn't generate an error condition once interrupts are disabled and
; trying to perform an fnsave which could wait for the error condition
; to be handled.
;
; The fix for this errata is that we "know" that the coprocessor is
; being used by a different thread then the one which may have caused
; the error condition. The round trip time to swap to a new thread
; is longer then ANY floating point instruction. We therefore know
; that any possible coprocessor error has already occured and been
; handled.
;
mov esi,[edx].ThInitialStack
sub esi, NPX_FRAME_LENGTH ; Space for NPX_FRAME
test byte ptr _KeI386FxsrPresent, 1 ; Is FXSR feature present
jz short Kt0703a
FXSAVE_ESI
jmp short Kt0703b
Kt0703a:
fnsave [esi] ; Save thread's coprocessor state
Kt0703b:
mov byte ptr [edx].ThNpxState, NPX_STATE_NOT_LOADED
Kt0704:
endif
;
; Load current thread's coprocessor state into the coprocessor
;
; (eax) - CurrentThread
; (ecx) - CurrentThread's NPX save area
; (ebx) - CR0
; (ebp) - trap frame
; Interrupts disabled
;
;
; frstor might generate a NPX exception if there's an error image being
; loaded. The handler will simply set the TS bit for this context an iret.
;
test byte ptr _KeI386FxsrPresent, 1 ; Is FXSR feature present
jz short Kt0704b
ifndef NT_UP
endif
FXRSTOR_ECX ; reload NPX context
jmp short Kt0704c
Kt0704b:
frstor [ecx] ; reload NPX context
Kt0704c:
mov byte ptr [eax].ThNpxState, NPX_STATE_LOADED
mov PCR[PcPrcbData+PbNpxThread], eax ; owner of coprocessors state
sti ; Allow interrupts & context switches
nop ; sti needs one cycle
cmp dword ptr [ecx].FpCr0NpxState, 0
jz _KiExceptionExit ; nothing to set, skip CR0 reload
;
; Note: we have to get the CR0 value again to ensure that we have the
; correct state for TS. We may have context switched since
; the last move from CR0, and our npx state may have been moved off
; of the npx.
;
cli
if DBG
test dword ptr [ecx].FpCr0NpxState, NOT (CR0_MP+CR0_EM+CR0_TS)
jnz short Kt07dbg1
endif
mov ebx,CR0
or ebx, [ecx].FpCr0NpxState
mov cr0, ebx ; restore thread's CR0 NPX state
sti
.errnz (CR0_TS AND 0FFFFFF00h)
test bl, CR0_TS ; Setting TS? (delayed error)
jz _KiExceptionExit ; No - continue
clts
cli ; Make sure interrupts disabled
jmp Kt0700 ; Dispatch delayed exception
if DBG
Kt07dbg1: int 3
Kt07dbg2: int 3
Kt07dbg3: int 3
sti
jmp short $-2
endif
Kt0705:
;
; A Trap07 or Trap10 has occured from a ring 0 ESCAPE instruction. This
; may occur when trying to load the coprocessors state. These
; code paths rely on Cr0NpxState to signal a delayed error (not CR0) - we
; set CR0_TS in Cr0NpxState to get a delayed error, and make sure CR0 CR0_TS
; is not set so the R0 ESC instruction(s) can complete.
;
; (ecx) - CurrentThread's NPX save area
; (ebp) - trap frame
; Interrupts disabled
;
if DBG
mov eax, cr0 ; Did we fault because some bit in CR0
test eax, (CR0_TS+CR0_MP+CR0_EM)
jnz short Kt07dbg3
endif
or dword ptr [ecx].FpCr0NpxState, CR0_TS ; signal a delayed error
cmp dword ptr [ebp]+TsEip, Kt0704b ; Is this fault on reload a thread's context?
jne short Kt0716 ; No, dispatch exception
add dword ptr [ebp]+TsEip, 3 ; Skip frstor ecx instruction
jmp _KiExceptionExit
; A floating point exception was just swallowed (instruction was of no-wait type).
Kt0709:
sti ; Re-enable interrupts
jmp _KiExceptionExit ; Already handled
Kt0710:
.errnz (CR0_TS AND 0FFFFFF00h)
test bl, CR0_TS ; check for task switch
jnz Kt07150
;
; WARNING: May enter here from the trap 10 handler.
; Expecting interrupts disabled.
;
Kt0715:
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt07110 ; v86 mode
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previousMode=USER?
jz Kt0705 ; if z, previousmode=SYSTEM
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne Kt07110
;
; We are about to dispatch a floating point exception to user mode.
; We need to check to see if the user's NPX instruction is supposed to
; cause an exception or not. Interrupts should be disabled.
;
; (ecx) - CurrentThread's NPX save area
;
Kt0716: stdCall _Ki386CheckDelayedNpxTrap,<ebp,ecx>
or al, al
jnz short Kt0709
Kt0719:
mov eax, PCR[PcPrcbData+PbCurrentThread]
; Since Ki386CheckDelayedNpxTrap toggled the interrupt state, the NPX state
; may no longer be resident.
cmp byte ptr [eax].ThNpxState, NPX_STATE_NOT_LOADED
mov ecx, [eax].ThInitialStack ; (ecx) -> top of kernel stack
lea ecx, [ecx-NPX_FRAME_LENGTH]
je Kt0726a
Kt0720:
;
; Some type of coprocessor exception has occured for the current thread.
;
; (eax) - CurrentThread
; (ecx) - CurrentThread's NPX save area
; (ebp) - TrapFrame
; Interrupts disabled
;
mov ebx, cr0
and ebx, NOT (CR0_MP+CR0_EM+CR0_TS)
mov cr0, ebx ; Clear MP+TS+EM to do fnsave & fwait
;
; Save the faulting state so we can inspect the cause of the floating
; point fault
;
test byte ptr _KeI386FxsrPresent, 1 ; Is FXSR feature present
jz short Kt0725a
FXSAVE_ECX
jmp short Kt0725b
Kt0725a:
fnsave [ecx] ; Save thread's coprocessor state
fwait ; in case fnsave hasn't finished yet
Kt0725b:
if DBG
test dword ptr [ecx].FpCr0NpxState, NOT (CR0_MP+CR0_EM+CR0_TS)
jnz Kt07dbg2
endif
or ebx, NPX_STATE_NOT_LOADED
or ebx,[ecx]+FpCr0NpxState ; restore this thread's CR0 NPX state
mov cr0, ebx ; set TS so next ESC access causes trap
;
; The state is no longer in the coprocessor. Clear ThNpxState and
; re-enable interrupts to allow context switching.
;
mov byte ptr [eax].ThNpxState, NPX_STATE_NOT_LOADED
mov dword ptr PCR[PcPrcbData+PbNpxThread], 0 ; No state in coprocessor
;
; Clear TS bit in Cr0NpxFlags in case it was set to trigger this trap.
;
Kt0726a:
and dword ptr [ecx].FpCr0NpxState, NOT CR0_TS
Kt0726b:
sti
;
; According to the floating error priority, we test what is the cause of
; the NPX error and raise an appropriate exception.
;
test byte ptr _KeI386FxsrPresent, 1 ; Is FXSR feature present
jz short Kt0727a
mov ebx, [ecx] + FxErrorOffset
movzx eax, word ptr [ecx] + FxControlWord
movzx edx, word ptr [ecx] + FxStatusWord
mov esi, [ecx] + FxDataOffset ; (esi) = operand addr
jmp short Kt0727b
Kt0727a:
mov ebx, [ecx] + FpErrorOffset
movzx eax, word ptr [ecx] + FpControlWord
movzx edx, word ptr [ecx] + FpStatusWord
mov esi, [ecx] + FpDataOffset ; (esi) = operand addr
Kt0727b:
and eax, FSW_INVALID_OPERATION + FSW_DENORMAL + FSW_ZERO_DIVIDE + FSW_OVERFLOW + FSW_UNDERFLOW + FSW_PRECISION
not eax ; ax = mask of enabled exceptions
and eax, edx
.errnz (FSW_INVALID_OPERATION AND 0FFFFFF00h)
test al, FSW_INVALID_OPERATION ; Is it an invalid op exception?
jz short Kt0740 ; if z, no, go Kt0740
.errnz (FSW_STACK_FAULT AND 0FFFFFF00h)
test al, FSW_STACK_FAULT ; Is it caused by stack fault?
jnz short Kt0730 ; if nz, yes, go Kt0730
; Raise Floating reserved operand exception
;
mov eax, STATUS_FLOAT_INVALID_OPERATION
jmp CommonDispatchException1Arg0d ; Won't return
Kt0730:
;
; Raise Access Violation exception for stack overflow/underflow
;
mov eax, STATUS_FLOAT_STACK_CHECK
jmp CommonDispatchException2Args0d ; Won't return
Kt0740:
; Check for floating zero divide exception
.errnz (FSW_ZERO_DIVIDE AND 0FFFFFF00h)
test al, FSW_ZERO_DIVIDE ; Is it a zero divide error?
jz short Kt0750 ; if z, no, go Kt0750
; Raise Floating divided by zero exception
mov eax, STATUS_FLOAT_DIVIDE_BY_ZERO
jmp CommonDispatchException1Arg0d ; Won't return
Kt0750:
; Check for denormal error
.errnz (FSW_DENORMAL AND 0FFFFFF00h)
test al, FSW_DENORMAL ; Is it a denormal error?
jz short Kt0760 ; if z, no, go Kt0760
; Raise floating reserved operand exception
mov eax, STATUS_FLOAT_INVALID_OPERATION
jmp CommonDispatchException1Arg0d ; Won't return
Kt0760:
; Check for floating overflow error
.errnz (FSW_OVERFLOW AND 0FFFFFF00h)
test al, FSW_OVERFLOW ; Is it an overflow error?
jz short Kt0770 ; if z, no, go Kt0770
; Raise floating overflow exception
mov eax, STATUS_FLOAT_OVERFLOW
jmp CommonDispatchException1Arg0d ; Won't return
Kt0770:
; Check for floating underflow error
.errnz (FSW_UNDERFLOW AND 0FFFFFF00h)
test al, FSW_UNDERFLOW ; Is it a underflow error?
jz short Kt0780 ; if z, no, go Kt0780
; Raise floating underflow exception
mov eax, STATUS_FLOAT_UNDERFLOW
jmp CommonDispatchException1Arg0d ; Won't return
Kt0780:
; Check for precision (IEEE inexact) error
.errnz (FSW_PRECISION AND 0FFFFFF00h)
test al, FSW_PRECISION ; Is it a precision error
jz short Kt07100 ; if z, no, go Kt07100
mov eax, STATUS_FLOAT_INEXACT_RESULT
jmp CommonDispatchException1Arg0d ; Won't return
Kt07100:
; If status word does not indicate error, then something is wrong...
;
; There is a known bug on Cyrix processors, up to and including
; the MII that causes Trap07 for no real reason (INTR is asserted
; during an FP instruction and is held high too long, we end up
; in the Trap07 handler with not exception set). Bugchecking seems
; a little heavy handed, if this is a Cyrix processor, just ignore
; the error.
cmp _KiIgnoreUnexpectedTrap07, 0
jnz _KiExceptionExit
; stop the system
sti
stdCall _KeBugCheck2, <TRAP_CAUSE_UNKNOWN,1,eax,0,0,ebp>
Kt07110:
; Check to see if this process is a vdm
mov eax,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[eax]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt0720 ; no, dispatch exception
Kt07130:
clts ; Turn off TS
and dword ptr [ecx]+FpCr0NpxState,NOT CR0_TS
; Reflect the exception to the vdm, the VdmHandler enables interrupts
; Raise Irql to APC level before enabling interrupts
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti
stdCall _VdmDispatchIRQ13, <ebp> ; ebp - Trapframe
test al,0fh
jnz Kt07135
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
; Could not reflect, generate exception.
;
; FP context may or may not still be loaded. If loaded, it needs to
; be saved now, if not loaded, skip save.
mov eax, PCR[PcPrcbData+PbCurrentThread]
mov ecx, [eax].ThInitialStack ; ecx -> top of kernel stack
sub ecx, NPX_FRAME_LENGTH ; ecx -> NPX save area
cli
cmp byte ptr [eax].ThNpxState, NPX_STATE_LOADED
je Kt0720 ; jif NPX state needs to be saved
jmp Kt0726b ; NPX state already saved
Kt07135:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp _KiExceptionExit
Kt07140:
;
; ensure that this is not an NPX instruction in the kernel. (If
; an app, such as C7, sets the EM bit after executing NPX instructions,
; the fsave in SwapContext will catch an NPX exception
;
cmp [ebp].TsSegCS, word ptr KGDT_R0_CODE
je Kt0701
;
; Check to see if it really is a VDM
;
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt07100
; A vdm is emulating NPX instructions on a machine with an NPX.
stdCall _Ki386VdmReflectException_A, <07h>
test al,0fh
jnz _KiExceptionExit
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov eax, STATUS_ACCESS_VIOLATION
mov esi, -1
jmp CommonDispatchException2Args0d ; Won't return
;
; If the processor took an NMI (or other task switch) CR0_TS will have
; been set. If this occured while the FP state was loaded it would
; appear that it is no longer valid. This is not actually true, the
; state is perfectly valid.
;
; Sanity: make sure CR0_MP is clear, if the OS had set CR0_TS, then
; CR0_MP should also be set.
;
Kt07150:
.errnz (CR0_MP AND 0FFFFFF00h)
test bl, CR0_MP
jnz short Kt07151
clts ; clear CR0_TS and continue
jmp _KiExceptionExit
Kt07151:
stdCall _KeBugCheck2, <TRAP_CAUSE_UNKNOWN,2,ebx,0,0,ebp>
jmp short Kt07151
_KiTrap07 endp
page ,132
subttl "Double Fault"
;++
;
; Routine Description:
;
; Handle double exception fault.
;
; Normally, when the processor detects an exception while trying to
; invoke the handler for a prior exception, the two exception can be
; handled serially. If, however, the processor cannot handle them
; serially, it signals the double-fault exception instead.
;
; If double exception is detected, no matter previous mode is USER
; or kernel, a bugcheck will be raised and the system will be terminated.
;
;
; Arguments:
;
; error code, which is always zero, is pushed on stack.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
public _KiTrap08
_KiTrap08 proc
.FPO (0, 0, 0, 0, 0, 2)
cli
;
; Set CR3, the I/O map base address, and LDT segment selector
; in the old TSS since they are not set on context
; switches. These values will be needed to return to the
; interrupted task.
mov eax, PCR[PcTss] ; get old TSS address
mov ecx, PCR[PcPrcbData+PbCurrentThread] ; get thread address
mov edi, [ecx].ThApcState.AsProcess ; get process address
mov ecx, [edi]+PrDirectoryTableBase ; get directory base
mov [eax]+TssCR3, ecx ; set previous cr3
mov cx, [edi]+PrIopmOffset ; get IOPM offset
mov [eax]+TssIoMapBase, cx ; set IOPM offset
mov ecx, [edi]+PrLdtDescriptor ; get LDT descriptor
test ecx, ecx ; does task use LDT?
jz @f
mov cx, KGDT_LDT
@@: mov [eax]+TssLDT, cx ; set LDT into old TSS
;
; Clear the busy bit in the TSS selector
;
mov ecx, PCR[PcGdt]
lea eax, [ecx] + KGDT_DF_TSS
mov byte ptr [eax+5], 089h ; 32bit, dpl=0, present, TSS32, not busy
;
; Clear Nested Task bit in EFLAGS
;
pushfd
and [esp], not 04000h
popfd
;
; Get address of the double-fault TSS which we are now running on.
;
mov eax, PCR[PcGdt]
mov ch, [eax+KGDT_DF_TSS+KgdtBaseHi]
mov cl, [eax+KGDT_DF_TSS+KgdtBaseMid]
shl ecx, 16
mov cx, [eax+KGDT_DF_TSS+KgdtBaseLow]
;
; Update the TSS pointer in the PCR to point to the double-fault TSS
; (which is what we're running on, or else we wouldn't be here)
;
mov eax, PCR[PcTss]
mov PCR[PcTss], ecx
;
; The original machine context is in original task's TSS
;
@@: stdCall _KeBugCheck2,<UNEXPECTED_KERNEL_MODE_TRAP,8,eax,0,0,0>
jmp short @b ; do not remove - for debugger
_KiTrap08 endp
page ,132
subttl "Coprocessor Segment Overrun"
;++
;
; Routine Description:
;
; Handle Coprocessor Segment Overrun exception.
;
; This exception only occurs on the 80286 (it's a trap 0d on the 80386),
; so choke if we get here.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the aborted instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit9_a, kit9_t, NoAbiosAssist
align dword
public _KiTrap09
_KiTrap09 proc
push 0 ; push dummy error code
ENTER_TRAP kit9_a, kit9_t
sti
mov eax, EXCEPTION_NPX_OVERRUN ; (eax) = exception type
jmp _KiSystemFatalException ; go terminate the system
_KiTrap09 endp
page ,132
subttl "Invalid TSS exception"
;++
;
; Routine Description:
;
; Handle Invalid TSS fault.
;
; This exception occurs if a segment exception other than the
; not-present exception is detected when loading a selector
; from the TSS.
;
; If the exception is caused as a result of the kernel, device
; drivers, or user incorrectly setting the NT bit in the flags
; while the back-link selector in the TSS is invalid and the
; IRET instruction being executed, in this case, this routine
; will clear the NT bit in the trap frame and restart the iret
; instruction. For other causes of the fault, the user process
; will be terminated if previous mode is user and the system
; will stop if the exception occurs in kernel mode. No exception
; is raised.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction or
; the first instruction of the task if the fault occurs as part of
; a task switch.
; Error code containing the segment causing the exception is provided.
;
; NT386 does not use TSS for context switching. So, the invalid tss
; fault should NEVER occur. If it does, something is wrong with
; the kernel. We simply shutdown the system.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kita_a, kita_t, NoAbiosAssist
align dword
public _KiTrap0A
_KiTrap0A proc
ENTER_TRAP kita_a, kita_t
; We can not enable interrupt here. If we came here because DOS/WOW
; iret with NT bit set, it is possible that vdm will swap the trap frame
; with their monitor context. If this happen before we check the NT bit
; we will bugcheck.
; sti
;
; If the trap occur in USER mode and is caused by iret instruction with
; OF bit set, we simply clear the OF bit and restart the iret.
; Any other causes of Invalid TSS cause system to be shutdown.
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2, EFLAGS_V86_MASK/010000h
jnz short Kt0a10
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz short Kt0a20
Kt0a10:
.errnz (EFLAGS_OF_BIT AND 0FFFF00FFh)
test byte ptr [ebp]+TsEFlags+1, EFLAGS_OF_BIT/0100h
sti
jz short Kt0a20
and dword ptr [ebp]+TsEFlags, NOT EFLAGS_OF_BIT
jmp _KiExceptionExit ; restart the instruction
Kt0a20:
mov eax, EXCEPTION_INVALID_TSS ; (eax) = trap type
jmp _KiSystemFatalException ; go terminate the system
_KiTrap0A endp
page ,132
subttl "Segment Not Present"
;++
;
; Routine Description:
;
; Handle Segment Not Present fault.
;
; This exception occurs when the processor finds the P bit 0
; when accessing an otherwise valid descriptor that is not to
; be loaded in SS register.
;
; The only place the fault can occur (in kernel mode) is Trap/Exception
; exit code. Otherwise, this exception causes system to be terminated.
; NT386 uses flat mode, the segment not present fault in Kernel mode
; indicates system malfunction.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction or
; the first instruction of the task if the fault occurs as part of
; a task switch.
; Error code containing the segment causing the exception is provided.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kitb_a, kitb_t, NoAbiosAssist
align dword
public _KiTrap0B
_KiTrap0B proc
; Set up machine state frame for displaying
ENTER_TRAP kitb_a, kitb_t
;
; Did the trap occur in a VDM?
;
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz Kt0b30
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
je Kt0b20
Kt0b10:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je short Kt0b20
; Raise Irql to APC level before enabling interrupts
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti
stdCall _Ki386VdmSegmentNotPresent
test eax, 0ffffh
jz short Kt0b15
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp _KiExceptionExit
Kt0b15:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
Kt0b20: sti
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov esi, [ebp]+TsErrCode
and esi, 0FFFFh
or esi, RPL_MASK
mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException2Args0d ; Won't return
Kt0b30:
;
; Check if the exception is caused by pop SegmentRegister.
; We need to deal with the case that user puts a NP selector in fs, ds, cs
; or es through kernel debugger. (kernel will trap while popping segment
; registers in trap exit code.)
; Note: We assume if the faulted instruction is pop segreg. It MUST be
; in trap exit code. So there MUST be a valid trap frame for the trap exit.
;
mov eax, [ebp]+TsEip ; (eax)->faulted Instruction
mov eax, [eax] ; (eax)= opcode of faulted instruction
mov edx, [ebp]+TsEbp ; (edx)->previous trap exit trapframe
add edx, TsSegDs ; [edx] = prev trapframe + TsSegDs
cmp al, POP_DS ; Is it pop ds instruction?
jz Kt0b90 ; if z, yes, go Kt0b90
add edx, TsSegEs - TsSegDs ; [edx] = prev trapframe + TsSegEs
cmp al, POP_ES ; Is it pop es instruction?
jz Kt0b90 ; if z, yes, go Kt0b90
add edx, TsSegFs - TsSegEs ; [edx] = prev trapframe + TsSegFs
cmp ax, POP_FS ; Is it pop fs (2-byte) instruction?
jz Kt0b90 ; If z, yes, go Kt0b90
add edx, TsSegGs - TsSegFs ; [edx] = prev trapframe + TsSegGs
cmp ax, POP_GS ; Is it pop gs (2-byte) instruction?
jz Kt0b90 ; If z, yes, go Kt0b90
;
; The exception is not caused by pop instruction. We still need to check
; if it is caused by iret (to user mode.) Because user may have a NP
; cs and we will trap at iret in trap exit code.
;
cmp al, IRET_OP ; Is it an iret instruction?
jne Kt0b199 ; if ne, not iret, go bugcheck
lea edx, [ebp]+TsHardwareEsp ; (edx)->trapped iret frame
.errnz (RPL_MASK AND 0FFFFFF00h)
test byte ptr [edx]+4, RPL_MASK ; Check CS of iret addr
; Does the iret have ring transition?
jz Kt0b199 ; if z, it's a real fault
;
; Before enabling interrupts we need to save off any debug registers again
; and build a good trap frame.
;
call SaveDebugReg
;
; we trapped at iret while returning back to user mode. We will dispatch
; the exception back to user program.
;
mov ecx, (TsErrCode+4) / 4
lea edx, [ebp]+TsErrCode
Kt0b40:
mov eax, [edx]
mov [edx+12], eax
sub edx, 4
loop Kt0b40
sti
add esp, 12 ; adjust esp and ebp
add ebp, 12
jmp Kt0b10
; mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
; xor edx, edx
; mov esi, [ebp]+TsErrCode
; or esi, RPL_MASK
; and esi, 0FFFFh
; mov ecx, 2
; mov eax, STATUS_ACCESS_VIOLATION
; call CommonDispatchException ; WOn't return
;
; The faulted instruction is pop seg
;
Kt0b90:
if DBG
lea eax, [ebp].TsHardwareEsp
cmp eax, edx
je @f
int 3
@@:
endif
mov dword ptr [edx], 0 ; set the segment reg to 0 such that
; we will trap in user mode.
jmp Kt0d01 ; continue in common code
Kt0b199:
sti
mov eax, EXCEPTION_SEGMENT_NOT_PRESENT ; (eax) = exception type
jmp _KiSystemFatalException ; terminate the system
_KiTrap0B endp
SaveDebugReg:
push ebx
mov ebx, dr7
;
; Check if any bits are set (ignoring the reserved bits).
;
test ebx, (NOT DR7_RESERVED_MASK)
mov [ebp]+TsDr7,ebx
je @f
push edi
push esi
mov ebx,dr0
mov esi,dr1
mov edi,dr2
mov [ebp]+TsDr0,ebx
mov [ebp]+TsDr1,esi
mov [ebp]+TsDr2,edi
mov ebx,dr3
mov esi,dr6
mov [ebp]+TsDr3,ebx
xor ebx, ebx
mov [ebp]+TsDr6,esi
mov dr7, ebx
;
; Load KernelDr* into processor
;
mov edi,dword ptr PCR[PcPrcb]
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr0
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr1
mov dr0,ebx
mov dr1,esi
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr2
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr3
mov dr2,ebx
mov dr3,esi
mov ebx,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr6
mov esi,[edi].PbProcessorState.PsSpecialRegisters.SrKernelDr7
mov dr6,ebx
mov dr7,esi
pop esi
pop edi
@@: pop ebx
ret
page ,132
subttl "Stack segment fault"
;++
;
; Routine Description:
;
; Handle Stack Segment fault.
;
; This exception occurs when the processor detects certain problem
; with the segment addressed by the SS segment register:
;
; 1. A limit violation in the segment addressed by the SS (error
; code = 0)
; 2. A limit violation in the inner stack during an interlevel
; call or interrupt (error code = selector for the inner stack)
; 3. If the descriptor to be loaded into SS has its present bit 0
; (error code = selector for the not-present segment)
;
; The exception should never occur in kernel mode except when we
; perform the iret back to user mode.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction or
; the first instruction of the task if the fault occurs as part of
; a task switch.
; Error code (whose value depends on detected condition) is provided.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kitc_a, kitc_t, NoAbiosAssist
align dword
public _KiTrap0C
_KiTrap0C proc
ENTER_TRAP kitc_a, kitc_t
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt0c20
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz Kt0c10
cmp word ptr [ebp]+TsSegCs, KGDT_R3_CODE OR RPL_MASK
jne Kt0c20 ; maybe in a vdm
Kt0c00: sti
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov edx, EXCEPT_LIMIT_ACCESS; assume it is limit violation
mov esi, [ebp]+TsHardwareEsp; (ecx) = User Stack pointer
cmp word ptr [ebp]+TsErrCode, 0 ; Is errorcode = 0?
jz short kt0c05 ; if z, yes, go dispatch exception
mov esi, [ebp]+TsErrCode ; Otherwise, set SS segment value
; to be the address causing the fault
mov edx, EXCEPT_UNKNOWN_ACCESS
or esi, RPL_MASK
and esi, 0FFFFh
kt0c05: mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException2Args ; Won't return
kt0c10:
;
; Check if the exception is caused by kernel mode iret to user code.
; We need to deal with the case that user puts a bogus value in ss
; through SetContext call. (kernel will trap while iret to user code
; in trap exit code.)
; Note: We assume if the faulted instruction is iret. It MUST be in
; trap/exception exit code. So there MUST be a valid trap frame for
; the trap exit.
;
mov eax, [ebp]+TsEip ; (eax)->faulted Instruction
;
; Note the eip is captured above before enabling interrupts to
; prevent a setcontext from editing a bogus eip into our trapframe.
;
movzx eax, byte ptr[eax]
; (eax)= opcode of faulted instruction
;
; Check if the exception is caused by iret (to user mode.)
; Because user may have a NOT PRESENT ss and we will trap at iret
; in trap exit code. (If user put a bogus/not valid SS in trap frame, we
; will catch it in trap 0D handler.
;
cmp al, IRET_OP ; Is it an iret instruction?
jne Kt0c15 ; if ne, not iret, go bugcheck
;
; Before enabling interrupts we need to save off any debug registers again
;
call SaveDebugReg
lea edx, [ebp]+TsHardwareEsp ; (edx)->trapped iret frame
test dword ptr [edx]+4, RPL_MASK ; Check CS of iret addr
; Does the iret have ring transition?
jz Kt0c15 ; if z, no SS involved, it's a real fault
;
; we trapped at iret while returning back to user mode. We will dispatch
; the exception back to user program.
;
mov ecx, (TsErrCode+4) / 4
lea edx, [ebp]+TsErrCode
@@:
mov eax, [edx]
mov [edx+12], eax
sub edx, 4
loop @b
sti
add esp, 12 ; adjust esp and ebp
add ebp, 12
;
; Now, we have user mode trap frame set up
;
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov edx, EXCEPT_LIMIT_ACCESS; assume it is limit violation
mov esi, [ebp]+TsHardwareEsp; (ecx) = User Stack pointer
cmp word ptr [ebp]+TsErrCode, 0 ; Is errorcode = 0?
jz short @f ; if z, yes, go dispatch exception
mov esi, [ebp]+TsErrCode ; Otherwise, set SS segment value
; to be the address causing the fault
and esi, 0FFFFh
mov edx, EXCEPT_UNKNOWN_ACCESS
or esi, RPL_MASK
@@:
mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException2Args ; Won't return
Kt0c15:
sti
mov eax, EXCEPTION_STACK_FAULT ; (eax) = trap type
jmp _KiSystemFatalException
Kt0c20:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt0c00
Kt0c30:
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz short @f
;
; Raise Irql to APC level before enabling interrupt
;
RaiseIrql APC_LEVEL
sti
mov edi, eax ; [edi] = OldIrql
call VdmFixEspEbp
push eax
mov ecx, edi
LowerIrql ecx
cli
pop eax
test al, 0fh
jz short @f
jmp _KiExceptionExit
@@:
stdCall _Ki386VdmReflectException_A,<0ch>
test al,0fh
jz Kt0c00
jmp _KiExceptionExit
_KiTrap0C endp
page ,132
subttl "TrapC handler for NTVDM"
;++
;
; Routine Description:
;
; Some protected dos games (ex, Duke3D) while running in a BIG code
; segment with SMALL Stack segment will hit trap c with higher 16bit
; of esp containing kernel esp higher 16 bit. The question it should
; not trapped because cpu should only look at sp. So, here we try
; to deal with this problem.
;
; Arguments:
;
; EBP - Trap frame
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
public VdmFixEspEbp
VdmFixEspEbp proc
;
; First check if user SS is small. If it is big, do nothing
;
mov eax, [ebp].TsHardwareSegSs
lar eax, eax ; [eax]= ss access right
jnz Vth_err
test eax, 400000h ; is SS a big segment?
jnz Vth_err ; nz, yes, do nothing
xor edx, edx ; [edx] = 0 no need to update tframe
mov eax, esp
and eax, 0ffff0000h ; [eax]=kernel esp higher 16bit
mov ecx, [ebp].TsHardwareEsp
and ecx, 0ffff0000h ; [ecx]=user esp higher 16bit
cmp ecx, eax ; are they the same
jnz short @f ; if nz, no, go check ebp
and dword ptr [ebp].TsHardwareEsp, 0ffffH ; zero higher 16 bit of user esp
mov edx, 1 ; [edx]=1 indicates we need to update trap frame
@@:
mov ecx, [ebp].TsEbp
and ecx, 0ffff0000h ; [ecx]=user ebp higher 16bit
cmp ecx, eax ; are they the same as kernel's
jnz short @f ; if nz, no, go check if we need to update tframe
and dword ptr [ebp].TsEbp, 0ffffH ; zero higher 16bit of user ebp
mov edx, 1 ; update kernel trap frame
@@: cmp edx, 1 ; do we need to update trap frame?
jnz short Vth_err ; if nz, no, do nothing
Vth_ok:
;
; copy user's cs:eip and ss:esp to vdmtib, note this needs to be done
; with proper probing and exception handling.
;
mov ebx, PCR[PcTeb]
mov eax, [ebp].TsSegCs
mov ecx, [ebp].TsEip
mov edx, [ebp].TsEbx
stdCall _VdmTibPass1, <eax,ecx,edx>
; eax now points at the VDM tib (or NULL if anything went wrong)
;
; Move the vdmtib to the trap frame such that we return back to ntvdm
; [ebx]->vdmtib
;
mov [ebp].TsEbx, eax
;
; dispatch control to ntvdm trapc handler which will load ss:esp
; and jump to the trapped cs:eip
;
mov eax,PCR[PcPrcbData+PbCurrentThread]
mov eax,[eax]+ThApcState+AsProcess
mov eax,[eax]+PrVdmTrapcHandler
mov dword ptr [ebp].TsSegCs, KGDT_R3_CODE OR RPL_MASK
mov dword ptr [ebp].TsEip, eax
mov eax, 1
ret
Vth_err:
xor eax, eax
ret
VdmFixEspEbp endp
page ,132
subttl "General Protection Fault"
;++
;
; Routine Description:
;
; Handle General protection fault.
;
; First, check to see if the fault occured in kernel mode with
; incorrect selector values. If so, this is a lazy segment load.
; Correct the selector values and restart the instruction. Otherwise,
; parse out various kinds of faults and report as exceptions.
;
; All protection violations that do not cause another exception
; cause a general exception. If the exception indicates a violation
; of the protection model by an application program executing a
; privileged instruction or I/O reference, a PRIVILEGED INSTRUCTION
; exception will be raised. All other causes of general protection
; fault cause a ACCESS VIOLATION exception to be raised.
;
; If previous mode = Kernel;
; the system will be terminated (assuming not lazy segment load)
; Else previous mode = USER
; the process will be terminated if the exception was not caused
; by privileged instruction.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction or
; the first instruction of the task if the fault occurs as part of
; a task switch.
; Error code (whose value depends on detected condition) is provided.
;
; Return value:
;
; None
;
;--
ASSUME DS:FLAT, SS:NOTHING, ES:FLAT
;
; Error and exception blocks for KiTrap0d
;
Ktd_ExceptionHandler proc
;
; WARNING: Here we directly unlink the exception handler from the
; exception registration chain. NO unwind is performed.
;
mov esp, [esp+8] ; (esp)-> ExceptionList
pop PCR[PcExceptionList]
add esp, 4 ; pop out except handler
pop ebp ; (ebp)-> trap frame
test dword ptr [ebp].TsSegCs, MODE_MASK ; if premode=kernel
jnz Kt0d103 ; nz, prevmode=user, go return
; raise bugcheck if prevmode=kernel
stdCall _KeBugCheck2, <KMODE_EXCEPTION_NOT_HANDLED,0,0,0,0,ebp>
Ktd_ExceptionHandler endp
ENTER_DR_ASSIST kitd_a, kitd_t, NoAbiosAssist,, kitd_v
align dword
public _KiTrap0D
_KiTrap0D proc
;
; Did the trap occur in a VDM in V86 mode? Trap0d is not critical from
; performance point of view to native NT, but it's super critical to
; VDMs. So here we are doing every thing to make v86 mode most
; efficient.
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [esp]+0ch+2,EFLAGS_V86_MASK/010000h
jz Ktdi
KtdV86Slow:
ENTER_TRAPV86 kitd_a, kitd_v
KtdV86Slow2:
mov ecx,PCR[PcPrcbData+PbCurrentThread]
mov ecx,[ecx]+ThApcState+AsProcess
cmp dword ptr [ecx]+PrVdmObjects,0 ; is this a vdm process?
jnz short @f ; if nz, yes
sti ; else, enable ints
jmp Kt0d105 ; and dispatch exception
@@:
; Raise Irql to APC level, before enabling interrupts
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti
stdCall _VdmDispatchOpcodeV86_try,<ebp>
KtdV86Exit:
test al,0FFh
jnz short Ktdi2
stdCall _Ki386VdmReflectException,<0dh>
test al,0fh
jnz short Ktdi2
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp Kt0d105
Ktdi2:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
cli
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jz Ktdi3
EXIT_TRAPV86
;
; EXIT_TRAPv86 does not exit if a user mode apc has switched
; the context from V86 mode to flat mode (VDM monitor context)
;
Ktdi3:
jmp _KiExceptionExit
Ktdi:
ENTER_TRAP kitd_a, kitd_t
;
; DO NOT TURN INTERRUPTS ON! If we're doing a lazy segment load,
; could be in an ISR or other code that needs ints off!
;
;
; Is this just a lazy segment load? First make sure the exception occurred
; in kernel mode.
;
test dword ptr [ebp]+TsSegCs,MODE_MASK
jnz Kt0d02 ; not kernel mode, go process normally
;
; Before handling kernel mode trap0d, we need to do some checks to make
; sure the kernel mode code is the one to blame.
;
if FAST_BOP
cmp dword ptr PCR[PcVdmAlert], 0
jne Kt0eVdmAlert
endif
;
; Check if the exception is caused by the handler trying to examine offending
; instruction. If yes, we raise exception to user mode program. This occurs
; when user cs is bogus. Note if cs is valid and eip is bogus, the exception
; will be caught by page fault and out Ktd_ExceptionHandler will be invoked.
; Both cases, the exception is dispatched back to user mode.
;
mov eax, [ebp]+TsEip
cmp eax, offset FLAT:Kt0d03
jbe short Kt0d000
cmp eax, offset FLAT:Kt0d60
jae short Kt0d000
sti
mov ebp, [ebp]+TsEbp ; remove the current trap frame
mov esp, ebp ; set ebp, esp to previous trap frame
jmp Kt0d105 ; and dispatch exception to user mode.
;
; Check if the exception is caused by pop SegmentRegister.
; We need to deal with the case that user puts a bogus value in fs, ds,
; or es through kernel debugger. (kernel will trap while popping segment
; registers in trap exit code.)
; Note: We assume if the faulted instruction is pop segreg. It MUST be
; in trap exit code. So there MUST be a valid trap frame for the trap exit.
;
Kt0d000:
mov eax, [ebp]+TsEip ; (eax)->faulted Instruction
mov eax, [eax] ; (eax)= opcode of faulted instruction
mov edx, [ebp]+TsEbp ; (edx)->previous trap exit trapframe
add edx, TsSegDs ; [edx] = prev trapframe + TsSegDs
cmp al, POP_DS ; Is it pop ds instruction?
jz Kt0d005 ; if z, yes, go Kt0d005
add edx, TsSegEs - TsSegDs ; [edx] = prev trapframe + TsSegEs
cmp al, POP_ES ; Is it pop es instruction?
jz Kt0d005 ; if z, yes, go Kt0d005
add edx, TsSegFs - TsSegEs ; [edx] = prev trapframe + TsSegFs
cmp ax, POP_FS ; Is it pop fs (2-byte) instruction?
jz Kt0d005 ; If z, yes, go Kt0d005
add edx, TsSegGs - TsSegFs ; [edx] = prev trapframe + TsSegGs
cmp ax, POP_GS ; Is it pop gs (2-byte) instruction?
jz Kt0d005 ; If z, yes, go Kt0d005
;
; The exception is not caused by pop instruction. We still need to check
; if it is caused by iret (to user mode.) Because user may have a bogus
; ss and we will trap at iret in trap exit code.
;
cmp al, IRET_OP ; Is it an iret instruction?
jne Kt0d002 ; if ne, not iret, go check lazy load
lea edx, [ebp]+TsHardwareEsp ; (edx)->trapped iret frame
mov ax, [ebp]+TsErrCode ; (ax) = Error Code
and ax, NOT RPL_MASK ; No need to do this ...
mov cx, word ptr [edx]+4 ; [cx] = cs selector
and cx, NOT RPL_MASK
cmp cx, ax ; is it faulted in CS?
jne short Kt0d0008 ; No
;
; Check if this is the code which we use to return to Ki386CallBios
; (see biosa.asm):
; cs should be KGDT_R0_CODE OR RPL_MASK
; eip should be Ki386BiosCallReturnAddress
; esi should be the esp of function Ki386SetUpAndExitToV86Code
; (edx) -> trapped iret frame
;
mov eax, OFFSET FLAT:Ki386BiosCallReturnAddress
cmp eax, [edx] ; [edx]= trapped eip
; Is eip what we're expecting?
jne short Kt0d0005 ; No, continue
mov eax, [edx]+4 ; (eax) = trapped cs
cmp ax, KGDT_R0_CODE OR RPL_MASK ; Is Cs what we're exptecting?
jne short Kt0d0005 ; No
jmp Ki386BiosCallReturnAddress ; with interrupts off
Kt0d0005:
;
; Since the CS is bogus, we cannot tell if we are going back to user mode...
;
mov ebx,PCR[PcPrcbData+PbCurrentThread] ; if previous mode is
test byte ptr [ebx]+ThPreviousMode, 0ffh ; kernel, we bugcheck
jz Kt0d02
or word ptr [edx]+4, RPL_MASK
Kt0d0008:
test dword ptr [edx]+4, RPL_MASK ; Check CS of iret addr
; Does the iret have ring transition?
jz Kt0d02 ; if z, no SS involved, it's a real fault
;
; Before enabling interrupts we need to save off any debug registers again
;
call SaveDebugReg
;
; we trapped at iret while returning back to user mode. We will dispatch
; the exception back to user program.
;
mov ecx, (TsErrCode+4)/4
lea edx, [ebp]+TsErrCode
Kt0d001:
mov eax, [edx]
mov [edx+12], eax
sub edx, 4
loop Kt0d001
sti
add esp, 12 ; adjust esp and ebp
add ebp, 12
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov esi, [ebp]+TsErrCode
and esi, 0FFFFh
mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException2Args0d ; Won't return
;
; Kernel mode, first opcode byte is 0f, check for rdmsr or wrmsr instruction
;
Kt0d001a:
shr eax, 8
cmp al, 30h
je short Kt0d001b
cmp al, 32h
jne short Kt0d002a
Kt0d001b:
.errnz(EFLAGS_INTERRUPT_MASK AND 0FFFF00FFh)
test [ebp+1]+TsEFlags, EFLAGS_INTERRUPT_MASK/0100h ; faulted with
jz short @f ; interrupts disabled?
sti ; interrupts were enabled so reenable
@@: mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException0Args ; Won't return
;
; The Exception is not caused by pop instruction. Check to see
; if the instruction is a rdmsr or wrmsr
;
Kt0d002:
cmp al, 0fh
je short Kt0d001a
;
; We now check if DS and ES contain correct value. If not, this is lazy
; segment load, we simply set them to valid selector.
;
Kt0d002a:
cmp word ptr [ebp]+TsSegDs, KGDT_R3_DATA OR RPL_MASK
je short Kt0d003
mov dword ptr [ebp]+TsSegDs, KGDT_R3_DATA OR RPL_MASK
jmp short Kt0d01
Kt0d003:
cmp word ptr [ebp]+TsSegEs, KGDT_R3_DATA OR RPL_MASK
je Kt0d02 ; Real fault, go process it
mov dword ptr [ebp]+TsSegEs, KGDT_R3_DATA OR RPL_MASK
jmp short Kt0d01
;
; The faulted instruction is pop seg
;
Kt0d005:
if DBG
lea eax, [ebp].TsHardwareEsp
cmp edx, eax
je @f
int 3
@@:
endif
xor eax, eax
mov dword ptr [edx], eax ; set the segment reg to 0 such that
; we will trap in user mode.
Kt0d01:
EXIT_ALL NoRestoreSegs,,NoPreviousMode ; RETURN
;
; Caller is not kernel mode, or DS and ES are OK. Therefore this
; is a real fault rather than a lazy segment load. Process as such.
; Since this is not a lazy segment load is now safe to turn interrupts on.
;
Kt0d02: mov eax, EXCEPTION_GP_FAULT ; (eax) = trap type
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is prevmode=User?
jz _KiSystemFatalException ; If z, prevmode=kernel, stop...
; preload pointer to process
mov ebx,PCR[PcPrcbData+PbCurrentThread]
mov ebx,[ebx]+ThApcState+AsProcess
; flat or protect mode ?
cmp word ptr [ebp]+TsSegCs, KGDT_R3_CODE OR RPL_MASK
jz kt0d0201
;
; if vdm running in protected mode, handle instruction
;
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
jne Kt0d110
sti
cmp word ptr [ebp]+TsErrCode, 0 ; if errcode<>0, raise access
; violation exception
jnz Kt0d105 ; if nz, raise access violation
jmp short Kt0d03
;
; if vdm running in flat mode, handle pop es,fs,gs by setting to Zero
;
kt0d0202:
add dword ptr [ebp].TsEip, 1
kt0d02021:
mov dword ptr [edx], 0
add dword ptr [ebp].TsEip, 1
add dword ptr [ebp].TsHardwareEsp, 4
jmp _KiExceptionExit
kt0d0201:
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je short Kt0d03
sti
mov eax, [ebp]+TsEip ; (eax)->faulted Instruction
stdCall _VdmFetchBop4, <eax> ; (eax)= opcode of faulted instruction
mov edx, ebp ; (edx)-> trap frame
add edx, TsSegEs ; [edx] = prev trapframe + TsSegEs
cmp al, POP_ES ; Is it pop es instruction?
jz short Kt0d02021
@@:
add edx, TsSegFs - TsSegEs ; [edx] = prev trapframe + TsSegFs
cmp ax, POP_FS ; Is it pop fs (2-byte) instruction?
jz short kt0d0202
add edx, TsSegGs - TsSegFs ; [edx] = prev trapframe + TsSegGs
cmp ax, POP_GS ; Is it pop gs (2-byte) instruction?
jz short kt0d0202
;
; we need to determine if the trap0d was caused by privileged instruction.
; First, we need to skip all the instruction prefix bytes
;
Kt0d03: sti
;
; First we need to set up an exception handler to handle the case that
; we fault while reading user mode instruction.
;
push ebp ; pass trapframe to handler
push offset FLAT:Ktd_ExceptionHandler
; set up exception registration record
push PCR[PcExceptionList]
mov PCR[PcExceptionList], esp
mov esi, [ebp]+TsEip ; (esi) -> flat address of faulting instruction
cmp esi, _MmUserProbeAddress ; Probe captured EIP
jb short @f
mov esi, _MmUserProbeAddress ; Use address of the GAP to force exception
@@: mov ecx, MAX_INSTRUCTION_LENGTH
@@:
push ecx ; save ecx for loop count
lods byte ptr [esi] ; (al)= instruction byte
mov ecx, PREFIX_REPEAT_COUNT
mov edi, offset FLAT:PrefixTable ; (EDI)->prefix table
repnz scasb ; search for matching (al)
pop ecx ; restore loop count
jnz short Kt0d10 ; (al) not a prefix byte, go kt0d10
loop short @b ; go check for prefix byte again
pop PCR[PcExceptionList]
add esp, 8 ; clear stack
jmp Kt0635 ; exceed max instruction length,
; raise ILLEGALINSTRUCTION exception
;
; (al) = first opcode which is NOT prefix byte
; (ds:esi)= points to the first opcode which is not prefix byte + 1
; We need to check if it is one of the privileged instructions
;
Kt0d10: cmp al, MI_HLT ; Is it a HLT instruction?
je Kt0d80 ; if e, yes, go kt0d80
cmp al, MI_TWO_BYTE ; Is it a two-byte instruction?
jne short Kt0d50 ; if ne, no, go check for IO inst.
lods byte ptr [esi] ; (al)= next instruction byte
cmp al, MI_LTR_LLDT ; Is it a LTR or LLDT ?
jne short Kt0d20 ; if ne, no, go kt0d20
lods byte ptr [esi] ; (al)= ModRM byte of instruction
and al, MI_MODRM_MASK ; (al)= bit 3-5 of ModRM byte
cmp al, MI_LLDT_MASK ; Is it a LLDT instruction?
je Kt0d80 ; if e, yes, go Kt0d80
cmp al, MI_LTR_MASK ; Is it a LTR instruction?
je Kt0d80 ; if e, yes, go Kt0d80
jmp Kt0d100 ; if ne, go raise access violation
Kt0d20: cmp al, MI_LGDT_LIDT_LMSW ; Is it one of these instructions?
jne short Kt0d30 ; if ne, no, go check special mov inst.
lods byte ptr [esi] ; (al)= ModRM byte of instruction
and al, MI_MODRM_MASK ; (al)= bit 3-5 of ModRM byte
cmp al, MI_LGDT_MASK ; Is it a LGDT instruction?
je Kt0d80 ; if e, yes, go Kt0d80
cmp al, MI_LIDT_MASK ; Is it a LIDT instruction?
je Kt0d80 ; if e, yes, go Kt0d80
cmp al, MI_LMSW_MASK ; Is it a LMSW instruction?
je Kt0d80 ; if e, yes, go Kt0d80
jmp Kt0d100 ; else, raise access violation except
Kt0d30:
;
; Check some individual privileged instructions
;
cmp al, MI_INVD
je kt0d80
cmp al, MI_WBINVD
je kt0d80
cmp al, MI_SYSEXIT
je short kt0d80
cmp al, MI_MOV_TO_TR ; mov tx, rx
je short kt0d80
cmp al, MI_CLTS
je short kt0d80
;
; Test ordering of these compares
;
if MI_MOV_FROM_CR GT MI_WRMSR
.err
endif
;
; Test for the mov instructions as a block with a single unused gap
;
.errnz (MI_MOV_FROM_CR + 1 - MI_MOV_FROM_DR)
.errnz (MI_MOV_FROM_DR + 1 - MI_MOV_TO_CR)
.errnz (MI_MOV_TO_CR + 1 - MI_MOV_TO_DR)
.errnz (MI_MOV_TO_DR + 1 - MI_MOV_FROM_TR)
cmp al, MI_MOV_FROM_CR ; See if we are a mov rx, cx
jb Kt0d100 ; mov cx, rx
cmp al, MI_MOV_FROM_TR ; mov rx, dx
jbe short kt0d80 ; mov dx, rx
; mov rx, tx
;
; Test the counter instructions as a block
;
.errnz (MI_WRMSR + 1 - MI_RDTSC)
.errnz (MI_RDTSC + 1 - MI_RDMSR)
.errnz (MI_RDMSR + 1 - MI_RDPMC)
cmp al, MI_WRMSR
jb Kt0d100
cmp al, MI_RDPMC
jbe short kt0d80
jmp Kt0d100 ; else, no, raise access violation
;
; Now, we need to check if the trap 0d was caused by IO privileged instruct.
; (al) = first opcode which is NOT prefix byte
; Also note, if we come here, the instruction has 1 byte opcode (still need to
; check REP case.)
;
Kt0d50: mov ebx, [ebp]+TsEflags ; (ebx) = client's eflags
and ebx, IOPL_MASK ;
shr ebx, IOPL_SHIFT_COUNT ; (ebx) = client's IOPL
mov ecx, [ebp]+TsSegCs
and ecx, RPL_MASK ; RPL_MASK NOT MODE_MASK!!!
; (ecx) = CPL, 1/2 of computation of
; whether IOPL applies.
cmp ebx,ecx ; compare IOPL with CPL of caller
jge short Kt0d100 ; if ge, not IO privileged,
; go raise access violation
Kt0d60: cmp al, CLI_OP ; Is it a CLI instruction
je short Kt0d80 ; if e, yes. Report it.
cmp al, STI_OP ; Is it a STI?
je short Kt0d80 ; if e, yes, report it.
mov ecx, IO_INSTRUCTION_TABLE_LENGTH
mov edi, offset FLAT:IOInstructionTable
repnz scasb ; Is it a IO instruction?
jnz short Kt0d100 ; if nz, not io instrct.
;
; We know the instr is an IO instr without IOPL. But, this doesn't mean
; this is a privileged instruction exception. We need to make sure the
; IO port access is not granted in the bit map
;
mov edi, PCR[PcSelfPcr] ; (edi)->Pcr
mov esi, [edi]+PcGdt ; (esi)->Gdt addr
add esi, KGDT_TSS
movzx ebx, word ptr [esi] ; (ebx) = Tss limit
mov edx, [ebp].TsEdx ; [edx] = port addr
mov ecx, edx
and ecx, 07 ; [ecx] = Bit position
shr edx, 3 ; [edx] = offset to the IoMap
mov edi, [edi]+PcTss ; (edi)->TSS
movzx eax, word ptr [edi + TssIoMapBase] ; [eax] = Iomap offset
add edx, eax
cmp edx, ebx ; is the offset addr beyond tss limit?
ja short Kt0d80 ; yes, no I/O priv.
add edi, edx ; (edi)-> byte corresponds to the port addr
mov edx, 1
shl edx, cl
test dword ptr [edi], edx ; Is the bit of the port disabled?
jz short Kt0d100 ; if z, no, then it is access violation
Kt0d80:
pop PCR[PcExceptionList]
add esp, 8 ; clear stack
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov eax, STATUS_PRIVILEGED_INSTRUCTION
jmp CommonDispatchException0Args ; Won't return
;
; NOTE All the GP fault (except the ones we can
; easily detect now) will cause access violation exception
; AND, all the access violation will be raised with additional
; parameters set to "read" and "virtual address which caused
; the violation = unknown (-1)"
;
Kt0d100:
pop PCR[PcExceptionList]
add esp, 8 ; clear stack
Kt0d103:
Kt0d105:
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov esi, -1
mov eax, STATUS_ACCESS_VIOLATION
jmp CommonDispatchException2Args0d ; Won't return
Kt0d110:
; Raise Irql to APC level, before enabling interrupts
RaiseIrql APC_LEVEL
sti
push eax ; Save OldIrql
stdCall _VdmDispatchOpcode_try <ebp>
or al,al
jnz short Kt0d120
stdCall _Ki386VdmReflectException,<0dh>
test al,0fh
jnz short Kt0d120
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp short Kt0d105
Kt0d120:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp _KiExceptionExit
_KiTrap0D endp
;
; The following code it to fix a bug in the Pentium Processor dealing with
; Invalid Opcodes.
;
PentiumTest: ; Is this access to the write protect
; IDT page?
test [ebp]+TsErrCode, 04h ; Do not allow user mode access to trap 6
jne NoPentiumFix ; vector. Let page fault code deal with it
mov eax, PCR[PcIDT] ; Get address of trap 6 IDT entry
add eax, (6 * 8)
cmp eax, edi ; Is that the faulting address?
jne NoPentiumFix ; No. Back to page fault code
; Yes. We have accessed the write
; protect page of the IDT
mov [ebp]+TsErrCode, 0 ; Overwrite error code
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2, EFLAGS_V86_MASK/010000h ; Was it a VM?
jne Kt06VMpf ; Yes. Go to VM part of trap 6
jmp Kt06pf ; Not from a VM
page ,132
subttl "Page fault processing"
;++
;
; Routine Description:
;
; Handle page fault.
;
; The page fault occurs if paging is enabled and any one of the
; conditions is true:
;
; 1. page not present
; 2. the faulting procedure does not have sufficient privilege to
; access the indicated page.
;
; For case 1, the referenced page will be loaded to memory and
; execution continues.
; For case 2, registered exception handler will be invoked with
; appropriate error code (in most cases STATUS_ACCESS_VIOLATION)
;
; N.B. It is assumed that no page fault is allowed during task
; switches.
;
; N.B. INTERRUPTS MUST REMAIN OFF UNTIL AFTER CR2 IS CAPTURED.
;
; Arguments:
;
; Error code left on stack.
; CR2 contains faulting address.
; Interrupts are turned off at entry by use of an interrupt gate.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kite_a, kite_t, NoAbiosAssist
align dword
public _KiTrap0E
_KiTrap0E proc
ENTER_TRAP kite_a, kite_t
if FAST_BOP
cmp dword ptr PCR[PcVdmAlert], 0
jne Kt0eVdmAlert
endif
MODIFY_BASE_TRAP_FRAME
mov edi,cr2
;
; Now that everything is in a sane state check for rest of the Pentium
; Processor bug work around for illegal operands
;
cmp _KiI386PentiumLockErrataPresent, 0
jne PentiumTest ; Check for special problems
NoPentiumFix: ; No. Skip it
sti
test [ebp]+TsEFlags, EFLAGS_INTERRUPT_MASK ; faulted with
jz Kt0e12b ; interrupts disabled?
Kt0e01:
;
; call _MmAccessFault to page in the not present page. If the cause
; of the fault is 2, _MmAccessFault will return appropriate error code
;
push ebp ; set trap frame address
mov eax, [ebp]+TsSegCs ; set previous mode
and eax, MODE_MASK ;
push eax ;
push edi ; set virtual address of page fault
mov eax, [ebp]+TsErrCode ; set load/store indicator
shr eax, 1 ;
and eax, _KeErrorMask ;
push eax ;
call _MmAccessFault@16
test eax, eax ; check if page fault resolved
jl short Kt0e05 ; if l, page fault not resolved
cmp _PsWatchEnabled, 0 ; check if working set watch enabled
je short @f ; if e, working set watch not enabled
mov ebx, [ebp]+TsEip ; set exception address
stdCall _PsWatchWorkingSet, <eax, ebx, edi> ; record working set information
@@: cmp _KdpOweBreakpoint, 0 ; check for owed breakpoints
je _KiExceptionExit ; if e, no owed breakpoints
stdCall _KdSetOwedBreakpoints ; notify the debugger
jmp _KiExceptionExit ; join common code
;
; Memory management could not resolve the page fault.
;
; Check to determine if the fault occured in the interlocked pop entry slist
; code. There is a case where a fault may occur in this code when the right
; set of circumstances occurs. The fault can be ignored by simply skipping
; the faulting instruction.
;
Kt0e05: mov ecx, offset FLAT:ExpInterlockedPopEntrySListFault ; get pop code address
cmp [ebp].TsEip, ecx ; check if fault at pop code address
je Kt0e10a ; if eq, skip faulting instruction
;
; Check to determine if the page fault occured in the user mode interlocked
; pop entry SLIST code.
;
mov ecx, _KeUserPopEntrySListFault
cmp [ebp].TsEip, ecx ; check if fault at USER pop code address
je Kt0e10b
;
; Did the fault occur in KiSystemService while copying arguments from
; user stack to kernel stack?
;
Kt0e05a:mov ecx, offset FLAT:KiSystemServiceCopyArguments
cmp [ebp].TsEip, ecx
je short Kt0e06
mov ecx, offset FLAT:KiSystemServiceAccessTeb
cmp [ebp].TsEip, ecx
jne short Kt0e07
mov ecx, [ebp].TsEbp ; (eax)->TrapFrame of SysService
test [ecx].TsSegCs, MODE_MASK
jz short Kt0e07 ; caller of SysService is k mode, we
; will let it bugcheck.
mov [ebp].TsEip, offset FLAT:kss61
mov eax, STATUS_ACCESS_VIOLATION
mov [ebp].TsEax, eax
jmp _KiExceptionExit
Kt0e06:
mov ecx, [ebp].TsEbp ; (eax)->TrapFrame of SysService
test [ecx].TsSegCs, MODE_MASK
jz short Kt0e07 ; caller of SysService is k mode, we
; will let it bugcheck.
mov [ebp].TsEip, offset FLAT:kss60
mov eax, STATUS_ACCESS_VIOLATION
mov [ebp].TsEax, eax
jmp _KiExceptionExit
Kt0e07:
mov ecx, [ebp]+TsErrCode ; (ecx) = error code
shr ecx, 1 ; isolate read/write bit
and ecx, _KeErrorMask ;
;
; Did the fault occur in a VDM?
;
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt0e7
;
; Did the fault occur in a VDM while running in protected mode?
;
mov esi,PCR[PcPrcbData+PbCurrentThread]
mov esi,[esi]+ThApcState+AsProcess
cmp dword ptr [esi]+PrVdmObjects,0 ; is this a vdm process?
je short Kt0e9 ; z -> not vdm
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK
jz short Kt0e9 ; kernel mode, just dispatch exception.
cmp word ptr [ebp]+TsSegCs, KGDT_R3_CODE OR RPL_MASK
jz short kt0e9 ; z -> not vdm
Kt0e7: mov esi, eax
stdCall _VdmDispatchPageFault, <ebp,ecx,edi>
test al,0fh ; returns TRUE, if success
jnz Kt0e11 ; Exit,No need to call the debugger
mov eax, esi
Kt0e9:
; Set up exception record and arguments and call _KiDispatchException
mov esi, [ebp]+TsEip ; (esi)-> faulting instruction
cmp eax, STATUS_ACCESS_VIOLATION ; dispatch access violation or
je short Kt0e9a ; or in_page_error?
cmp eax, STATUS_GUARD_PAGE_VIOLATION
je short Kt0e9b
cmp eax, STATUS_STACK_OVERFLOW
je short Kt0e9b
;
; test to see if reserved status code bit is set. If so, then bugchecka
;
cmp eax, STATUS_IN_PAGE_ERROR or 10000000h
je Kt0e12 ; bugchecka
;
; (ecx) = ExceptionInfo 1
; (edi) = ExceptionInfo 2
; (eax) = ExceptionInfo 3
; (esi) -> Exception Addr
;
mov edx, ecx
mov ebx, esi
mov esi, edi
mov ecx, 3
mov edi, eax
mov eax, STATUS_IN_PAGE_ERROR
call CommonDispatchException ; Won't return
Kt0e9a: mov eax, KI_EXCEPTION_ACCESS_VIOLATION
Kt0e9b:
mov ebx, esi
mov edx, ecx
mov esi, edi
jmp CommonDispatchException2Args ; Won't return
.FPO ( 0, 0, 0, 0, 0, FPO_TRAPFRAME )
;
; The fault occured in the kernel interlocked pop slist function. The operation should
; be retried.
Kt0e10a:mov ecx, offset FLAT:ExpInterlockedPopEntrySListResume ; get resume address
jmp Kt0e10e
;
; An unresolved page fault occured in the user mode interlocked pop slist
; code at the resumable fault address.
;
; Within the KTHREAD structure are these fields:
;
; ThSListFaultAddress - The VA of the last slist pop fault
; ThSListFaultCount - The number of consecutive faults at that address
;
; If the current VA != ThSListFaultAddress, then update both fields and retry
; the operation.
;
; Otherwise, if ThSListFaultCount < KI_SLIST_FAULT_COUNT_MAXIMUM, increment
; ThSListFaultCount and retry the operation.
;
; Otherwise, reset ThSListFaultCount and DO NOT retry the operation.
;
Kt0e10b:test byte ptr [ebp]+TsSegCs, MODE_MASK
jz Kt0e05a ; not in usermode
mov ecx, PCR[PcPrcbData+PbCurrentThread]; get pointer to KTHREAD
cmp edi, [ecx].ThSListFaultAddress ; get faulting VA - same as
jne Kt0e10d ; last time? no - update fault state
cmp DWORD PTR [ecx].ThSListFaultCount, KI_SLIST_FAULT_COUNT_MAXIMUM
inc DWORD PTR [ecx].ThSListFaultCount ; presuppose under threshold. carry unchanged.
jc Kt0e10c ; same VA as last, but less than threshold
mov DWORD PTR [ecx].ThSListFaultCount, 0; over threshold - reset count
jmp Kt0e05a ; and do not retry
Kt0e10d:mov [ecx].ThSListFaultAddress, edi ; update new faulting VA
mov DWORD PTR [ecx].ThSListFaultCount, 0; and reset count
Kt0e10c:mov ecx, _KeUserPopEntrySListResume ; get resume address
Kt0e10e:mov [ebp].TsEip, ecx ; set resume address and fall through
Kt0e10:
mov esp,ebp ; (esp) -> trap frame
test _KdpOweBreakpoint, 1 ; do we have any owed breakpoints?
jz _KiExceptionExit ; No, all done
stdCall _KdSetOwedBreakpoints ; notify the debugger
Kt0e11: mov esp,ebp ; (esp) -> trap frame
jmp _KiExceptionExit ; join common code
Kt0e12:
CurrentIrql ; (eax) = OldIrql
Kt0e12a:
lock inc ds:_KiHardwareTrigger ; trip hardware analyzer
;
; bugcheck a, addr, irql, load/store, pc
;
mov ecx, [ebp]+TsErrCode ; (ecx)= error code
shr ecx, 1 ; isolate read/write bit
and ecx, _KeErrorMask ;
mov esi, [ebp]+TsEip ; [esi] = faulting instruction
stdCall _KeBugCheck2,<IRQL_NOT_LESS_OR_EQUAL,edi,eax,ecx,esi,ebp>
Kt0e12b:cmp _KiFreezeFlag,0 ; during boot we can take
jnz Kt0e01 ; 'transition faults' on the
; debugger before it's been locked
cmp _KiBugCheckData, 0 ; If crashed, handle trap in
jnz Kt0e01 ; normal manner
mov eax, 0ffh ; OldIrql = -1
jmp short Kt0e12a
if FAST_BOP
Kt0eVdmAlert:
;
; If a page fault occured while we are in VDM alert mode (processing
; v86 trap without building trap frame), we will restore all the
; registers and return to its recovery routine which is stored in
; the TsSegGs of original trap frame.
;
mov eax, PCR[PcVdmAlert]
mov dword ptr PCR[PcVdmAlert], 0
mov [ebp].TsEip, eax
mov esp,ebp ; (esp) -> trap frame
jmp _KiExceptionExit ; join common code
endif ; FAST_BOP
_KiTrap0E endp
page ,132
subttl "Trap0F -- Intel Reserved"
;++
;
; Routine Description:
;
; The trap 0F should never occur. If, however, the exception occurs in
; USER mode, the current process will be terminated. If the exception
; occurs in KERNEL mode, a bugcheck will be raised. NO registered
; handler, if any, will be invoked to handle the exception.
;
; Arguments:
;
; None
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kitf_a, kitf_t, NoAbiosAssist
align dword
public _KiTrap0F
_KiTrap0F proc
push 0 ; push dummy error code
ENTER_TRAP kitf_a, kitf_t
sti
mov eax, EXCEPTION_RESERVED_TRAP ; (eax) = trap type
jmp _KiSystemFatalException ; go terminate the system
_KiTrap0F endp
page ,132
subttl "Coprocessor Error"
;++
;
; Routine Description:
;
; Handle Coprocessor Error.
;
; This exception is used on 486 or above only. For i386, it uses
; IRQ 13 instead.
;
; Arguments:
;
; At entry, the saved CS:EIP point to the aborted instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit10_a, kit10_t, NoAbiosAssist
align dword
public _KiTrap10
_KiTrap10 proc
push 0 ; push dummy error code
ENTER_TRAP kit10_a, kit10_t
mov eax, PCR[PcPrcbData+PbCurrentThread] ; Correct context for
cmp eax, PCR[PcPrcbData+PbNpxThread] ; fault?
mov ecx, [eax].ThInitialStack
lea ecx, [ecx]-NPX_FRAME_LENGTH
je Kt0715 ; Yes - go try to dispatch it
;
; We are in the wrong NPX context and can not dispatch the exception right now.
; Set up the target thread for a delay exception.
;
; Note: we don't think this is a possible case, but just to be safe...
;
sti ; Re-enable context switches
or dword ptr [ecx].FpCr0NpxState, CR0_TS ; Set for delayed error
jmp _KiExceptionExit
_KiTrap10 endp
page ,132
subttl "Alignment fault"
;++
;
; Routine Description:
;
; Handle alignment faults.
;
; This exception occurs when an unaligned data access is made by a thread
; with alignment checking turned on.
;
; The x86 will not do any alignment checking. Only threads which have
; the appropriate bit set in EFLAGS will generate alignment faults.
;
; The exception will never occur in kernel mode. (hardware limitation)
;
; Arguments:
;
; At entry, the saved CS:EIP point to the faulting instruction.
; Error code is provided.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit11_a, kit11_t, NoAbiosAssist
align dword
public _KiTrap11
_KiTrap11 proc
ENTER_TRAP kit11_a, kit11_t
sti
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt11_01 ; v86 mode => usermode
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previous mode = USER
jz Kt11_10
;
; Check to make sure that the AutoAlignment state of this thread is FALSE.
; If not, this fault occurred because the thread messed with its own EFLAGS.
; In order to "fixup" this fault, we just clear the ALIGN_CHECK bit in the
; EFLAGS and restart the instruction. Exceptions will only be generated if
; AutoAlignment is FALSE.
;
Kt11_01:
mov ebx,PCR[PcPrcbData+PbCurrentThread] ; (ebx)-> Current Thread
bt dword [ebx].ThThreadFlags, KTHREAD_AUTO_ALIGNMENT_BIT
jnc kt11_00
;
; This fault was generated even though the thread had AutoAlignment set to
; TRUE. So we fix it up by setting the correct state in his EFLAGS and
; restarting the instruction.
;
and dword ptr [ebp]+TsEflags, NOT EFLAGS_ALIGN_CHECK
jmp _KiExceptionExit
kt11_00:
mov ebx, [ebp]+TsEip ; (ebx)->faulting instruction
mov edx, EXCEPT_LIMIT_ACCESS; assume it is limit violation
mov esi, [ebp]+TsHardwareEsp; (esi) = User Stack pointer
cmp word ptr [ebp]+TsErrCode, 0 ; Is errorcode = 0?
jz short kt11_05 ; if z, yes, go dispatch exception
mov edx, EXCEPT_UNKNOWN_ACCESS
kt11_05:
mov eax, STATUS_DATATYPE_MISALIGNMENT
jmp CommonDispatchException2Args ; Won't return
kt11_10:
;
; We should never be here, since the 486 will not generate alignment faults
; in kernel mode.
;
mov eax, EXCEPTION_ALIGNMENT_CHECK ; (eax) = trap type
jmp _KiSystemFatalException
_KiTrap11 endp
;++
;
; Routine Description:
;
; Handle XMMI Exception.
;;
; Arguments:
;
; At entry, the saved CS:EIP point to the aborted instruction.
; No error code is provided with the error.
;
; Return value:
;
; None
;
;--
ASSUME DS:NOTHING, SS:NOTHING, ES:NOTHING
ENTER_DR_ASSIST kit13_a, kit13_t, NoAbiosAssist
align dword
public _KiTrap13
_KiTrap13 proc
push 0 ; push dummy error code
ENTER_TRAP kit13_a, kit13_t
mov eax, PCR[PcPrcbData+PbNpxThread] ; Correct context for fault?
cmp eax, PCR[PcPrcbData+PbCurrentThread]
je Kt13_10 ; Yes - go try to dispatch it
;
; Katmai New Instruction exceptions are precise and occur immediately.
; if we are in the wrong NPX context, bugcheck the system.
;
; stop the system
stdCall _KeBugCheck2,<TRAP_CAUSE_UNKNOWN,13,eax,0,0,ebp>
Kt13_10:
mov ecx, [eax].ThInitialStack ; (ecx) -> top of kernel stack
sub ecx, NPX_FRAME_LENGTH
;
; TrapFrame is built by ENTER_TRAP.
; XMMI are accessible from all IA execution modes:
; Protected Mode, Real address mode, Virtual 8086 mode
;
Kt13_15:
.errnz (EFLAGS_V86_MASK AND 0FF00FFFFh)
test byte ptr [ebp]+TsEFlags+2,EFLAGS_V86_MASK/010000h
jnz Kt13_130 ; v86 mode
;
; eflags.vm=0 (not v86 mode)
;
.errnz (MODE_MASK AND 0FFFFFF00h)
test byte ptr [ebp]+TsSegCs, MODE_MASK ; Is previousMode=USER?
jz Kt13_05 ; if z, previousmode=SYSTEM
;
; eflags.vm=0 (not v86 mode)
; previousMode=USER
;
cmp word ptr [ebp]+TsSegCs,KGDT_R3_CODE OR RPL_MASK
jne Kt13_110 ; May still be a vdm...
;
; eflags.vm=0 (not v86 mode)
; previousMode=USER
; Cs=00011011
;
; We are about to dispatch a XMMI floating point exception to user mode.
;
; (ebp) - Trap frame
; (ecx) - CurrentThread's NPX save area (PCR[PcInitialStack])
; (eax) - CurrentThread
; Dispatch
Kt13_20:
;
; Some type of coprocessor exception has occured for the current thread.
;
; Interrupts disabled
;
mov ebx, cr0
and ebx, NOT (CR0_MP+CR0_EM+CR0_TS)
mov cr0, ebx ; Clear MP+TS+EM to do fxsave
;
; Save the faulting state so we can inspect the cause of the floating
; point fault
;
FXSAVE_ECX
if DBG
test dword ptr [ecx].FpCr0NpxState, NOT (CR0_MP+CR0_EM+CR0_TS)
jnz Kt13_dbg2
endif
or ebx, NPX_STATE_NOT_LOADED ; CR0_TS | CR0_MP
or ebx,[ecx]+FpCr0NpxState ; restore this thread's CR0 NPX state
mov cr0, ebx ; set TS so next ESC access causes trap
;
; Clear TS bit in Cr0NpxFlags in case it was set to trigger this trap.
;
and dword ptr [ecx].FpCr0NpxState, NOT CR0_TS
;
; The state is no longer in the coprocessor. Clear ThNpxState and
; re-enable interrupts to allow context switching.
;
mov byte ptr [eax].ThNpxState, NPX_STATE_NOT_LOADED
mov dword ptr PCR[PcPrcbData+PbNpxThread], 0 ; No state in coprocessor
sti
; (eax) = ExcepCode - Exception code to put into exception record
; (ebx) = ExceptAddress - Addr of instruction which the hardware exception occurs
; (ecx) = NumParms - Number of additional parameters
; (edx) = Parameter1
; (esi) = Parameter2
; (edi) = Parameter3
mov ebx, [ebp].TsEip ; Eip is from trap frame, not from FxErrorOffset
movzx eax, word ptr [ecx] + FxMXCsr
mov edx, eax
shr edx, 7 ; get the mask
not edx
mov esi, 0 ; (esi) = operand addr, addr is computed from
; trap frame, not from FxDataOffset
;
; Exception will be handled in user's handler if there is one declared.
;
and eax, FSW_INVALID_OPERATION + FSW_DENORMAL + FSW_ZERO_DIVIDE + FSW_OVERFLOW + FSW_UNDERFLOW + FSW_PRECISION
and eax, edx
.errnz (FSW_INVALID_OPERATION AND 0FFFFFF00h)
test al, FSW_INVALID_OPERATION ; Is it an invalid op exception?
jz short Kt13_40 ; if z, no, go Kt13_40
;
; Invalid Operation Exception - Invalid arithmetic operand
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_TRAPS
jmp CommonDispatchException1Arg0d ; Won't return
Kt13_40:
; Check for floating zero divide exception
;
.errnz (FSW_ZERO_DIVIDE AND 0FFFFFF00h)
test al, FSW_ZERO_DIVIDE ; Is it a zero divide error?
jz short Kt13_50 ; if z, no, go Kt13_50
;
; Division-By-Zero Exception
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_TRAPS
jmp CommonDispatchException1Arg0d ; Won't return
Kt13_50:
; Check for denormal error
;
.errnz (FSW_DENORMAL AND 0FFFFFF00h)
test al, FSW_DENORMAL ; Is it a denormal error?
jz short Kt13_60 ; if z, no, go Kt13_60
;
; Denormal Operand Exception
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_TRAPS
jmp CommonDispatchException1Arg0d ; Won't return
Kt13_60:
; Check for floating overflow error
;
.errnz (FSW_OVERFLOW AND 0FFFFFF00h)
test al, FSW_OVERFLOW ; Is it an overflow error?
jz short Kt13_70 ; if z, no, go Kt13_70
;
; Numeric Overflow Exception
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_FAULTS
jmp CommonDispatchException1Arg0d ; Won't return
Kt13_70:
; Check for floating underflow error
;
.errnz (FSW_UNDERFLOW AND 0FFFFFF00h)
test al, FSW_UNDERFLOW ; Is it a underflow error?
jz short Kt13_80 ; if z, no, go Kt13_80
;
; Numeric Underflow Exception
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_FAULTS
jmp CommonDispatchException1Arg0d ; Won't return
Kt13_80:
; Check for precision (IEEE inexact) error
;
.errnz (FSW_PRECISION AND 0FFFFFF00h)
test al, FSW_PRECISION ; Is it a precision error
jz short Kt13_100 ; if z, no, go Kt13_100
;
; Inexact-Result (Precision) Exception
; Raise exception
;
mov eax, STATUS_FLOAT_MULTIPLE_FAULTS
jmp CommonDispatchException1Arg0d ; Won't return
; Huh?
Kt13_100:
; If status word does not indicate error, then something is wrong...
; (Note: that we have done a sti, before the status is examined)
sti
; stop the system
stdCall _KeBugCheck2,<TRAP_CAUSE_UNKNOWN,13,eax,0,1,ebp>
;
; eflags.vm=0 (not v86 mode)
; previousMode=USER
; Cs=!00011011
; (We should have (eax) -> CurrentThread)
;
Kt13_110:
; Check to see if this process is a vdm
mov ebx,PCR[PcPrcbData+PbCurrentThread] ; (ebx) -> CurrentThread
mov ebx,[ebx]+ThApcState+AsProcess ; (ebx) -> CurrentProcess
cmp dword ptr [ebx]+PrVdmObjects,0 ; is this a vdm process?
je Kt13_20 ; no, dispatch exception
; yes, drop down to v86 mode
;
; eflags.vm=1 (v86 mode)
;
Kt13_130:
; Turn off TS
mov ebx,CR0
and ebx,NOT CR0_TS
mov CR0,ebx
and dword ptr [ecx]+FpCr0NpxState,NOT CR0_TS
;
; Reflect the exception to the vdm, the VdmHandler enables interrupts
;
; Raise Irql to APC level before enabling interrupts
RaiseIrql APC_LEVEL
push eax ; Save OldIrql
sti
stdCall _VdmDispatchIRQ13, <ebp> ; ebp - Trapframe
test al,0fh
jnz Kt13_135
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp Kt13_20 ; could not reflect, gen exception
Kt13_135:
pop ecx ; (TOS) = OldIrql
LowerIrql ecx
jmp _KiExceptionExit
;
; eflags.vm=0 (not v86 mode)
; previousMode=SYSTEM
;
Kt13_05:
; stop the system
stdCall _KeBugCheck2,<TRAP_CAUSE_UNKNOWN,13,0,0,2,ebp>
if DBG
Kt13_dbg1: int 3
Kt13_dbg2: int 3
Kt13_dbg3: int 3
sti
jmp short $-2
endif
_KiTrap13 endp
page ,132
subttl "Coprocessor Error Handler"
;++
;
; Routine Description:
;
; When the FPU detects an error, it raises its error line. This
; was supposed to be routed directly to the x86 to cause a trap 16
; (which would actually occur when the x86 encountered the next FP
; instruction).
;
; However, the ISA design routes the error line to IRQ13 on the
; slave 8259. So an interrupt will be generated whenever the FPU
; discovers an error. Unfortunately, we could be executing system
; code at the time, in which case we can't dispatch the exception.
;
; So we force emulation of the intended behavior. This interrupt
; handler merely sets TS and Cr0NpxState TS and dismisses the interrupt.
; Then, on the next user FP instruction, a trap 07 will be generated, and
; the exception can be dispatched then.
;
; Note that we don't have to clear the FP exeception here,
; since that will be done in the trap 07 handler. The x86 will
; generate the trap 07 before the FPU gets a chance to raise another
; error interrupt. We'll want to save the FPU state in the trap 07
; handler WITH the error information.
;
; Note the caller must clear the FPU error latch. (this is done in
; the hal).
;
; Arguments:
;
; None
;
; Return value:
;
; None
;
;--
ASSUME DS:FLAT, SS:NOTHING, ES:NOTHING
align dword
cPublicProc _KiCoprocessorError ,0
;
; Set TS in Cr0NpxState - the next time this thread runs an ESC
; instruction the error will be dispatched. We also need to set TS
; in CR0 in case the owner of the NPX is currently running.
;
; Bit must be set in FpCr0NpxState before CR0.
;
mov eax, PCR[PcPrcbData+PbNpxThread]
mov eax, [eax].ThInitialStack
sub eax, NPX_FRAME_LENGTH ; Space for NPX_FRAME
or dword ptr [eax].FpCr0NpxState, CR0_TS
mov eax, cr0
or eax, CR0_TS
mov cr0, eax
stdRET _KiCoprocessorError
stdENDP _KiCoprocessorError
;
; BBT cannot instrument code between BBT_Exclude_Trap_Code_Begin and this label
;
public _BBT_Exclude_Trap_Code_End
_BBT_Exclude_Trap_Code_End equ $
int 3
;++
;
; VOID
; KiFlushNPXState (
; PFLOATING_SAVE_AREA SaveArea
; )
;
; Routine Description:
;
; When a thread's NPX context is requested (most likely by a debugger)
; this function is called to flush the thread's NPX context out of the
; compressor if required.
;
; Arguments:
;
; Pointer to a location where this function must do fnsave for the
; current thread.
;
; NOTE that this pointer can be NON-NULL only if KeI386FxsrPresent is
; set (FXSR feature is present)
;
; Return value:
;
; None
;
;--
ASSUME DS:FLAT, SS:NOTHING, ES:NOTHING
align dword
SaveArea equ [esp + 20]
cPublicProc _KiFlushNPXState ,1
cPublicFpo 1, 4
push esi
push edi
push ebx
pushfd
cli ; don't context switch
mov edi, PCR[PcSelfPcr]
mov esi, [edi].PcPrcbData+PbCurrentThread
cmp byte ptr [esi].ThNpxState, NPX_STATE_LOADED
je short fnpx20
fnpx00:
; NPX state is not loaded. If SaveArea is non-null, we need to return
; the saved FP state in fnsave format.
cmp dword ptr SaveArea, 0
je fnpx70
if DBG
;
; SaveArea can be NON-NULL ONLY when FXSR feature is present
;
test byte ptr _KeI386FxsrPresent, 1
jnz @f
int 3
@@:
endif
;
; Need to convert the (not loaded) NPX state of the current thread
; to FNSAVE format into the SaveArea
;
mov ebx, cr0
.errnz ((CR0_MP+CR0_TS+CR0_EM) AND 0FFFFFF00h)
test bl, CR0_MP+CR0_TS+CR0_EM
jz short fnpx07
and ebx, NOT (CR0_MP+CR0_TS+CR0_EM)
mov cr0, ebx ; allow frstor (& fnsave) to work
fnpx07:
;
; If NPX state is for some other thread, save it away
;
mov eax, [edi].PcPrcbData+PbNpxThread ; Owner of NPX state
or eax, eax
jz short fnpx10 ; no - skip save
cmp byte ptr [eax].ThNpxState, NPX_STATE_LOADED
jne short fnpx10 ; not loaded, skip save
ifndef NT_UP
if DBG
; This can only happen UP where the context is not unloaded on a swap
int 3
endif
endif
;
; Save current owners NPX state
;
mov ecx, [eax].ThInitialStack
sub ecx, NPX_FRAME_LENGTH ; Space for NPX_FRAME
FXSAVE_ECX
mov byte ptr [eax].ThNpxState, NPX_STATE_NOT_LOADED
fnpx10:
;
; Load current thread's NPX state
;
mov ecx, [esi].ThInitialStack ; (ecx) -> top of kernel stack
sub ecx, NPX_FRAME_LENGTH
FXRSTOR_ECX ; reload NPX context
mov edx, [ecx]+FpCr0NpxState
mov ecx, SaveArea
jmp short fnpx40
fnpx20:
;
; Current thread has NPX state in the coprocessor, flush it
;
mov ebx, cr0
.errnz ((CR0_MP+CR0_TS+CR0_EM) AND 0FFFFFF00h)
test bl, CR0_MP+CR0_TS+CR0_EM
jz short fnpx30
and ebx, NOT (CR0_MP+CR0_TS+CR0_EM)
mov cr0, ebx ; allow frstor (& fnsave) to work
fnpx30:
mov ecx, [esi].ThInitialStack ; (ecx) -> top of kernel stack
test byte ptr _KeI386FxsrPresent, 1
lea ecx, dword ptr [ecx-NPX_FRAME_LENGTH]
; This thread's NPX state can be flagged as not loaded
mov byte ptr [esi].ThNpxState, NPX_STATE_NOT_LOADED
mov edx, [ecx]+FpCr0NpxState
jz short fnpx40
FXSAVE_ECX
; Do fnsave to SaveArea if it is non-null
mov ecx, SaveArea
jecxz short fnpx50
fnpx40:
fnsave [ecx] ; Flush NPX state to save area
fwait ; Make sure data is in save area
fnpx50:
xor eax, eax
or ebx, NPX_STATE_NOT_LOADED ; Or in new thread's CR0
mov [edi].PcPrcbData+PbNpxThread, eax ; Clear NPX owner
or ebx, edx ; Merge new thread setable state
mov cr0, ebx
fnpx70:
popfd ; enable interrupts
pop ebx
pop edi
pop esi
stdRET _KiFlushNPXState
stdENDP _KiFlushNPXState
page ,132
subttl "Processing System Fatal Exceptions"
;++
;
; Routine Description:
;
; This routine processes the system fatal exceptions.
; The machine state and trap type will be displayed and
; System will be stopped.
;
; Arguments:
;
; (eax) = Trap type
; (ebp) -> machine state frame
;
; Return value:
;
; system stopped.
;
;--
assume ds:nothing, es:nothing, ss:nothing, fs:nothing, gs:nothing
align dword
public _KiSystemFatalException
_KiSystemFatalException proc
.FPO (0, 0, 0, 0, 0, FPO_TRAPFRAME)
stdCall _KeBugCheck2,<UNEXPECTED_KERNEL_MODE_TRAP,eax,0,0,0,ebp>
ret
_KiSystemFatalException endp
page
subttl "Continue Execution System Service"
;++
;
; NTSTATUS
; NtContinue (
; IN PCONTEXT ContextRecord,
; IN BOOLEAN TestAlert
; )
;
; Routine Description:
;
; This routine is called as a system service to continue execution after
; an exception has occurred. Its function is to transfer information from
; the specified context record into the trap frame that was built when the
; system service was executed, and then exit the system as if an exception
; had occurred.
;
; WARNING - Do not call this routine directly, always call it as
; ZwContinue!!! This is required because it needs the
; trapframe built by KiSystemService.
;
; Arguments:
;
; KTrapFrame (ebp+0: after setup) -> base of KTrapFrame
;
; ContextRecord (ebp+8: after setup) = Supplies a pointer to a context rec.
;
; TestAlert (esp+12: after setup) = Supplies a boolean value that specifies
; whether alert should be tested for the previous processor mode.
;
; Return Value:
;
; Normally there is no return from this routine. However, if the specified
; context record is misaligned or is not accessible, then the appropriate
; status code is returned.
;
;--
NcTrapFrame equ [ebp + 0]
NcContextRecord equ [ebp + 8]
NcTestAlert equ [ebp + 12]
align dword
cPublicProc _NtContinue ,2
push ebp
;
; Restore old trap frame address since this service exits directly rather
; than returning.
;
mov ebx, PCR[PcPrcbData+PbCurrentThread] ; get current thread address
mov edx, [ebp].TsEdx ; restore old trap frame address
mov [ebx].ThTrapFrame, edx ;
;
; Call KiContinue to load ContextRecord into TrapFrame. On x86 TrapFrame
; is an atomic entity, so we don't need to allocate any other space here.
;
; KiContinue(NcContextRecord, 0, NcTrapFrame)
;
mov ebp,esp
mov eax, NcTrapFrame
mov ecx, NcContextRecord
stdCall _KiContinue, <ecx, 0, eax>
or eax,eax ; return value 0?
jnz short Nc20 ; KiContinue failed, go report error
;
; Check to determine if alert should be tested for the previous processor mode.
;
cmp byte ptr NcTestAlert,0 ; Check test alert flag
je short Nc10 ; if z, don't test alert, go Nc10
mov al,byte ptr [ebx]+ThPreviousMode ; No need to xor eax, eax.
stdCall _KeTestAlertThread, <eax> ; test alert for current thread
Nc10: pop ebp ; (ebp) -> TrapFrame
mov esp,ebp ; (esp) = (ebp) -> trapframe
jmp _KiServiceExit2 ; common exit
Nc20: pop ebp ; (ebp) -> TrapFrame
mov esp,ebp ; (esp) = (ebp) -> trapframe
jmp _KiServiceExit ; common exit
stdENDP _NtContinue
page
subttl "Raise Exception System Service"
;++
;
; NTSTATUS
; NtRaiseException (
; IN PEXCEPTION_RECORD ExceptionRecord,
; IN PCONTEXT ContextRecord,
; IN BOOLEAN FirstChance
; )
;
; Routine Description:
;
; This routine is called as a system service to raise an exception. Its
; function is to transfer information from the specified context record
; into the trap frame that was built when the system service was executed.
; The exception may be raised as a first or second chance exception.
;
; WARNING - Do not call this routine directly, always call it as
; ZwRaiseException!!! This is required because it needs the
; trapframe built by KiSystemService.
;
; NOTE - KiSystemService will terminate the ExceptionList, which is
; not what we want for this case, so we will fish it out of
; the trap frame and restore it.
;
; Arguments:
;
; TrapFrame (ebp+0: before setup) -> System trap frame for this call
;
; ExceptionRecord (ebp+8: after setup) -> An exception record.
;
; ContextRecord (ebp+12: after setup) -> Points to a context record.
;
; FirstChance (ebp+16: after setup) -> Supplies a boolean value that
; specifies whether the exception is to be raised as a first (TRUE)
; or second chance (FALSE) exception.
;
; Return Value:
;
; None.
;--
align dword
cPublicProc _NtRaiseException ,3
NtRaiseException:
push ebp
;
; Restore old trap frame address since this service exits directly rather
; than returning.
;
mov ebx, PCR[PcPrcbData+PbCurrentThread] ; get current thread address
mov edx, [ebp].TsEdx ; restore old trap frame address
mov [ebx].ThTrapFrame, edx ;
;
; Put back the ExceptionList so the exception can be properly
; dispatched.
;
mov ebp,esp ; [ebp+0] -> TrapFrame
mov ebx, [ebp+0] ; (ebx)->TrapFrame
mov edx, [ebp+16] ; (edx) = First chance indicator
mov eax, [ebx]+TsExceptionList ; Old exception list
mov ecx, [ebp+12] ; (ecx)->ContextRecord
mov PCR[PcExceptionList],eax
mov eax, [ebp+8] ; (eax)->ExceptionRecord
;
; KiRaiseException(ExceptionRecord, ContextRecord, ExceptionFrame,
; TrapFrame, FirstChance)
;
stdCall _KiRaiseException,<eax, ecx, 0, ebx, edx>
pop ebp
mov esp,ebp ; (esp) = (ebp) -> trap frame
;
; If the exception was handled, then the trap frame has been edited to
; reflect new state, and we'll simply exit the system service to get
; the effect of a continue.
;
; If the exception was not handled, exit via KiServiceExit so the
; return status is propagated back to the caller.
;
or eax, eax ; test exception handled
jnz _KiServiceExit ; if exception not handled
jmp _KiServiceExit2
stdENDP _NtRaiseException
page
subttl "Reflect Exception to a Vdm"
;++
;
; Routine Description:
; Local stub which reflects an exception to a VDM using
; Ki386VdmReflectException,
;
; Arguments:
;
; ebp -> Trap frame
; ss:esp + 4 = trap number
;
; Returns
; ret value from Ki386VdmReflectException
; interrupts are disabled uppon return
;
cPublicProc _Ki386VdmReflectException_A, 1
sub esp, 4*2
RaiseIrql APC_LEVEL
sti
mov [esp+4], eax ; Save OldIrql
mov eax, [esp+12] ; Pick up trap number
mov [esp+0], eax
call _Ki386VdmReflectException@4 ; pops one dword
mov ecx, [esp+0] ; (ecx) = OldIrql
mov [esp+0], eax ; Save return code
LowerIrql ecx
pop eax ; pops second dword
ret 4
stdENDP _Ki386VdmReflectException_A
_TEXT$00 ends
end
|
; ----------------------------------------------------------------
; Z88DK INTERFACE LIBRARY FOR THE BIFROST* ENGINE - RELEASE 1.2/L
;
; See "bifrost_l.h" for further details
; ----------------------------------------------------------------
SECTION code_clib
SECTION code_bifrost_l
PUBLIC asm_BIFROSTL_getAnimGroup
asm_BIFROSTL_getAnimGroup:
; L=tile
bit 7,l ; compare with BIFROST_STATIC
ret nz ; if (static tile) return tile
srl l
ld a,(58780)
and a
ret z ; if (2 frames per animation) return tile/2
srl l
ret ; if (4 frames per animation) return tile/4
|
<%
import collections
import pwnlib.abi
import pwnlib.constants
import pwnlib.shellcraft
import six
%>
<%docstring>msync(addr, length, flags) -> str
Invokes the syscall msync.
See 'man 2 msync' for more information.
Arguments:
addr(void*): addr
len(size_t): len
flags(int): flags
Returns:
int
</%docstring>
<%page args="addr=0, length=0, flags=0"/>
<%
abi = pwnlib.abi.ABI.syscall()
stack = abi.stack
regs = abi.register_arguments[1:]
allregs = pwnlib.shellcraft.registers.current()
can_pushstr = ['addr']
can_pushstr_array = []
argument_names = ['addr', 'length', 'flags']
argument_values = [addr, length, 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=%r' % (name, arg))
# 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_msync']:
if hasattr(pwnlib.constants, syscall):
break
else:
raise Exception("Could not locate any syscalls: %r" % syscalls)
%>
/* msync(${', '.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)} |
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r13
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x1935d, %r11
nop
nop
nop
dec %r9
mov $0x6162636465666768, %r13
movq %r13, %xmm1
movups %xmm1, (%r11)
nop
inc %r12
lea addresses_D_ht+0x1c87d, %rsi
lea addresses_D_ht+0x6ced, %rdi
nop
nop
cmp %r10, %r10
mov $107, %rcx
rep movsw
nop
nop
nop
nop
nop
sub $8048, %r11
lea addresses_D_ht+0x16a7d, %r11
clflush (%r11)
nop
nop
nop
nop
nop
and $21822, %rdi
movl $0x61626364, (%r11)
nop
nop
nop
nop
inc %rcx
lea addresses_D_ht+0x14a55, %rcx
nop
xor $53938, %r10
movw $0x6162, (%rcx)
nop
nop
nop
sub %rsi, %rsi
lea addresses_normal_ht+0xea7d, %r11
nop
nop
add %rdi, %rdi
movb $0x61, (%r11)
nop
nop
nop
nop
nop
add %rsi, %rsi
lea addresses_WT_ht+0xe47d, %rdi
clflush (%rdi)
nop
nop
nop
nop
nop
sub $63183, %r12
mov (%rdi), %r9w
nop
nop
nop
xor $57279, %r13
lea addresses_A_ht+0x11415, %rsi
lea addresses_UC_ht+0x113ca, %rdi
nop
nop
nop
nop
dec %r9
mov $61, %rcx
rep movsl
add $61387, %r10
lea addresses_D_ht+0x1e97d, %r12
nop
nop
nop
dec %rdi
mov (%r12), %esi
nop
nop
nop
nop
and %rsi, %rsi
lea addresses_normal_ht+0xb9b5, %rsi
lea addresses_A_ht+0x15b7d, %rdi
nop
nop
nop
nop
nop
sub %r12, %r12
mov $51, %rcx
rep movsb
dec %rcx
lea addresses_WC_ht+0x8afd, %rsi
lea addresses_WT_ht+0x7421, %rdi
nop
nop
xor %r9, %r9
mov $8, %rcx
rep movsb
nop
nop
nop
nop
and %rdi, %rdi
lea addresses_UC_ht+0x4f85, %rsi
lea addresses_normal_ht+0x1dd7d, %rdi
nop
cmp %r9, %r9
mov $77, %rcx
rep movsb
nop
nop
nop
sub %r10, %r10
lea addresses_WC_ht+0x12bf9, %r13
nop
nop
nop
dec %rcx
movups (%r13), %xmm3
vpextrq $0, %xmm3, %rsi
nop
nop
nop
nop
and %r13, %r13
lea addresses_WC_ht+0x3fbd, %rsi
lea addresses_D_ht+0xe87d, %rdi
nop
nop
mfence
mov $69, %rcx
rep movsl
inc %r9
lea addresses_WC_ht+0x8a7d, %rsi
lea addresses_D_ht+0x1cbf5, %rdi
nop
nop
add $5629, %r11
mov $35, %rcx
rep movsl
nop
nop
cmp $40364, %r11
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r13
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r14
push %r8
push %r9
push %rax
push %rbx
// Store
lea addresses_normal+0xdc0d, %r9
nop
nop
nop
and %r8, %r8
movl $0x51525354, (%r9)
nop
nop
nop
nop
cmp $45387, %r12
// Store
lea addresses_PSE+0xc37d, %rax
add %r9, %r9
mov $0x5152535455565758, %r12
movq %r12, %xmm5
vmovaps %ymm5, (%rax)
add $52241, %rax
// Store
mov $0x76ab4d0000000575, %r14
nop
nop
nop
nop
nop
sub %r10, %r10
movl $0x51525354, (%r14)
nop
nop
nop
inc %rax
// Store
lea addresses_A+0x7c7d, %r8
clflush (%r8)
nop
nop
nop
sub $15059, %r9
movl $0x51525354, (%r8)
nop
nop
nop
add $6437, %rax
// Faulty Load
lea addresses_UC+0x1827d, %r9
nop
and $48604, %r14
vmovntdqa (%r9), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $0, %xmm6, %rax
lea oracles, %r14
and $0xff, %rax
shlq $12, %rax
mov (%r14,%rax,1), %rax
pop %rbx
pop %rax
pop %r9
pop %r8
pop %r14
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': True, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal'}}
{'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': True, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_PSE'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': True, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_A_ht'}}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_normal_ht'}}
{'src': {'congruent': 2, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}}
{'46': 12, '00': 151, '48': 880, '45': 20786}
45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 00 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 48 00 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 00 45 45 45 45 45 45 48 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 48 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 00 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 48 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 00 00 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 45 48 45 45 45 45 45 45
*/
|
extern m7_ippsSM3Pack:function
extern n8_ippsSM3Pack:function
extern y8_ippsSM3Pack:function
extern e9_ippsSM3Pack:function
extern l9_ippsSM3Pack:function
extern n0_ippsSM3Pack:function
extern k0_ippsSM3Pack:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsSM3Pack
.Larraddr_ippsSM3Pack:
dq m7_ippsSM3Pack
dq n8_ippsSM3Pack
dq y8_ippsSM3Pack
dq e9_ippsSM3Pack
dq l9_ippsSM3Pack
dq n0_ippsSM3Pack
dq k0_ippsSM3Pack
segment .text
global ippsSM3Pack:function (ippsSM3Pack.LEndippsSM3Pack - ippsSM3Pack)
.Lin_ippsSM3Pack:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsSM3Pack:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsSM3Pack]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsSM3Pack:
|
;
; Copyright (c) 2010 The WebM project authors. All Rights Reserved.
;
; Use of this source code is governed by a BSD-style license
; that can be found in the LICENSE file in the root of the source
; tree. An additional intellectual property rights grant can be found
; in the file PATENTS. All contributing project authors may
; be found in the AUTHORS file in the root of the source tree.
;
%include "vpx_ports/x86_abi_support.asm"
extern sym(vp8_bilinear_filters_x86_8)
%define BLOCK_HEIGHT_WIDTH 4
%define vp8_filter_weight 128
%define VP8_FILTER_SHIFT 7
SECTION .text
;void vp8_filter_block1d_h6_mmx
;(
; unsigned char *src_ptr,
; unsigned short *output_ptr,
; unsigned int src_pixels_per_line,
; unsigned int pixel_step,
; unsigned int output_height,
; unsigned int output_width,
; short * vp8_filter
;)
global sym(vp8_filter_block1d_h6_mmx) PRIVATE
sym(vp8_filter_block1d_h6_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 7
GET_GOT rbx
push rsi
push rdi
; end prolog
mov rdx, arg(6) ;vp8_filter
movq mm1, [rdx + 16] ; do both the negative taps first!!!
movq mm2, [rdx + 32] ;
movq mm6, [rdx + 48] ;
movq mm7, [rdx + 64] ;
mov rdi, arg(1) ;output_ptr
mov rsi, arg(0) ;src_ptr
movsxd rcx, dword ptr arg(4) ;output_height
movsxd rax, dword ptr arg(5) ;output_width ; destination pitch?
pxor mm0, mm0 ; mm0 = 00000000
.nextrow:
movq mm3, [rsi-2] ; mm3 = p-2..p5
movq mm4, mm3 ; mm4 = p-2..p5
psrlq mm3, 8 ; mm3 = p-1..p5
punpcklbw mm3, mm0 ; mm3 = p-1..p2
pmullw mm3, mm1 ; mm3 *= kernel 1 modifiers.
movq mm5, mm4 ; mm5 = p-2..p5
punpckhbw mm4, mm0 ; mm5 = p2..p5
pmullw mm4, mm7 ; mm5 *= kernel 4 modifiers
paddsw mm3, mm4 ; mm3 += mm5
movq mm4, mm5 ; mm4 = p-2..p5;
psrlq mm5, 16 ; mm5 = p0..p5;
punpcklbw mm5, mm0 ; mm5 = p0..p3
pmullw mm5, mm2 ; mm5 *= kernel 2 modifiers
paddsw mm3, mm5 ; mm3 += mm5
movq mm5, mm4 ; mm5 = p-2..p5
psrlq mm4, 24 ; mm4 = p1..p5
punpcklbw mm4, mm0 ; mm4 = p1..p4
pmullw mm4, mm6 ; mm5 *= kernel 3 modifiers
paddsw mm3, mm4 ; mm3 += mm5
; do outer positive taps
movd mm4, [rsi+3]
punpcklbw mm4, mm0 ; mm5 = p3..p6
pmullw mm4, [rdx+80] ; mm5 *= kernel 0 modifiers
paddsw mm3, mm4 ; mm3 += mm5
punpcklbw mm5, mm0 ; mm5 = p-2..p1
pmullw mm5, [rdx] ; mm5 *= kernel 5 modifiers
paddsw mm3, mm5 ; mm3 += mm5
paddsw mm3, [GLOBAL(rd)] ; mm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; mm3 /= 128
packuswb mm3, mm0 ; pack and unpack to saturate
punpcklbw mm3, mm0 ;
movq [rdi], mm3 ; store the results in the destination
%if ABI_IS_32BIT
add rsi, dword ptr arg(2) ;src_pixels_per_line ; next line
add rdi, rax;
%else
movsxd r8, dword ptr arg(2) ;src_pixels_per_line
add rdi, rax;
add rsi, r8 ; next line
%endif
dec rcx ; decrement count
jnz .nextrow ; next row
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
UNSHADOW_ARGS
pop rbp
ret
;void vp8_filter_block1dc_v6_mmx
;(
; short *src_ptr,
; unsigned char *output_ptr,
; int output_pitch,
; unsigned int pixels_per_line,
; unsigned int pixel_step,
; unsigned int output_height,
; unsigned int output_width,
; short * vp8_filter
;)
global sym(vp8_filter_block1dc_v6_mmx) PRIVATE
sym(vp8_filter_block1dc_v6_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 8
GET_GOT rbx
push rsi
push rdi
; end prolog
movq mm5, [GLOBAL(rd)]
push rbx
mov rbx, arg(7) ;vp8_filter
movq mm1, [rbx + 16] ; do both the negative taps first!!!
movq mm2, [rbx + 32] ;
movq mm6, [rbx + 48] ;
movq mm7, [rbx + 64] ;
movsxd rdx, dword ptr arg(3) ;pixels_per_line
mov rdi, arg(1) ;output_ptr
mov rsi, arg(0) ;src_ptr
sub rsi, rdx
sub rsi, rdx
movsxd rcx, DWORD PTR arg(5) ;output_height
movsxd rax, DWORD PTR arg(2) ;output_pitch ; destination pitch?
pxor mm0, mm0 ; mm0 = 00000000
.nextrow_cv:
movq mm3, [rsi+rdx] ; mm3 = p0..p8 = row -1
pmullw mm3, mm1 ; mm3 *= kernel 1 modifiers.
movq mm4, [rsi + 4*rdx] ; mm4 = p0..p3 = row 2
pmullw mm4, mm7 ; mm4 *= kernel 4 modifiers.
paddsw mm3, mm4 ; mm3 += mm4
movq mm4, [rsi + 2*rdx] ; mm4 = p0..p3 = row 0
pmullw mm4, mm2 ; mm4 *= kernel 2 modifiers.
paddsw mm3, mm4 ; mm3 += mm4
movq mm4, [rsi] ; mm4 = p0..p3 = row -2
pmullw mm4, [rbx] ; mm4 *= kernel 0 modifiers.
paddsw mm3, mm4 ; mm3 += mm4
add rsi, rdx ; move source forward 1 line to avoid 3 * pitch
movq mm4, [rsi + 2*rdx] ; mm4 = p0..p3 = row 1
pmullw mm4, mm6 ; mm4 *= kernel 3 modifiers.
paddsw mm3, mm4 ; mm3 += mm4
movq mm4, [rsi + 4*rdx] ; mm4 = p0..p3 = row 3
pmullw mm4, [rbx +80] ; mm4 *= kernel 3 modifiers.
paddsw mm3, mm4 ; mm3 += mm4
paddsw mm3, mm5 ; mm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; mm3 /= 128
packuswb mm3, mm0 ; pack and saturate
movd [rdi],mm3 ; store the results in the destination
; the subsequent iterations repeat 3 out of 4 of these reads. Since the
; recon block should be in cache this shouldn't cost much. Its obviously
; avoidable!!!.
lea rdi, [rdi+rax] ;
dec rcx ; decrement count
jnz .nextrow_cv ; next row
pop rbx
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
UNSHADOW_ARGS
pop rbp
ret
;void bilinear_predict8x4_mmx
;(
; unsigned char *src_ptr,
; int src_pixels_per_line,
; int xoffset,
; int yoffset,
; unsigned char *dst_ptr,
; int dst_pitch
;)
global sym(vp8_bilinear_predict8x4_mmx) PRIVATE
sym(vp8_bilinear_predict8x4_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
GET_GOT rbx
push rsi
push rdi
; end prolog
;const short *HFilter = vp8_bilinear_filters_x86_8[xoffset];
;const short *VFilter = vp8_bilinear_filters_x86_8[yoffset];
movsxd rax, dword ptr arg(2) ;xoffset
mov rdi, arg(4) ;dst_ptr ;
lea rcx, [GLOBAL(sym(vp8_bilinear_filters_x86_8))]
shl rax, 5
mov rsi, arg(0) ;src_ptr ;
add rax, rcx
movsxd rdx, dword ptr arg(5) ;dst_pitch
movq mm1, [rax] ;
movq mm2, [rax+16] ;
movsxd rax, dword ptr arg(3) ;yoffset
pxor mm0, mm0 ;
shl rax, 5
add rax, rcx
lea rcx, [rdi+rdx*4] ;
movsxd rdx, dword ptr arg(1) ;src_pixels_per_line ;
; get the first horizontal line done ;
movq mm3, [rsi] ; xx 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14
movq mm4, mm3 ; make a copy of current line
punpcklbw mm3, mm0 ; xx 00 01 02 03 04 05 06
punpckhbw mm4, mm0 ;
pmullw mm3, mm1 ;
pmullw mm4, mm1 ;
movq mm5, [rsi+1] ;
movq mm6, mm5 ;
punpcklbw mm5, mm0 ;
punpckhbw mm6, mm0 ;
pmullw mm5, mm2 ;
pmullw mm6, mm2 ;
paddw mm3, mm5 ;
paddw mm4, mm6 ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
paddw mm4, [GLOBAL(rd)] ;
psraw mm4, VP8_FILTER_SHIFT ;
movq mm7, mm3 ;
packuswb mm7, mm4 ;
add rsi, rdx ; next line
.next_row_8x4:
movq mm3, [rsi] ; xx 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14
movq mm4, mm3 ; make a copy of current line
punpcklbw mm3, mm0 ; xx 00 01 02 03 04 05 06
punpckhbw mm4, mm0 ;
pmullw mm3, mm1 ;
pmullw mm4, mm1 ;
movq mm5, [rsi+1] ;
movq mm6, mm5 ;
punpcklbw mm5, mm0 ;
punpckhbw mm6, mm0 ;
pmullw mm5, mm2 ;
pmullw mm6, mm2 ;
paddw mm3, mm5 ;
paddw mm4, mm6 ;
movq mm5, mm7 ;
movq mm6, mm7 ;
punpcklbw mm5, mm0 ;
punpckhbw mm6, mm0
pmullw mm5, [rax] ;
pmullw mm6, [rax] ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
paddw mm4, [GLOBAL(rd)] ;
psraw mm4, VP8_FILTER_SHIFT ;
movq mm7, mm3 ;
packuswb mm7, mm4 ;
pmullw mm3, [rax+16] ;
pmullw mm4, [rax+16] ;
paddw mm3, mm5 ;
paddw mm4, mm6 ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
paddw mm4, [GLOBAL(rd)] ;
psraw mm4, VP8_FILTER_SHIFT ;
packuswb mm3, mm4
movq [rdi], mm3 ; store the results in the destination
%if ABI_IS_32BIT
add rsi, rdx ; next line
add rdi, dword ptr arg(5) ;dst_pitch ;
%else
movsxd r8, dword ptr arg(5) ;dst_pitch
add rsi, rdx ; next line
add rdi, r8
%endif
cmp rdi, rcx ;
jne .next_row_8x4
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
UNSHADOW_ARGS
pop rbp
ret
;void bilinear_predict4x4_mmx
;(
; unsigned char *src_ptr,
; int src_pixels_per_line,
; int xoffset,
; int yoffset,
; unsigned char *dst_ptr,
; int dst_pitch
;)
global sym(vp8_bilinear_predict4x4_mmx) PRIVATE
sym(vp8_bilinear_predict4x4_mmx):
push rbp
mov rbp, rsp
SHADOW_ARGS_TO_STACK 6
GET_GOT rbx
push rsi
push rdi
; end prolog
;const short *HFilter = vp8_bilinear_filters_x86_8[xoffset];
;const short *VFilter = vp8_bilinear_filters_x86_8[yoffset];
movsxd rax, dword ptr arg(2) ;xoffset
mov rdi, arg(4) ;dst_ptr ;
lea rcx, [GLOBAL(sym(vp8_bilinear_filters_x86_8))]
shl rax, 5
add rax, rcx ; HFilter
mov rsi, arg(0) ;src_ptr ;
movsxd rdx, dword ptr arg(5) ;ldst_pitch
movq mm1, [rax] ;
movq mm2, [rax+16] ;
movsxd rax, dword ptr arg(3) ;yoffset
pxor mm0, mm0 ;
shl rax, 5
add rax, rcx
lea rcx, [rdi+rdx*4] ;
movsxd rdx, dword ptr arg(1) ;src_pixels_per_line ;
; get the first horizontal line done ;
movd mm3, [rsi] ; xx 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14
punpcklbw mm3, mm0 ; xx 00 01 02 03 04 05 06
pmullw mm3, mm1 ;
movd mm5, [rsi+1] ;
punpcklbw mm5, mm0 ;
pmullw mm5, mm2 ;
paddw mm3, mm5 ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
movq mm7, mm3 ;
packuswb mm7, mm0 ;
add rsi, rdx ; next line
.next_row_4x4:
movd mm3, [rsi] ; xx 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14
punpcklbw mm3, mm0 ; xx 00 01 02 03 04 05 06
pmullw mm3, mm1 ;
movd mm5, [rsi+1] ;
punpcklbw mm5, mm0 ;
pmullw mm5, mm2 ;
paddw mm3, mm5 ;
movq mm5, mm7 ;
punpcklbw mm5, mm0 ;
pmullw mm5, [rax] ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
movq mm7, mm3 ;
packuswb mm7, mm0 ;
pmullw mm3, [rax+16] ;
paddw mm3, mm5 ;
paddw mm3, [GLOBAL(rd)] ; xmm3 += round value
psraw mm3, VP8_FILTER_SHIFT ; xmm3 /= 128
packuswb mm3, mm0
movd [rdi], mm3 ; store the results in the destination
%if ABI_IS_32BIT
add rsi, rdx ; next line
add rdi, dword ptr arg(5) ;dst_pitch ;
%else
movsxd r8, dword ptr arg(5) ;dst_pitch ;
add rsi, rdx ; next line
add rdi, r8
%endif
cmp rdi, rcx ;
jne .next_row_4x4
; begin epilog
pop rdi
pop rsi
RESTORE_GOT
UNSHADOW_ARGS
pop rbp
ret
SECTION_RODATA
align 16
rd:
times 4 dw 0x40
align 16
global HIDDEN_DATA(sym(vp8_six_tap_x86))
sym(vp8_six_tap_x86):
times 8 dw 0
times 8 dw 0
times 8 dw 128
times 8 dw 0
times 8 dw 0
times 8 dw 0
times 8 dw 0
times 8 dw -6
times 8 dw 123
times 8 dw 12
times 8 dw -1
times 8 dw 0
times 8 dw 2
times 8 dw -11
times 8 dw 108
times 8 dw 36
times 8 dw -8
times 8 dw 1
times 8 dw 0
times 8 dw -9
times 8 dw 93
times 8 dw 50
times 8 dw -6
times 8 dw 0
times 8 dw 3
times 8 dw -16
times 8 dw 77
times 8 dw 77
times 8 dw -16
times 8 dw 3
times 8 dw 0
times 8 dw -6
times 8 dw 50
times 8 dw 93
times 8 dw -9
times 8 dw 0
times 8 dw 1
times 8 dw -8
times 8 dw 36
times 8 dw 108
times 8 dw -11
times 8 dw 2
times 8 dw 0
times 8 dw -1
times 8 dw 12
times 8 dw 123
times 8 dw -6
times 8 dw 0
|
bits 64
section .text
add [rax], al
|
db 0 ; species ID placeholder
db 70, 75, 60, 105, 100, 60
; hp atk def spd sat sdf
db ELECTRIC, ELECTRIC ; type
db 45 ; catch rate
db 166 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F50 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/manectric/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_SLOW ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, TOXIC, ZAP_CANNON, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, PSYCHIC_M, SHADOW_BALL, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, THUNDERPUNCH, DREAM_EATER, REST, ATTRACT, THIEF, FIRE_PUNCH, NIGHTMARE, FLASH
; end
|
;
; Copyright (c) 2016, Alliance for Open Media. All rights reserved
;
; This source code is subject to the terms of the BSD 2 Clause License and
; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
; was not distributed with this source code in the LICENSE file, you can
; obtain it at www.aomedia.org/license/software. If the Alliance for Open
; Media Patent License 1.0 was not distributed with this source code in the
; PATENTS file, you can obtain it at www.aomedia.org/license/patent.
;
;
%include "aom_ports/x86_abi_support.asm"
%macro STACK_FRAME_CREATE_X3 0
%if ABI_IS_32BIT
%define src_ptr rsi
%define src_stride rax
%define ref_ptr rdi
%define ref_stride rdx
%define end_ptr rcx
%define ret_var rbx
%define result_ptr arg(4)
%define height dword ptr arg(4)
push rbp
mov rbp, rsp
push rsi
push rdi
push rbx
mov rsi, arg(0) ; src_ptr
mov rdi, arg(2) ; ref_ptr
movsxd rax, dword ptr arg(1) ; src_stride
movsxd rdx, dword ptr arg(3) ; ref_stride
%else
%if LIBAOM_YASM_WIN64
SAVE_XMM 7, u
%define src_ptr rcx
%define src_stride rdx
%define ref_ptr r8
%define ref_stride r9
%define end_ptr r10
%define ret_var r11
%define result_ptr [rsp+xmm_stack_space+8+4*8]
%define height dword ptr [rsp+xmm_stack_space+8+4*8]
%else
%define src_ptr rdi
%define src_stride rsi
%define ref_ptr rdx
%define ref_stride rcx
%define end_ptr r9
%define ret_var r10
%define result_ptr r8
%define height r8
%endif
%endif
%endmacro
%macro STACK_FRAME_DESTROY_X3 0
%define src_ptr
%define src_stride
%define ref_ptr
%define ref_stride
%define end_ptr
%define ret_var
%define result_ptr
%define height
%if ABI_IS_32BIT
pop rbx
pop rdi
pop rsi
pop rbp
%else
%if LIBAOM_YASM_WIN64
RESTORE_XMM
%endif
%endif
ret
%endmacro
%macro PROCESS_16X2X3 5
%if %1==0
movdqa xmm0, XMMWORD PTR [%2]
lddqu xmm5, XMMWORD PTR [%3]
lddqu xmm6, XMMWORD PTR [%3+1]
lddqu xmm7, XMMWORD PTR [%3+2]
psadbw xmm5, xmm0
psadbw xmm6, xmm0
psadbw xmm7, xmm0
%else
movdqa xmm0, XMMWORD PTR [%2]
lddqu xmm1, XMMWORD PTR [%3]
lddqu xmm2, XMMWORD PTR [%3+1]
lddqu xmm3, XMMWORD PTR [%3+2]
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
paddw xmm5, xmm1
paddw xmm6, xmm2
paddw xmm7, xmm3
%endif
movdqa xmm0, XMMWORD PTR [%2+%4]
lddqu xmm1, XMMWORD PTR [%3+%5]
lddqu xmm2, XMMWORD PTR [%3+%5+1]
lddqu xmm3, XMMWORD PTR [%3+%5+2]
%if %1==0 || %1==1
lea %2, [%2+%4*2]
lea %3, [%3+%5*2]
%endif
psadbw xmm1, xmm0
psadbw xmm2, xmm0
psadbw xmm3, xmm0
paddw xmm5, xmm1
paddw xmm6, xmm2
paddw xmm7, xmm3
%endmacro
%macro PROCESS_8X2X3 5
%if %1==0
movq mm0, QWORD PTR [%2]
movq mm5, QWORD PTR [%3]
movq mm6, QWORD PTR [%3+1]
movq mm7, QWORD PTR [%3+2]
psadbw mm5, mm0
psadbw mm6, mm0
psadbw mm7, mm0
%else
movq mm0, QWORD PTR [%2]
movq mm1, QWORD PTR [%3]
movq mm2, QWORD PTR [%3+1]
movq mm3, QWORD PTR [%3+2]
psadbw mm1, mm0
psadbw mm2, mm0
psadbw mm3, mm0
paddw mm5, mm1
paddw mm6, mm2
paddw mm7, mm3
%endif
movq mm0, QWORD PTR [%2+%4]
movq mm1, QWORD PTR [%3+%5]
movq mm2, QWORD PTR [%3+%5+1]
movq mm3, QWORD PTR [%3+%5+2]
%if %1==0 || %1==1
lea %2, [%2+%4*2]
lea %3, [%3+%5*2]
%endif
psadbw mm1, mm0
psadbw mm2, mm0
psadbw mm3, mm0
paddw mm5, mm1
paddw mm6, mm2
paddw mm7, mm3
%endmacro
;void int aom_sad16x16x3_sse3(
; unsigned char *src_ptr,
; int src_stride,
; unsigned char *ref_ptr,
; int ref_stride,
; int *results)
global sym(aom_sad16x16x3_sse3) PRIVATE
sym(aom_sad16x16x3_sse3):
STACK_FRAME_CREATE_X3
PROCESS_16X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride
mov rcx, result_ptr
movq xmm0, xmm5
psrldq xmm5, 8
paddw xmm0, xmm5
movd [rcx], xmm0
;-
movq xmm0, xmm6
psrldq xmm6, 8
paddw xmm0, xmm6
movd [rcx+4], xmm0
;-
movq xmm0, xmm7
psrldq xmm7, 8
paddw xmm0, xmm7
movd [rcx+8], xmm0
STACK_FRAME_DESTROY_X3
;void int aom_sad16x8x3_sse3(
; unsigned char *src_ptr,
; int src_stride,
; unsigned char *ref_ptr,
; int ref_stride,
; int *results)
global sym(aom_sad16x8x3_sse3) PRIVATE
sym(aom_sad16x8x3_sse3):
STACK_FRAME_CREATE_X3
PROCESS_16X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_16X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride
mov rcx, result_ptr
movq xmm0, xmm5
psrldq xmm5, 8
paddw xmm0, xmm5
movd [rcx], xmm0
;-
movq xmm0, xmm6
psrldq xmm6, 8
paddw xmm0, xmm6
movd [rcx+4], xmm0
;-
movq xmm0, xmm7
psrldq xmm7, 8
paddw xmm0, xmm7
movd [rcx+8], xmm0
STACK_FRAME_DESTROY_X3
;void int aom_sad8x16x3_sse3(
; unsigned char *src_ptr,
; int src_stride,
; unsigned char *ref_ptr,
; int ref_stride,
; int *results)
global sym(aom_sad8x16x3_sse3) PRIVATE
sym(aom_sad8x16x3_sse3):
STACK_FRAME_CREATE_X3
PROCESS_8X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride
mov rcx, result_ptr
punpckldq mm5, mm6
movq [rcx], mm5
movd [rcx+8], mm7
STACK_FRAME_DESTROY_X3
;void int aom_sad8x8x3_sse3(
; unsigned char *src_ptr,
; int src_stride,
; unsigned char *ref_ptr,
; int ref_stride,
; int *results)
global sym(aom_sad8x8x3_sse3) PRIVATE
sym(aom_sad8x8x3_sse3):
STACK_FRAME_CREATE_X3
PROCESS_8X2X3 0, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 1, src_ptr, ref_ptr, src_stride, ref_stride
PROCESS_8X2X3 2, src_ptr, ref_ptr, src_stride, ref_stride
mov rcx, result_ptr
punpckldq mm5, mm6
movq [rcx], mm5
movd [rcx+8], mm7
STACK_FRAME_DESTROY_X3
;void int aom_sad4x4x3_sse3(
; unsigned char *src_ptr,
; int src_stride,
; unsigned char *ref_ptr,
; int ref_stride,
; int *results)
global sym(aom_sad4x4x3_sse3) PRIVATE
sym(aom_sad4x4x3_sse3):
STACK_FRAME_CREATE_X3
movd mm0, DWORD PTR [src_ptr]
movd mm1, DWORD PTR [ref_ptr]
movd mm2, DWORD PTR [src_ptr+src_stride]
movd mm3, DWORD PTR [ref_ptr+ref_stride]
punpcklbw mm0, mm2
punpcklbw mm1, mm3
movd mm4, DWORD PTR [ref_ptr+1]
movd mm5, DWORD PTR [ref_ptr+2]
movd mm2, DWORD PTR [ref_ptr+ref_stride+1]
movd mm3, DWORD PTR [ref_ptr+ref_stride+2]
psadbw mm1, mm0
punpcklbw mm4, mm2
punpcklbw mm5, mm3
psadbw mm4, mm0
psadbw mm5, mm0
lea src_ptr, [src_ptr+src_stride*2]
lea ref_ptr, [ref_ptr+ref_stride*2]
movd mm0, DWORD PTR [src_ptr]
movd mm2, DWORD PTR [ref_ptr]
movd mm3, DWORD PTR [src_ptr+src_stride]
movd mm6, DWORD PTR [ref_ptr+ref_stride]
punpcklbw mm0, mm3
punpcklbw mm2, mm6
movd mm3, DWORD PTR [ref_ptr+1]
movd mm7, DWORD PTR [ref_ptr+2]
psadbw mm2, mm0
paddw mm1, mm2
movd mm2, DWORD PTR [ref_ptr+ref_stride+1]
movd mm6, DWORD PTR [ref_ptr+ref_stride+2]
punpcklbw mm3, mm2
punpcklbw mm7, mm6
psadbw mm3, mm0
psadbw mm7, mm0
paddw mm3, mm4
paddw mm7, mm5
mov rcx, result_ptr
punpckldq mm1, mm3
movq [rcx], mm1
movd [rcx+8], mm7
STACK_FRAME_DESTROY_X3
|
;
; Amstrad CPC library
; (CALLER linkage for function pointers)
;
; creates a copy of a string in CPC format
;
; char __LIB__ *cpc_rsx_strcpy(char *dst, char *src);
;
; $Id: cpc_rsx_strcpy.asm,v 1.1 2008/05/26 06:38:08 stefano Exp $
;
XLIB cpc_rsx_strcpy
LIB cpc_rsx_strcpy_callee
XREF ASMDISP_CPC_RSX_STRCPY_CALLEE
.cpc_rsx_strcpy
pop bc
pop hl
pop de
push de
push hl
push bc
jp cpc_rsx_strcpy_callee + ASMDISP_CPC_RSX_STRCPY_CALLEE
|
// Copyright (c) 2017-2019 Hartmut Kaiser
// Copyright (c) 2018 Shahrzad Shirzad
// Copyright (c) 2018 Tianyi Zhang
//
// 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)
#if !defined(PHYLANX_PRIMITIVES_COMPARISON_IMPL_SEP_02_2018_0443PM)
#define PHYLANX_PRIMITIVES_COMPARISON_IMPL_SEP_02_2018_0443PM
#include <phylanx/config.hpp>
#include <phylanx/execution_tree/primitives/node_data_helpers.hpp>
#include <phylanx/ir/node_data.hpp>
#include <phylanx/ir/ranges.hpp>
#include <phylanx/plugins/booleans/comparison.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/naming.hpp>
#include <hpx/include/util.hpp>
#include <hpx/throw_exception.hpp>
#include <array>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <numeric>
#include <string>
#include <utility>
#include <vector>
#include <blaze/Math.h>
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
#include <blaze_tensor/Math.h>
#endif
///////////////////////////////////////////////////////////////////////////////
namespace phylanx { namespace execution_tree { namespace primitives
{
///////////////////////////////////////////////////////////////////////////
template <typename Op>
comparison<Op>::comparison(primitive_arguments_type&& operands,
std::string const& name, std::string const& codename)
: primitive_component_base(std::move(operands), name, codename)
{}
///////////////////////////////////////////////////////////////////////////
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison0d(
ir::node_data<T>&& lhs, ir::node_data<T>&& rhs,
bool propagate_type) const
{
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{
Op{}(lhs.scalar(), rhs.scalar()) ? T(1) : T(0)});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs.scalar(), rhs.scalar())});
}
///////////////////////////////////////////////////////////////////////////
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison1d1d(
ir::node_data<T>&& lhs, ir::node_data<T>&& rhs,
bool propagate_type) const
{
std::size_t lhs_size = lhs.dimension(0);
std::size_t rhs_size = rhs.dimension(0);
if (lhs_size != rhs_size)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::comparison1d1d",
util::generate_error_message(
"the dimensions of the operands do not match",
name_, codename_));
}
// TODO: SIMD functionality should be added, blaze implementation
// is not currently available
if (lhs.is_ref())
{
lhs = blaze::map(lhs.vector(), rhs.vector(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
else
{
lhs.vector() = blaze::map(lhs.vector(), rhs.vector(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{std::move(lhs)});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{std::move(lhs)});
}
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison1d(ir::node_data<T>&& lhs,
ir::node_data<T>&& rhs, bool propagate_type,
std::array<std::size_t, PHYLANX_MAX_DIMENSIONS> const& sizes) const
{
if (lhs.dimensions() != rhs.dimensions())
{
blaze::DynamicVector<T> lhs_data, rhs_data;
extract_value_vector(
lhs_data, std::move(lhs), sizes[0], name_, codename_);
extract_value_vector(
rhs_data, std::move(rhs), sizes[0], name_, codename_);
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{
blaze::map(lhs_data, rhs_data, [&](T x, T y) -> T {
return Op{}(x, y) ? T(1) : T(0);
})});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{blaze::map(lhs_data, rhs_data,
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); })});
}
return comparison1d1d(std::move(lhs), std::move(rhs), propagate_type);
}
///////////////////////////////////////////////////////////////////////////
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison2d2d(
ir::node_data<T>&& lhs, ir::node_data<T>&& rhs,
bool propagate_type) const
{
auto lhs_size = lhs.dimensions();
auto rhs_size = rhs.dimensions();
if (lhs_size != rhs_size)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::comparison2d2d",
util::generate_error_message(
"the dimensions of the operands do not match",
name_, codename_));
}
// TODO: SIMD functionality should be added, blaze implementation
// is not currently available
if (lhs.is_ref())
{
lhs = blaze::map(lhs.matrix(), rhs.matrix(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
else
{
lhs.matrix() = blaze::map(lhs.matrix(), rhs.matrix(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{std::move(lhs)});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{std::move(lhs)});
}
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison2d(ir::node_data<T>&& lhs,
ir::node_data<T>&& rhs, bool propagate_type,
std::array<std::size_t, PHYLANX_MAX_DIMENSIONS> const& sizes) const
{
if (lhs.dimensions() != rhs.dimensions())
{
blaze::DynamicMatrix<T> lhs_data, rhs_data;
extract_value_matrix(
lhs_data, std::move(lhs), sizes[0], sizes[1], name_, codename_);
extract_value_matrix(
rhs_data, std::move(rhs), sizes[0], sizes[1], name_, codename_);
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{
blaze::map(lhs_data, rhs_data, [&](T x, T y) -> T {
return Op{}(x, y) ? T(1) : T(0);
})});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{blaze::map(lhs_data, rhs_data,
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); })});
}
return comparison2d2d(std::move(lhs), std::move(rhs), propagate_type);
}
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
///////////////////////////////////////////////////////////////////////////
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison3d3d(
ir::node_data<T>&& lhs, ir::node_data<T>&& rhs,
bool propagate_type) const
{
auto lhs_size = lhs.dimensions();
auto rhs_size = rhs.dimensions();
if (lhs_size != rhs_size)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::comparison3d3d",
util::generate_error_message(
"the dimensions of the operands do not match",
name_, codename_));
}
// TODO: SIMD functionality should be added, blaze implementation
// is not currently available
if (lhs.is_ref())
{
lhs = blaze::map(lhs.tensor(), rhs.tensor(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
else
{
lhs.tensor() = blaze::map(lhs.tensor(), rhs.tensor(),
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); });
}
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{std::move(lhs)});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{std::move(lhs)});
}
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison3d(ir::node_data<T>&& lhs,
ir::node_data<T>&& rhs, bool propagate_type,
std::array<std::size_t, PHYLANX_MAX_DIMENSIONS> const& sizes) const
{
if (lhs.dimensions() != rhs.dimensions())
{
blaze::DynamicTensor<T> lhs_data, rhs_data;
extract_value_tensor(lhs_data, std::move(lhs), sizes[0], sizes[1],
sizes[2], name_, codename_);
extract_value_tensor(rhs_data, std::move(rhs), sizes[0], sizes[1],
sizes[2], name_, codename_);
if (propagate_type)
{
return primitive_argument_type(ir::node_data<T>{
blaze::map(lhs_data, rhs_data, [&](T x, T y) -> T {
return Op{}(x, y) ? T(1) : T(0);
})});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{blaze::map(lhs_data, rhs_data,
[&](T x, T y) -> std::uint8_t { return Op{}(x, y); })});
}
return comparison3d3d(std::move(lhs), std::move(rhs), propagate_type);
}
#endif
template <typename Op>
template <typename T>
primitive_argument_type comparison<Op>::comparison_all(
ir::node_data<T>&& lhs, ir::node_data<T>&& rhs,
bool propagate_type) const
{
auto sizes = extract_largest_dimensions(name_, codename_, lhs, rhs);
switch (extract_largest_dimension(name_, codename_, lhs, rhs))
{
case 0:
return comparison0d(std::move(lhs), std::move(rhs), propagate_type);
case 1:
return comparison1d(
std::move(lhs), std::move(rhs), propagate_type, sizes);
case 2:
return comparison2d(
std::move(lhs), std::move(rhs), propagate_type, sizes);
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
case 3:
return comparison3d(
std::move(lhs), std::move(rhs), propagate_type, sizes);
#endif
default:
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::comparison_all",
util::generate_error_message(
"left hand side operand has unsupported number of "
"dimensions",
name_, codename_));
}
}
template <typename Op>
struct comparison<Op>::visit_comparison
{
template <typename T1, typename T2>
primitive_argument_type operator()(T1, T2) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
primitive_argument_type operator()(std::vector<ast::expression>&&,
std::vector<ast::expression>&&) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
primitive_argument_type operator()(
ast::expression&&, ast::expression&&) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
primitive_argument_type operator()(primitive&&, primitive&&) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
template <typename T>
primitive_argument_type operator()(T && lhs, T && rhs) const
{
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs, rhs)});
}
primitive_argument_type operator()(ir::range&&, ir::range&&) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
primitive_argument_type operator()(
ir::dictionary&&, ir::dictionary&&) const
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
util::generate_error_message(
"left hand side and right hand side are incompatible "
"and can't be compared",
comparison_.name_, comparison_.codename_));
}
primitive_argument_type operator()(ir::node_data<double>&& lhs,
ir::node_data<std::int64_t>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(std::move(lhs),
ir::node_data<double>(std::move(rhs)), propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(
ir::node_data<double>{Op{}(lhs[0], rhs[0]) ? 1.0 : 0.0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(ir::node_data<std::int64_t>&& lhs,
ir::node_data<double>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(
ir::node_data<double>(std::move(lhs)), std::move(rhs),
propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(
ir::node_data<double>{Op{}(lhs[0], rhs[0]) ? 1.0 : 0.0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(ir::node_data<std::uint8_t>&& lhs,
ir::node_data<std::int64_t>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(std::move(lhs),
ir::node_data<std::uint8_t>{
std::move(rhs) != ir::node_data<std::int64_t>(0)},
propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(ir::node_data<std::int64_t>{
Op{}(lhs[0], rhs[0]) ? 1 : 0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(ir::node_data<std::int64_t>&& lhs,
ir::node_data<std::uint8_t>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(
ir::node_data<std::uint8_t>{
std::move(lhs) != ir::node_data<std::int64_t>(0)},
std::move(rhs), propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(ir::node_data<std::int64_t>{
Op{}(lhs[0], rhs[0]) ? 1 : 0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(ir::node_data<std::uint8_t>&& lhs,
ir::node_data<double>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(std::move(lhs),
ir::node_data<std::uint8_t>{
std::move(rhs) != ir::node_data<double>(0)},
propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(ir::node_data<double>{
Op{}(lhs[0], rhs[0]) ? 1.0 : 0.0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(ir::node_data<double>&& lhs,
ir::node_data<std::uint8_t>&& rhs) const
{
if (lhs.num_dimensions() != 0 || rhs.num_dimensions() != 0)
{
return comparison_.comparison_all(
ir::node_data<std::uint8_t>{
std::move(lhs) != ir::node_data<double>(0)},
std::move(rhs), propagate_type_);
}
if (propagate_type_)
{
return primitive_argument_type(ir::node_data<double>{
Op{}(lhs[0], rhs[0]) ? 1.0 : 0.0});
}
return primitive_argument_type(
ir::node_data<std::uint8_t>{Op{}(lhs[0], rhs[0])});
}
primitive_argument_type operator()(
ir::node_data<double>&& lhs, ir::node_data<double>&& rhs) const
{
return comparison_.comparison_all(
std::move(lhs), std::move(rhs), propagate_type_);
}
primitive_argument_type operator()(ir::node_data<std::uint8_t>&& lhs,
ir::node_data<std::uint8_t>&& rhs) const
{
return comparison_.comparison_all(
std::move(lhs), std::move(rhs), propagate_type_);
}
primitive_argument_type operator()(ir::node_data<std::int64_t>&& lhs,
ir::node_data<std::int64_t>&& rhs) const
{
return comparison_.comparison_all(
std::move(lhs), std::move(rhs), propagate_type_);
}
comparison const& comparison_;
bool propagate_type_;
};
template <typename Op>
hpx::future<primitive_argument_type> comparison<Op>::eval(
primitive_arguments_type const& operands,
primitive_arguments_type const& args, eval_context ctx) const
{
if (operands.size() < 2 || operands.size() > 3)
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
generate_error_message(
"the comparison primitive requires two or three operands"));
}
// either operand is allowed to be 'nil'
if (operands.size() == 3 && !valid(operands[2]))
{
HPX_THROW_EXCEPTION(hpx::bad_parameter,
"comparison<Op>::eval",
generate_error_message(
"the comparison primitive requires that the "
"arguments given by the operands array are valid"));
}
auto this_ = this->shared_from_this();
bool propagate_type = (operands.size() == 3 &&
phylanx::execution_tree::extract_scalar_boolean_value(operands[2]));
return hpx::dataflow(hpx::launch::sync, hpx::util::unwrapping(
[this_ = std::move(this_), propagate_type](
primitive_argument_type&& op1,
primitive_argument_type&& op2)
-> primitive_argument_type
{
return primitive_argument_type(
util::visit(visit_comparison{*this_, propagate_type},
std::move(op1.variant()), std::move(op2.variant())));
}),
value_operand(operands[0], args, name_, codename_, ctx),
value_operand(operands[1], args, name_, codename_, ctx));
}
}}}
#endif
|
#include <WiFi.h>
#include "network.hpp"
#include "pins.hpp"
#include "html.hpp"
void Network::setup(const Measurements* measurements) {
_measurements = measurements;
WiFi.disconnect();
WiFi.mode(WIFI_OFF);
WiFi.persistent(false);
setupWebserver();
pinMode(pins::Button1, INPUT);
const auto button1 = digitalRead(pins::Button1) == LOW;
if (button1) {
Serial.printf("Button 1 pressed. Going into configuration mode.\r\n");
gotoState(State::CONFIGURATION_MODE);
} else if (isWifiConfigured()) {
gotoState(State::CONFIGURED);
} else {
gotoState(State::NOT_CONFIGURED);
}
}
void Network::setupWebserver() {
_webServer.on("/", [this]() { onWebServerRoot(); });
_webServer.on("/config", [this]() { onWebServerConfig(); });
_webServer.onNotFound([this]() { onWebServerConfig(); });
}
void Network::loop() {
switch (_state) {
case State::INITIAL:
break;
case State::CONFIGURATION_MODE:
_dnsServer.processNextRequest();
_webServer.handleClient();
break;
case State::CONFIGURED:
if ((_onConnectHandled == false) and (isWifiConnected())) {
_onConnectHandled = true;
onWifiConnect();
} else if ((_onConnectHandled == true) and (not isWifiConnected())) {
_onConnectHandled = false;
}
_webServer.handleClient();
break;
case State::NOT_CONFIGURED:
break;
}
}
void Network::gotoState(State state) {
switch (_state) {
case State::INITIAL:
break;
case State::CONFIGURATION_MODE:
exitConfigurationMode();
break;
case State::CONFIGURED:
exitConfiguredMode();
break;
case State::NOT_CONFIGURED:
exitNotConfiguredMode();
break;
}
_state = state;
switch (_state) {
case State::INITIAL:
break;
case State::CONFIGURATION_MODE:
enterConfigurationMode();
break;
case State::CONFIGURED:
enterConfiguredMode();
break;
case State::NOT_CONFIGURED:
enterNotConfiguredMode();
break;
}
}
void Network::enterConfigurationMode() {
Serial.println(__FUNCTION__);
WiFi.mode(WIFI_AP);
// WiFi.persistent(false);
const IPAddress apIP(192, 168, 4, 1);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
WiFi.softAP("Co2-Sensor", nullptr, 1, false, 1);//, "", selectChannelForAp());
_dnsServer.setTTL(0);
_dnsServer.setErrorReplyCode(DNSReplyCode::NoError);
_dnsServer.start(53, "*", apIP);
_webServer.begin();
}
void Network::exitConfigurationMode() {
Serial.println(__FUNCTION__);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_MODE_NULL);
_dnsServer.stop();
_webServer.stop();
}
void Network::enterConfiguredMode() {
if (WiFi.getAutoConnect()) {
WiFi.setAutoConnect(false);
}
if (!WiFi.getAutoReconnect()) {
WiFi.setAutoReconnect(true);
}
WiFi.mode(WIFI_STA);
WiFi.setHostname(_config.getValueAsString("hostname").value_or("").c_str());
_webServer.begin();
WiFi.begin(
_config.getValueAsString("wifiSsid").value_or("").c_str(),
_config.getValueAsString("wifiPassword").value_or("").c_str()
);
}
void Network::exitConfiguredMode() {
Serial.println(__FUNCTION__);
WiFi.softAPdisconnect(true);
WiFi.mode(WIFI_MODE_NULL);
_webServer.stop();
}
void Network::enterNotConfiguredMode() {
}
void Network::exitNotConfiguredMode() {
}
bool Network::isWifiConfigured() const {
for (auto key : {"wifiSsid", "wifiPassword"}) {
auto value = _config.getValueAsString(key);
if ((not value) or (value.value().empty())) {
return false;
}
}
return true;
}
bool Network::isWifiConnected() const {
return (WiFi.status() == WL_CONNECTED);
}
void Network::onWifiConnect() {
const auto ntpServer = _config.getValueAsString("ntpServer").value_or("");
const auto tzInfo = _config.getValueAsString("tzInfo").value_or("");
if (not ntpServer.empty()) {
Serial.printf("Getting time from %s.\r\n", ntpServer.c_str());
configTzTime(tzInfo.c_str(), ntpServer.c_str());
// Call getLocalTime to trigger update of time. Unclear why this is required.
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("Failed to obtain time");
return;
}
Serial.println(&timeinfo, "Time is %A, %B %d %Y %H:%M:%S.");
}
}
long Network::getWifiRssi() const {
return WiFi.RSSI();
}
void Network::sendHttpRedirect(const char* url) {
_webServer.sendHeader("Location", url);
_webServer.send(302, contentTypeHtmlUtf8, "");
}
void Network::onWebServerRoot() {
if (_state == State::CONFIGURATION_MODE) {
sendHttpRedirect("http://192.168.4.1/config");
return;
}
if (not requestWebServerAuthentication()) {
return;
}
_webServer.setContentLength(CONTENT_LENGTH_UNKNOWN);
_webServer.send(200, contentTypeHtmlUtf8, html::header);
_webServer.sendContent("<meta http-equiv='refresh' content='15'>");
_webServer.sendContent(html::body);
char* s = nullptr;
auto& measurement = _measurements->dataLast().getMeasurement(0);
_webServer.sendContent("<div><table>");
if ((asprintf(&s,"<tr><td>Co2</td><td>%5.0f ppm</td></tr>", measurement.data[static_cast<std::underlying_type_t<Quantity>>(Quantity::Scd30Co2)]) != -1) and s) {
_webServer.sendContent(s);
free(s);
}
if ((asprintf(&s,"<tr><td>Temperature</td><td>%5.1f °C</td></tr>", measurement.data[static_cast<std::underlying_type_t<Quantity>>(Quantity::Scd30Temperature)]) != -1) and s) {
_webServer.sendContent(s);
free(s);
}
if ((asprintf(&s,"<tr><td>Humidity</td><td>%5.1f %%</td></tr>", measurement.data[static_cast<std::underlying_type_t<Quantity>>(Quantity::Scd30Humidity)]) != -1) and s) {
_webServer.sendContent(s);
free(s);
}
if ((asprintf(&s,"<tr><td>Pressure</td><td>%5.0f mBar</td></tr>", measurement.data[static_cast<std::underlying_type_t<Quantity>>(Quantity::Bmp280Pressure)]) != -1) and s) {
_webServer.sendContent(s);
free(s);
}
// #if 1
// struct tm timeinfo;
// if(!getLocalTime(&timeinfo)){
// Serial.println("Failed to obtain time");
// return;
// }
// Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
// #endif
_webServer.sendContent("</table></div>");
_webServer.sendContent(html::footer);
_webServer.client().stop();
}
bool Network::requestWebServerAuthentication() {
if (_config.getValueAsBool("webAuthentification").value_or(false) and (_state != State::CONFIGURATION_MODE)) {
if (!_webServer.authenticate(_config.getValueAsString("webUserName").value_or("").c_str(), _config.getValueAsString("webPassword").value_or("").c_str())) {
_webServer.requestAuthentication(BASIC_AUTH, "Sensor Login", "Authentication failed");
return false;
}
}
return true;
}
void Network::onWebServerConfig() {
if ((_state != State::CONFIGURATION_MODE) and (not requestWebServerAuthentication())) {
return;
}
_webServer.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
_webServer.sendHeader("Pragma", "no-cache");
_webServer.sendHeader("Expires", "0");
// Enable Pagination (Chunked Transfer)
_webServer.setContentLength(CONTENT_LENGTH_UNKNOWN);
_webServer.send(200, contentTypeHtmlUtf8, html::header);
_webServer.sendContent(html::body);
if (_webServer.method() == HTTP_GET) {
_webServer.sendContent("<form method='POST' action='/config'>");
for (const auto &entry : _config) {
char* s = nullptr;
int ret = 0;
_webServer.sendContent("<div>");
if (auto* value = std::get_if<std::string>(&entry._value)) {
ret = asprintf(&s,
"<label for='%s'>%s</label>"
"<input type='text' name='%s' id='%s' value='%s'/>"
, entry._name, entry._name, entry._name, entry._name, value->c_str());
} else if (auto* value = std::get_if<int>(&entry._value)) {
ret = asprintf(&s,
"<label for='%s'>%s</label>"
"<input type='number' name='%s' id='%s' value='%i'/>"
, entry._name, entry._name, entry._name, entry._name, *value);
} else if (auto* value = std::get_if<bool>(&entry._value)) {
ret = asprintf(&s,
"<label for='%s'>%s</label>"
"<input type='checkbox' name='%s' id='%s' value='1'%s/><input type='hidden' name='%s' value='0'/>"
, entry._name, entry._name, entry._name, entry._name, *value ? " checked='checked'" : "", entry._name);
}
if ((ret != -1) and s) {
_webServer.sendContent(s);
free(s);
}
_webServer.sendContent("</div>");
}
_webServer.sendContent(
"<div>"
"<input type='submit' name='submit' value='Save' />"
"</div>"
"</form>"
);
} else {
for (auto &entry : _config) {
if (not _webServer.hasArg(entry._name)) {
continue;
}
auto arg = _webServer.arg(entry._name);
if (auto* value = std::get_if<std::string>(&entry._value)) {
*value = std::string(arg.c_str());
} else if (auto* value = std::get_if<int>(&entry._value)) {
*value = arg.toInt();
} else if (auto* value = std::get_if<bool>(&entry._value)) {
*value = (arg == "1");
}
}
}
_webServer.sendContent(html::footer);
_webServer.client().stop();
if (_webServer.method() == HTTP_POST) {
_restartCallback();
}
}
void Network::onWebServerNotFound() {
if (_state == State::CONFIGURATION_MODE) {
sendHttpRedirect("http://192.168.4.1/config");
} else {
_webServer.send(404, contentTypePlain, "Not found.");
}
}
|
#include "extensions/filters/http/gfunction/gfunction_filter.h"
#include <algorithm>
#include <list>
#include <string>
#include <vector>
#include "envoy/http/header_map.h"
#include "common/buffer/buffer_impl.h"
#include "common/common/empty_string.h"
#include "common/common/hex.h"
#include "common/common/utility.h"
#include "common/http/headers.h"
#include "common/http/solo_filter_utility.h"
#include "common/http/utility.h"
#include "common/singleton/const_singleton.h"
#include "extensions/filters/http/solo_well_known_names.h"
namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace GcloudGfunc {
struct RcDetailsValues {
// The jwt_authn filter rejected the request
const std::string FunctionNotFound = "gfunction_function_not_found";
};
typedef ConstSingleton<RcDetailsValues> RcDetails;
class GcloudGfuncHeaderValues {
public:
const Http::LowerCaseString InvocationType{"x-amz-invocation-type"};
const std::string InvocationTypeEvent{"Event"};
const std::string InvocationTypeRequestResponse{"RequestResponse"};
const Http::LowerCaseString LogType{"x-amz-log-type"};
const std::string LogNone{"None"};
const Http::LowerCaseString HostHead{"x-amz-log-type"};
};
typedef ConstSingleton<GcloudGfuncHeaderValues> GcloudGfuncHeaderNames;
//const HeaderList GcloudGfuncFilter::HeadersToSign =
// GcloudAuthenticator::createHeaderToSign(
// {GcloudGfuncHeaderNames::get().InvocationType,
// GcloudGfuncHeaderNames::get().LogType, Http::Headers::get().HostLegacy,
// Http::Headers::get().ContentType});
GcloudGfuncFilter::GcloudGfuncFilter(Upstream::ClusterManager &cluster_manager
)
// TimeSource &time_source)
// : gcloud_authenticator_(time_source), cluster_manager_(cluster_manager) {}
: cluster_manager_(cluster_manager) {}
GcloudGfuncFilter::~GcloudGfuncFilter() {}
std::string GcloudGfuncFilter::functionUrlPath(const std::string &url) {
std::stringstream val;
absl::string_view host;
absl::string_view path;
Http::Utility::extractHostPathFromUri(url, host, path);
val << path;
return val.str();
}
std::string GcloudGfuncFilter::functionUrlHost(const std::string &url) {
std::stringstream val;
absl::string_view host;
absl::string_view path;
Http::Utility::extractHostPathFromUri(url, host, path);
val << host;
return val.str();
}
Http::FilterHeadersStatus
GcloudGfuncFilter::decodeHeaders(Http::HeaderMap &headers, bool end_stream) {
protocol_options_ = Http::SoloFilterUtility::resolveProtocolOptions<
const GcloudGfuncProtocolExtensionConfig>(
SoloHttpFilterNames::get().GcloudGfunc, decoder_callbacks_,
cluster_manager_);
if (!protocol_options_) {
return Http::FilterHeadersStatus::Continue;
}
route_ = decoder_callbacks_->route();
// great! this is an gcloud cluster. get the function information:
function_on_route_ =
Http::SoloFilterUtility::resolvePerFilterConfig<GcloudGfuncRouteConfig>(
SoloHttpFilterNames::get().GcloudGfunc, route_);
if (!function_on_route_) {
decoder_callbacks_->sendLocalReply(Http::Code::NotFound,
"no function present for Gcloud upstream",
nullptr, absl::nullopt, RcDetails::get().FunctionNotFound);
return Http::FilterHeadersStatus::StopIteration;
}
// gcloud_authenticator_.init(&protocol_options_->accessKey(),
// &protocol_options_->secretKey());
request_headers_ = &headers;
request_headers_->insertMethod().value().setReference(
Http::Headers::get().MethodValues.Post);
request_headers_->insertPath().value(functionUrlPath(
function_on_route_->url()));
if (end_stream) {
gfuncfy();
return Http::FilterHeadersStatus::Continue;
}
return Http::FilterHeadersStatus::StopIteration;
}
Http::FilterDataStatus GcloudGfuncFilter::decodeData(Buffer::Instance &data,
bool end_stream) {
if (!function_on_route_) {
return Http::FilterDataStatus::Continue;
}
if (data.length() != 0) {
has_body_ = true;
}
// gcloud_authenticator_.updatePayloadHash(data);
if (end_stream) {
gfuncfy();
return Http::FilterDataStatus::Continue;
}
return Http::FilterDataStatus::StopIterationAndBuffer;
}
Http::FilterTrailersStatus GcloudGfuncFilter::decodeTrailers(Http::HeaderMap &) {
if (function_on_route_ != nullptr) {
gfuncfy();
}
return Http::FilterTrailersStatus::Continue;
}
void GcloudGfuncFilter::gfuncfy() {
handleDefaultBody();
request_headers_->addReference(GcloudGfuncHeaderNames::get().LogType,
GcloudGfuncHeaderNames::get().LogNone);
request_headers_->insertHost().value(functionUrlHost(
function_on_route_->url()));
// gcloud_authenticator_.sign(request_headers_, HeadersToSign,
// protocol_options_->region());
cleanup();
}
void GcloudGfuncFilter::handleDefaultBody() {
if ((!has_body_) && function_on_route_->defaultBody()) {
Buffer::OwnedImpl data(function_on_route_->defaultBody().value());
request_headers_->insertContentType().value().setReference(
Http::Headers::get().ContentTypeValues.Json);
request_headers_->insertContentLength().value(data.length());
// gcloud_authenticator_.updatePayloadHash(data);
decoder_callbacks_->addDecodedData(data, false);
}
}
void GcloudGfuncFilter::cleanup() {
request_headers_ = nullptr;
function_on_route_ = nullptr;
protocol_options_.reset();
}
} // namespace GcloudGfunc
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy
|
object_const_def ; object_event constants
const ROUTE32_FISHER1
const ROUTE32_FISHER2
const ROUTE32_FISHER3
const ROUTE32_YOUNGSTER1
const ROUTE32_YOUNGSTER2
const ROUTE32_YOUNGSTER3
const ROUTE32_LASS1
const ROUTE32_COOLTRAINER_M
const ROUTE32_YOUNGSTER4
const ROUTE32_FISHER4
const ROUTE32_POKE_BALL1
const ROUTE32_FISHER5
const ROUTE32_FRIEDA
const ROUTE32_POKE_BALL2
Route32_MapScripts:
db 3 ; scene scripts
scene_script .DummyScene0 ; SCENE_DEFAULT
scene_script .DummyScene1 ; SCENE_ROUTE32_OFFER_SLOWPOKETAIL
scene_script .DummyScene2 ; SCENE_ROUTE32_NOTHING
db 1 ; callbacks
callback MAPCALLBACK_OBJECTS, .Frieda
.DummyScene0:
end
.DummyScene1:
end
.DummyScene2:
end
.Frieda:
readvar VAR_WEEKDAY
ifequal FRIDAY, .FriedaAppears
disappear ROUTE32_FRIEDA
return
.FriedaAppears:
appear ROUTE32_FRIEDA
return
Route32CooltrainerMScript:
faceplayer
Route32CooltrainerMContinueScene:
opentext
checkevent EVENT_GOT_MIRACLE_SEED_IN_ROUTE_32
iftrue .GotMiracleSeed
checkflag ENGINE_ZEPHYRBADGE
iffalse .DontHaveZephyrBadge
checkevent EVENT_GOT_TOGEPI_EGG_FROM_ELMS_AIDE
iftrue .GiveMiracleSeed
writetext Route32CooltrainerMText_AideIsWaiting
waitbutton
closetext
end
.Unreferenced:
writetext Route32CooltrainerMText_UnusedSproutTower
waitbutton
closetext
end
.GiveMiracleSeed:
writetext Route32CooltrainerMText_HaveThisSeed
buttonsound
verbosegiveitem MIRACLE_SEED
iffalse .BagFull
setevent EVENT_GOT_MIRACLE_SEED_IN_ROUTE_32
sjump .GotMiracleSeed
.DontHaveZephyrBadge:
writetext Route32CooltrainerMText_VioletGym
waitbutton
closetext
end
.GotMiracleSeed:
writetext Route32CooltrainerMText_ExperiencesShouldBeUseful
waitbutton
.BagFull:
closetext
end
Route32CooltrainerMStopsYouScene:
turnobject ROUTE32_COOLTRAINER_M, LEFT
turnobject PLAYER, RIGHT
opentext
writetext Route32CooltrainerMText_WhatsTheHurry
waitbutton
closetext
follow PLAYER, ROUTE32_COOLTRAINER_M
applymovement PLAYER, Movement_Route32CooltrainerMPushesYouBackToViolet
stopfollow
turnobject PLAYER, DOWN
scall Route32CooltrainerMContinueScene
applymovement ROUTE32_COOLTRAINER_M, Movement_Route32CooltrainerMReset1
applymovement ROUTE32_COOLTRAINER_M, Movement_Route32CooltrainerMReset2
end
Route32RoarTMGuyScript:
faceplayer
opentext
checkevent EVENT_GOT_TM05_ROAR
iftrue .AlreadyHaveRoar
writetext Text_RoarIntro
buttonsound
verbosegivetmhm TM_ROAR
iffalse .Finish
setevent EVENT_GOT_TM05_ROAR
.AlreadyHaveRoar:
writetext Text_RoarOutro
waitbutton
.Finish:
closetext
end
Route32WannaBuyASlowpokeTailScript:
turnobject ROUTE32_FISHER4, DOWN
turnobject PLAYER, UP
sjump _OfferToSellSlowpokeTail
SlowpokeTailSalesmanScript:
faceplayer
_OfferToSellSlowpokeTail:
setscene SCENE_ROUTE32_NOTHING
opentext
writetext Text_MillionDollarSlowpokeTail
yesorno
iffalse .refused
writetext Text_ThoughtKidsWereLoaded
waitbutton
closetext
end
.refused
writetext Text_RefusedToBuySlowpokeTail
waitbutton
closetext
end
TrainerCamperRoland:
trainer CAMPER, ROLAND, EVENT_BEAT_CAMPER_ROLAND, CamperRolandSeenText, CamperRolandBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext CamperRolandAfterText
waitbutton
closetext
end
TrainerFisherJustin:
trainer FISHER, JUSTIN, EVENT_BEAT_FISHER_JUSTIN, FisherJustinSeenText, FisherJustinBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext FisherJustinAfterText
waitbutton
closetext
end
TrainerFisherRalph1:
trainer FISHER, RALPH1, EVENT_BEAT_FISHER_RALPH, FisherRalph1SeenText, FisherRalph1BeatenText, 0, .Script
.Script:
loadvar VAR_CALLERID, PHONE_FISHER_RALPH
endifjustbattled
opentext
checkflag ENGINE_RALPH
iftrue .Rematch
checkflag ENGINE_FISH_SWARM
iftrue .Swarm
checkcellnum PHONE_FISHER_RALPH
iftrue .NumberAccepted
checkevent EVENT_RALPH_ASKED_FOR_PHONE_NUMBER
iftrue .AskAgain
writetext FisherRalphAfterText
buttonsound
setevent EVENT_RALPH_ASKED_FOR_PHONE_NUMBER
scall .AskNumber1
sjump .AskForNumber
.AskAgain:
scall .AskNumber2
.AskForNumber:
askforphonenumber PHONE_FISHER_RALPH
ifequal PHONE_CONTACTS_FULL, .PhoneFull
ifequal PHONE_CONTACT_REFUSED, .NumberDeclined
gettrainername STRING_BUFFER_3, FISHER, RALPH1
scall .RegisteredNumber
sjump .NumberAccepted
.Rematch:
scall .RematchStd
winlosstext FisherRalph1BeatenText, 0
readmem wRalphFightCount
ifequal 4, .Fight4
ifequal 3, .Fight3
ifequal 2, .Fight2
ifequal 1, .Fight1
ifequal 0, .LoadFight0
.Fight4:
checkevent EVENT_RESTORED_POWER_TO_KANTO
iftrue .LoadFight4
.Fight3:
checkevent EVENT_BEAT_ELITE_FOUR
iftrue .LoadFight3
.Fight2:
checkflag ENGINE_FLYPOINT_LAKE_OF_RAGE
iftrue .LoadFight2
.Fight1:
checkflag ENGINE_FLYPOINT_ECRUTEAK
iftrue .LoadFight1
.LoadFight0:
loadtrainer FISHER, RALPH1
startbattle
reloadmapafterbattle
loadmem wRalphFightCount, 1
clearflag ENGINE_RALPH
end
.LoadFight1:
loadtrainer FISHER, RALPH2
startbattle
reloadmapafterbattle
loadmem wRalphFightCount, 2
clearflag ENGINE_RALPH
end
.LoadFight2:
loadtrainer FISHER, RALPH3
startbattle
reloadmapafterbattle
loadmem wRalphFightCount, 3
clearflag ENGINE_RALPH
end
.LoadFight3:
loadtrainer FISHER, RALPH4
startbattle
reloadmapafterbattle
loadmem wRalphFightCount, 4
clearflag ENGINE_RALPH
end
.LoadFight4:
loadtrainer FISHER, RALPH5
startbattle
reloadmapafterbattle
clearflag ENGINE_RALPH
end
.Swarm:
writetext FisherRalphSwarmText
waitbutton
closetext
end
.AskNumber1:
jumpstd asknumber1m
end
.AskNumber2:
jumpstd asknumber2m
end
.RegisteredNumber:
jumpstd registerednumberm
end
.NumberAccepted:
jumpstd numberacceptedm
end
.NumberDeclined:
jumpstd numberdeclinedm
end
.PhoneFull:
jumpstd phonefullm
end
.RematchStd:
jumpstd rematchm
end
TrainerFisherHenry:
trainer FISHER, HENRY, EVENT_BEAT_FISHER_HENRY, FisherHenrySeenText, FisherHenryBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext FisherHenryAfterText
waitbutton
closetext
end
TrainerPicnickerLiz1:
trainer PICNICKER, LIZ1, EVENT_BEAT_PICNICKER_LIZ, PicnickerLiz1SeenText, PicnickerLiz1BeatenText, 0, .Script
.Script:
loadvar VAR_CALLERID, PHONE_PICNICKER_LIZ
endifjustbattled
opentext
checkflag ENGINE_LIZ
iftrue .Rematch
checkcellnum PHONE_PICNICKER_LIZ
iftrue .NumberAccepted
checkevent EVENT_LIZ_ASKED_FOR_PHONE_NUMBER
iftrue .AskAgain
writetext PicnickerLiz1AfterText
buttonsound
setevent EVENT_LIZ_ASKED_FOR_PHONE_NUMBER
scall .AskNumber1
sjump .AskForNumber
.AskAgain:
scall .AskNumber2
.AskForNumber:
askforphonenumber PHONE_PICNICKER_LIZ
ifequal PHONE_CONTACTS_FULL, .PhoneFull
ifequal PHONE_CONTACT_REFUSED, .NumberDeclined
gettrainername STRING_BUFFER_3, PICNICKER, LIZ1
scall .RegisteredNumber
sjump .NumberAccepted
.Rematch:
scall .RematchStd
winlosstext PicnickerLiz1BeatenText, 0
readmem wLizFightCount
ifequal 4, .Fight4
ifequal 3, .Fight3
ifequal 2, .Fight2
ifequal 1, .Fight1
ifequal 0, .LoadFight0
.Fight4:
checkevent EVENT_BEAT_ELITE_FOUR
iftrue .LoadFight4
.Fight3:
checkevent EVENT_CLEARED_RADIO_TOWER
iftrue .LoadFight3
.Fight2:
checkevent EVENT_CLEARED_ROCKET_HIDEOUT
iftrue .LoadFight2
.Fight1:
checkflag ENGINE_FLYPOINT_ECRUTEAK
iftrue .LoadFight1
.LoadFight0:
loadtrainer PICNICKER, LIZ1
startbattle
reloadmapafterbattle
loadmem wLizFightCount, 1
clearflag ENGINE_LIZ
end
.LoadFight1:
loadtrainer PICNICKER, LIZ2
startbattle
reloadmapafterbattle
loadmem wLizFightCount, 2
clearflag ENGINE_LIZ
end
.LoadFight2:
loadtrainer PICNICKER, LIZ3
startbattle
reloadmapafterbattle
loadmem wLizFightCount, 3
clearflag ENGINE_LIZ
end
.LoadFight3:
loadtrainer PICNICKER, LIZ4
startbattle
reloadmapafterbattle
loadmem wLizFightCount, 4
clearflag ENGINE_LIZ
end
.LoadFight4:
loadtrainer PICNICKER, LIZ5
startbattle
reloadmapafterbattle
clearflag ENGINE_LIZ
end
.AskNumber1:
jumpstd asknumber1f
end
.AskNumber2:
jumpstd asknumber2f
end
.RegisteredNumber:
jumpstd registerednumberf
end
.NumberAccepted:
jumpstd numberacceptedf
end
.NumberDeclined:
jumpstd numberdeclinedf
end
.PhoneFull:
jumpstd phonefullf
end
.RematchStd:
jumpstd rematchf
end
TrainerYoungsterAlbert:
trainer YOUNGSTER, ALBERT, EVENT_BEAT_YOUNGSTER_ALBERT, YoungsterAlbertSeenText, YoungsterAlbertBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext YoungsterAlbertAfterText
waitbutton
closetext
end
TrainerYoungsterGordon:
trainer YOUNGSTER, GORDON, EVENT_BEAT_YOUNGSTER_GORDON, YoungsterGordonSeenText, YoungsterGordonBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext YoungsterGordonAfterText
waitbutton
closetext
end
TrainerBirdKeeperPeter:
trainer BIRD_KEEPER, PETER, EVENT_BEAT_BIRD_KEEPER_PETER, BirdKeeperPeterSeenText, BirdKeeperPeterBeatenText, 0, .Script
.Script:
endifjustbattled
opentext
writetext BirdKeeperPeterAfterText
waitbutton
closetext
end
FriedaScript:
faceplayer
opentext
checkevent EVENT_GOT_POISON_BARB_FROM_FRIEDA
iftrue .Friday
readvar VAR_WEEKDAY
ifnotequal FRIDAY, .NotFriday
checkevent EVENT_MET_FRIEDA_OF_FRIDAY
iftrue .MetFrieda
writetext MeetFriedaText
buttonsound
setevent EVENT_MET_FRIEDA_OF_FRIDAY
.MetFrieda:
writetext FriedaGivesGiftText
buttonsound
verbosegiveitem POISON_BARB
iffalse .Done
setevent EVENT_GOT_POISON_BARB_FROM_FRIEDA
writetext FriedaGaveGiftText
waitbutton
closetext
end
.Friday:
writetext FriedaFridayText
waitbutton
.Done:
closetext
end
.NotFriday:
writetext FriedaNotFridayText
waitbutton
closetext
end
Route32GreatBall:
itemball GREAT_BALL
Route32Repel:
itemball REPEL
Route32Sign:
jumptext Route32SignText
Route32RuinsSign:
jumptext Route32RuinsSignText
Route32UnionCaveSign:
jumptext Route32UnionCaveSignText
Route32PokecenterSign:
jumpstd pokecentersign
Route32HiddenGreatBall:
hiddenitem GREAT_BALL, EVENT_ROUTE_32_HIDDEN_GREAT_BALL
Route32HiddenSuperPotion:
hiddenitem SUPER_POTION, EVENT_ROUTE_32_HIDDEN_SUPER_POTION
Movement_Route32CooltrainerMPushesYouBackToViolet:
step UP
step UP
step_end
Movement_Route32CooltrainerMReset1:
step DOWN
step_end
Movement_Route32CooltrainerMReset2:
step RIGHT
step_end
Route32CooltrainerMText_WhatsTheHurry:
text "Wait up!"
line "What's the hurry?"
done
Route32CooltrainerMText_AideIsWaiting:
text "<PLAYER>, right?"
line "Some guy wearing"
para "glasses was look-"
line "ing for you."
para "See for yourself."
line "He's waiting for"
para "you at the #MON"
line "CENTER."
done
Route32CooltrainerMText_UnusedSproutTower:
; unused
text "Have you gone to"
line "SPROUT TOWER?"
para "If you ever visit"
line "VIOLET CITY, "
para "they'll expect you"
line "to train there."
para "That's basic for"
line "trainers. Go to"
cont "SPROUT TOWER!"
done
Route32CooltrainerMText_VioletGym:
text "Have you gone to"
line "the #MON GYM?"
para "You can test your"
line "#MON and your-"
cont "self there."
para "It's a rite of"
line "passage for all"
cont "trainers!"
done
Route32CooltrainerMText_HaveThisSeed:
text "You have some good"
line "#MON there."
para "It must be from"
line "the training you"
para "gave them around"
line "VIOLET CITY."
para "The training at"
line "the GYM must have"
para "been especially"
line "helpful."
para "As a souvenir of"
line "VIOLET CITY, take"
cont "this."
para "It increases the"
line "power of grass-"
cont "type moves."
done
Route32CooltrainerMText_ExperiencesShouldBeUseful:
text "Your experiences"
line "in VIOLET CITY"
para "should be useful"
line "for your journey."
done
Text_MillionDollarSlowpokeTail:
text "How would you like"
line "to have this"
para "tasty, nutritious"
line "SLOWPOKETAIL?"
para "For you right now,"
line "just ¥1,000,000!"
para "You'll want this!"
done
Text_ThoughtKidsWereLoaded:
text "Tch! I thought"
line "kids these days"
cont "were loaded…"
done
Text_RefusedToBuySlowpokeTail:
text "You don't want it?"
line "Then scram. Shoo!"
done
FisherJustinSeenText:
text "Whoa!"
para "You made me lose"
line "that fish!"
done
FisherJustinBeatenText:
text "Sploosh!"
done
FisherJustinAfterText:
text "Calm, collected…"
line "The essence of"
para "fishing and #-"
line "MON is the same."
done
FisherRalph1SeenText:
text "I'm really good at"
line "both fishing and"
cont "#MON."
para "I'm not about to"
line "lose to any kid!"
done
FisherRalph1BeatenText:
text "Tch! I tried to"
line "rush things…"
done
FisherRalphAfterText:
text "Fishing is a life-"
line "long passion."
para "#MON are life-"
line "long friends!"
done
FisherRalphSwarmText:
text "One, two, three…"
line "Muahahaha, what a"
para "great haul!"
line "I'm done! Go ahead"
para "and catch as many"
line "as you can, kid!"
done
; --- start a segment of unused text
Route32UnusedFisher1SeenText:
text "I keep catching"
line "the same #MON…"
para "Maybe a battle"
line "will turn things"
cont "around for me."
done
Route32UnusedFisher1BeatenText:
text "Nothing ever goes"
line "right for me now…"
done
Route32UnusedFisher1AfterText:
text "How come the guy"
line "next to me catches"
cont "good #MON?"
done
Route32UnusedFisher2SeenText:
text "Heh, I'm on a roll"
line "today. How about a"
cont "battle, kid?"
done
Route32UnusedFisher2BeatenText:
text "Oof. I wasn't"
line "lucky that time."
done
Route32UnusedFisher2AfterText:
text "You have to have a"
line "good ROD if you"
para "want to catch good"
line "#MON."
done
; --- end a segment of unused texts
FisherHenrySeenText:
text "My #MON?"
line "Freshly caught!"
done
FisherHenryBeatenText:
text "SPLASH?"
done
FisherHenryAfterText:
text "Freshly caught"
line "#MON are no"
para "match for properly"
line "raised ones."
done
YoungsterAlbertSeenText:
text "I haven't seen you"
line "around before."
para "So you think you"
line "are pretty tough?"
done
YoungsterAlbertBeatenText:
text "You're strong!"
done
YoungsterAlbertAfterText:
text "I'm going to try"
line "to be the best"
cont "with my favorites."
para "I'm not using the"
line "same tough #MON"
cont "as everyone else."
done
YoungsterGordonSeenText:
text "I found some good"
line "#MON in the"
cont "grass!"
para "I think they'll do"
line "it for me!"
done
YoungsterGordonBeatenText:
text "Darn. I thought I"
line "could win."
done
YoungsterGordonAfterText:
text "The grass is full"
line "of clingy things."
done
CamperRolandSeenText:
text "That glance…"
line "It's intriguing."
done
CamperRolandBeatenText:
text "Hmmm. This is"
line "disappointing."
done
CamperRolandAfterText:
text "If you don't want"
line "to battle, just"
cont "avoid eye contact."
done
PicnickerLiz1SeenText:
text "Uh-huh. Yeah, and"
line "you know…"
para "Pardon? Battle?"
line "I'm on the phone."
para "Oh, all right. But"
line "make it fast."
done
PicnickerLiz1BeatenText:
text "Oh! I've got to"
line "relieve my anger!"
done
PicnickerLiz1AfterText:
text "I was having a"
line "nice chat too."
done
BirdKeeperPeterSeenText:
text "That BADGE! It's"
line "from VIOLET CITY!"
para "You beat FALKNER?"
done
BirdKeeperPeterBeatenText:
text "I know what my"
line "weaknesses are."
done
BirdKeeperPeterAfterText:
text "I should train"
line "again at the GYM"
cont "in VIOLET CITY."
done
Route32UnusedText:
; unused
text "The fishermen"
line "yelled at me for"
cont "bugging them…"
done
Text_RoarIntro:
text "WROOOOAR!"
line "PEOPLE RUN WHEN I"
para "ROAR! BUT YOU"
line "CAME LOOKING!"
para "THAT PLEASES ME!"
line "NOW TAKE THIS!"
done
Text_RoarOutro:
text "WROOOAR!"
line "IT'S ROAR!"
para "EVEN #MON RUN"
line "FROM A GOOD ROAR!"
done
MeetFriedaText:
text "FRIEDA: Yahoo!"
line "It's Friday!"
para "I'm FRIEDA of"
line "Friday!"
para "Nice to meet you!"
done
FriedaGivesGiftText:
text "Here's a POISON"
line "BARB for you!"
done
FriedaGaveGiftText:
text "FRIEDA: Give it to"
line "a #MON that has"
cont "poison-type moves."
para "Oh!"
para "It's wicked!"
para "You'll be shocked"
line "how good it makes"
cont "poison moves!"
done
FriedaFridayText:
text "FRIEDA: Hiya! What"
line "day do you like?"
para "I love Friday. No"
line "doubt about it!"
para "Don't you think"
line "it's great too?"
done
FriedaNotFridayText:
text "FRIEDA: Isn't it"
line "Friday today?"
para "It's so boring"
line "when it's not!"
done
Route32SignText:
text "ROUTE 32"
para "VIOLET CITY -"
line "AZALEA TOWN"
done
Route32RuinsSignText:
text "RUINS OF ALPH"
line "EAST ENTRANCE"
done
Route32UnionCaveSignText:
text "UNION CAVE"
line "AHEAD"
done
Route32_MapEvents:
db 0, 0 ; filler
db 4 ; warp events
warp_event 11, 73, ROUTE_32_POKECENTER_1F, 1
warp_event 4, 2, ROUTE_32_RUINS_OF_ALPH_GATE, 3
warp_event 4, 3, ROUTE_32_RUINS_OF_ALPH_GATE, 4
warp_event 6, 79, UNION_CAVE_1F, 4
db 2 ; coord events
coord_event 18, 8, SCENE_DEFAULT, Route32CooltrainerMStopsYouScene
coord_event 7, 71, SCENE_ROUTE32_OFFER_SLOWPOKETAIL, Route32WannaBuyASlowpokeTailScript
db 6 ; bg events
bg_event 13, 5, BGEVENT_READ, Route32Sign
bg_event 9, 1, BGEVENT_READ, Route32RuinsSign
bg_event 10, 84, BGEVENT_READ, Route32UnionCaveSign
bg_event 12, 73, BGEVENT_READ, Route32PokecenterSign
bg_event 12, 67, BGEVENT_ITEM, Route32HiddenGreatBall
bg_event 11, 40, BGEVENT_ITEM, Route32HiddenSuperPotion
db 14 ; object events
object_event 8, 49, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, PAL_NPC_GREEN, OBJECTTYPE_TRAINER, 1, TrainerFisherJustin, -1
object_event 12, 56, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_UP, 0, 0, -1, -1, PAL_NPC_GREEN, OBJECTTYPE_TRAINER, 3, TrainerFisherRalph1, -1
object_event 6, 48, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, PAL_NPC_GREEN, OBJECTTYPE_TRAINER, 1, TrainerFisherHenry, -1
object_event 12, 22, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerYoungsterAlbert, -1
object_event 4, 63, SPRITE_YOUNGSTER, SPRITEMOVEDATA_SPINRANDOM_FAST, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerYoungsterGordon, -1
object_event 3, 45, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_UP, 0, 0, -1, -1, PAL_NPC_GREEN, OBJECTTYPE_TRAINER, 3, TrainerCamperRoland, -1
object_event 10, 30, SPRITE_LASS, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, PAL_NPC_GREEN, OBJECTTYPE_TRAINER, 1, TrainerPicnickerLiz1, -1
object_event 19, 8, SPRITE_COOLTRAINER_M, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Route32CooltrainerMScript, -1
object_event 11, 82, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_UP, 0, 0, -1, -1, PAL_NPC_BLUE, OBJECTTYPE_TRAINER, 3, TrainerBirdKeeperPeter, -1
object_event 7, 70, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, SlowpokeTailSalesmanScript, EVENT_SLOWPOKE_WELL_ROCKETS
object_event 6, 53, SPRITE_POKE_BALL, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, 0, OBJECTTYPE_ITEMBALL, 0, Route32GreatBall, EVENT_ROUTE_32_GREAT_BALL
object_event 15, 13, SPRITE_FISHER, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, Route32RoarTMGuyScript, -1
object_event 12, 67, SPRITE_LASS, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, FriedaScript, EVENT_ROUTE_32_FRIEDA_OF_FRIDAY
object_event 3, 30, SPRITE_POKE_BALL, SPRITEMOVEDATA_STILL, 0, 0, -1, -1, 0, OBJECTTYPE_ITEMBALL, 0, Route32Repel, EVENT_ROUTE_32_REPEL
|
; SMS Priviledge Violation Recovery for 68020/68030/68040 1992 Tony Tebby
section base
xdef sms_privv
include 'dev8_smsq_smsq_base_keys'
;+++
; Priviledge violation recovery
; This assumes that there are two long words below the exception frame.
; These will usually be a return address (jsr sms_privv) and the exception
; identification (offset address, pointer to message etc.).
; This routine will attempt to identify and execute all instructions of the
; type MOVE.W SR,ea
; If no recovery is possible, this routine returns.
; If recovery is possible, the two long words on the stack are thrown away,
; the saved program counter is updated by 2, 4 or 6 bytes and execution
; resumed.
;---
sms_privv
spv.reg reg d0/d1/d2/d3/a0
stk_a0 equ $10
stk.ret equ $08
stk_sr equ $1c
stk_pc equ $1e
movem.l spv.reg,-(sp)
move.w stk_sr(sp),d3
move.l stk_pc(sp),a0 ; address of offending instruction
moveq #2,d2 ; assumed instruction length
moveq #$ffffffc0,d0
and.w (a0),d0 ; mask all but destination
cmp.w #$40c0,d0 ; move.w SR,ea?
bne.s spv_exit
moveq #7,d1
and.w (a0),d1 ; register
lsl.w #2,d1 ; register * 4
moveq #$38,d0
and.w (a0),d0 ; mode
lsr.w #2,d0 ; *2
move.w spv_mtab(pc,d0.w),d0
jmp spv_mtab(pc,d0.w)
spv_mtab
dc.w spv_dreg-spv_mtab
dc.w spv_exit-spv_mtab
dc.w spv_indr-spv_mtab
dc.w spv_psti-spv_mtab
dc.w spv_pred-spv_mtab
dc.w spv_disp-spv_mtab
dc.w spv_indx-spv_mtab
dc.w spv_abs-spv_mtab
spv_exit
movem.l (sp)+,spv.reg
rts
; set data register
spv_dreg
cmp.w #3*4,d1 ; 0 to 3?
bgt.s spv_dset
move.w d3,2(sp,d1.w) ; set register on stack
bra.s spv_ok ; done
spv_dset
jmp spv_dset-3*4(pc,d1.w) ; code for each D register
move.w d3,d4 ; set d4
bra.s spv_ok
move.w d3,d5 ; set d5
bra.s spv_ok
move.w d3,d6 ; set d6
bra.s spv_ok
move.w d3,d7 ; set d7
bra.s spv_ok
; set register indirect
spv_indr
jmp spv_indr+4(pc,d1.l) ; code for each A reg
bra.s spv_ina0
nop
move.w d3,(a1)
bra.s spv_ok
move.w d3,(a2)
bra.s spv_ok
move.w d3,(a3)
bra.s spv_ok
move.w d3,(a4)
bra.s spv_ok
move.w d3,(a5)
bra.s spv_ok
move.w d3,(a6)
bra.s spv_ok
move.l usp,a0
move.w d3,(a0)
bra.s spv_aok
spv_ina0
move.l stk_a0(sp),a0
move.w d3,(a0)
bra.s spv_aok
; set post increment
spv_psti
jmp spv_psti+4(pc,d1.l) ; code for each A reg
bra.s spv_psa0
nop
move.w d3,(a1)+
bra.s spv_ok
move.w d3,(a2)+
bra.s spv_ok
move.w d3,(a3)+
bra.s spv_ok
move.w d3,(a4)+
bra.s spv_ok
move.w d3,(a5)+
bra.s spv_ok
move.w d3,(a6)+
bra.s spv_ok
move.l usp,a0
move.w d3,(a0)+
move.l a0,usp
bra.s spv_aok
spv_psa0
move.l stk_a0(sp),a0
move.w d3,(a0)+
move.l a0,stk_a0(sp)
;; bra.s spv_aok
spv_aok
move.l stk_pc(sp),a0
spv_ok
add.w d2,a0
move.l a0,stk_pc(sp) ; move program counter on
jsr sms.cinvd ; code modified in data cache
jsr sms.cinvi ; code modified
movem.l (sp)+,spv.reg ; restore regs
addq.l #8,sp ; skip two return addresses
rte
; set predecrement
spv_pred
jmp spv_pred+4(pc,d1.l) ; code for each A reg
bra.s spv_pra0
nop
move.w d3,-(a1)
bra.s spv_ok
move.w d3,-(a2)
bra.s spv_ok
move.w d3,-(a3)
bra.s spv_ok
move.w d3,-(a4)
bra.s spv_ok
move.w d3,-(a5)
bra.s spv_ok
move.w d3,-(a6)
bra.s spv_ok
move.l usp,a0
move.w d3,-(a0)
move.l a0,usp
bra.s spv_aok
spv_pra0
move.l stk_a0(sp),a0
move.w d3,-(a0)
move.l a0,stk_a0(sp)
bra.s spv_aok
; register indirect with displacement
spv_disp
moveq #4,d2 ; four byte instruction
move.w 2(a0),d0 ; the displacement
jmp spv_dscd(pc,d1.w)
spv_dscd
bra.s spv_dsa0
nop
move.l a1,a0
bra.s spv_dsst
move.l a2,a0
bra.s spv_dsst
move.l a3,a0
bra.s spv_dsst
move.l a4,a0
bra.s spv_dsst
move.l a5,a0
bra.s spv_dsst
move.l a6,a0
bra.s spv_dsst
move.l usp,a0
bra.s spv_dsst
spv_dsa0
move.l stk_a0(sp),a0
spv_dsst
move.w d3,(a0,d0.w)
bra spv_aok
; Register with index and displacement
spv_indx
move.w 2(a0),d0 ; index+displacement
jmp spv_ixc(pc,d1.w)
spv_ixc
bra.s spv_ixa0
nop
move.l a1,a0
bra.s spv_ixsi
move.l a2,a0
bra.s spv_ixsi
move.l a3,a0
bra.s spv_ixsi
move.l a4,a0
bra.s spv_ixsi
move.l a5,a0
bra.s spv_ixsi
move.l a6,a0
bra.s spv_ixsi
move.l usp,a0
bra.s spv_ixsi
spv_ixa0
move.l stk_a0(sp),a0
spv_ixsi
move.b d0,d1
ext.w d1
add.w d1,a0 ; displacement
move.l a0,d2 ; save it
lsl.l #4,d0
swap d0 ; index reg in lsw word / long in msb
lsl.w #2,d0
cmp.w #3*4,d0 ; low D reg?
bhi.s spc_ixim ; ... no
move.l (sp,d0.w),a0 ; ... yes
bra.s spv_ixst
spc_ixim
jmp spc_ixim-3*4(pc,d0.w)
move.l d4,a0
bra.s spv_ixst
move.l d5,a0
bra.s spv_ixst
move.l d6,a0
bra.s spv_ixst
move.l d7,a0
bra.s spv_ixst
bra.s spv_iia0
nop
move.l a1,a0
bra.s spv_ixst
move.l a2,a0
bra.s spv_ixst
move.l a3,a0
bra.s spv_ixst
move.l a4,a0
bra.s spv_ixst
move.l a5,a0
bra.s spv_ixst
move.l a6,a0
bra.s spv_ixst
move.l usp,a0
bra.s spv_ixst
spv_iia0
move.l stk_a0(sp),a0
spv_ixst
tst.l d0 ; long word index?
bmi.s spv_ixsl
move.w a0,a0 ; ... no, sign extend a0
spv_ixsl
move.w d3,(a0,d2.l) ; set status register
moveq #4,d2 ; four byte instruction
bra.l spv_aok
; absolute addresses
spv_abs
subq.w #1*4,d1 ; long address
beq.s spv_absl
bhi spv_exit ; ... no, and not short
move.w 2(a0),a0 ; absolute short
moveq #4,d2
bra.s spv_aset
spv_absl
move.l 2(a0),a0
moveq #6,d2 ; absolute long
spv_aset
move.w d3,(a0)
bra.l spv_aok
end
|
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2020, LAAS-CNRS, The University of Edinburgh
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#ifndef CROCODDYL_MULTIBODY_COSTS_FRAME_PLACEMENT_HPP_
#define CROCODDYL_MULTIBODY_COSTS_FRAME_PLACEMENT_HPP_
#include "crocoddyl/multibody/cost-base.hpp"
#include "crocoddyl/multibody/data/multibody.hpp"
#include "crocoddyl/multibody/frames.hpp"
#include "crocoddyl/core/utils/exception.hpp"
namespace crocoddyl {
class CostModelFramePlacement : public CostModelAbstract {
public:
CostModelFramePlacement(boost::shared_ptr<StateMultibody> state,
boost::shared_ptr<ActivationModelAbstract> activation, const FramePlacement& Fref,
const std::size_t& nu);
CostModelFramePlacement(boost::shared_ptr<StateMultibody> state,
boost::shared_ptr<ActivationModelAbstract> activation, const FramePlacement& Fref);
CostModelFramePlacement(boost::shared_ptr<StateMultibody> state, const FramePlacement& Fref, const std::size_t& nu);
CostModelFramePlacement(boost::shared_ptr<StateMultibody> state, const FramePlacement& Fref);
~CostModelFramePlacement();
void calc(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const Eigen::VectorXd>& x,
const Eigen::Ref<const Eigen::VectorXd>& u);
void calcDiff(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const Eigen::VectorXd>& x,
const Eigen::Ref<const Eigen::VectorXd>& u, const bool& recalc = true);
boost::shared_ptr<CostDataAbstract> createData(DataCollectorAbstract* const data);
const FramePlacement& get_Mref() const;
void set_Mref(const FramePlacement& Mref_in);
private:
FramePlacement Mref_;
pinocchio::SE3 oMf_inv_;
};
struct CostDataFramePlacement : public CostDataAbstract {
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
template <typename Model>
CostDataFramePlacement(Model* const model, DataCollectorAbstract* const data)
: CostDataAbstract(model, data),
J(6, model->get_state()->get_nv()),
rJf(6, 6),
fJf(6, model->get_state()->get_nv()),
Arr_J(6, model->get_state()->get_nv()) {
r.fill(0);
J.fill(0);
rJf.fill(0);
fJf.fill(0);
Arr_J.fill(0);
// Check that proper shared data has been passed
DataCollectorMultibody* d = dynamic_cast<DataCollectorMultibody*>(shared);
if (d == NULL) {
throw_pretty("Invalid argument: the shared data should be derived from DataCollectorMultibody");
}
// Avoids data casting at runtime
pinocchio = d->pinocchio;
}
pinocchio::Data* pinocchio;
pinocchio::Motion::Vector6 r;
pinocchio::SE3 rMf;
pinocchio::Data::Matrix6x J;
pinocchio::Data::Matrix6 rJf;
pinocchio::Data::Matrix6x fJf;
pinocchio::Data::Matrix6x Arr_J;
};
} // namespace crocoddyl
#endif // CROCODDYL_MULTIBODY_COSTS_FRAME_PLACEMENT_HPP_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.